var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => {
  __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  return value;
};
(function polyfill() {
  const relList = document.createElement("link").relList;
  if (relList && relList.supports && relList.supports("modulepreload")) {
    return;
  }
  for (const link2 of document.querySelectorAll('link[rel="modulepreload"]')) {
    processPreload(link2);
  }
  new MutationObserver((mutations) => {
    for (const mutation of mutations) {
      if (mutation.type !== "childList") {
        continue;
      }
      for (const node2 of mutation.addedNodes) {
        if (node2.tagName === "LINK" && node2.rel === "modulepreload")
          processPreload(node2);
      }
    }
  }).observe(document, { childList: true, subtree: true });
  function getFetchOpts(link2) {
    const fetchOpts = {};
    if (link2.integrity)
      fetchOpts.integrity = link2.integrity;
    if (link2.referrerPolicy)
      fetchOpts.referrerPolicy = link2.referrerPolicy;
    if (link2.crossOrigin === "use-credentials")
      fetchOpts.credentials = "include";
    else if (link2.crossOrigin === "anonymous")
      fetchOpts.credentials = "omit";
    else
      fetchOpts.credentials = "same-origin";
    return fetchOpts;
  }
  function processPreload(link2) {
    if (link2.ep)
      return;
    link2.ep = true;
    const fetchOpts = getFetchOpts(link2);
    fetch(link2.href, fetchOpts);
  }
})();
function makeMap$1(str2, expectsLowerCase) {
  const map2 = /* @__PURE__ */ Object.create(null);
  const list2 = str2.split(",");
  for (let i = 0; i < list2.length; i++) {
    map2[list2[i]] = true;
  }
  return expectsLowerCase ? (val) => !!map2[val.toLowerCase()] : (val) => !!map2[val];
}
const EMPTY_OBJ$1 = {};
const EMPTY_ARR = [];
const NOOP$1 = () => {
};
const NO$1 = () => false;
const onRE$1 = /^on[^a-z]/;
const isOn$1 = (key) => onRE$1.test(key);
const isModelListener = (key) => key.startsWith("onUpdate:");
const extend$1 = Object.assign;
const remove = (arr, el) => {
  const i = arr.indexOf(el);
  if (i > -1) {
    arr.splice(i, 1);
  }
};
const hasOwnProperty$8 = Object.prototype.hasOwnProperty;
const hasOwn$1 = (val, key) => hasOwnProperty$8.call(val, key);
const isArray$5 = Array.isArray;
const isMap$1 = (val) => toTypeString$1(val) === "[object Map]";
const isSet$1 = (val) => toTypeString$1(val) === "[object Set]";
const isDate$1 = (val) => toTypeString$1(val) === "[object Date]";
const isFunction$3 = (val) => typeof val === "function";
const isString$5 = (val) => typeof val === "string";
const isSymbol$2 = (val) => typeof val === "symbol";
const isObject$5 = (val) => val !== null && typeof val === "object";
const isPromise$1 = (val) => {
  return isObject$5(val) && isFunction$3(val.then) && isFunction$3(val.catch);
};
const objectToString$2 = Object.prototype.toString;
const toTypeString$1 = (value) => objectToString$2.call(value);
const toRawType = (value) => {
  return toTypeString$1(value).slice(8, -1);
};
const isPlainObject$1 = (val) => toTypeString$1(val) === "[object Object]";
const isIntegerKey = (key) => isString$5(key) && key !== "NaN" && key[0] !== "-" && "" + parseInt(key, 10) === key;
const isReservedProp$1 = /* @__PURE__ */ makeMap$1(
  // the leading comma is intentional so empty string "" is also included
  ",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"
);
const cacheStringFunction$1 = (fn) => {
  const cache2 = /* @__PURE__ */ Object.create(null);
  return (str2) => {
    const hit = cache2[str2];
    return hit || (cache2[str2] = fn(str2));
  };
};
const camelizeRE$1 = /-(\w)/g;
const camelize$1 = cacheStringFunction$1((str2) => {
  return str2.replace(camelizeRE$1, (_, c) => c ? c.toUpperCase() : "");
});
const hyphenateRE$1 = /\B([A-Z])/g;
const hyphenate$1 = cacheStringFunction$1(
  (str2) => str2.replace(hyphenateRE$1, "-$1").toLowerCase()
);
const capitalize$2 = cacheStringFunction$1(
  (str2) => str2.charAt(0).toUpperCase() + str2.slice(1)
);
const toHandlerKey$1 = cacheStringFunction$1(
  (str2) => str2 ? `on${capitalize$2(str2)}` : ``
);
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 looseToNumber = (val) => {
  const n2 = parseFloat(val);
  return isNaN(n2) ? val : n2;
};
let _globalThis;
const getGlobalThis = () => {
  return _globalThis || (_globalThis = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {});
};
function normalizeStyle$1(value) {
  if (isArray$5(value)) {
    const res = {};
    for (let i = 0; i < value.length; i++) {
      const item = value[i];
      const normalized = isString$5(item) ? parseStringStyle$1(item) : normalizeStyle$1(item);
      if (normalized) {
        for (const key in normalized) {
          res[key] = normalized[key];
        }
      }
    }
    return res;
  } else if (isString$5(value)) {
    return value;
  } else if (isObject$5(value)) {
    return value;
  }
}
const listDelimiterRE$1 = /;(?![^(]*\))/g;
const propertyDelimiterRE$1 = /:([^]+)/;
const styleCommentRE$1 = /\/\*[^]*?\*\//g;
function parseStringStyle$1(cssText) {
  const ret = {};
  cssText.replace(styleCommentRE$1, "").split(listDelimiterRE$1).forEach((item) => {
    if (item) {
      const tmp = item.split(propertyDelimiterRE$1);
      tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
    }
  });
  return ret;
}
function normalizeClass$1(value) {
  let res = "";
  if (isString$5(value)) {
    res = value;
  } else if (isArray$5(value)) {
    for (let i = 0; i < value.length; i++) {
      const normalized = normalizeClass$1(value[i]);
      if (normalized) {
        res += normalized + " ";
      }
    }
  } else if (isObject$5(value)) {
    for (const name in value) {
      if (value[name]) {
        res += name + " ";
      }
    }
  }
  return res.trim();
}
const specialBooleanAttrs$1 = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;
const isSpecialBooleanAttr = /* @__PURE__ */ makeMap$1(specialBooleanAttrs$1);
function includeBooleanAttr(value) {
  return !!value || value === "";
}
function looseCompareArrays(a, b) {
  if (a.length !== b.length)
    return false;
  let equal = true;
  for (let i = 0; equal && i < a.length; i++) {
    equal = looseEqual(a[i], b[i]);
  }
  return equal;
}
function looseEqual(a, b) {
  if (a === b)
    return true;
  let aValidType = isDate$1(a);
  let bValidType = isDate$1(b);
  if (aValidType || bValidType) {
    return aValidType && bValidType ? a.getTime() === b.getTime() : false;
  }
  aValidType = isSymbol$2(a);
  bValidType = isSymbol$2(b);
  if (aValidType || bValidType) {
    return a === b;
  }
  aValidType = isArray$5(a);
  bValidType = isArray$5(b);
  if (aValidType || bValidType) {
    return aValidType && bValidType ? looseCompareArrays(a, b) : false;
  }
  aValidType = isObject$5(a);
  bValidType = isObject$5(b);
  if (aValidType || bValidType) {
    if (!aValidType || !bValidType) {
      return false;
    }
    const aKeysCount = Object.keys(a).length;
    const bKeysCount = Object.keys(b).length;
    if (aKeysCount !== bKeysCount) {
      return false;
    }
    for (const key in a) {
      const aHasKey = a.hasOwnProperty(key);
      const bHasKey = b.hasOwnProperty(key);
      if (aHasKey && !bHasKey || !aHasKey && bHasKey || !looseEqual(a[key], b[key])) {
        return false;
      }
    }
  }
  return String(a) === String(b);
}
function looseIndexOf(arr, val) {
  return arr.findIndex((item) => looseEqual(item, val));
}
const toDisplayString$1 = (val) => {
  return isString$5(val) ? val : val == null ? "" : isArray$5(val) || isObject$5(val) && (val.toString === objectToString$2 || !isFunction$3(val.toString)) ? JSON.stringify(val, replacer$2, 2) : String(val);
};
const replacer$2 = (_key, val) => {
  if (val && val.__v_isRef) {
    return replacer$2(_key, val.value);
  } else if (isMap$1(val)) {
    return {
      [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val2]) => {
        entries[`${key} =>`] = val2;
        return entries;
      }, {})
    };
  } else if (isSet$1(val)) {
    return {
      [`Set(${val.size})`]: [...val.values()]
    };
  } else if (isObject$5(val) && !isArray$5(val) && !isPlainObject$1(val)) {
    return String(val);
  }
  return val;
};
let activeEffectScope;
class EffectScope {
  constructor(detached = false) {
    this.detached = detached;
    this._active = true;
    this.effects = [];
    this.cleanups = [];
    this.parent = activeEffectScope;
    if (!detached && activeEffectScope) {
      this.index = (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push(
        this
      ) - 1;
    }
  }
  get active() {
    return this._active;
  }
  run(fn) {
    if (this._active) {
      const currentEffectScope = activeEffectScope;
      try {
        activeEffectScope = this;
        return fn();
      } finally {
        activeEffectScope = currentEffectScope;
      }
    }
  }
  /**
   * This should only be called on non-detached scopes
   * @internal
   */
  on() {
    activeEffectScope = this;
  }
  /**
   * This should only be called on non-detached scopes
   * @internal
   */
  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.detached && this.parent && !fromParent) {
        const last2 = this.parent.scopes.pop();
        if (last2 && last2 !== this) {
          this.parent.scopes[this.index] = last2;
          last2.index = this.index;
        }
      }
      this.parent = void 0;
      this._active = false;
    }
  }
}
function recordEffectScope(effect, scope = activeEffectScope) {
  if (scope && scope.active) {
    scope.effects.push(effect);
  }
}
function getCurrentScope() {
  return activeEffectScope;
}
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(effect2) {
  const { deps } = effect2;
  if (deps.length) {
    for (let i = 0; i < deps.length; i++) {
      deps[i].delete(effect2);
    }
    deps.length = 0;
  }
}
let shouldTrack = true;
const trackStack = [];
function pauseTracking() {
  trackStack.push(shouldTrack);
  shouldTrack = false;
}
function resetTracking() {
  const last2 = trackStack.pop();
  shouldTrack = last2 === void 0 ? true : last2;
}
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$5(target)) {
    const newLength = Number(newValue);
    depsMap.forEach((dep, key2) => {
      if (key2 === "length" || key2 >= newLength) {
        deps.push(dep);
      }
    });
  } else {
    if (key !== void 0) {
      deps.push(depsMap.get(key));
    }
    switch (type) {
      case "add":
        if (!isArray$5(target)) {
          deps.push(depsMap.get(ITERATE_KEY));
          if (isMap$1(target)) {
            deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
          }
        } else if (isIntegerKey(key)) {
          deps.push(depsMap.get("length"));
        }
        break;
      case "delete":
        if (!isArray$5(target)) {
          deps.push(depsMap.get(ITERATE_KEY));
          if (isMap$1(target)) {
            deps.push(depsMap.get(MAP_KEY_ITERATE_KEY));
          }
        }
        break;
      case "set":
        if (isMap$1(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$5(dep) ? dep : [...dep];
  for (const effect2 of effects) {
    if (effect2.computed) {
      triggerEffect(effect2);
    }
  }
  for (const effect2 of effects) {
    if (!effect2.computed) {
      triggerEffect(effect2);
    }
  }
}
function triggerEffect(effect2, debuggerEventExtraInfo) {
  if (effect2 !== activeEffect || effect2.allowRecurse) {
    if (effect2.scheduler) {
      effect2.scheduler();
    } else {
      effect2.run();
    }
  }
}
const isNonTrackableKeys = /* @__PURE__ */ makeMap$1(`__proto__,__v_isRef,__isVue`);
const builtInSymbols = new Set(
  /* @__PURE__ */ Object.getOwnPropertyNames(Symbol).filter((key) => key !== "arguments" && key !== "caller").map((key) => Symbol[key]).filter(isSymbol$2)
);
const get$1 = /* @__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 hasOwnProperty$7(key) {
  const obj = toRaw(this);
  track(obj, "has", key);
  return obj.hasOwnProperty(key);
}
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$5(target);
    if (!isReadonly2) {
      if (targetIsArray && hasOwn$1(arrayInstrumentations, key)) {
        return Reflect.get(arrayInstrumentations, key, receiver);
      }
      if (key === "hasOwnProperty") {
        return hasOwnProperty$7;
      }
    }
    const res = Reflect.get(target, key, receiver);
    if (isSymbol$2(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$5(res)) {
      return isReadonly2 ? readonly(res) : reactive(res);
    }
    return res;
  };
}
const set$1 = /* @__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) {
      if (!isShallow(value) && !isReadonly(value)) {
        oldValue = toRaw(oldValue);
        value = toRaw(value);
      }
      if (!isArray$5(target) && isRef(oldValue) && !isRef(value)) {
        oldValue.value = value;
        return true;
      }
    }
    const hadKey = isArray$5(target) && isIntegerKey(key) ? Number(key) < target.length : hasOwn$1(target, key);
    const result2 = 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 result2;
  };
}
function deleteProperty(target, key) {
  const hadKey = hasOwn$1(target, key);
  target[key];
  const result2 = Reflect.deleteProperty(target, key);
  if (result2 && hadKey) {
    trigger(target, "delete", key, void 0);
  }
  return result2;
}
function has$1$1(target, key) {
  const result2 = Reflect.has(target, key);
  if (!isSymbol$2(key) || !builtInSymbols.has(key)) {
    track(target, "has", key);
  }
  return result2;
}
function ownKeys(target) {
  track(target, "iterate", isArray$5(target) ? "length" : ITERATE_KEY);
  return Reflect.ownKeys(target);
}
const mutableHandlers = {
  get: get$1,
  set: set$1,
  deleteProperty,
  has: has$1$1,
  ownKeys
};
const readonlyHandlers = {
  get: readonlyGet,
  set(target, key) {
    return true;
  },
  deleteProperty(target, key) {
    return true;
  }
};
const shallowReactiveHandlers = /* @__PURE__ */ extend$1(
  {},
  mutableHandlers,
  {
    get: shallowGet,
    set: shallowSet
  }
);
const toShallow = (value) => value;
const getProto = (v) => Reflect.getPrototypeOf(v);
function get$2(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$2(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$1(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(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 result2 = target.delete(key);
  if (hadKey) {
    trigger(target, "delete", key, void 0);
  }
  return result2;
}
function clear() {
  const target = toRaw(this);
  const hadItems = target.size !== 0;
  const result2 = target.clear();
  if (hadItems) {
    trigger(target, "clear", void 0, void 0);
  }
  return result2;
}
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$1(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 {
      // iterator protocol
      next() {
        const { value, done } = innerIterator.next();
        return done ? { value, done } : {
          value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
          done
        };
      },
      // iterable protocol
      [Symbol.iterator]() {
        return this;
      }
    };
  };
}
function createReadonlyMethod(type) {
  return function(...args) {
    return type === "delete" ? false : this;
  };
}
function createInstrumentations() {
  const mutableInstrumentations2 = {
    get(key) {
      return get$2(this, key);
    },
    get size() {
      return size$1(this);
    },
    has: has$2,
    add,
    set,
    delete: deleteEntry,
    clear,
    forEach: createForEach(false, false)
  };
  const shallowInstrumentations2 = {
    get(key) {
      return get$2(this, key, false, true);
    },
    get size() {
      return size$1(this);
    },
    has: has$2,
    add,
    set,
    delete: deleteEntry,
    clear,
    forEach: createForEach(false, true)
  };
  const readonlyInstrumentations2 = {
    get(key) {
      return get$2(this, key, true);
    },
    get size() {
      return size$1(this, true);
    },
    has(key) {
      return has$2.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$2(this, key, true, true);
    },
    get size() {
      return size$1(this, true);
    },
    has(key) {
      return has$2.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$1(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$5(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$5(value) ? reactive(value) : value;
const toReadonly = (value) => isObject$5(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);
  const dep = ref2.dep;
  if (dep) {
    {
      triggerEffects(dep);
    }
  }
}
function isRef(r) {
  return !!(r && r.__v_isRef === true);
}
function ref(value) {
  return createRef(value, false);
}
function shallowRef(value) {
  return createRef(value, true);
}
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) {
    const useDirectValue = this.__v_isShallow || isShallow(newVal) || isReadonly(newVal);
    newVal = useDirectValue ? newVal : toRaw(newVal);
    if (hasChanged(newVal, this._rawValue)) {
      this._rawValue = newVal;
      this._value = useDirectValue ? newVal : toReactive(newVal);
      triggerRefValue(this);
    }
  }
}
function triggerRef(ref2) {
  triggerRefValue(ref2);
}
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["__v_isReadonly"] = false;
    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$3(getterOrOptions);
  if (onlyGetter) {
    getter = getterOrOptions;
    setter = NOOP$1;
  } else {
    getter = getterOrOptions.get;
    setter = getterOrOptions.set;
  }
  const cRef = new ComputedRefImpl(getter, setter, onlyGetter || !setter, isSSR);
  return cRef;
}
function warn(msg, ...args) {
  return;
}
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$3(fn)) {
    const res = callWithErrorHandling(fn, instance, type, args);
    if (res && isPromise$1(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$1 = [];
let flushIndex = 0;
const pendingPostFlushCbs = [];
let activePostFlushCbs = null;
let postFlushIndex = 0;
const resolvedPromise = /* @__PURE__ */ Promise.resolve();
let currentFlushPromise = null;
function nextTick$1(fn) {
  const p2 = currentFlushPromise || resolvedPromise;
  return fn ? p2.then(this ? fn.bind(this) : fn) : p2;
}
function findInsertionIndex(id3) {
  let start = flushIndex + 1;
  let end = queue$1.length;
  while (start < end) {
    const middle = start + end >>> 1;
    const middleJobId = getId(queue$1[middle]);
    middleJobId < id3 ? start = middle + 1 : end = middle;
  }
  return start;
}
function queueJob(job) {
  if (!queue$1.length || !queue$1.includes(
    job,
    isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex
  )) {
    if (job.id == null) {
      queue$1.push(job);
    } else {
      queue$1.splice(findInsertionIndex(job.id), 0, job);
    }
    queueFlush();
  }
}
function queueFlush() {
  if (!isFlushing && !isFlushPending) {
    isFlushPending = true;
    currentFlushPromise = resolvedPromise.then(flushJobs);
  }
}
function invalidateJob(job) {
  const i = queue$1.indexOf(job);
  if (i > flushIndex) {
    queue$1.splice(i, 1);
  }
}
function queuePostFlushCb(cb) {
  if (!isArray$5(cb)) {
    if (!activePostFlushCbs || !activePostFlushCbs.includes(
      cb,
      cb.allowRecurse ? postFlushIndex + 1 : postFlushIndex
    )) {
      pendingPostFlushCbs.push(cb);
    }
  } else {
    pendingPostFlushCbs.push(...cb);
  }
  queueFlush();
}
function flushPreFlushCbs(seen2, i = isFlushing ? flushIndex + 1 : 0) {
  for (; i < queue$1.length; i++) {
    const cb = queue$1[i];
    if (cb && cb.pre) {
      queue$1.splice(i, 1);
      i--;
      cb();
    }
  }
}
function flushPostFlushCbs(seen2) {
  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;
const comparator = (a, b) => {
  const diff = getId(a) - getId(b);
  if (diff === 0) {
    if (a.pre && !b.pre)
      return -1;
    if (b.pre && !a.pre)
      return 1;
  }
  return diff;
};
function flushJobs(seen2) {
  isFlushPending = false;
  isFlushing = true;
  queue$1.sort(comparator);
  const check = NOOP$1;
  try {
    for (flushIndex = 0; flushIndex < queue$1.length; flushIndex++) {
      const job = queue$1[flushIndex];
      if (job && job.active !== false) {
        if (false)
          ;
        callWithErrorHandling(job, null, 14);
      }
    }
  } finally {
    flushIndex = 0;
    queue$1.length = 0;
    flushPostFlushCbs();
    isFlushing = false;
    currentFlushPromise = null;
    if (queue$1.length || pendingPostFlushCbs.length) {
      flushJobs();
    }
  }
}
function emit$1(instance, event, ...rawArgs) {
  if (instance.isUnmounted)
    return;
  const props = instance.vnode.props || EMPTY_OBJ$1;
  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: trim2 } = props[modifiersKey] || EMPTY_OBJ$1;
    if (trim2) {
      args = rawArgs.map((a) => isString$5(a) ? a.trim() : a);
    }
    if (number) {
      args = rawArgs.map(looseToNumber);
    }
  }
  let handlerName;
  let handler = props[handlerName = toHandlerKey$1(event)] || // also try camelCase event handler (#2249)
  props[handlerName = toHandlerKey$1(camelize$1(event))];
  if (!handler && isModelListener2) {
    handler = props[handlerName = toHandlerKey$1(hyphenate$1(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 cache2 = appContext.emitsCache;
  const cached = cache2.get(comp);
  if (cached !== void 0) {
    return cached;
  }
  const raw = comp.emits;
  let normalized = {};
  let hasExtends = false;
  if (!isFunction$3(comp)) {
    const extendEmits = (raw2) => {
      const normalizedFromExtend = normalizeEmitsOptions(raw2, appContext, true);
      if (normalizedFromExtend) {
        hasExtends = true;
        extend$1(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) {
    if (isObject$5(comp)) {
      cache2.set(comp, null);
    }
    return null;
  }
  if (isArray$5(raw)) {
    raw.forEach((key) => normalized[key] = null);
  } else {
    extend$1(normalized, raw);
  }
  if (isObject$5(comp)) {
    cache2.set(comp, normalized);
  }
  return normalized;
}
function isEmitListener(options, key) {
  if (!options || !isOn$1(key)) {
    return false;
  }
  key = key.slice(2).replace(/Once$/, "");
  return hasOwn$1(options, key[0].toLowerCase() + key.slice(1)) || hasOwn$1(options, hyphenate$1(key)) || hasOwn$1(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(id3) {
  currentScopeId = id3;
}
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);
    let res;
    try {
      res = fn(...args);
    } finally {
      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: emit2,
    render,
    renderCache,
    data,
    setupState,
    ctx,
    inheritAttrs
  } = instance;
  let result2;
  let fallthroughAttrs;
  const prev = setCurrentRenderingInstance(instance);
  try {
    if (vnode.shapeFlag & 4) {
      const proxyToUse = withProxy || proxy;
      result2 = normalizeVNode(
        render.call(
          proxyToUse,
          proxyToUse,
          renderCache,
          props,
          setupState,
          data,
          ctx
        )
      );
      fallthroughAttrs = attrs;
    } else {
      const render2 = Component;
      if (false)
        ;
      result2 = normalizeVNode(
        render2.length > 1 ? render2(
          props,
          false ? {
            get attrs() {
              markAttrsAccessed();
              return attrs;
            },
            slots,
            emit: emit2
          } : { attrs, slots, emit: emit2 }
        ) : render2(
          props,
          null
          /* we know it doesn't need it */
        )
      );
      fallthroughAttrs = Component.props ? attrs : getFunctionalFallthrough(attrs);
    }
  } catch (err) {
    blockStack.length = 0;
    handleError(err, instance, 1);
    result2 = createVNode(Comment$5);
  }
  let root3 = result2;
  if (fallthroughAttrs && inheritAttrs !== false) {
    const keys = Object.keys(fallthroughAttrs);
    const { shapeFlag } = root3;
    if (keys.length) {
      if (shapeFlag & (1 | 6)) {
        if (propsOptions && keys.some(isModelListener)) {
          fallthroughAttrs = filterModelListeners(
            fallthroughAttrs,
            propsOptions
          );
        }
        root3 = cloneVNode(root3, fallthroughAttrs);
      }
    }
  }
  if (vnode.dirs) {
    root3 = cloneVNode(root3);
    root3.dirs = root3.dirs ? root3.dirs.concat(vnode.dirs) : vnode.dirs;
  }
  if (vnode.transition) {
    root3.transition = vnode.transition;
  }
  {
    result2 = root3;
  }
  setCurrentRenderingInstance(prev);
  return result2;
}
const getFunctionalFallthrough = (attrs) => {
  let res;
  for (const key in attrs) {
    if (key === "class" || key === "style" || isOn$1(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$5(fn)) {
      suspense.effects.push(...fn);
    } else {
      suspense.effects.push(fn);
    }
  } else {
    queuePostFlushCb(fn);
  }
}
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$1) {
  var _a2;
  const instance = getCurrentScope() === ((_a2 = currentInstance) == null ? void 0 : _a2.scope) ? currentInstance : null;
  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$5(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$3(s)) {
        return callWithErrorHandling(s, instance, 2);
      } else
        ;
    });
  } else if (isFunction$3(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$1;
  }
  if (cb && deep) {
    const baseGetter = getter;
    getter = () => traverse(baseGetter());
  }
  let cleanup;
  let onCleanup = (fn) => {
    cleanup = effect.onStop = () => {
      callWithErrorHandling(fn, instance, 4);
    };
  };
  let ssrCleanup;
  if (isInSSRComponentSetup) {
    onCleanup = NOOP$1;
    if (!cb) {
      getter();
    } else if (immediate) {
      callWithAsyncErrorHandling(cb, instance, 3, [
        getter(),
        isMultiSource ? [] : void 0,
        onCleanup
      ]);
    }
    if (flush === "sync") {
      const ctx = useSSRContext();
      ssrCleanup = ctx.__watcherHandles || (ctx.__watcherHandles = []);
    } else {
      return NOOP$1;
    }
  }
  let oldValue = isMultiSource ? new Array(source.length).fill(INITIAL_WATCHER_VALUE) : 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,
          // pass undefined as the old value when it's changed for the first time
          oldValue === INITIAL_WATCHER_VALUE ? void 0 : isMultiSource && oldValue[0] === INITIAL_WATCHER_VALUE ? [] : 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 {
    job.pre = true;
    if (instance)
      job.id = instance.uid;
    scheduler = () => queueJob(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();
  }
  const unwatch = () => {
    effect.stop();
    if (instance && instance.scope) {
      remove(instance.scope.effects, effect);
    }
  };
  if (ssrCleanup)
    ssrCleanup.push(unwatch);
  return unwatch;
}
function instanceWatch(source, value, options) {
  const publicThis = this.proxy;
  const getter = isString$5(source) ? source.includes(".") ? createPathGetter(publicThis, source) : () => publicThis[source] : source.bind(publicThis, publicThis);
  let cb;
  if (isFunction$3(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, path2) {
  const segments = path2.split(".");
  return () => {
    let cur = ctx;
    for (let i = 0; i < segments.length && cur; i++) {
      cur = cur[segments[i]];
    }
    return cur;
  };
}
function traverse(value, seen2) {
  if (!isObject$5(value) || value["__v_skip"]) {
    return value;
  }
  seen2 = seen2 || /* @__PURE__ */ new Set();
  if (seen2.has(value)) {
    return value;
  }
  seen2.add(value);
  if (isRef(value)) {
    traverse(value.value, seen2);
  } else if (isArray$5(value)) {
    for (let i = 0; i < value.length; i++) {
      traverse(value[i], seen2);
    }
  } else if (isSet$1(value) || isMap$1(value)) {
    value.forEach((v) => {
      traverse(v, seen2);
    });
  } else if (isPlainObject$1(value)) {
    for (const key in value) {
      traverse(value[key], seen2);
    }
  }
  return value;
}
function withDirectives(vnode, directives) {
  const internalInstance = currentRenderingInstance;
  if (internalInstance === null) {
    return vnode;
  }
  const instance = getExposeProxy(internalInstance) || internalInstance.proxy;
  const bindings = vnode.dirs || (vnode.dirs = []);
  for (let i = 0; i < directives.length; i++) {
    let [dir, value, arg, modifiers = EMPTY_OBJ$1] = directives[i];
    if (dir) {
      if (isFunction$3(dir)) {
        dir = {
          mounted: dir,
          updated: dir
        };
      }
      if (dir.deep) {
        traverse(value);
      }
      bindings.push({
        dir,
        instance,
        value,
        oldValue: void 0,
        arg,
        modifiers
      });
    }
  }
  return vnode;
}
function invokeDirectiveHook(vnode, prevVNode, instance, name) {
  const bindings = vnode.dirs;
  const oldBindings = prevVNode && prevVNode.dirs;
  for (let i = 0; i < bindings.length; i++) {
    const binding2 = bindings[i];
    if (oldBindings) {
      binding2.oldValue = oldBindings[i].value;
    }
    let hook = binding2.dir[name];
    if (hook) {
      pauseTracking();
      callWithAsyncErrorHandling(hook, instance, 8, [
        vnode.el,
        binding2,
        vnode,
        prevVNode
      ]);
      resetTracking();
    }
  }
}
function defineComponent(options, extraOptions) {
  return isFunction$3(options) ? (
    // #8326: extend call and options.name access are considered side-effects
    // by Rollup, so we have to wrap it in a pure-annotated IIFE.
    /* @__PURE__ */ (() => extend$1({ name: options.name }, extraOptions, { setup: options }))()
  ) : 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
    /* prepend */
  );
  onUnmounted(() => {
    remove(keepAliveRoot[type], injected);
  }, target);
}
function injectHook(type, hook, target = currentInstance, prepend2 = 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 (prepend2) {
      hooks.unshift(wrappedHook);
    } else {
      hooks.push(wrappedHook);
    }
    return wrappedHook;
  }
}
const createHook = (lifecycle) => (hook, target = currentInstance) => (
  // post-create lifecycle registrations are noops during SSR (except for serverPrefetch)
  (!isInSSRComponentSetup || lifecycle === "sp") && injectHook(lifecycle, (...args) => hook(...args), 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);
}
const NULL_DYNAMIC_COMPONENT = Symbol.for("v-ndc");
function renderList(source, renderItem, cache2, index) {
  let ret;
  const cached = cache2 && cache2[index];
  if (isArray$5(source) || isString$5(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$5(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 (cache2) {
    cache2[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 = (
  // Move PURE marker to new line to workaround compiler discarding it
  // due to type annotation
  /* @__PURE__ */ extend$1(/* @__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$1.bind(i.proxy)),
    $watch: (i) => instanceWatch.bind(i)
  })
);
const hasSetupBinding = (state, key) => state !== EMPTY_OBJ$1 && !state.__isScriptSetup && hasOwn$1(state, key);
const PublicInstanceProxyHandlers = {
  get({ _: instance }, key) {
    const { ctx, setupState, data, props, accessCache, type, appContext } = instance;
    let normalizedProps;
    if (key[0] !== "$") {
      const n2 = accessCache[key];
      if (n2 !== void 0) {
        switch (n2) {
          case 1:
            return setupState[key];
          case 2:
            return data[key];
          case 4:
            return ctx[key];
          case 3:
            return props[key];
        }
      } else if (hasSetupBinding(setupState, key)) {
        accessCache[key] = 1;
        return setupState[key];
      } else if (data !== EMPTY_OBJ$1 && hasOwn$1(data, key)) {
        accessCache[key] = 2;
        return data[key];
      } else if (
        // only cache other properties when instance has declared (thus stable)
        // props
        (normalizedProps = instance.propsOptions[0]) && hasOwn$1(normalizedProps, key)
      ) {
        accessCache[key] = 3;
        return props[key];
      } else if (ctx !== EMPTY_OBJ$1 && hasOwn$1(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 (
      // css module (injected by vue-loader)
      (cssModule = type.__cssModules) && (cssModule = cssModule[key])
    ) {
      return cssModule;
    } else if (ctx !== EMPTY_OBJ$1 && hasOwn$1(ctx, key)) {
      accessCache[key] = 4;
      return ctx[key];
    } else if (
      // global properties
      globalProperties = appContext.config.globalProperties, hasOwn$1(globalProperties, key)
    ) {
      {
        return globalProperties[key];
      }
    } else
      ;
  },
  set({ _: instance }, key, value) {
    const { data, setupState, ctx } = instance;
    if (hasSetupBinding(setupState, key)) {
      setupState[key] = value;
      return true;
    } else if (data !== EMPTY_OBJ$1 && hasOwn$1(data, key)) {
      data[key] = value;
      return true;
    } else if (hasOwn$1(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$1 && hasOwn$1(data, key) || hasSetupBinding(setupState, key) || (normalizedProps = propsOptions[0]) && hasOwn$1(normalizedProps, key) || hasOwn$1(ctx, key) || hasOwn$1(publicPropertiesMap, key) || hasOwn$1(appContext.config.globalProperties, key);
  },
  defineProperty(target, key, descriptor) {
    if (descriptor.get != null) {
      target._.accessCache[key] = 0;
    } else if (hasOwn$1(descriptor, "value")) {
      this.set(target, key, descriptor.value, null);
    }
    return Reflect.defineProperty(target, key, descriptor);
  }
};
function normalizePropsOrEmits(props) {
  return isArray$5(props) ? props.reduce(
    (normalized, p2) => (normalized[p2] = null, normalized),
    {}
  ) : props;
}
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 {
    // state
    data: dataOptions,
    computed: computedOptions,
    methods,
    watch: watchOptions,
    provide: provideOptions,
    inject: injectOptions,
    // lifecycle
    created,
    beforeMount,
    mounted,
    beforeUpdate,
    updated,
    activated,
    deactivated,
    beforeDestroy,
    beforeUnmount,
    destroyed,
    unmounted,
    render,
    renderTracked,
    renderTriggered,
    errorCaptured,
    serverPrefetch,
    // public API
    expose,
    inheritAttrs,
    // assets
    components,
    directives,
    filters
  } = options;
  const checkDuplicateProperties = null;
  if (injectOptions) {
    resolveInjections(injectOptions, ctx, checkDuplicateProperties);
  }
  if (methods) {
    for (const key in methods) {
      const methodHandler = methods[key];
      if (isFunction$3(methodHandler)) {
        {
          ctx[key] = methodHandler.bind(publicThis);
        }
      }
    }
  }
  if (dataOptions) {
    const data = dataOptions.call(publicThis, publicThis);
    if (!isObject$5(data))
      ;
    else {
      instance.data = reactive(data);
    }
  }
  shouldCacheAccess = true;
  if (computedOptions) {
    for (const key in computedOptions) {
      const opt = computedOptions[key];
      const get2 = isFunction$3(opt) ? opt.bind(publicThis, publicThis) : isFunction$3(opt.get) ? opt.get.bind(publicThis, publicThis) : NOOP$1;
      const set2 = !isFunction$3(opt) && isFunction$3(opt.set) ? opt.set.bind(publicThis) : NOOP$1;
      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$3(provideOptions) ? provideOptions.call(publicThis) : provideOptions;
    Reflect.ownKeys(provides).forEach((key) => {
      provide(key, provides[key]);
    });
  }
  if (created) {
    callHook(created, instance, "c");
  }
  function registerLifecycleHook(register2, hook) {
    if (isArray$5(hook)) {
      hook.forEach((_hook) => register2(_hook.bind(publicThis)));
    } else if (hook) {
      register2(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$5(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$1) {
    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$1) {
  if (isArray$5(injectOptions)) {
    injectOptions = normalizeInject(injectOptions);
  }
  for (const key in injectOptions) {
    const opt = injectOptions[key];
    let injected;
    if (isObject$5(opt)) {
      if ("default" in opt) {
        injected = inject(
          opt.from || key,
          opt.default,
          true
          /* treat default function as factory */
        );
      } else {
        injected = inject(opt.from || key);
      }
    } else {
      injected = inject(opt);
    }
    if (isRef(injected)) {
      Object.defineProperty(ctx, key, {
        enumerable: true,
        configurable: true,
        get: () => injected.value,
        set: (v) => injected.value = v
      });
    } else {
      ctx[key] = injected;
    }
  }
}
function callHook(hook, instance, type) {
  callWithAsyncErrorHandling(
    isArray$5(hook) ? hook.map((h2) => h2.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$5(raw)) {
    const handler = ctx[raw];
    if (isFunction$3(handler)) {
      watch(getter, handler);
    }
  } else if (isFunction$3(raw)) {
    watch(getter, raw.bind(publicThis));
  } else if (isObject$5(raw)) {
    if (isArray$5(raw)) {
      raw.forEach((r) => createWatcher(r, ctx, publicThis, key));
    } else {
      const handler = isFunction$3(raw.handler) ? raw.handler.bind(publicThis) : ctx[raw.handler];
      if (isFunction$3(handler)) {
        watch(getter, handler, raw);
      }
    }
  } else
    ;
}
function resolveMergedOptions(instance) {
  const base2 = instance.type;
  const { mixins, extends: extendsOptions } = base2;
  const {
    mixins: globalMixins,
    optionsCache: cache2,
    config: { optionMergeStrategies }
  } = instance.appContext;
  const cached = cache2.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);
  }
  if (isObject$5(base2)) {
    cache2.set(base2, resolved);
  }
  return resolved;
}
function mergeOptions(to, from2, strats, asMixin = false) {
  const { mixins, extends: extendsOptions } = from2;
  if (extendsOptions) {
    mergeOptions(to, extendsOptions, strats, true);
  }
  if (mixins) {
    mixins.forEach(
      (m) => mergeOptions(to, m, strats, true)
    );
  }
  for (const key in from2) {
    if (asMixin && key === "expose")
      ;
    else {
      const strat = internalOptionMergeStrats[key] || strats && strats[key];
      to[key] = strat ? strat(to[key], from2[key]) : from2[key];
    }
  }
  return to;
}
const internalOptionMergeStrats = {
  data: mergeDataFn,
  props: mergeEmitsOrPropsOptions,
  emits: mergeEmitsOrPropsOptions,
  // objects
  methods: mergeObjectOptions,
  computed: mergeObjectOptions,
  // lifecycle
  beforeCreate: mergeAsArray$1,
  created: mergeAsArray$1,
  beforeMount: mergeAsArray$1,
  mounted: mergeAsArray$1,
  beforeUpdate: mergeAsArray$1,
  updated: mergeAsArray$1,
  beforeDestroy: mergeAsArray$1,
  beforeUnmount: mergeAsArray$1,
  destroyed: mergeAsArray$1,
  unmounted: mergeAsArray$1,
  activated: mergeAsArray$1,
  deactivated: mergeAsArray$1,
  errorCaptured: mergeAsArray$1,
  serverPrefetch: mergeAsArray$1,
  // assets
  components: mergeObjectOptions,
  directives: mergeObjectOptions,
  // watch
  watch: mergeWatchOptions,
  // provide / inject
  provide: mergeDataFn,
  inject: mergeInject
};
function mergeDataFn(to, from2) {
  if (!from2) {
    return to;
  }
  if (!to) {
    return from2;
  }
  return function mergedDataFn() {
    return extend$1(
      isFunction$3(to) ? to.call(this, this) : to,
      isFunction$3(from2) ? from2.call(this, this) : from2
    );
  };
}
function mergeInject(to, from2) {
  return mergeObjectOptions(normalizeInject(to), normalizeInject(from2));
}
function normalizeInject(raw) {
  if (isArray$5(raw)) {
    const res = {};
    for (let i = 0; i < raw.length; i++) {
      res[raw[i]] = raw[i];
    }
    return res;
  }
  return raw;
}
function mergeAsArray$1(to, from2) {
  return to ? [...new Set([].concat(to, from2))] : from2;
}
function mergeObjectOptions(to, from2) {
  return to ? extend$1(/* @__PURE__ */ Object.create(null), to, from2) : from2;
}
function mergeEmitsOrPropsOptions(to, from2) {
  if (to) {
    if (isArray$5(to) && isArray$5(from2)) {
      return [.../* @__PURE__ */ new Set([...to, ...from2])];
    }
    return extend$1(
      /* @__PURE__ */ Object.create(null),
      normalizePropsOrEmits(to),
      normalizePropsOrEmits(from2 != null ? from2 : {})
    );
  } else {
    return from2;
  }
}
function mergeWatchOptions(to, from2) {
  if (!to)
    return from2;
  if (!from2)
    return to;
  const merged = extend$1(/* @__PURE__ */ Object.create(null), to);
  for (const key in from2) {
    merged[key] = mergeAsArray$1(to[key], from2[key]);
  }
  return merged;
}
function createAppContext() {
  return {
    app: null,
    config: {
      isNativeTag: NO$1,
      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$1 = 0;
function createAppAPI(render, hydrate) {
  return function createApp2(rootComponent, rootProps = null) {
    if (!isFunction$3(rootComponent)) {
      rootComponent = extend$1({}, rootComponent);
    }
    if (rootProps != null && !isObject$5(rootProps)) {
      rootProps = null;
    }
    const context = createAppContext();
    const installedPlugins = /* @__PURE__ */ new Set();
    let isMounted = false;
    const app2 = context.app = {
      _uid: uid$1++,
      _component: rootComponent,
      _props: rootProps,
      _container: null,
      _context: context,
      _instance: null,
      version,
      get config() {
        return context.config;
      },
      set config(v) {
      },
      use(plugin2, ...options) {
        if (installedPlugins.has(plugin2))
          ;
        else if (plugin2 && isFunction$3(plugin2.install)) {
          installedPlugins.add(plugin2);
          plugin2.install(app2, ...options);
        } else if (isFunction$3(plugin2)) {
          installedPlugins.add(plugin2);
          plugin2(app2, ...options);
        } else
          ;
        return app2;
      },
      mixin(mixin2) {
        {
          if (!context.mixins.includes(mixin2)) {
            context.mixins.push(mixin2);
          }
        }
        return app2;
      },
      component(name, component) {
        if (!component) {
          return context.components[name];
        }
        context.components[name] = component;
        return app2;
      },
      directive(name, directive) {
        if (!directive) {
          return context.directives[name];
        }
        context.directives[name] = directive;
        return app2;
      },
      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;
          app2._container = rootContainer;
          rootContainer.__vue_app__ = app2;
          return getExposeProxy(vnode.component) || vnode.component.proxy;
        }
      },
      unmount() {
        if (isMounted) {
          render(null, app2._container);
          delete app2._container.__vue_app__;
        }
      },
      provide(key, value) {
        context.provides[key] = value;
        return app2;
      },
      runWithContext(fn) {
        currentApp = app2;
        try {
          return fn();
        } finally {
          currentApp = null;
        }
      }
    };
    return app2;
  };
}
let currentApp = null;
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 || currentApp) {
    const provides = instance ? instance.parent == null ? instance.vnode.appContext && instance.vnode.appContext.provides : instance.parent.provides : currentApp._context.provides;
    if (provides && key in provides) {
      return provides[key];
    } else if (arguments.length > 1) {
      return treatDefaultAsFactory && isFunction$3(defaultValue) ? defaultValue.call(instance && instance.proxy) : defaultValue;
    } else
      ;
  }
}
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 (
    // always force full diff in dev
    // - #1942 if hmr is enabled with sfc component
    // - vite#872 non-sfc component used by sfc component
    (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$1(attrs, key)) {
            if (value !== attrs[key]) {
              attrs[key] = value;
              hasAttrsChanged = true;
            }
          } else {
            const camelizedKey = camelize$1(key);
            props[camelizedKey] = resolvePropValue(
              options,
              rawCurrentProps,
              camelizedKey,
              value,
              instance,
              false
              /* isAbsent */
            );
          }
        } 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 || // for camelCase
      !hasOwn$1(rawProps, key) && // it's possible the original props was passed in as kebab-case
      // and converted to camelCase (#955)
      ((kebabKey = hyphenate$1(key)) === key || !hasOwn$1(rawProps, kebabKey))) {
        if (options) {
          if (rawPrevProps && // for camelCase
          (rawPrevProps[key] !== void 0 || // for kebab-case
          rawPrevProps[kebabKey] !== void 0)) {
            props[key] = resolvePropValue(
              options,
              rawCurrentProps,
              key,
              void 0,
              instance,
              true
              /* isAbsent */
            );
          }
        } else {
          delete props[key];
        }
      }
    }
    if (attrs !== rawCurrentProps) {
      for (const key in attrs) {
        if (!rawProps || !hasOwn$1(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$1(key)) {
        continue;
      }
      const value = rawProps[key];
      let camelKey;
      if (options && hasOwn$1(options, camelKey = camelize$1(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$1;
    for (let i = 0; i < needCastKeys.length; i++) {
      const key = needCastKeys[i];
      props[key] = resolvePropValue(
        options,
        rawCurrentProps,
        key,
        castValues[key],
        instance,
        !hasOwn$1(castValues, key)
      );
    }
  }
  return hasAttrsChanged;
}
function resolvePropValue(options, props, key, value, instance, isAbsent) {
  const opt = options[key];
  if (opt != null) {
    const hasDefault = hasOwn$1(opt, "default");
    if (hasDefault && value === void 0) {
      const defaultValue = opt.default;
      if (opt.type !== Function && !opt.skipFactory && isFunction$3(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
      /* shouldCast */
    ]) {
      if (isAbsent && !hasDefault) {
        value = false;
      } else if (opt[
        1
        /* shouldCastTrue */
      ] && (value === "" || value === hyphenate$1(key))) {
        value = true;
      }
    }
  }
  return value;
}
function normalizePropsOptions(comp, appContext, asMixin = false) {
  const cache2 = appContext.propsCache;
  const cached = cache2.get(comp);
  if (cached) {
    return cached;
  }
  const raw = comp.props;
  const normalized = {};
  const needCastKeys = [];
  let hasExtends = false;
  if (!isFunction$3(comp)) {
    const extendProps = (raw2) => {
      hasExtends = true;
      const [props, keys] = normalizePropsOptions(raw2, appContext, true);
      extend$1(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) {
    if (isObject$5(comp)) {
      cache2.set(comp, EMPTY_ARR);
    }
    return EMPTY_ARR;
  }
  if (isArray$5(raw)) {
    for (let i = 0; i < raw.length; i++) {
      const normalizedKey = camelize$1(raw[i]);
      if (validatePropName(normalizedKey)) {
        normalized[normalizedKey] = EMPTY_OBJ$1;
      }
    }
  } else if (raw) {
    for (const key in raw) {
      const normalizedKey = camelize$1(key);
      if (validatePropName(normalizedKey)) {
        const opt = raw[key];
        const prop = normalized[normalizedKey] = isArray$5(opt) || isFunction$3(opt) ? { type: opt } : extend$1({}, opt);
        if (prop) {
          const booleanIndex = getTypeIndex(Boolean, prop.type);
          const stringIndex = getTypeIndex(String, prop.type);
          prop[
            0
            /* shouldCast */
          ] = booleanIndex > -1;
          prop[
            1
            /* shouldCastTrue */
          ] = stringIndex < 0 || booleanIndex < stringIndex;
          if (booleanIndex > -1 || hasOwn$1(prop, "default")) {
            needCastKeys.push(normalizedKey);
          }
        }
      }
    }
  }
  const res = [normalized, needCastKeys];
  if (isObject$5(comp)) {
    cache2.set(comp, res);
  }
  return res;
}
function validatePropName(key) {
  if (key[0] !== "$") {
    return true;
  }
  return false;
}
function getType(ctor) {
  const match2 = ctor && ctor.toString().match(/^\s*(function|class) (\w+)/);
  return match2 ? match2[2] : ctor === null ? "null" : "";
}
function isSameType(a, b) {
  return getType(a) === getType(b);
}
function getTypeIndex(type, expectedTypes) {
  if (isArray$5(expectedTypes)) {
    return expectedTypes.findIndex((t) => isSameType(t, type));
  } else if (isFunction$3(expectedTypes)) {
    return isSameType(expectedTypes, type) ? 0 : -1;
  }
  return -1;
}
const isInternalKey = (key) => key[0] === "_" || key === "$stable";
const normalizeSlotValue = (value) => isArray$5(value) ? value.map(normalizeVNode) : [normalizeVNode(value)];
const normalizeSlot = (key, rawSlot, ctx) => {
  if (rawSlot._n) {
    return rawSlot;
  }
  const normalized = withCtx((...args) => {
    if (false)
      ;
    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$3(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$1;
  if (vnode.shapeFlag & 32) {
    const type = children._;
    if (type) {
      if (optimized && type === 1) {
        needDeletionCheck = false;
      } else {
        extend$1(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 setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) {
  if (isArray$5(rawRef)) {
    rawRef.forEach(
      (r, i) => setRef(
        r,
        oldRawRef && (isArray$5(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$1 ? owner.refs = {} : owner.refs;
  const setupState = owner.setupState;
  if (oldRef != null && oldRef !== ref2) {
    if (isString$5(oldRef)) {
      refs[oldRef] = null;
      if (hasOwn$1(setupState, oldRef)) {
        setupState[oldRef] = null;
      }
    } else if (isRef(oldRef)) {
      oldRef.value = null;
    }
  }
  if (isFunction$3(ref2)) {
    callWithErrorHandling(ref2, owner, 12, [value, refs]);
  } else {
    const _isString = isString$5(ref2);
    const _isRef = isRef(ref2);
    if (_isString || _isRef) {
      const doSet = () => {
        if (rawRef.f) {
          const existing = _isString ? hasOwn$1(setupState, ref2) ? setupState[ref2] : refs[ref2] : ref2.value;
          if (isUnmount) {
            isArray$5(existing) && remove(existing, refValue);
          } else {
            if (!isArray$5(existing)) {
              if (_isString) {
                refs[ref2] = [refValue];
                if (hasOwn$1(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$1(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$1,
    insertStaticContent: hostInsertStaticContent
  } = options;
  const patch = (n1, n2, container2, 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, container2, anchor);
        break;
      case Comment$5:
        processCommentNode(n1, n2, container2, anchor);
        break;
      case Static:
        if (n1 == null) {
          mountStaticNode(n2, container2, anchor, isSVG);
        }
        break;
      case Fragment:
        processFragment(
          n1,
          n2,
          container2,
          anchor,
          parentComponent,
          parentSuspense,
          isSVG,
          slotScopeIds,
          optimized
        );
        break;
      default:
        if (shapeFlag & 1) {
          processElement(
            n1,
            n2,
            container2,
            anchor,
            parentComponent,
            parentSuspense,
            isSVG,
            slotScopeIds,
            optimized
          );
        } else if (shapeFlag & 6) {
          processComponent(
            n1,
            n2,
            container2,
            anchor,
            parentComponent,
            parentSuspense,
            isSVG,
            slotScopeIds,
            optimized
          );
        } else if (shapeFlag & 64) {
          type.process(
            n1,
            n2,
            container2,
            anchor,
            parentComponent,
            parentSuspense,
            isSVG,
            slotScopeIds,
            optimized,
            internals
          );
        } else if (shapeFlag & 128) {
          type.process(
            n1,
            n2,
            container2,
            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, container2, anchor) => {
    if (n1 == null) {
      hostInsert(
        n2.el = hostCreateText(n2.children),
        container2,
        anchor
      );
    } else {
      const el = n2.el = n1.el;
      if (n2.children !== n1.children) {
        hostSetText(el, n2.children);
      }
    }
  };
  const processCommentNode = (n1, n2, container2, anchor) => {
    if (n1 == null) {
      hostInsert(
        n2.el = hostCreateComment(n2.children || ""),
        container2,
        anchor
      );
    } else {
      n2.el = n1.el;
    }
  };
  const mountStaticNode = (n2, container2, anchor, isSVG) => {
    [n2.el, n2.anchor] = hostInsertStaticContent(
      n2.children,
      container2,
      anchor,
      isSVG,
      n2.el,
      n2.anchor
    );
  };
  const moveStaticNode = ({ el, anchor }, container2, nextSibling) => {
    let next;
    while (el && el !== anchor) {
      next = hostNextSibling(el);
      hostInsert(el, container2, nextSibling);
      el = next;
    }
    hostInsert(anchor, container2, nextSibling);
  };
  const removeStaticNode = ({ el, anchor }) => {
    let next;
    while (el && el !== anchor) {
      next = hostNextSibling(el);
      hostRemove(el);
      el = next;
    }
    hostRemove(anchor);
  };
  const processElement = (n1, n2, container2, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
    isSVG = isSVG || n2.type === "svg";
    if (n1 == null) {
      mountElement(
        n2,
        container2,
        anchor,
        parentComponent,
        parentSuspense,
        isSVG,
        slotScopeIds,
        optimized
      );
    } else {
      patchElement(
        n1,
        n2,
        parentComponent,
        parentSuspense,
        isSVG,
        slotScopeIds,
        optimized
      );
    }
  };
  const mountElement = (vnode, container2, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
    let el;
    let vnodeHook;
    const { type, props, shapeFlag, transition, dirs } = vnode;
    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");
    }
    setScopeId(el, vnode, vnode.scopeId, slotScopeIds, parentComponent);
    if (props) {
      for (const key in props) {
        if (key !== "value" && !isReservedProp$1(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);
      }
    }
    if (dirs) {
      invokeDirectiveHook(vnode, null, parentComponent, "beforeMount");
    }
    const needCallTransitionHooks = (!parentSuspense || parentSuspense && !parentSuspense.pendingBranch) && transition && !transition.persisted;
    if (needCallTransitionHooks) {
      transition.beforeEnter(el);
    }
    hostInsert(el, container2, 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, container2, 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,
        container2,
        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$1;
    const newProps = n2.props || EMPTY_OBJ$1;
    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 container2 = (
        // oldVNode may be an errored async setup() component inside Suspense
        // which will not have a mounted element
        oldVNode.el && // - In the case of a Fragment, we need to provide the actual parent
        // of the Fragment itself so it can move its children.
        (oldVNode.type === Fragment || // - In the case of different nodes, there is going to be a replacement
        // which also requires the correct parent container
        !isSameVNodeType(oldVNode, newVNode) || // - In the case of a component, it could contain anything.
        oldVNode.shapeFlag & (6 | 64)) ? hostParentNode(oldVNode.el) : (
          // In other cases, the parent container is not actually used so we
          // just pass the block element here to avoid a DOM parentNode call.
          fallbackContainer
        )
      );
      patch(
        oldVNode,
        newVNode,
        container2,
        null,
        parentComponent,
        parentSuspense,
        isSVG,
        slotScopeIds,
        true
      );
    }
  };
  const patchProps = (el, vnode, oldProps, newProps, parentComponent, parentSuspense, isSVG) => {
    if (oldProps !== newProps) {
      if (oldProps !== EMPTY_OBJ$1) {
        for (const key in oldProps) {
          if (!isReservedProp$1(key) && !(key in newProps)) {
            hostPatchProp(
              el,
              key,
              oldProps[key],
              null,
              isSVG,
              vnode.children,
              parentComponent,
              parentSuspense,
              unmountChildren
            );
          }
        }
      }
      for (const key in newProps) {
        if (isReservedProp$1(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 ("value" in newProps) {
        hostPatchProp(el, "value", oldProps.value, newProps.value);
      }
    }
  };
  const processFragment = (n1, n2, container2, 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, container2, anchor);
      hostInsert(fragmentEndAnchor, container2, anchor);
      mountChildren(
        n2.children,
        container2,
        fragmentEndAnchor,
        parentComponent,
        parentSuspense,
        isSVG,
        slotScopeIds,
        optimized
      );
    } else {
      if (patchFlag > 0 && patchFlag & 64 && dynamicChildren && // #2715 the previous fragment could've been a BAILed one as a result
      // of renderSlot() with no valid children
      n1.dynamicChildren) {
        patchBlockChildren(
          n1.dynamicChildren,
          dynamicChildren,
          container2,
          parentComponent,
          parentSuspense,
          isSVG,
          slotScopeIds
        );
        if (
          // #2080 if the stable fragment has a key, it's a <template v-for> that may
          //  get moved around. Make sure all root level vnodes inherit el.
          // #2134 or if it's a component root, it may also get moved around
          // as the component is being moved.
          n2.key != null || parentComponent && n2 === parentComponent.subTree
        ) {
          traverseStaticChildren(
            n1,
            n2,
            true
            /* shallow */
          );
        }
      } else {
        patchChildren(
          n1,
          n2,
          container2,
          fragmentEndAnchor,
          parentComponent,
          parentSuspense,
          isSVG,
          slotScopeIds,
          optimized
        );
      }
    }
  };
  const processComponent = (n1, n2, container2, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
    n2.slotScopeIds = slotScopeIds;
    if (n1 == null) {
      if (n2.shapeFlag & 512) {
        parentComponent.ctx.activate(
          n2,
          container2,
          anchor,
          isSVG,
          optimized
        );
      } else {
        mountComponent(
          n2,
          container2,
          anchor,
          parentComponent,
          parentSuspense,
          isSVG,
          optimized
        );
      }
    } else {
      updateComponent(n1, n2, optimized);
    }
  };
  const mountComponent = (initialVNode, container2, 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$5);
        processCommentNode(null, placeholder, container2, anchor);
      }
      return;
    }
    setupRenderEffect(
      instance,
      initialVNode,
      container2,
      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, container2, 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(
              // note: we are moving the render call into an async callback,
              // which means it won't track dependencies - but it's ok because
              // a server-rendered async wrapper is already in resolved state
              // and it will never need to change.
              () => !instance.isUnmounted && hydrateSubTree()
            );
          } else {
            hydrateSubTree();
          }
        } else {
          const subTree = instance.subTree = renderComponentRoot(instance);
          patch(
            null,
            subTree,
            container2,
            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 = container2 = 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,
          // parent may have changed if it's in a teleport
          hostParentNode(prevTree.el),
          // anchor may have changed if it's in a fragment
          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
      // track it in component's effect 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();
    resetTracking();
  };
  const patchChildren = (n1, n2, container2, 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,
          container2,
          anchor,
          parentComponent,
          parentSuspense,
          isSVG,
          slotScopeIds,
          optimized
        );
        return;
      } else if (patchFlag & 256) {
        patchUnkeyedChildren(
          c1,
          c2,
          container2,
          anchor,
          parentComponent,
          parentSuspense,
          isSVG,
          slotScopeIds,
          optimized
        );
        return;
      }
    }
    if (shapeFlag & 8) {
      if (prevShapeFlag & 16) {
        unmountChildren(c1, parentComponent, parentSuspense);
      }
      if (c2 !== c1) {
        hostSetElementText(container2, c2);
      }
    } else {
      if (prevShapeFlag & 16) {
        if (shapeFlag & 16) {
          patchKeyedChildren(
            c1,
            c2,
            container2,
            anchor,
            parentComponent,
            parentSuspense,
            isSVG,
            slotScopeIds,
            optimized
          );
        } else {
          unmountChildren(c1, parentComponent, parentSuspense, true);
        }
      } else {
        if (prevShapeFlag & 8) {
          hostSetElementText(container2, "");
        }
        if (shapeFlag & 16) {
          mountChildren(
            c2,
            container2,
            anchor,
            parentComponent,
            parentSuspense,
            isSVG,
            slotScopeIds,
            optimized
          );
        }
      }
    }
  };
  const patchUnkeyedChildren = (c1, c2, container2, 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,
        container2,
        null,
        parentComponent,
        parentSuspense,
        isSVG,
        slotScopeIds,
        optimized
      );
    }
    if (oldLength > newLength) {
      unmountChildren(
        c1,
        parentComponent,
        parentSuspense,
        true,
        false,
        commonLength
      );
    } else {
      mountChildren(
        c2,
        container2,
        anchor,
        parentComponent,
        parentSuspense,
        isSVG,
        slotScopeIds,
        optimized,
        commonLength
      );
    }
  };
  const patchKeyedChildren = (c1, c2, container2, 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,
          container2,
          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,
          container2,
          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]),
            container2,
            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],
            container2,
            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,
            container2,
            anchor,
            parentComponent,
            parentSuspense,
            isSVG,
            slotScopeIds,
            optimized
          );
        } else if (moved) {
          if (j < 0 || i !== increasingNewIndexSequence[j]) {
            move(nextChild, container2, anchor, 2);
          } else {
            j--;
          }
        }
      }
    }
  };
  const move = (vnode, container2, anchor, moveType, parentSuspense = null) => {
    const { el, type, transition, children, shapeFlag } = vnode;
    if (shapeFlag & 6) {
      move(vnode.component.subTree, container2, anchor, moveType);
      return;
    }
    if (shapeFlag & 128) {
      vnode.suspense.move(container2, anchor, moveType);
      return;
    }
    if (shapeFlag & 64) {
      type.move(vnode, container2, anchor, internals);
      return;
    }
    if (type === Fragment) {
      hostInsert(el, container2, anchor);
      for (let i = 0; i < children.length; i++) {
        move(children[i], container2, anchor, moveType);
      }
      hostInsert(vnode.anchor, container2, anchor);
      return;
    }
    if (type === Static) {
      moveStaticNode(vnode, container2, anchor);
      return;
    }
    const needTransition = moveType !== 2 && shapeFlag & 1 && transition;
    if (needTransition) {
      if (moveType === 0) {
        transition.beforeEnter(el);
        hostInsert(el, container2, anchor);
        queuePostRenderEffect(() => transition.enter(el), parentSuspense);
      } else {
        const { leave, delayLeave, afterLeave } = transition;
        const remove22 = () => hostInsert(el, container2, anchor);
        const performLeave = () => {
          leave(el, () => {
            remove22();
            afterLeave && afterLeave();
          });
        };
        if (delayLeave) {
          delayLeave(el, remove22, performLeave);
        } else {
          performLeave();
        }
      }
    } else {
      hostInsert(el, container2, 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 && // #1153: fast path should not be taken for non-stable (v-for) fragments
      (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, container2, isSVG) => {
    if (vnode == null) {
      if (container2._vnode) {
        unmount(container2._vnode, null, null, true);
      }
    } else {
      patch(container2._vnode || null, vnode, container2, null, null, null, isSVG);
    }
    flushPreFlushCbs();
    flushPostFlushCbs();
    container2._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$5(ch1) && isArray$5(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);
      }
      if (c2.type === Text$1) {
        c2.el = c1.el;
      }
    }
  }
}
function getSequence(arr) {
  const p2 = arr.slice();
  const result2 = [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 = result2[result2.length - 1];
      if (arr[j] < arrI) {
        p2[i] = j;
        result2.push(i);
        continue;
      }
      u = 0;
      v = result2.length - 1;
      while (u < v) {
        c = u + v >> 1;
        if (arr[result2[c]] < arrI) {
          u = c + 1;
        } else {
          v = c;
        }
      }
      if (arrI < arr[result2[u]]) {
        if (u > 0) {
          p2[i] = result2[u - 1];
        }
        result2[u] = i;
      }
    }
  }
  u = result2.length;
  v = result2[u - 1];
  while (u-- > 0) {
    result2[u] = v;
    v = p2[v];
  }
  return result2;
}
const isTeleport = (type) => type.__isTeleport;
const Fragment = Symbol.for("v-fgt");
const Text$1 = Symbol.for("v-txt");
const Comment$5 = Symbol.for("v-cmt");
const Static = Symbol.for("v-stc");
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
      /* isBlock */
    )
  );
}
function createBlock$1(type, props, children, patchFlag, dynamicProps) {
  return setupBlock(
    createVNode(
      type,
      props,
      children,
      patchFlag,
      dynamicProps,
      true
      /* isBlock: prevent a block from tracking itself */
    )
  );
}
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
}) => {
  if (typeof ref2 === "number") {
    ref2 = "" + ref2;
  }
  return ref2 != null ? isString$5(ref2) || isRef(ref2) || isFunction$3(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,
    ctx: currentRenderingInstance
  };
  if (needFullChildrenNormalization) {
    normalizeChildren(vnode, children);
    if (shapeFlag & 128) {
      type.normalize(vnode);
    }
  } else if (children) {
    vnode.shapeFlag |= isString$5(children) ? 8 : 16;
  }
  if (isBlockTreeEnabled > 0 && // avoid a block node from tracking itself
  !isBlockNode && // has current parent block
  currentBlock && // presence of a patch flag indicates this node needs patching on updates.
  // component nodes also should always be patched, because even if the
  // component doesn't need to update, it needs to persist the instance on to
  // the next vnode so that it can be properly unmounted later.
  (vnode.patchFlag > 0 || shapeFlag & 6) && // the EVENTS flag is only for hydration and if it is the only flag, the
  // vnode should not be considered dynamic due to handler caching.
  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$5;
  }
  if (isVNode(type)) {
    const cloned = cloneVNode(
      type,
      props,
      true
      /* mergeRef: 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: style2 } = props;
    if (klass && !isString$5(klass)) {
      props.class = normalizeClass$1(klass);
    }
    if (isObject$5(style2)) {
      if (isProxy(style2) && !isArray$5(style2)) {
        style2 = extend$1({}, style2);
      }
      props.style = normalizeStyle$1(style2);
    }
  }
  const shapeFlag = isString$5(type) ? 1 : isSuspense(type) ? 128 : isTeleport(type) ? 64 : isObject$5(type) ? 4 : isFunction$3(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$1({}, 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 ? (
      // #2078 in the case of <component :is="vnode" ref="extra"/>
      // if the vnode itself already has a ref, cloneVNode will need to merge
      // the refs so the single vnode can be set on multiple refs
      mergeRef && ref2 ? isArray$5(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,
    // if the vnode is cloned with extra props, we can no longer assume its
    // existing patch flag to be reliable and need to add the FULL_PROPS flag.
    // note: preserve flag for fragments since they use the flag for children
    // fast paths only.
    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,
    // These should technically only be non-null on mounted VNodes. However,
    // they *should* be copied for kept-alive vnodes. So we just always copy
    // them since them being non-null during a mount doesn't affect the logic as
    // they will simply be overwritten.
    component: vnode.component,
    suspense: vnode.suspense,
    ssContent: vnode.ssContent && cloneVNode(vnode.ssContent),
    ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback),
    el: vnode.el,
    anchor: vnode.anchor,
    ctx: vnode.ctx,
    ce: vnode.ce
  };
  return cloned;
}
function createTextVNode(text2 = " ", flag = 0) {
  return createVNode(Text$1, null, text2, flag);
}
function normalizeVNode(child) {
  if (child == null || typeof child === "boolean") {
    return createVNode(Comment$5);
  } else if (isArray$5(child)) {
    return createVNode(
      Fragment,
      null,
      // #3666, avoid reference pollution when reusing vnode
      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.patchFlag !== -1 || child.memo ? child : cloneVNode(child);
}
function normalizeChildren(vnode, children) {
  let type = 0;
  const { shapeFlag } = vnode;
  if (children == null) {
    children = null;
  } else if (isArray$5(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$3(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$1([ret.class, toMerge.class]);
        }
      } else if (key === "style") {
        ret.style = normalizeStyle$1([ret.style, toMerge.style]);
      } else if (isOn$1(key)) {
        const existing = ret[key];
        const incoming = toMerge[key];
        if (incoming && existing !== incoming && !(isArray$5(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 = 0;
function createComponentInstance(vnode, parent, suspense) {
  const type = vnode.type;
  const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext;
  const instance = {
    uid: uid++,
    vnode,
    type,
    parent,
    appContext,
    root: null,
    // to be immediately set
    next: null,
    subTree: null,
    // will be set synchronously right after creation
    effect: null,
    update: null,
    // will be set synchronously right after creation
    scope: new EffectScope(
      true
      /* detached */
    ),
    render: null,
    proxy: null,
    exposed: null,
    exposeProxy: null,
    withProxy: null,
    provides: parent ? parent.provides : Object.create(appContext.provides),
    accessCache: null,
    renderCache: [],
    // local resolved assets
    components: null,
    directives: null,
    // resolved props and emits options
    propsOptions: normalizePropsOptions(type, appContext),
    emitsOptions: normalizeEmitsOptions(type, appContext),
    // emit
    emit: null,
    // to be set immediately
    emitted: null,
    // props default value
    propsDefaults: EMPTY_OBJ$1,
    // inheritAttrs
    inheritAttrs: type.inheritAttrs,
    // state
    ctx: EMPTY_OBJ$1,
    data: EMPTY_OBJ$1,
    props: EMPTY_OBJ$1,
    attrs: EMPTY_OBJ$1,
    slots: EMPTY_OBJ$1,
    refs: EMPTY_OBJ$1,
    setupState: EMPTY_OBJ$1,
    setupContext: null,
    attrsProxy: null,
    slotsProxy: null,
    // suspense related
    suspense,
    suspenseId: suspense ? suspense.pendingId : 0,
    asyncDep: null,
    asyncResolved: false,
    // lifecycle hooks
    // not using enums here because it results in computed properties
    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;
let internalSetCurrentInstance;
let globalCurrentInstanceSetters;
let settersKey = "__VUE_INSTANCE_SETTERS__";
{
  if (!(globalCurrentInstanceSetters = getGlobalThis()[settersKey])) {
    globalCurrentInstanceSetters = getGlobalThis()[settersKey] = [];
  }
  globalCurrentInstanceSetters.push((i) => currentInstance = i);
  internalSetCurrentInstance = (instance) => {
    if (globalCurrentInstanceSetters.length > 1) {
      globalCurrentInstanceSetters.forEach((s) => s(instance));
    } else {
      globalCurrentInstanceSetters[0](instance);
    }
  };
}
const setCurrentInstance = (instance) => {
  internalSetCurrentInstance(instance);
  instance.scope.on();
};
const unsetCurrentInstance = () => {
  currentInstance && currentInstance.scope.off();
  internalSetCurrentInstance(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$1(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$3(setupResult)) {
    if (instance.type.__ssrInlineRender) {
      instance.ssrRender = setupResult;
    } else {
      instance.render = setupResult;
    }
  } else if (isObject$5(setupResult)) {
    instance.setupState = proxyRefs(setupResult);
  } else
    ;
  finishComponentSetup(instance, isSSR);
}
let compile$2;
function finishComponentSetup(instance, isSSR, skipOptions) {
  const Component = instance.type;
  if (!instance.render) {
    if (!isSSR && compile$2 && !Component.render) {
      const template = Component.template || resolveMergedOptions(instance).template;
      if (template) {
        const { isCustomElement, compilerOptions } = instance.appContext.config;
        const { delimiters, compilerOptions: componentCompilerOptions } = Component;
        const finalCompilerOptions = extend$1(
          extend$1(
            {
              isCustomElement,
              delimiters
            },
            compilerOptions
          ),
          componentCompilerOptions
        );
        Component.render = compile$2(template, finalCompilerOptions);
      }
    }
    instance.render = Component.render || NOOP$1;
  }
  {
    setCurrentInstance(instance);
    pauseTracking();
    applyOptions(instance);
    resetTracking();
    unsetCurrentInstance();
  }
}
function getAttrsProxy(instance) {
  return instance.attrsProxy || (instance.attrsProxy = new Proxy(
    instance.attrs,
    {
      get(target, key) {
        track(instance, "get", "$attrs");
        return target[key];
      }
    }
  ));
}
function createSetupContext(instance) {
  const expose = (exposed) => {
    instance.exposed = exposed || {};
  };
  {
    return {
      get attrs() {
        return getAttrsProxy(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);
        }
      },
      has(target, key) {
        return key in target || key in publicPropertiesMap;
      }
    }));
  }
}
function isClassComponent(value) {
  return isFunction$3(value) && "__vccOpts" in value;
}
const computed = (getterOrOptions, debugOptions) => {
  return computed$1(getterOrOptions, debugOptions, isInSSRComponentSetup);
};
const ssrContextKey = Symbol.for("v-scx");
const useSSRContext = () => {
  {
    const ctx = inject(ssrContextKey);
    return ctx;
  }
};
const version = "3.3.4";
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: (tag3, isSVG, is, props) => {
    const el = isSVG ? doc.createElementNS(svgNS, tag3) : doc.createElement(tag3, is ? { is } : void 0);
    if (tag3 === "select" && props && props.multiple != null) {
      el.setAttribute("multiple", props.multiple);
    }
    return el;
  },
  createText: (text2) => doc.createTextNode(text2),
  createComment: (text2) => doc.createComment(text2),
  setText: (node2, text2) => {
    node2.nodeValue = text2;
  },
  setElementText: (el, text2) => {
    el.textContent = text2;
  },
  parentNode: (node2) => node2.parentNode,
  nextSibling: (node2) => node2.nextSibling,
  querySelector: (selector3) => doc.querySelector(selector3),
  setScopeId(el, id3) {
    el.setAttribute(id3, "");
  },
  // __UNSAFE__
  // Reason: innerHTML.
  // Static content here can only come from compiled templates.
  // As long as the user only uses trusted templates, this is safe.
  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 [
      // first
      before ? before.nextSibling : parent.firstChild,
      // last
      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 style2 = el.style;
  const isCssString = isString$5(next);
  if (next && !isCssString) {
    if (prev && !isString$5(prev)) {
      for (const key in prev) {
        if (next[key] == null) {
          setStyle(style2, key, "");
        }
      }
    }
    for (const key in next) {
      setStyle(style2, key, next[key]);
    }
  } else {
    const currentDisplay = style2.display;
    if (isCssString) {
      if (prev !== next) {
        style2.cssText = next;
      }
    } else if (prev) {
      el.removeAttribute("style");
    }
    if ("_vod" in el) {
      style2.display = currentDisplay;
    }
  }
}
const importantRE = /\s*!important$/;
function setStyle(style2, name, val) {
  if (isArray$5(val)) {
    val.forEach((v) => setStyle(style2, name, v));
  } else {
    if (val == null)
      val = "";
    if (name.startsWith("--")) {
      style2.setProperty(name, val);
    } else {
      const prefixed = autoPrefix(style2, name);
      if (importantRE.test(val)) {
        style2.setProperty(
          hyphenate$1(prefixed),
          val.replace(importantRE, ""),
          "important"
        );
      } else {
        style2[prefixed] = val;
      }
    }
  }
}
const prefixes = ["Webkit", "Moz", "ms"];
const prefixCache = {};
function autoPrefix(style2, rawName) {
  const cached = prefixCache[rawName];
  if (cached) {
    return cached;
  }
  let name = camelize$1(rawName);
  if (name !== "filter" && name in style2) {
    return prefixCache[rawName] = name;
  }
  name = capitalize$2(name);
  for (let i = 0; i < prefixes.length; i++) {
    const prefixed = prefixes[i] + name;
    if (prefixed in style2) {
      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 isBoolean2 = isSpecialBooleanAttr(key);
    if (value == null || isBoolean2 && !includeBooleanAttr(value)) {
      el.removeAttribute(key);
    } else {
      el.setAttribute(key, isBoolean2 ? "" : 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;
  }
  const tag3 = el.tagName;
  if (key === "value" && tag3 !== "PROGRESS" && // custom elements may use _value internally
  !tag3.includes("-")) {
    el._value = value;
    const oldValue = tag3 === "OPTION" ? el.getAttribute("value") : el.value;
    const newValue = value == null ? "" : value;
    if (oldValue !== newValue) {
      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);
}
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;
    }
  }
  const event = name[2] === ":" ? name.slice(3) : hyphenate$1(name.slice(2));
  return [event, options];
}
let cachedNow = 0;
const p = /* @__PURE__ */ Promise.resolve();
const getNow = () => cachedNow || (p.then(() => cachedNow = 0), cachedNow = Date.now());
function createInvoker(initialValue, instance) {
  const invoker = (e) => {
    if (!e._vts) {
      e._vts = Date.now();
    } else if (e._vts <= invoker.attached) {
      return;
    }
    callWithAsyncErrorHandling(
      patchStopImmediatePropagation(e, invoker.value),
      instance,
      5,
      [e]
    );
  };
  invoker.value = initialValue;
  invoker.attached = getNow();
  return invoker;
}
function patchStopImmediatePropagation(e, value) {
  if (isArray$5(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$1(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$3(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$5(value)) {
    return false;
  }
  return key in el;
}
const getModelAssigner = (vnode) => {
  const fn = vnode.props["onUpdate:modelValue"] || false;
  return isArray$5(fn) ? (value) => invokeArrayFns(fn, value) : fn;
};
function onCompositionStart(e) {
  e.target.composing = true;
}
function onCompositionEnd(e) {
  const target = e.target;
  if (target.composing) {
    target.composing = false;
    target.dispatchEvent(new Event("input"));
  }
}
const vModelText = {
  created(el, { modifiers: { lazy, trim: trim2, number } }, vnode) {
    el._assign = getModelAssigner(vnode);
    const castToNumber = number || vnode.props && vnode.props.type === "number";
    addEventListener(el, lazy ? "change" : "input", (e) => {
      if (e.target.composing)
        return;
      let domValue = el.value;
      if (trim2) {
        domValue = domValue.trim();
      }
      if (castToNumber) {
        domValue = looseToNumber(domValue);
      }
      el._assign(domValue);
    });
    if (trim2) {
      addEventListener(el, "change", () => {
        el.value = el.value.trim();
      });
    }
    if (!lazy) {
      addEventListener(el, "compositionstart", onCompositionStart);
      addEventListener(el, "compositionend", onCompositionEnd);
      addEventListener(el, "change", onCompositionEnd);
    }
  },
  // set value on mounted so it's after min/max for type="range"
  mounted(el, { value }) {
    el.value = value == null ? "" : value;
  },
  beforeUpdate(el, { value, modifiers: { lazy, trim: trim2, number } }, vnode) {
    el._assign = getModelAssigner(vnode);
    if (el.composing)
      return;
    if (document.activeElement === el && el.type !== "range") {
      if (lazy) {
        return;
      }
      if (trim2 && el.value.trim() === value) {
        return;
      }
      if ((number || el.type === "number") && looseToNumber(el.value) === value) {
        return;
      }
    }
    const newValue = value == null ? "" : value;
    if (el.value !== newValue) {
      el.value = newValue;
    }
  }
};
const vModelSelect = {
  // <select multiple> value need to be deep traversed
  deep: true,
  created(el, { value, modifiers: { number } }, vnode) {
    const isSetModel = isSet$1(value);
    addEventListener(el, "change", () => {
      const selectedVal = Array.prototype.filter.call(el.options, (o) => o.selected).map(
        (o) => number ? looseToNumber(getValue(o)) : getValue(o)
      );
      el._assign(
        el.multiple ? isSetModel ? new Set(selectedVal) : selectedVal : selectedVal[0]
      );
    });
    el._assign = getModelAssigner(vnode);
  },
  // set value in mounted & updated because <select> relies on its children
  // <option>s.
  mounted(el, { value }) {
    setSelected(el, value);
  },
  beforeUpdate(el, _binding, vnode) {
    el._assign = getModelAssigner(vnode);
  },
  updated(el, { value }) {
    setSelected(el, value);
  }
};
function setSelected(el, value) {
  const isMultiple = el.multiple;
  if (isMultiple && !isArray$5(value) && !isSet$1(value)) {
    return;
  }
  for (let i = 0, l = el.options.length; i < l; i++) {
    const option = el.options[i];
    const optionValue = getValue(option);
    if (isMultiple) {
      if (isArray$5(value)) {
        option.selected = looseIndexOf(value, optionValue) > -1;
      } else {
        option.selected = value.has(optionValue);
      }
    } else {
      if (looseEqual(getValue(option), value)) {
        if (el.selectedIndex !== i)
          el.selectedIndex = i;
        return;
      }
    }
  }
  if (!isMultiple && el.selectedIndex !== -1) {
    el.selectedIndex = -1;
  }
}
function getValue(el) {
  return "_value" in el ? el._value : el.value;
}
const rendererOptions = /* @__PURE__ */ extend$1({ patchProp }, nodeOps);
let renderer;
function ensureRenderer() {
  return renderer || (renderer = createRenderer(rendererOptions));
}
const createApp = (...args) => {
  const app2 = ensureRenderer().createApp(...args);
  const { mount } = app2;
  app2.mount = (containerOrSelector) => {
    const container2 = normalizeContainer(containerOrSelector);
    if (!container2)
      return;
    const component = app2._component;
    if (!isFunction$3(component) && !component.render && !component.template) {
      component.template = container2.innerHTML;
    }
    container2.innerHTML = "";
    const proxy = mount(container2, false, container2 instanceof SVGElement);
    if (container2 instanceof Element) {
      container2.removeAttribute("v-cloak");
      container2.setAttribute("data-v-app", "");
    }
    return proxy;
  };
  return app2;
};
function normalizeContainer(container2) {
  if (isString$5(container2)) {
    const res = document.querySelector(container2);
    return res;
  }
  return container2;
}
const normalize$2 = "";
const style$1 = "";
globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
let isPseudo$1 = typeof document !== "undefined" && document.location && document.location.hash.indexOf("pseudo=true") >= 0;
function _format$1(message, args) {
  let result2;
  if (args.length === 0) {
    result2 = message;
  } else {
    result2 = message.replace(/\{(\d+)\}/g, (match2, rest) => {
      const index = rest[0];
      const arg = args[index];
      let result3 = match2;
      if (typeof arg === "string") {
        result3 = arg;
      } else if (typeof arg === "number" || typeof arg === "boolean" || arg === void 0 || arg === null) {
        result3 = String(arg);
      }
      return result3;
    });
  }
  if (isPseudo$1) {
    result2 = "［" + result2.replace(/[aouei]/g, "$&$&") + "］";
  }
  return result2;
}
function localize(data, message, ...args) {
  return _format$1(message, args);
}
function getConfiguredDefaultLocale(_) {
  return void 0;
}
class ErrorHandler {
  constructor() {
    this.listeners = [];
    this.unexpectedErrorHandler = function(e) {
      setTimeout(() => {
        if (e.stack) {
          if (ErrorNoTelemetry.isErrorNoTelemetry(e)) {
            throw new ErrorNoTelemetry(e.message + "\n\n" + e.stack);
          }
          throw new Error(e.message + "\n\n" + e.stack);
        }
        throw e;
      }, 0);
    };
  }
  emit(e) {
    this.listeners.forEach((listener) => {
      listener(e);
    });
  }
  onUnexpectedError(e) {
    this.unexpectedErrorHandler(e);
    this.emit(e);
  }
  // For external errors, we don't want the listeners to be called
  onUnexpectedExternalError(e) {
    this.unexpectedErrorHandler(e);
  }
}
const errorHandler = new ErrorHandler();
function onUnexpectedError(e) {
  if (!isCancellationError(e)) {
    errorHandler.onUnexpectedError(e);
  }
  return void 0;
}
function onUnexpectedExternalError(e) {
  if (!isCancellationError(e)) {
    errorHandler.onUnexpectedExternalError(e);
  }
  return void 0;
}
function transformErrorForSerialization(error2) {
  if (error2 instanceof Error) {
    const { name, message } = error2;
    const stack = error2.stacktrace || error2.stack;
    return {
      $isError: true,
      name,
      message,
      stack,
      noTelemetry: ErrorNoTelemetry.isErrorNoTelemetry(error2)
    };
  }
  return error2;
}
const canceledName = "Canceled";
function isCancellationError(error2) {
  if (error2 instanceof CancellationError) {
    return true;
  }
  return error2 instanceof Error && error2.name === canceledName && error2.message === canceledName;
}
class CancellationError extends Error {
  constructor() {
    super(canceledName);
    this.name = this.message;
  }
}
function canceled() {
  const error2 = new Error(canceledName);
  error2.name = error2.message;
  return error2;
}
function illegalArgument(name) {
  if (name) {
    return new Error(`Illegal argument: ${name}`);
  } else {
    return new Error("Illegal argument");
  }
}
function illegalState(name) {
  if (name) {
    return new Error(`Illegal state: ${name}`);
  } else {
    return new Error("Illegal state");
  }
}
class NotSupportedError extends Error {
  constructor(message) {
    super("NotSupported");
    if (message) {
      this.message = message;
    }
  }
}
class ErrorNoTelemetry extends Error {
  constructor(msg) {
    super(msg);
    this.name = "CodeExpectedError";
  }
  static fromError(err) {
    if (err instanceof ErrorNoTelemetry) {
      return err;
    }
    const result2 = new ErrorNoTelemetry();
    result2.message = err.message;
    result2.stack = err.stack;
    return result2;
  }
  static isErrorNoTelemetry(err) {
    return err.name === "CodeExpectedError";
  }
}
class BugIndicatingError extends Error {
  constructor(message) {
    super(message || "An unexpected bug occurred.");
    Object.setPrototypeOf(this, BugIndicatingError.prototype);
  }
}
function once$2(fn) {
  const _this = this;
  let didCall = false;
  let result2;
  return function() {
    if (didCall) {
      return result2;
    }
    didCall = true;
    result2 = fn.apply(_this, arguments);
    return result2;
  };
}
var Iterable;
(function(Iterable2) {
  function is(thing) {
    return thing && typeof thing === "object" && typeof thing[Symbol.iterator] === "function";
  }
  Iterable2.is = is;
  const _empty2 = Object.freeze([]);
  function empty2() {
    return _empty2;
  }
  Iterable2.empty = empty2;
  function* single(element) {
    yield element;
  }
  Iterable2.single = single;
  function wrap(iterableOrElement) {
    if (is(iterableOrElement)) {
      return iterableOrElement;
    } else {
      return single(iterableOrElement);
    }
  }
  Iterable2.wrap = wrap;
  function from2(iterable) {
    return iterable || _empty2;
  }
  Iterable2.from = from2;
  function isEmpty2(iterable) {
    return !iterable || iterable[Symbol.iterator]().next().done === true;
  }
  Iterable2.isEmpty = isEmpty2;
  function first2(iterable) {
    return iterable[Symbol.iterator]().next().value;
  }
  Iterable2.first = first2;
  function some(iterable, predicate) {
    for (const element of iterable) {
      if (predicate(element)) {
        return true;
      }
    }
    return false;
  }
  Iterable2.some = some;
  function find(iterable, predicate) {
    for (const element of iterable) {
      if (predicate(element)) {
        return element;
      }
    }
    return void 0;
  }
  Iterable2.find = find;
  function* filter2(iterable, predicate) {
    for (const element of iterable) {
      if (predicate(element)) {
        yield element;
      }
    }
  }
  Iterable2.filter = filter2;
  function* map2(iterable, fn) {
    let index = 0;
    for (const element of iterable) {
      yield fn(element, index++);
    }
  }
  Iterable2.map = map2;
  function* concat3(...iterables) {
    for (const iterable of iterables) {
      for (const element of iterable) {
        yield element;
      }
    }
  }
  Iterable2.concat = concat3;
  function reduce(iterable, reducer, initialValue) {
    let value = initialValue;
    for (const element of iterable) {
      value = reducer(value, element);
    }
    return value;
  }
  Iterable2.reduce = reduce;
  function* slice2(arr, from3, to = arr.length) {
    if (from3 < 0) {
      from3 += arr.length;
    }
    if (to < 0) {
      to += arr.length;
    } else if (to > arr.length) {
      to = arr.length;
    }
    for (; from3 < to; from3++) {
      yield arr[from3];
    }
  }
  Iterable2.slice = slice2;
  function consume(iterable, atMost = Number.POSITIVE_INFINITY) {
    const consumed = [];
    if (atMost === 0) {
      return [consumed, iterable];
    }
    const iterator2 = iterable[Symbol.iterator]();
    for (let i = 0; i < atMost; i++) {
      const next = iterator2.next();
      if (next.done) {
        return [consumed, Iterable2.empty()];
      }
      consumed.push(next.value);
    }
    return [consumed, { [Symbol.iterator]() {
      return iterator2;
    } }];
  }
  Iterable2.consume = consume;
})(Iterable || (Iterable = {}));
function trackDisposable(x) {
  return x;
}
function setParentOfDisposable(child, parent) {
}
function markAsSingleton(singleton) {
  return singleton;
}
function isDisposable(thing) {
  return typeof thing.dispose === "function" && thing.dispose.length === 0;
}
function dispose(arg) {
  if (Iterable.is(arg)) {
    const errors2 = [];
    for (const d of arg) {
      if (d) {
        try {
          d.dispose();
        } catch (e) {
          errors2.push(e);
        }
      }
    }
    if (errors2.length === 1) {
      throw errors2[0];
    } else if (errors2.length > 1) {
      throw new AggregateError(errors2, "Encountered errors while disposing of store");
    }
    return Array.isArray(arg) ? [] : arg;
  } else if (arg) {
    arg.dispose();
    return arg;
  }
}
function combinedDisposable(...disposables) {
  const parent = toDisposable(() => dispose(disposables));
  return parent;
}
function toDisposable(fn) {
  const self2 = trackDisposable({
    dispose: once$2(() => {
      fn();
    })
  });
  return self2;
}
class DisposableStore {
  constructor() {
    this._toDispose = /* @__PURE__ */ new Set();
    this._isDisposed = false;
  }
  /**
   * Dispose of all registered disposables and mark this object as disposed.
   *
   * Any future disposables added to this object will be disposed of on `add`.
   */
  dispose() {
    if (this._isDisposed) {
      return;
    }
    this._isDisposed = true;
    this.clear();
  }
  /**
   * @return `true` if this object has been disposed of.
   */
  get isDisposed() {
    return this._isDisposed;
  }
  /**
   * Dispose of all registered disposables but do not mark this object as disposed.
   */
  clear() {
    if (this._toDispose.size === 0) {
      return;
    }
    try {
      dispose(this._toDispose);
    } finally {
      this._toDispose.clear();
    }
  }
  /**
   * Add a new {@link IDisposable disposable} to the collection.
   */
  add(o) {
    if (!o) {
      return o;
    }
    if (o === this) {
      throw new Error("Cannot register a disposable on itself!");
    }
    if (this._isDisposed) {
      if (!DisposableStore.DISABLE_DISPOSED_WARNING) {
        console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack);
      }
    } else {
      this._toDispose.add(o);
    }
    return o;
  }
}
DisposableStore.DISABLE_DISPOSED_WARNING = false;
class Disposable {
  constructor() {
    this._store = new DisposableStore();
    setParentOfDisposable(this._store);
  }
  dispose() {
    this._store.dispose();
  }
  /**
   * Adds `o` to the collection of disposables managed by this object.
   */
  _register(o) {
    if (o === this) {
      throw new Error("Cannot register a disposable on itself!");
    }
    return this._store.add(o);
  }
}
Disposable.None = Object.freeze({ dispose() {
} });
class MutableDisposable {
  constructor() {
    this._isDisposed = false;
  }
  get value() {
    return this._isDisposed ? void 0 : this._value;
  }
  set value(value) {
    var _a2;
    if (this._isDisposed || value === this._value) {
      return;
    }
    (_a2 = this._value) === null || _a2 === void 0 ? void 0 : _a2.dispose();
    this._value = value;
  }
  /**
   * Resets the stored value and disposed of the previously stored value.
   */
  clear() {
    this.value = void 0;
  }
  dispose() {
    var _a2;
    this._isDisposed = true;
    (_a2 = this._value) === null || _a2 === void 0 ? void 0 : _a2.dispose();
    this._value = void 0;
  }
}
class RefCountedDisposable {
  constructor(_disposable) {
    this._disposable = _disposable;
    this._counter = 1;
  }
  acquire() {
    this._counter++;
    return this;
  }
  release() {
    if (--this._counter === 0) {
      this._disposable.dispose();
    }
    return this;
  }
}
class ImmortalReference {
  constructor(object2) {
    this.object = object2;
  }
  dispose() {
  }
}
class DisposableMap {
  constructor() {
    this._store = /* @__PURE__ */ new Map();
    this._isDisposed = false;
  }
  /**
   * Disposes of all stored values and mark this object as disposed.
   *
   * Trying to use this object after it has been disposed of is an error.
   */
  dispose() {
    this._isDisposed = true;
    this.clearAndDisposeAll();
  }
  /**
   * Disposes of all stored values and clear the map, but DO NOT mark this object as disposed.
   */
  clearAndDisposeAll() {
    if (!this._store.size) {
      return;
    }
    try {
      dispose(this._store.values());
    } finally {
      this._store.clear();
    }
  }
  get(key) {
    return this._store.get(key);
  }
  set(key, value, skipDisposeOnOverwrite = false) {
    var _a2;
    if (this._isDisposed) {
      console.warn(new Error("Trying to add a disposable to a DisposableMap that has already been disposed of. The added object will be leaked!").stack);
    }
    if (!skipDisposeOnOverwrite) {
      (_a2 = this._store.get(key)) === null || _a2 === void 0 ? void 0 : _a2.dispose();
    }
    this._store.set(key, value);
  }
  /**
   * Delete the value stored for `key` from this map and also dispose of it.
   */
  deleteAndDispose(key) {
    var _a2;
    (_a2 = this._store.get(key)) === null || _a2 === void 0 ? void 0 : _a2.dispose();
    this._store.delete(key);
  }
  [Symbol.iterator]() {
    return this._store[Symbol.iterator]();
  }
}
let Node$8 = class Node2 {
  constructor(element) {
    this.element = element;
    this.next = Node2.Undefined;
    this.prev = Node2.Undefined;
  }
};
Node$8.Undefined = new Node$8(void 0);
class LinkedList {
  constructor() {
    this._first = Node$8.Undefined;
    this._last = Node$8.Undefined;
    this._size = 0;
  }
  get size() {
    return this._size;
  }
  isEmpty() {
    return this._first === Node$8.Undefined;
  }
  clear() {
    let node2 = this._first;
    while (node2 !== Node$8.Undefined) {
      const next = node2.next;
      node2.prev = Node$8.Undefined;
      node2.next = Node$8.Undefined;
      node2 = next;
    }
    this._first = Node$8.Undefined;
    this._last = Node$8.Undefined;
    this._size = 0;
  }
  unshift(element) {
    return this._insert(element, false);
  }
  push(element) {
    return this._insert(element, true);
  }
  _insert(element, atTheEnd) {
    const newNode = new Node$8(element);
    if (this._first === Node$8.Undefined) {
      this._first = newNode;
      this._last = newNode;
    } else if (atTheEnd) {
      const oldLast = this._last;
      this._last = newNode;
      newNode.prev = oldLast;
      oldLast.next = newNode;
    } else {
      const oldFirst = this._first;
      this._first = newNode;
      newNode.next = oldFirst;
      oldFirst.prev = newNode;
    }
    this._size += 1;
    let didRemove = false;
    return () => {
      if (!didRemove) {
        didRemove = true;
        this._remove(newNode);
      }
    };
  }
  shift() {
    if (this._first === Node$8.Undefined) {
      return void 0;
    } else {
      const res = this._first.element;
      this._remove(this._first);
      return res;
    }
  }
  pop() {
    if (this._last === Node$8.Undefined) {
      return void 0;
    } else {
      const res = this._last.element;
      this._remove(this._last);
      return res;
    }
  }
  _remove(node2) {
    if (node2.prev !== Node$8.Undefined && node2.next !== Node$8.Undefined) {
      const anchor = node2.prev;
      anchor.next = node2.next;
      node2.next.prev = anchor;
    } else if (node2.prev === Node$8.Undefined && node2.next === Node$8.Undefined) {
      this._first = Node$8.Undefined;
      this._last = Node$8.Undefined;
    } else if (node2.next === Node$8.Undefined) {
      this._last = this._last.prev;
      this._last.next = Node$8.Undefined;
    } else if (node2.prev === Node$8.Undefined) {
      this._first = this._first.next;
      this._first.prev = Node$8.Undefined;
    }
    this._size -= 1;
  }
  *[Symbol.iterator]() {
    let node2 = this._first;
    while (node2 !== Node$8.Undefined) {
      yield node2.element;
      node2 = node2.next;
    }
  }
}
const hasPerformanceNow = globalThis.performance && typeof globalThis.performance.now === "function";
class StopWatch {
  static create(highResolution) {
    return new StopWatch(highResolution);
  }
  constructor(highResolution) {
    this._now = hasPerformanceNow && highResolution === false ? Date.now : globalThis.performance.now.bind(globalThis.performance);
    this._startTime = this._now();
    this._stopTime = -1;
  }
  stop() {
    this._stopTime = this._now();
  }
  elapsed() {
    if (this._stopTime !== -1) {
      return this._stopTime - this._startTime;
    }
    return this._now() - this._startTime;
  }
}
var Event$1;
(function(Event2) {
  Event2.None = () => Disposable.None;
  function defer(event, disposable) {
    return debounce(event, () => void 0, 0, void 0, true, void 0, disposable);
  }
  Event2.defer = defer;
  function once2(event) {
    return (listener, thisArgs = null, disposables) => {
      let didFire = false;
      let result2 = void 0;
      result2 = event((e) => {
        if (didFire) {
          return;
        } else if (result2) {
          result2.dispose();
        } else {
          didFire = true;
        }
        return listener.call(thisArgs, e);
      }, null, disposables);
      if (didFire) {
        result2.dispose();
      }
      return result2;
    };
  }
  Event2.once = once2;
  function map2(event, map3, disposable) {
    return snapshot((listener, thisArgs = null, disposables) => event((i) => listener.call(thisArgs, map3(i)), null, disposables), disposable);
  }
  Event2.map = map2;
  function forEach(event, each, disposable) {
    return snapshot((listener, thisArgs = null, disposables) => event((i) => {
      each(i);
      listener.call(thisArgs, i);
    }, null, disposables), disposable);
  }
  Event2.forEach = forEach;
  function filter2(event, filter3, disposable) {
    return snapshot((listener, thisArgs = null, disposables) => event((e) => filter3(e) && listener.call(thisArgs, e), null, disposables), disposable);
  }
  Event2.filter = filter2;
  function signal(event) {
    return event;
  }
  Event2.signal = signal;
  function any(...events) {
    return (listener, thisArgs = null, disposables) => combinedDisposable(...events.map((event) => event((e) => listener.call(thisArgs, e), null, disposables)));
  }
  Event2.any = any;
  function reduce(event, merge2, initial, disposable) {
    let output = initial;
    return map2(event, (e) => {
      output = merge2(output, e);
      return output;
    }, disposable);
  }
  Event2.reduce = reduce;
  function snapshot(event, disposable) {
    let listener;
    const options = {
      onWillAddFirstListener() {
        listener = event(emitter.fire, emitter);
      },
      onDidRemoveLastListener() {
        listener === null || listener === void 0 ? void 0 : listener.dispose();
      }
    };
    const emitter = new Emitter$1(options);
    disposable === null || disposable === void 0 ? void 0 : disposable.add(emitter);
    return emitter.event;
  }
  function debounce(event, merge2, delay = 100, leading = false, flushOnListenerRemove = false, leakWarningThreshold, disposable) {
    let subscription;
    let output = void 0;
    let handle = void 0;
    let numDebouncedCalls = 0;
    let doFire;
    const options = {
      leakWarningThreshold,
      onWillAddFirstListener() {
        subscription = event((cur) => {
          numDebouncedCalls++;
          output = merge2(output, cur);
          if (leading && !handle) {
            emitter.fire(output);
            output = void 0;
          }
          doFire = () => {
            const _output = output;
            output = void 0;
            handle = void 0;
            if (!leading || numDebouncedCalls > 1) {
              emitter.fire(_output);
            }
            numDebouncedCalls = 0;
          };
          if (typeof delay === "number") {
            clearTimeout(handle);
            handle = setTimeout(doFire, delay);
          } else {
            if (handle === void 0) {
              handle = 0;
              queueMicrotask(doFire);
            }
          }
        });
      },
      onWillRemoveListener() {
        if (flushOnListenerRemove && numDebouncedCalls > 0) {
          doFire === null || doFire === void 0 ? void 0 : doFire();
        }
      },
      onDidRemoveLastListener() {
        doFire = void 0;
        subscription.dispose();
      }
    };
    const emitter = new Emitter$1(options);
    disposable === null || disposable === void 0 ? void 0 : disposable.add(emitter);
    return emitter.event;
  }
  Event2.debounce = debounce;
  function accumulate(event, delay = 0, disposable) {
    return Event2.debounce(event, (last2, e) => {
      if (!last2) {
        return [e];
      }
      last2.push(e);
      return last2;
    }, delay, void 0, true, void 0, disposable);
  }
  Event2.accumulate = accumulate;
  function latch(event, equals3 = (a, b) => a === b, disposable) {
    let firstCall = true;
    let cache2;
    return filter2(event, (value) => {
      const shouldEmit = firstCall || !equals3(value, cache2);
      firstCall = false;
      cache2 = value;
      return shouldEmit;
    }, disposable);
  }
  Event2.latch = latch;
  function split(event, isT, disposable) {
    return [
      Event2.filter(event, isT, disposable),
      Event2.filter(event, (e) => !isT(e), disposable)
    ];
  }
  Event2.split = split;
  function buffer(event, flushAfterTimeout = false, _buffer = []) {
    let buffer2 = _buffer.slice();
    let listener = event((e) => {
      if (buffer2) {
        buffer2.push(e);
      } else {
        emitter.fire(e);
      }
    });
    const flush = () => {
      buffer2 === null || buffer2 === void 0 ? void 0 : buffer2.forEach((e) => emitter.fire(e));
      buffer2 = null;
    };
    const emitter = new Emitter$1({
      onWillAddFirstListener() {
        if (!listener) {
          listener = event((e) => emitter.fire(e));
        }
      },
      onDidAddFirstListener() {
        if (buffer2) {
          if (flushAfterTimeout) {
            setTimeout(flush);
          } else {
            flush();
          }
        }
      },
      onDidRemoveLastListener() {
        if (listener) {
          listener.dispose();
        }
        listener = null;
      }
    });
    return emitter.event;
  }
  Event2.buffer = buffer;
  class ChainableEvent {
    constructor(event) {
      this.event = event;
      this.disposables = new DisposableStore();
    }
    /** @see {@link Event.map} */
    map(fn) {
      return new ChainableEvent(map2(this.event, fn, this.disposables));
    }
    /** @see {@link Event.forEach} */
    forEach(fn) {
      return new ChainableEvent(forEach(this.event, fn, this.disposables));
    }
    filter(fn) {
      return new ChainableEvent(filter2(this.event, fn, this.disposables));
    }
    /** @see {@link Event.reduce} */
    reduce(merge2, initial) {
      return new ChainableEvent(reduce(this.event, merge2, initial, this.disposables));
    }
    /** @see {@link Event.reduce} */
    latch() {
      return new ChainableEvent(latch(this.event, void 0, this.disposables));
    }
    debounce(merge2, delay = 100, leading = false, flushOnListenerRemove = false, leakWarningThreshold) {
      return new ChainableEvent(debounce(this.event, merge2, delay, leading, flushOnListenerRemove, leakWarningThreshold, this.disposables));
    }
    /**
     * Attach a listener to the event.
     */
    on(listener, thisArgs, disposables) {
      return this.event(listener, thisArgs, disposables);
    }
    /** @see {@link Event.once} */
    once(listener, thisArgs, disposables) {
      return once2(this.event)(listener, thisArgs, disposables);
    }
    dispose() {
      this.disposables.dispose();
    }
  }
  function chain(event) {
    return new ChainableEvent(event);
  }
  Event2.chain = chain;
  function fromNodeEventEmitter(emitter, eventName, map3 = (id3) => id3) {
    const fn = (...args) => result2.fire(map3(...args));
    const onFirstListenerAdd = () => emitter.on(eventName, fn);
    const onLastListenerRemove = () => emitter.removeListener(eventName, fn);
    const result2 = new Emitter$1({ onWillAddFirstListener: onFirstListenerAdd, onDidRemoveLastListener: onLastListenerRemove });
    return result2.event;
  }
  Event2.fromNodeEventEmitter = fromNodeEventEmitter;
  function fromDOMEventEmitter(emitter, eventName, map3 = (id3) => id3) {
    const fn = (...args) => result2.fire(map3(...args));
    const onFirstListenerAdd = () => emitter.addEventListener(eventName, fn);
    const onLastListenerRemove = () => emitter.removeEventListener(eventName, fn);
    const result2 = new Emitter$1({ onWillAddFirstListener: onFirstListenerAdd, onDidRemoveLastListener: onLastListenerRemove });
    return result2.event;
  }
  Event2.fromDOMEventEmitter = fromDOMEventEmitter;
  function toPromise(event) {
    return new Promise((resolve2) => once2(event)(resolve2));
  }
  Event2.toPromise = toPromise;
  function runAndSubscribe(event, handler) {
    handler(void 0);
    return event((e) => handler(e));
  }
  Event2.runAndSubscribe = runAndSubscribe;
  function runAndSubscribeWithStore(event, handler) {
    let store = null;
    function run(e) {
      store === null || store === void 0 ? void 0 : store.dispose();
      store = new DisposableStore();
      handler(e, store);
    }
    run(void 0);
    const disposable = event((e) => run(e));
    return toDisposable(() => {
      disposable.dispose();
      store === null || store === void 0 ? void 0 : store.dispose();
    });
  }
  Event2.runAndSubscribeWithStore = runAndSubscribeWithStore;
  class EmitterObserver {
    constructor(_observable, store) {
      this._observable = _observable;
      this._counter = 0;
      this._hasChanged = false;
      const options = {
        onWillAddFirstListener: () => {
          _observable.addObserver(this);
        },
        onDidRemoveLastListener: () => {
          _observable.removeObserver(this);
        }
      };
      this.emitter = new Emitter$1(options);
      if (store) {
        store.add(this.emitter);
      }
    }
    beginUpdate(_observable) {
      this._counter++;
    }
    handlePossibleChange(_observable) {
    }
    handleChange(_observable, _change) {
      this._hasChanged = true;
    }
    endUpdate(_observable) {
      this._counter--;
      if (this._counter === 0) {
        this._observable.reportChanges();
        if (this._hasChanged) {
          this._hasChanged = false;
          this.emitter.fire(this._observable.get());
        }
      }
    }
  }
  function fromObservable(obs, store) {
    const observer = new EmitterObserver(obs, store);
    return observer.emitter.event;
  }
  Event2.fromObservable = fromObservable;
  function fromObservableLight(observable) {
    return (listener) => {
      let count = 0;
      let didChange = false;
      const observer = {
        beginUpdate() {
          count++;
        },
        endUpdate() {
          count--;
          if (count === 0) {
            observable.reportChanges();
            if (didChange) {
              didChange = false;
              listener();
            }
          }
        },
        handlePossibleChange() {
        },
        handleChange() {
          didChange = true;
        }
      };
      observable.addObserver(observer);
      observable.reportChanges();
      return {
        dispose() {
          observable.removeObserver(observer);
        }
      };
    };
  }
  Event2.fromObservableLight = fromObservableLight;
})(Event$1 || (Event$1 = {}));
class EventProfiling {
  constructor(name) {
    this.listenerCount = 0;
    this.invocationCount = 0;
    this.elapsedOverall = 0;
    this.durations = [];
    this.name = `${name}_${EventProfiling._idPool++}`;
    EventProfiling.all.add(this);
  }
  start(listenerCount) {
    this._stopWatch = new StopWatch();
    this.listenerCount = listenerCount;
  }
  stop() {
    if (this._stopWatch) {
      const elapsed = this._stopWatch.elapsed();
      this.durations.push(elapsed);
      this.elapsedOverall += elapsed;
      this.invocationCount += 1;
      this._stopWatch = void 0;
    }
  }
}
EventProfiling.all = /* @__PURE__ */ new Set();
EventProfiling._idPool = 0;
let _globalLeakWarningThreshold = -1;
class LeakageMonitor {
  constructor(threshold, name = Math.random().toString(18).slice(2, 5)) {
    this.threshold = threshold;
    this.name = name;
    this._warnCountdown = 0;
  }
  dispose() {
    var _a2;
    (_a2 = this._stacks) === null || _a2 === void 0 ? void 0 : _a2.clear();
  }
  check(stack, listenerCount) {
    const threshold = this.threshold;
    if (threshold <= 0 || listenerCount < threshold) {
      return void 0;
    }
    if (!this._stacks) {
      this._stacks = /* @__PURE__ */ new Map();
    }
    const count = this._stacks.get(stack.value) || 0;
    this._stacks.set(stack.value, count + 1);
    this._warnCountdown -= 1;
    if (this._warnCountdown <= 0) {
      this._warnCountdown = threshold * 0.5;
      let topStack;
      let topCount = 0;
      for (const [stack2, count2] of this._stacks) {
        if (!topStack || topCount < count2) {
          topStack = stack2;
          topCount = count2;
        }
      }
      console.warn(`[${this.name}] potential listener LEAK detected, having ${listenerCount} listeners already. MOST frequent listener (${topCount}):`);
      console.warn(topStack);
    }
    return () => {
      const count2 = this._stacks.get(stack.value) || 0;
      this._stacks.set(stack.value, count2 - 1);
    };
  }
}
class Stacktrace {
  static create() {
    var _a2;
    return new Stacktrace((_a2 = new Error().stack) !== null && _a2 !== void 0 ? _a2 : "");
  }
  constructor(value) {
    this.value = value;
  }
  print() {
    console.warn(this.value.split("\n").slice(2).join("\n"));
  }
}
class UniqueContainer {
  constructor(value) {
    this.value = value;
  }
}
const compactionThreshold = 2;
let Emitter$1 = class Emitter {
  constructor(options) {
    var _a2, _b2, _c2, _d2, _e2;
    this._size = 0;
    this._options = options;
    this._leakageMon = ((_a2 = this._options) === null || _a2 === void 0 ? void 0 : _a2.leakWarningThreshold) ? new LeakageMonitor((_c2 = (_b2 = this._options) === null || _b2 === void 0 ? void 0 : _b2.leakWarningThreshold) !== null && _c2 !== void 0 ? _c2 : _globalLeakWarningThreshold) : void 0;
    this._perfMon = ((_d2 = this._options) === null || _d2 === void 0 ? void 0 : _d2._profName) ? new EventProfiling(this._options._profName) : void 0;
    this._deliveryQueue = (_e2 = this._options) === null || _e2 === void 0 ? void 0 : _e2.deliveryQueue;
  }
  dispose() {
    var _a2, _b2, _c2, _d2;
    if (!this._disposed) {
      this._disposed = true;
      if (((_a2 = this._deliveryQueue) === null || _a2 === void 0 ? void 0 : _a2.current) === this) {
        this._deliveryQueue.reset();
      }
      if (this._listeners) {
        this._listeners = void 0;
        this._size = 0;
      }
      (_c2 = (_b2 = this._options) === null || _b2 === void 0 ? void 0 : _b2.onDidRemoveLastListener) === null || _c2 === void 0 ? void 0 : _c2.call(_b2);
      (_d2 = this._leakageMon) === null || _d2 === void 0 ? void 0 : _d2.dispose();
    }
  }
  /**
   * For the public to allow to subscribe
   * to events from this Emitter
   */
  get event() {
    var _a2;
    (_a2 = this._event) !== null && _a2 !== void 0 ? _a2 : this._event = (callback, thisArgs, disposables) => {
      var _a3, _b2, _c2, _d2, _e2;
      if (this._leakageMon && this._size > this._leakageMon.threshold * 3) {
        console.warn(`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far`);
        return Disposable.None;
      }
      if (this._disposed) {
        return Disposable.None;
      }
      if (thisArgs) {
        callback = callback.bind(thisArgs);
      }
      const contained = new UniqueContainer(callback);
      let removeMonitor;
      if (this._leakageMon && this._size >= Math.ceil(this._leakageMon.threshold * 0.2)) {
        contained.stack = Stacktrace.create();
        removeMonitor = this._leakageMon.check(contained.stack, this._size + 1);
      }
      if (!this._listeners) {
        (_b2 = (_a3 = this._options) === null || _a3 === void 0 ? void 0 : _a3.onWillAddFirstListener) === null || _b2 === void 0 ? void 0 : _b2.call(_a3, this);
        this._listeners = contained;
        (_d2 = (_c2 = this._options) === null || _c2 === void 0 ? void 0 : _c2.onDidAddFirstListener) === null || _d2 === void 0 ? void 0 : _d2.call(_c2, this);
      } else if (this._listeners instanceof UniqueContainer) {
        (_e2 = this._deliveryQueue) !== null && _e2 !== void 0 ? _e2 : this._deliveryQueue = new EventDeliveryQueuePrivate();
        this._listeners = [this._listeners, contained];
      } else {
        this._listeners.push(contained);
      }
      this._size++;
      const result2 = toDisposable(() => {
        removeMonitor === null || removeMonitor === void 0 ? void 0 : removeMonitor();
        this._removeListener(contained);
      });
      if (disposables instanceof DisposableStore) {
        disposables.add(result2);
      } else if (Array.isArray(disposables)) {
        disposables.push(result2);
      }
      return result2;
    };
    return this._event;
  }
  _removeListener(listener) {
    var _a2, _b2, _c2, _d2;
    (_b2 = (_a2 = this._options) === null || _a2 === void 0 ? void 0 : _a2.onWillRemoveListener) === null || _b2 === void 0 ? void 0 : _b2.call(_a2, this);
    if (!this._listeners) {
      return;
    }
    if (this._size === 1) {
      this._listeners = void 0;
      (_d2 = (_c2 = this._options) === null || _c2 === void 0 ? void 0 : _c2.onDidRemoveLastListener) === null || _d2 === void 0 ? void 0 : _d2.call(_c2, this);
      this._size = 0;
      return;
    }
    const listeners = this._listeners;
    const index = listeners.indexOf(listener);
    if (index === -1) {
      console.log("disposed?", this._disposed);
      console.log("size?", this._size);
      console.log("arr?", JSON.stringify(this._listeners));
      throw new Error("Attempted to dispose unknown listener");
    }
    this._size--;
    listeners[index] = void 0;
    const adjustDeliveryQueue = this._deliveryQueue.current === this;
    if (this._size * compactionThreshold <= listeners.length) {
      let n2 = 0;
      for (let i = 0; i < listeners.length; i++) {
        if (listeners[i]) {
          listeners[n2++] = listeners[i];
        } else if (adjustDeliveryQueue) {
          this._deliveryQueue.end--;
          if (n2 < this._deliveryQueue.i) {
            this._deliveryQueue.i--;
          }
        }
      }
      listeners.length = n2;
    }
  }
  _deliver(listener, value) {
    var _a2;
    if (!listener) {
      return;
    }
    const errorHandler2 = ((_a2 = this._options) === null || _a2 === void 0 ? void 0 : _a2.onListenerError) || onUnexpectedError;
    if (!errorHandler2) {
      listener.value(value);
      return;
    }
    try {
      listener.value(value);
    } catch (e) {
      errorHandler2(e);
    }
  }
  /** Delivers items in the queue. Assumes the queue is ready to go. */
  _deliverQueue(dq) {
    const listeners = dq.current._listeners;
    while (dq.i < dq.end) {
      this._deliver(listeners[dq.i++], dq.value);
    }
    dq.reset();
  }
  /**
   * To be kept private to fire an event to
   * subscribers
   */
  fire(event) {
    var _a2, _b2, _c2, _d2;
    if ((_a2 = this._deliveryQueue) === null || _a2 === void 0 ? void 0 : _a2.current) {
      this._deliverQueue(this._deliveryQueue);
      (_b2 = this._perfMon) === null || _b2 === void 0 ? void 0 : _b2.stop();
    }
    (_c2 = this._perfMon) === null || _c2 === void 0 ? void 0 : _c2.start(this._size);
    if (!this._listeners)
      ;
    else if (this._listeners instanceof UniqueContainer) {
      this._deliver(this._listeners, event);
    } else {
      const dq = this._deliveryQueue;
      dq.enqueue(this, event, this._listeners.length);
      this._deliverQueue(dq);
    }
    (_d2 = this._perfMon) === null || _d2 === void 0 ? void 0 : _d2.stop();
  }
  hasListeners() {
    return this._size > 0;
  }
};
const createEventDeliveryQueue = () => new EventDeliveryQueuePrivate();
class EventDeliveryQueuePrivate {
  constructor() {
    this.i = -1;
    this.end = 0;
  }
  enqueue(emitter, value, end) {
    this.i = 0;
    this.end = end;
    this.current = emitter;
    this.value = value;
  }
  reset() {
    this.i = this.end;
    this.current = void 0;
    this.value = void 0;
  }
}
class PauseableEmitter extends Emitter$1 {
  constructor(options) {
    super(options);
    this._isPaused = 0;
    this._eventQueue = new LinkedList();
    this._mergeFn = options === null || options === void 0 ? void 0 : options.merge;
  }
  pause() {
    this._isPaused++;
  }
  resume() {
    if (this._isPaused !== 0 && --this._isPaused === 0) {
      if (this._mergeFn) {
        if (this._eventQueue.size > 0) {
          const events = Array.from(this._eventQueue);
          this._eventQueue.clear();
          super.fire(this._mergeFn(events));
        }
      } else {
        while (!this._isPaused && this._eventQueue.size !== 0) {
          super.fire(this._eventQueue.shift());
        }
      }
    }
  }
  fire(event) {
    if (this._size) {
      if (this._isPaused !== 0) {
        this._eventQueue.push(event);
      } else {
        super.fire(event);
      }
    }
  }
}
class DebounceEmitter extends PauseableEmitter {
  constructor(options) {
    var _a2;
    super(options);
    this._delay = (_a2 = options.delay) !== null && _a2 !== void 0 ? _a2 : 100;
  }
  fire(event) {
    if (!this._handle) {
      this.pause();
      this._handle = setTimeout(() => {
        this._handle = void 0;
        this.resume();
      }, this._delay);
    }
    super.fire(event);
  }
}
class MicrotaskEmitter extends Emitter$1 {
  constructor(options) {
    super(options);
    this._queuedEvents = [];
    this._mergeFn = options === null || options === void 0 ? void 0 : options.merge;
  }
  fire(event) {
    if (!this.hasListeners()) {
      return;
    }
    this._queuedEvents.push(event);
    if (this._queuedEvents.length === 1) {
      queueMicrotask(() => {
        if (this._mergeFn) {
          super.fire(this._mergeFn(this._queuedEvents));
        } else {
          this._queuedEvents.forEach((e) => super.fire(e));
        }
        this._queuedEvents = [];
      });
    }
  }
}
class EventMultiplexer {
  constructor() {
    this.hasListeners = false;
    this.events = [];
    this.emitter = new Emitter$1({
      onWillAddFirstListener: () => this.onFirstListenerAdd(),
      onDidRemoveLastListener: () => this.onLastListenerRemove()
    });
  }
  get event() {
    return this.emitter.event;
  }
  add(event) {
    const e = { event, listener: null };
    this.events.push(e);
    if (this.hasListeners) {
      this.hook(e);
    }
    const dispose2 = () => {
      if (this.hasListeners) {
        this.unhook(e);
      }
      const idx = this.events.indexOf(e);
      this.events.splice(idx, 1);
    };
    return toDisposable(once$2(dispose2));
  }
  onFirstListenerAdd() {
    this.hasListeners = true;
    this.events.forEach((e) => this.hook(e));
  }
  onLastListenerRemove() {
    this.hasListeners = false;
    this.events.forEach((e) => this.unhook(e));
  }
  hook(e) {
    e.listener = e.event((r) => this.emitter.fire(r));
  }
  unhook(e) {
    if (e.listener) {
      e.listener.dispose();
    }
    e.listener = null;
  }
  dispose() {
    this.emitter.dispose();
  }
}
class EventBufferer {
  constructor() {
    this.buffers = [];
  }
  wrapEvent(event) {
    return (listener, thisArgs, disposables) => {
      return event((i) => {
        const buffer = this.buffers[this.buffers.length - 1];
        if (buffer) {
          buffer.push(() => listener.call(thisArgs, i));
        } else {
          listener.call(thisArgs, i);
        }
      }, void 0, disposables);
    };
  }
  bufferEvents(fn) {
    const buffer = [];
    this.buffers.push(buffer);
    const r = fn();
    this.buffers.pop();
    buffer.forEach((flush) => flush());
    return r;
  }
}
class Relay {
  constructor() {
    this.listening = false;
    this.inputEvent = Event$1.None;
    this.inputEventListener = Disposable.None;
    this.emitter = new Emitter$1({
      onDidAddFirstListener: () => {
        this.listening = true;
        this.inputEventListener = this.inputEvent(this.emitter.fire, this.emitter);
      },
      onDidRemoveLastListener: () => {
        this.listening = false;
        this.inputEventListener.dispose();
      }
    });
    this.event = this.emitter.event;
  }
  set input(event) {
    this.inputEvent = event;
    if (this.listening) {
      this.inputEventListener.dispose();
      this.inputEventListener = event(this.emitter.fire, this.emitter);
    }
  }
  dispose() {
    this.inputEventListener.dispose();
    this.emitter.dispose();
  }
}
class WindowManager {
  constructor() {
    this._zoomFactor = 1;
  }
  getZoomFactor() {
    return this._zoomFactor;
  }
}
WindowManager.INSTANCE = new WindowManager();
class DevicePixelRatioMonitor extends Disposable {
  constructor() {
    super();
    this._onDidChange = this._register(new Emitter$1());
    this.onDidChange = this._onDidChange.event;
    this._listener = () => this._handleChange(true);
    this._mediaQueryList = null;
    this._handleChange(false);
  }
  _handleChange(fireEvent) {
    var _a2;
    (_a2 = this._mediaQueryList) === null || _a2 === void 0 ? void 0 : _a2.removeEventListener("change", this._listener);
    this._mediaQueryList = window.matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`);
    this._mediaQueryList.addEventListener("change", this._listener);
    if (fireEvent) {
      this._onDidChange.fire();
    }
  }
}
class PixelRatioImpl extends Disposable {
  get value() {
    return this._value;
  }
  constructor() {
    super();
    this._onDidChange = this._register(new Emitter$1());
    this.onDidChange = this._onDidChange.event;
    this._value = this._getPixelRatio();
    const dprMonitor = this._register(new DevicePixelRatioMonitor());
    this._register(dprMonitor.onDidChange(() => {
      this._value = this._getPixelRatio();
      this._onDidChange.fire(this._value);
    }));
  }
  _getPixelRatio() {
    const ctx = document.createElement("canvas").getContext("2d");
    const dpr = window.devicePixelRatio || 1;
    const bsr = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1;
    return dpr / bsr;
  }
}
class PixelRatioFacade {
  constructor() {
    this._pixelRatioMonitor = null;
  }
  _getOrCreatePixelRatioMonitor() {
    if (!this._pixelRatioMonitor) {
      this._pixelRatioMonitor = markAsSingleton(new PixelRatioImpl());
    }
    return this._pixelRatioMonitor;
  }
  /**
   * Get the current value.
   */
  get value() {
    return this._getOrCreatePixelRatioMonitor().value;
  }
  /**
   * Listen for changes.
   */
  get onDidChange() {
    return this._getOrCreatePixelRatioMonitor().onDidChange;
  }
}
function addMatchMediaChangeListener(query, callback) {
  if (typeof query === "string") {
    query = window.matchMedia(query);
  }
  query.addEventListener("change", callback);
}
const PixelRatio = new PixelRatioFacade();
function getZoomFactor() {
  return WindowManager.INSTANCE.getZoomFactor();
}
const userAgent$1 = navigator.userAgent;
const isFirefox$1 = userAgent$1.indexOf("Firefox") >= 0;
const isWebKit = userAgent$1.indexOf("AppleWebKit") >= 0;
const isChrome$1 = userAgent$1.indexOf("Chrome") >= 0;
const isSafari$1 = !isChrome$1 && userAgent$1.indexOf("Safari") >= 0;
const isWebkitWebView = !isChrome$1 && !isSafari$1 && isWebKit;
userAgent$1.indexOf("Electron/") >= 0;
const isAndroid = userAgent$1.indexOf("Android") >= 0;
let standalone = false;
if (window.matchMedia) {
  const standaloneMatchMedia = window.matchMedia("(display-mode: standalone) or (display-mode: window-controls-overlay)");
  const fullScreenMatchMedia = window.matchMedia("(display-mode: fullscreen)");
  standalone = standaloneMatchMedia.matches;
  addMatchMediaChangeListener(standaloneMatchMedia, ({ matches }) => {
    if (standalone && fullScreenMatchMedia.matches) {
      return;
    }
    standalone = matches;
  });
}
function isStandalone() {
  return standalone;
}
function isString$4(str2) {
  return typeof str2 === "string";
}
function isObject$4(obj) {
  return typeof obj === "object" && obj !== null && !Array.isArray(obj) && !(obj instanceof RegExp) && !(obj instanceof Date);
}
function isTypedArray(obj) {
  const TypedArray = Object.getPrototypeOf(Uint8Array);
  return typeof obj === "object" && obj instanceof TypedArray;
}
function isNumber$3(obj) {
  return typeof obj === "number" && !isNaN(obj);
}
function isIterable(obj) {
  return !!obj && typeof obj[Symbol.iterator] === "function";
}
function isBoolean$1(obj) {
  return obj === true || obj === false;
}
function isUndefined$1(obj) {
  return typeof obj === "undefined";
}
function isDefined(arg) {
  return !isUndefinedOrNull(arg);
}
function isUndefinedOrNull(obj) {
  return isUndefined$1(obj) || obj === null;
}
function assertType(condition, type) {
  if (!condition) {
    throw new Error(type ? `Unexpected type, expected '${type}'` : "Unexpected type");
  }
}
function assertIsDefined(arg) {
  if (isUndefinedOrNull(arg)) {
    throw new Error("Assertion Failed: argument is undefined or null");
  }
  return arg;
}
function isFunction$2(obj) {
  return typeof obj === "function";
}
function validateConstraints(args, constraints) {
  const len = Math.min(args.length, constraints.length);
  for (let i = 0; i < len; i++) {
    validateConstraint(args[i], constraints[i]);
  }
}
function validateConstraint(arg, constraint) {
  if (isString$4(constraint)) {
    if (typeof arg !== constraint) {
      throw new Error(`argument does not match constraint: typeof ${constraint}`);
    }
  } else if (isFunction$2(constraint)) {
    try {
      if (arg instanceof constraint) {
        return;
      }
    } catch (_a2) {
    }
    if (!isUndefinedOrNull(arg) && arg.constructor === constraint) {
      return;
    }
    if (constraint.length === 1 && constraint.call(void 0, arg) === true) {
      return;
    }
    throw new Error(`argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true`);
  }
}
function withNullAsUndefined(x) {
  return x === null ? void 0 : x;
}
function withUndefinedAsNull(x) {
  return typeof x === "undefined" ? null : x;
}
var _a$4;
const LANGUAGE_DEFAULT = "en";
let _isWindows = false;
let _isMacintosh = false;
let _isLinux = false;
let _isNative = false;
let _isWeb = false;
let _isIOS = false;
let _isMobile = false;
let _locale = void 0;
let _language = LANGUAGE_DEFAULT;
let _platformLocale = LANGUAGE_DEFAULT;
let _translationsConfigFile = void 0;
let _userAgent = void 0;
const globals = typeof self === "object" ? self : typeof global === "object" ? global : {};
let nodeProcess = void 0;
if (typeof globals.vscode !== "undefined" && typeof globals.vscode.process !== "undefined") {
  nodeProcess = globals.vscode.process;
} else if (typeof process !== "undefined") {
  nodeProcess = process;
}
const isElectronProcess = typeof ((_a$4 = nodeProcess === null || nodeProcess === void 0 ? void 0 : nodeProcess.versions) === null || _a$4 === void 0 ? void 0 : _a$4.electron) === "string";
const isElectronRenderer = isElectronProcess && (nodeProcess === null || nodeProcess === void 0 ? void 0 : nodeProcess.type) === "renderer";
if (typeof navigator === "object" && !isElectronRenderer) {
  _userAgent = navigator.userAgent;
  _isWindows = _userAgent.indexOf("Windows") >= 0;
  _isMacintosh = _userAgent.indexOf("Macintosh") >= 0;
  _isIOS = (_userAgent.indexOf("Macintosh") >= 0 || _userAgent.indexOf("iPad") >= 0 || _userAgent.indexOf("iPhone") >= 0) && !!navigator.maxTouchPoints && navigator.maxTouchPoints > 0;
  _isLinux = _userAgent.indexOf("Linux") >= 0;
  _isMobile = (_userAgent === null || _userAgent === void 0 ? void 0 : _userAgent.indexOf("Mobi")) >= 0;
  _isWeb = true;
  getConfiguredDefaultLocale(
    // This call _must_ be done in the file that calls `nls.getConfiguredDefaultLocale`
    // to ensure that the NLS AMD Loader plugin has been loaded and configured.
    // This is because the loader plugin decides what the default locale is based on
    // how it's able to resolve the strings.
    localize({ key: "ensureLoaderPluginIsLoaded", comment: ["{Locked}"] }, "_")
  );
  _locale = LANGUAGE_DEFAULT;
  _language = _locale;
  _platformLocale = navigator.language;
} else if (typeof nodeProcess === "object") {
  _isWindows = nodeProcess.platform === "win32";
  _isMacintosh = nodeProcess.platform === "darwin";
  _isLinux = nodeProcess.platform === "linux";
  _isLinux && !!nodeProcess.env["SNAP"] && !!nodeProcess.env["SNAP_REVISION"];
  !!nodeProcess.env["CI"] || !!nodeProcess.env["BUILD_ARTIFACTSTAGINGDIRECTORY"];
  _locale = LANGUAGE_DEFAULT;
  _language = LANGUAGE_DEFAULT;
  const rawNlsConfig = nodeProcess.env["VSCODE_NLS_CONFIG"];
  if (rawNlsConfig) {
    try {
      const nlsConfig = JSON.parse(rawNlsConfig);
      const resolved = nlsConfig.availableLanguages["*"];
      _locale = nlsConfig.locale;
      _platformLocale = nlsConfig.osLocale;
      _language = resolved ? resolved : LANGUAGE_DEFAULT;
      _translationsConfigFile = nlsConfig._translationsConfigFile;
    } catch (e) {
    }
  }
  _isNative = true;
} else {
  console.error("Unable to resolve platform.");
}
const isWindows = _isWindows;
const isMacintosh = _isMacintosh;
const isLinux = _isLinux;
const isNative = _isNative;
const isWeb = _isWeb;
const isWebWorker = _isWeb && typeof globals.importScripts === "function";
const isIOS = _isIOS;
const isMobile = _isMobile;
const userAgent = _userAgent;
const language = _language;
const setTimeout0IsFaster = typeof globals.postMessage === "function" && !globals.importScripts;
const setTimeout0 = (() => {
  if (setTimeout0IsFaster) {
    const pending = [];
    globals.addEventListener("message", (e) => {
      if (e.data && e.data.vscodeScheduleAsyncWork) {
        for (let i = 0, len = pending.length; i < len; i++) {
          const candidate = pending[i];
          if (candidate.id === e.data.vscodeScheduleAsyncWork) {
            pending.splice(i, 1);
            candidate.callback();
            return;
          }
        }
      }
    });
    let lastId = 0;
    return (callback) => {
      const myId = ++lastId;
      pending.push({
        id: myId,
        callback
      });
      globals.postMessage({ vscodeScheduleAsyncWork: myId }, "*");
    };
  }
  return (callback) => setTimeout(callback);
})();
const OS = _isMacintosh || _isIOS ? 2 : _isWindows ? 1 : 3;
let _isLittleEndian = true;
let _isLittleEndianComputed = false;
function isLittleEndian() {
  if (!_isLittleEndianComputed) {
    _isLittleEndianComputed = true;
    const test = new Uint8Array(2);
    test[0] = 1;
    test[1] = 2;
    const view = new Uint16Array(test.buffer);
    _isLittleEndian = view[0] === (2 << 8) + 1;
  }
  return _isLittleEndian;
}
const isChrome = !!(userAgent && userAgent.indexOf("Chrome") >= 0);
const isFirefox = !!(userAgent && userAgent.indexOf("Firefox") >= 0);
const isSafari = !!(!isChrome && (userAgent && userAgent.indexOf("Safari") >= 0));
const isEdge = !!(userAgent && userAgent.indexOf("Edg/") >= 0);
!!(userAgent && userAgent.indexOf("Android") >= 0);
const BrowserFeatures = {
  clipboard: {
    writeText: isNative || document.queryCommandSupported && document.queryCommandSupported("copy") || !!(navigator && navigator.clipboard && navigator.clipboard.writeText),
    readText: isNative || !!(navigator && navigator.clipboard && navigator.clipboard.readText)
  },
  keyboard: (() => {
    if (isNative || isStandalone()) {
      return 0;
    }
    if (navigator.keyboard || isSafari$1) {
      return 1;
    }
    return 2;
  })(),
  // 'ontouchstart' in window always evaluates to true with typescript's modern typings. This causes `window` to be
  // `never` later in `window.navigator`. That's why we need the explicit `window as Window` cast
  touch: "ontouchstart" in window || navigator.maxTouchPoints > 0,
  pointerEvents: window.PointerEvent && ("ontouchstart" in window || window.navigator.maxTouchPoints > 0 || navigator.maxTouchPoints > 0)
};
class KeyCodeStrMap {
  constructor() {
    this._keyCodeToStr = [];
    this._strToKeyCode = /* @__PURE__ */ Object.create(null);
  }
  define(keyCode, str2) {
    this._keyCodeToStr[keyCode] = str2;
    this._strToKeyCode[str2.toLowerCase()] = keyCode;
  }
  keyCodeToStr(keyCode) {
    return this._keyCodeToStr[keyCode];
  }
  strToKeyCode(str2) {
    return this._strToKeyCode[str2.toLowerCase()] || 0;
  }
}
const uiMap = new KeyCodeStrMap();
const userSettingsUSMap = new KeyCodeStrMap();
const userSettingsGeneralMap = new KeyCodeStrMap();
const EVENT_KEY_CODE_MAP = new Array(230);
const scanCodeStrToInt = /* @__PURE__ */ Object.create(null);
const scanCodeLowerCaseStrToInt = /* @__PURE__ */ Object.create(null);
const IMMUTABLE_CODE_TO_KEY_CODE = [];
for (let i = 0; i <= 193; i++) {
  IMMUTABLE_CODE_TO_KEY_CODE[i] = -1;
}
(function() {
  const empty2 = "";
  const mappings = [
    // immutable, scanCode, scanCodeStr, keyCode, keyCodeStr, eventKeyCode, vkey, usUserSettingsLabel, generalUserSettingsLabel
    [1, 0, "None", 0, "unknown", 0, "VK_UNKNOWN", empty2, empty2],
    [1, 1, "Hyper", 0, empty2, 0, empty2, empty2, empty2],
    [1, 2, "Super", 0, empty2, 0, empty2, empty2, empty2],
    [1, 3, "Fn", 0, empty2, 0, empty2, empty2, empty2],
    [1, 4, "FnLock", 0, empty2, 0, empty2, empty2, empty2],
    [1, 5, "Suspend", 0, empty2, 0, empty2, empty2, empty2],
    [1, 6, "Resume", 0, empty2, 0, empty2, empty2, empty2],
    [1, 7, "Turbo", 0, empty2, 0, empty2, empty2, empty2],
    [1, 8, "Sleep", 0, empty2, 0, "VK_SLEEP", empty2, empty2],
    [1, 9, "WakeUp", 0, empty2, 0, empty2, empty2, empty2],
    [0, 10, "KeyA", 31, "A", 65, "VK_A", empty2, empty2],
    [0, 11, "KeyB", 32, "B", 66, "VK_B", empty2, empty2],
    [0, 12, "KeyC", 33, "C", 67, "VK_C", empty2, empty2],
    [0, 13, "KeyD", 34, "D", 68, "VK_D", empty2, empty2],
    [0, 14, "KeyE", 35, "E", 69, "VK_E", empty2, empty2],
    [0, 15, "KeyF", 36, "F", 70, "VK_F", empty2, empty2],
    [0, 16, "KeyG", 37, "G", 71, "VK_G", empty2, empty2],
    [0, 17, "KeyH", 38, "H", 72, "VK_H", empty2, empty2],
    [0, 18, "KeyI", 39, "I", 73, "VK_I", empty2, empty2],
    [0, 19, "KeyJ", 40, "J", 74, "VK_J", empty2, empty2],
    [0, 20, "KeyK", 41, "K", 75, "VK_K", empty2, empty2],
    [0, 21, "KeyL", 42, "L", 76, "VK_L", empty2, empty2],
    [0, 22, "KeyM", 43, "M", 77, "VK_M", empty2, empty2],
    [0, 23, "KeyN", 44, "N", 78, "VK_N", empty2, empty2],
    [0, 24, "KeyO", 45, "O", 79, "VK_O", empty2, empty2],
    [0, 25, "KeyP", 46, "P", 80, "VK_P", empty2, empty2],
    [0, 26, "KeyQ", 47, "Q", 81, "VK_Q", empty2, empty2],
    [0, 27, "KeyR", 48, "R", 82, "VK_R", empty2, empty2],
    [0, 28, "KeyS", 49, "S", 83, "VK_S", empty2, empty2],
    [0, 29, "KeyT", 50, "T", 84, "VK_T", empty2, empty2],
    [0, 30, "KeyU", 51, "U", 85, "VK_U", empty2, empty2],
    [0, 31, "KeyV", 52, "V", 86, "VK_V", empty2, empty2],
    [0, 32, "KeyW", 53, "W", 87, "VK_W", empty2, empty2],
    [0, 33, "KeyX", 54, "X", 88, "VK_X", empty2, empty2],
    [0, 34, "KeyY", 55, "Y", 89, "VK_Y", empty2, empty2],
    [0, 35, "KeyZ", 56, "Z", 90, "VK_Z", empty2, empty2],
    [0, 36, "Digit1", 22, "1", 49, "VK_1", empty2, empty2],
    [0, 37, "Digit2", 23, "2", 50, "VK_2", empty2, empty2],
    [0, 38, "Digit3", 24, "3", 51, "VK_3", empty2, empty2],
    [0, 39, "Digit4", 25, "4", 52, "VK_4", empty2, empty2],
    [0, 40, "Digit5", 26, "5", 53, "VK_5", empty2, empty2],
    [0, 41, "Digit6", 27, "6", 54, "VK_6", empty2, empty2],
    [0, 42, "Digit7", 28, "7", 55, "VK_7", empty2, empty2],
    [0, 43, "Digit8", 29, "8", 56, "VK_8", empty2, empty2],
    [0, 44, "Digit9", 30, "9", 57, "VK_9", empty2, empty2],
    [0, 45, "Digit0", 21, "0", 48, "VK_0", empty2, empty2],
    [1, 46, "Enter", 3, "Enter", 13, "VK_RETURN", empty2, empty2],
    [1, 47, "Escape", 9, "Escape", 27, "VK_ESCAPE", empty2, empty2],
    [1, 48, "Backspace", 1, "Backspace", 8, "VK_BACK", empty2, empty2],
    [1, 49, "Tab", 2, "Tab", 9, "VK_TAB", empty2, empty2],
    [1, 50, "Space", 10, "Space", 32, "VK_SPACE", empty2, empty2],
    [0, 51, "Minus", 88, "-", 189, "VK_OEM_MINUS", "-", "OEM_MINUS"],
    [0, 52, "Equal", 86, "=", 187, "VK_OEM_PLUS", "=", "OEM_PLUS"],
    [0, 53, "BracketLeft", 92, "[", 219, "VK_OEM_4", "[", "OEM_4"],
    [0, 54, "BracketRight", 94, "]", 221, "VK_OEM_6", "]", "OEM_6"],
    [0, 55, "Backslash", 93, "\\", 220, "VK_OEM_5", "\\", "OEM_5"],
    [0, 56, "IntlHash", 0, empty2, 0, empty2, empty2, empty2],
    [0, 57, "Semicolon", 85, ";", 186, "VK_OEM_1", ";", "OEM_1"],
    [0, 58, "Quote", 95, "'", 222, "VK_OEM_7", "'", "OEM_7"],
    [0, 59, "Backquote", 91, "`", 192, "VK_OEM_3", "`", "OEM_3"],
    [0, 60, "Comma", 87, ",", 188, "VK_OEM_COMMA", ",", "OEM_COMMA"],
    [0, 61, "Period", 89, ".", 190, "VK_OEM_PERIOD", ".", "OEM_PERIOD"],
    [0, 62, "Slash", 90, "/", 191, "VK_OEM_2", "/", "OEM_2"],
    [1, 63, "CapsLock", 8, "CapsLock", 20, "VK_CAPITAL", empty2, empty2],
    [1, 64, "F1", 59, "F1", 112, "VK_F1", empty2, empty2],
    [1, 65, "F2", 60, "F2", 113, "VK_F2", empty2, empty2],
    [1, 66, "F3", 61, "F3", 114, "VK_F3", empty2, empty2],
    [1, 67, "F4", 62, "F4", 115, "VK_F4", empty2, empty2],
    [1, 68, "F5", 63, "F5", 116, "VK_F5", empty2, empty2],
    [1, 69, "F6", 64, "F6", 117, "VK_F6", empty2, empty2],
    [1, 70, "F7", 65, "F7", 118, "VK_F7", empty2, empty2],
    [1, 71, "F8", 66, "F8", 119, "VK_F8", empty2, empty2],
    [1, 72, "F9", 67, "F9", 120, "VK_F9", empty2, empty2],
    [1, 73, "F10", 68, "F10", 121, "VK_F10", empty2, empty2],
    [1, 74, "F11", 69, "F11", 122, "VK_F11", empty2, empty2],
    [1, 75, "F12", 70, "F12", 123, "VK_F12", empty2, empty2],
    [1, 76, "PrintScreen", 0, empty2, 0, empty2, empty2, empty2],
    [1, 77, "ScrollLock", 84, "ScrollLock", 145, "VK_SCROLL", empty2, empty2],
    [1, 78, "Pause", 7, "PauseBreak", 19, "VK_PAUSE", empty2, empty2],
    [1, 79, "Insert", 19, "Insert", 45, "VK_INSERT", empty2, empty2],
    [1, 80, "Home", 14, "Home", 36, "VK_HOME", empty2, empty2],
    [1, 81, "PageUp", 11, "PageUp", 33, "VK_PRIOR", empty2, empty2],
    [1, 82, "Delete", 20, "Delete", 46, "VK_DELETE", empty2, empty2],
    [1, 83, "End", 13, "End", 35, "VK_END", empty2, empty2],
    [1, 84, "PageDown", 12, "PageDown", 34, "VK_NEXT", empty2, empty2],
    [1, 85, "ArrowRight", 17, "RightArrow", 39, "VK_RIGHT", "Right", empty2],
    [1, 86, "ArrowLeft", 15, "LeftArrow", 37, "VK_LEFT", "Left", empty2],
    [1, 87, "ArrowDown", 18, "DownArrow", 40, "VK_DOWN", "Down", empty2],
    [1, 88, "ArrowUp", 16, "UpArrow", 38, "VK_UP", "Up", empty2],
    [1, 89, "NumLock", 83, "NumLock", 144, "VK_NUMLOCK", empty2, empty2],
    [1, 90, "NumpadDivide", 113, "NumPad_Divide", 111, "VK_DIVIDE", empty2, empty2],
    [1, 91, "NumpadMultiply", 108, "NumPad_Multiply", 106, "VK_MULTIPLY", empty2, empty2],
    [1, 92, "NumpadSubtract", 111, "NumPad_Subtract", 109, "VK_SUBTRACT", empty2, empty2],
    [1, 93, "NumpadAdd", 109, "NumPad_Add", 107, "VK_ADD", empty2, empty2],
    [1, 94, "NumpadEnter", 3, empty2, 0, empty2, empty2, empty2],
    [1, 95, "Numpad1", 99, "NumPad1", 97, "VK_NUMPAD1", empty2, empty2],
    [1, 96, "Numpad2", 100, "NumPad2", 98, "VK_NUMPAD2", empty2, empty2],
    [1, 97, "Numpad3", 101, "NumPad3", 99, "VK_NUMPAD3", empty2, empty2],
    [1, 98, "Numpad4", 102, "NumPad4", 100, "VK_NUMPAD4", empty2, empty2],
    [1, 99, "Numpad5", 103, "NumPad5", 101, "VK_NUMPAD5", empty2, empty2],
    [1, 100, "Numpad6", 104, "NumPad6", 102, "VK_NUMPAD6", empty2, empty2],
    [1, 101, "Numpad7", 105, "NumPad7", 103, "VK_NUMPAD7", empty2, empty2],
    [1, 102, "Numpad8", 106, "NumPad8", 104, "VK_NUMPAD8", empty2, empty2],
    [1, 103, "Numpad9", 107, "NumPad9", 105, "VK_NUMPAD9", empty2, empty2],
    [1, 104, "Numpad0", 98, "NumPad0", 96, "VK_NUMPAD0", empty2, empty2],
    [1, 105, "NumpadDecimal", 112, "NumPad_Decimal", 110, "VK_DECIMAL", empty2, empty2],
    [0, 106, "IntlBackslash", 97, "OEM_102", 226, "VK_OEM_102", empty2, empty2],
    [1, 107, "ContextMenu", 58, "ContextMenu", 93, empty2, empty2, empty2],
    [1, 108, "Power", 0, empty2, 0, empty2, empty2, empty2],
    [1, 109, "NumpadEqual", 0, empty2, 0, empty2, empty2, empty2],
    [1, 110, "F13", 71, "F13", 124, "VK_F13", empty2, empty2],
    [1, 111, "F14", 72, "F14", 125, "VK_F14", empty2, empty2],
    [1, 112, "F15", 73, "F15", 126, "VK_F15", empty2, empty2],
    [1, 113, "F16", 74, "F16", 127, "VK_F16", empty2, empty2],
    [1, 114, "F17", 75, "F17", 128, "VK_F17", empty2, empty2],
    [1, 115, "F18", 76, "F18", 129, "VK_F18", empty2, empty2],
    [1, 116, "F19", 77, "F19", 130, "VK_F19", empty2, empty2],
    [1, 117, "F20", 78, "F20", 131, "VK_F20", empty2, empty2],
    [1, 118, "F21", 79, "F21", 132, "VK_F21", empty2, empty2],
    [1, 119, "F22", 80, "F22", 133, "VK_F22", empty2, empty2],
    [1, 120, "F23", 81, "F23", 134, "VK_F23", empty2, empty2],
    [1, 121, "F24", 82, "F24", 135, "VK_F24", empty2, empty2],
    [1, 122, "Open", 0, empty2, 0, empty2, empty2, empty2],
    [1, 123, "Help", 0, empty2, 0, empty2, empty2, empty2],
    [1, 124, "Select", 0, empty2, 0, empty2, empty2, empty2],
    [1, 125, "Again", 0, empty2, 0, empty2, empty2, empty2],
    [1, 126, "Undo", 0, empty2, 0, empty2, empty2, empty2],
    [1, 127, "Cut", 0, empty2, 0, empty2, empty2, empty2],
    [1, 128, "Copy", 0, empty2, 0, empty2, empty2, empty2],
    [1, 129, "Paste", 0, empty2, 0, empty2, empty2, empty2],
    [1, 130, "Find", 0, empty2, 0, empty2, empty2, empty2],
    [1, 131, "AudioVolumeMute", 117, "AudioVolumeMute", 173, "VK_VOLUME_MUTE", empty2, empty2],
    [1, 132, "AudioVolumeUp", 118, "AudioVolumeUp", 175, "VK_VOLUME_UP", empty2, empty2],
    [1, 133, "AudioVolumeDown", 119, "AudioVolumeDown", 174, "VK_VOLUME_DOWN", empty2, empty2],
    [1, 134, "NumpadComma", 110, "NumPad_Separator", 108, "VK_SEPARATOR", empty2, empty2],
    [0, 135, "IntlRo", 115, "ABNT_C1", 193, "VK_ABNT_C1", empty2, empty2],
    [1, 136, "KanaMode", 0, empty2, 0, empty2, empty2, empty2],
    [0, 137, "IntlYen", 0, empty2, 0, empty2, empty2, empty2],
    [1, 138, "Convert", 0, empty2, 0, empty2, empty2, empty2],
    [1, 139, "NonConvert", 0, empty2, 0, empty2, empty2, empty2],
    [1, 140, "Lang1", 0, empty2, 0, empty2, empty2, empty2],
    [1, 141, "Lang2", 0, empty2, 0, empty2, empty2, empty2],
    [1, 142, "Lang3", 0, empty2, 0, empty2, empty2, empty2],
    [1, 143, "Lang4", 0, empty2, 0, empty2, empty2, empty2],
    [1, 144, "Lang5", 0, empty2, 0, empty2, empty2, empty2],
    [1, 145, "Abort", 0, empty2, 0, empty2, empty2, empty2],
    [1, 146, "Props", 0, empty2, 0, empty2, empty2, empty2],
    [1, 147, "NumpadParenLeft", 0, empty2, 0, empty2, empty2, empty2],
    [1, 148, "NumpadParenRight", 0, empty2, 0, empty2, empty2, empty2],
    [1, 149, "NumpadBackspace", 0, empty2, 0, empty2, empty2, empty2],
    [1, 150, "NumpadMemoryStore", 0, empty2, 0, empty2, empty2, empty2],
    [1, 151, "NumpadMemoryRecall", 0, empty2, 0, empty2, empty2, empty2],
    [1, 152, "NumpadMemoryClear", 0, empty2, 0, empty2, empty2, empty2],
    [1, 153, "NumpadMemoryAdd", 0, empty2, 0, empty2, empty2, empty2],
    [1, 154, "NumpadMemorySubtract", 0, empty2, 0, empty2, empty2, empty2],
    [1, 155, "NumpadClear", 131, "Clear", 12, "VK_CLEAR", empty2, empty2],
    [1, 156, "NumpadClearEntry", 0, empty2, 0, empty2, empty2, empty2],
    [1, 0, empty2, 5, "Ctrl", 17, "VK_CONTROL", empty2, empty2],
    [1, 0, empty2, 4, "Shift", 16, "VK_SHIFT", empty2, empty2],
    [1, 0, empty2, 6, "Alt", 18, "VK_MENU", empty2, empty2],
    [1, 0, empty2, 57, "Meta", 91, "VK_COMMAND", empty2, empty2],
    [1, 157, "ControlLeft", 5, empty2, 0, "VK_LCONTROL", empty2, empty2],
    [1, 158, "ShiftLeft", 4, empty2, 0, "VK_LSHIFT", empty2, empty2],
    [1, 159, "AltLeft", 6, empty2, 0, "VK_LMENU", empty2, empty2],
    [1, 160, "MetaLeft", 57, empty2, 0, "VK_LWIN", empty2, empty2],
    [1, 161, "ControlRight", 5, empty2, 0, "VK_RCONTROL", empty2, empty2],
    [1, 162, "ShiftRight", 4, empty2, 0, "VK_RSHIFT", empty2, empty2],
    [1, 163, "AltRight", 6, empty2, 0, "VK_RMENU", empty2, empty2],
    [1, 164, "MetaRight", 57, empty2, 0, "VK_RWIN", empty2, empty2],
    [1, 165, "BrightnessUp", 0, empty2, 0, empty2, empty2, empty2],
    [1, 166, "BrightnessDown", 0, empty2, 0, empty2, empty2, empty2],
    [1, 167, "MediaPlay", 0, empty2, 0, empty2, empty2, empty2],
    [1, 168, "MediaRecord", 0, empty2, 0, empty2, empty2, empty2],
    [1, 169, "MediaFastForward", 0, empty2, 0, empty2, empty2, empty2],
    [1, 170, "MediaRewind", 0, empty2, 0, empty2, empty2, empty2],
    [1, 171, "MediaTrackNext", 124, "MediaTrackNext", 176, "VK_MEDIA_NEXT_TRACK", empty2, empty2],
    [1, 172, "MediaTrackPrevious", 125, "MediaTrackPrevious", 177, "VK_MEDIA_PREV_TRACK", empty2, empty2],
    [1, 173, "MediaStop", 126, "MediaStop", 178, "VK_MEDIA_STOP", empty2, empty2],
    [1, 174, "Eject", 0, empty2, 0, empty2, empty2, empty2],
    [1, 175, "MediaPlayPause", 127, "MediaPlayPause", 179, "VK_MEDIA_PLAY_PAUSE", empty2, empty2],
    [1, 176, "MediaSelect", 128, "LaunchMediaPlayer", 181, "VK_MEDIA_LAUNCH_MEDIA_SELECT", empty2, empty2],
    [1, 177, "LaunchMail", 129, "LaunchMail", 180, "VK_MEDIA_LAUNCH_MAIL", empty2, empty2],
    [1, 178, "LaunchApp2", 130, "LaunchApp2", 183, "VK_MEDIA_LAUNCH_APP2", empty2, empty2],
    [1, 179, "LaunchApp1", 0, empty2, 0, "VK_MEDIA_LAUNCH_APP1", empty2, empty2],
    [1, 180, "SelectTask", 0, empty2, 0, empty2, empty2, empty2],
    [1, 181, "LaunchScreenSaver", 0, empty2, 0, empty2, empty2, empty2],
    [1, 182, "BrowserSearch", 120, "BrowserSearch", 170, "VK_BROWSER_SEARCH", empty2, empty2],
    [1, 183, "BrowserHome", 121, "BrowserHome", 172, "VK_BROWSER_HOME", empty2, empty2],
    [1, 184, "BrowserBack", 122, "BrowserBack", 166, "VK_BROWSER_BACK", empty2, empty2],
    [1, 185, "BrowserForward", 123, "BrowserForward", 167, "VK_BROWSER_FORWARD", empty2, empty2],
    [1, 186, "BrowserStop", 0, empty2, 0, "VK_BROWSER_STOP", empty2, empty2],
    [1, 187, "BrowserRefresh", 0, empty2, 0, "VK_BROWSER_REFRESH", empty2, empty2],
    [1, 188, "BrowserFavorites", 0, empty2, 0, "VK_BROWSER_FAVORITES", empty2, empty2],
    [1, 189, "ZoomToggle", 0, empty2, 0, empty2, empty2, empty2],
    [1, 190, "MailReply", 0, empty2, 0, empty2, empty2, empty2],
    [1, 191, "MailForward", 0, empty2, 0, empty2, empty2, empty2],
    [1, 192, "MailSend", 0, empty2, 0, empty2, empty2, empty2],
    // See https://lists.w3.org/Archives/Public/www-dom/2010JulSep/att-0182/keyCode-spec.html
    // If an Input Method Editor is processing key input and the event is keydown, return 229.
    [1, 0, empty2, 114, "KeyInComposition", 229, empty2, empty2, empty2],
    [1, 0, empty2, 116, "ABNT_C2", 194, "VK_ABNT_C2", empty2, empty2],
    [1, 0, empty2, 96, "OEM_8", 223, "VK_OEM_8", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_KANA", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_HANGUL", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_JUNJA", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_FINAL", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_HANJA", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_KANJI", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_CONVERT", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_NONCONVERT", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_ACCEPT", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_MODECHANGE", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_SELECT", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_PRINT", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_EXECUTE", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_SNAPSHOT", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_HELP", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_APPS", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_PROCESSKEY", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_PACKET", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_DBE_SBCSCHAR", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_DBE_DBCSCHAR", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_ATTN", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_CRSEL", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_EXSEL", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_EREOF", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_PLAY", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_ZOOM", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_NONAME", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_PA1", empty2, empty2],
    [1, 0, empty2, 0, empty2, 0, "VK_OEM_CLEAR", empty2, empty2]
  ];
  const seenKeyCode = [];
  const seenScanCode = [];
  for (const mapping of mappings) {
    const [immutable, scanCode, scanCodeStr, keyCode, keyCodeStr, eventKeyCode, vkey, usUserSettingsLabel, generalUserSettingsLabel] = mapping;
    if (!seenScanCode[scanCode]) {
      seenScanCode[scanCode] = true;
      scanCodeStrToInt[scanCodeStr] = scanCode;
      scanCodeLowerCaseStrToInt[scanCodeStr.toLowerCase()] = scanCode;
      if (immutable) {
        IMMUTABLE_CODE_TO_KEY_CODE[scanCode] = keyCode;
      }
    }
    if (!seenKeyCode[keyCode]) {
      seenKeyCode[keyCode] = true;
      if (!keyCodeStr) {
        throw new Error(`String representation missing for key code ${keyCode} around scan code ${scanCodeStr}`);
      }
      uiMap.define(keyCode, keyCodeStr);
      userSettingsUSMap.define(keyCode, usUserSettingsLabel || keyCodeStr);
      userSettingsGeneralMap.define(keyCode, generalUserSettingsLabel || usUserSettingsLabel || keyCodeStr);
    }
    if (eventKeyCode) {
      EVENT_KEY_CODE_MAP[eventKeyCode] = keyCode;
    }
  }
})();
var KeyCodeUtils;
(function(KeyCodeUtils2) {
  function toString3(keyCode) {
    return uiMap.keyCodeToStr(keyCode);
  }
  KeyCodeUtils2.toString = toString3;
  function fromString2(key) {
    return uiMap.strToKeyCode(key);
  }
  KeyCodeUtils2.fromString = fromString2;
  function toUserSettingsUS(keyCode) {
    return userSettingsUSMap.keyCodeToStr(keyCode);
  }
  KeyCodeUtils2.toUserSettingsUS = toUserSettingsUS;
  function toUserSettingsGeneral(keyCode) {
    return userSettingsGeneralMap.keyCodeToStr(keyCode);
  }
  KeyCodeUtils2.toUserSettingsGeneral = toUserSettingsGeneral;
  function fromUserSettings(key) {
    return userSettingsUSMap.strToKeyCode(key) || userSettingsGeneralMap.strToKeyCode(key);
  }
  KeyCodeUtils2.fromUserSettings = fromUserSettings;
  function toElectronAccelerator(keyCode) {
    if (keyCode >= 98 && keyCode <= 113) {
      return null;
    }
    switch (keyCode) {
      case 16:
        return "Up";
      case 18:
        return "Down";
      case 15:
        return "Left";
      case 17:
        return "Right";
    }
    return uiMap.keyCodeToStr(keyCode);
  }
  KeyCodeUtils2.toElectronAccelerator = toElectronAccelerator;
})(KeyCodeUtils || (KeyCodeUtils = {}));
function KeyChord(firstPart, secondPart) {
  const chordPart = (secondPart & 65535) << 16 >>> 0;
  return (firstPart | chordPart) >>> 0;
}
function decodeKeybinding(keybinding, OS2) {
  if (typeof keybinding === "number") {
    if (keybinding === 0) {
      return null;
    }
    const firstChord = (keybinding & 65535) >>> 0;
    const secondChord = (keybinding & 4294901760) >>> 16;
    if (secondChord !== 0) {
      return new Keybinding([
        createSimpleKeybinding(firstChord, OS2),
        createSimpleKeybinding(secondChord, OS2)
      ]);
    }
    return new Keybinding([createSimpleKeybinding(firstChord, OS2)]);
  } else {
    const chords = [];
    for (let i = 0; i < keybinding.length; i++) {
      chords.push(createSimpleKeybinding(keybinding[i], OS2));
    }
    return new Keybinding(chords);
  }
}
function createSimpleKeybinding(keybinding, OS2) {
  const ctrlCmd = keybinding & 2048 ? true : false;
  const winCtrl = keybinding & 256 ? true : false;
  const ctrlKey = OS2 === 2 ? winCtrl : ctrlCmd;
  const shiftKey = keybinding & 1024 ? true : false;
  const altKey = keybinding & 512 ? true : false;
  const metaKey = OS2 === 2 ? ctrlCmd : winCtrl;
  const keyCode = keybinding & 255;
  return new KeyCodeChord(ctrlKey, shiftKey, altKey, metaKey, keyCode);
}
class KeyCodeChord {
  constructor(ctrlKey, shiftKey, altKey, metaKey, keyCode) {
    this.ctrlKey = ctrlKey;
    this.shiftKey = shiftKey;
    this.altKey = altKey;
    this.metaKey = metaKey;
    this.keyCode = keyCode;
  }
  equals(other) {
    return other instanceof KeyCodeChord && this.ctrlKey === other.ctrlKey && this.shiftKey === other.shiftKey && this.altKey === other.altKey && this.metaKey === other.metaKey && this.keyCode === other.keyCode;
  }
  isModifierKey() {
    return this.keyCode === 0 || this.keyCode === 5 || this.keyCode === 57 || this.keyCode === 6 || this.keyCode === 4;
  }
  /**
   * Does this keybinding refer to the key code of a modifier and it also has the modifier flag?
   */
  isDuplicateModifierCase() {
    return this.ctrlKey && this.keyCode === 5 || this.shiftKey && this.keyCode === 4 || this.altKey && this.keyCode === 6 || this.metaKey && this.keyCode === 57;
  }
}
class Keybinding {
  constructor(chords) {
    if (chords.length === 0) {
      throw illegalArgument(`chords`);
    }
    this.chords = chords;
  }
}
class ResolvedChord {
  constructor(ctrlKey, shiftKey, altKey, metaKey, keyLabel, keyAriaLabel) {
    this.ctrlKey = ctrlKey;
    this.shiftKey = shiftKey;
    this.altKey = altKey;
    this.metaKey = metaKey;
    this.keyLabel = keyLabel;
    this.keyAriaLabel = keyAriaLabel;
  }
}
class ResolvedKeybinding {
}
function extractKeyCode(e) {
  if (e.charCode) {
    const char = String.fromCharCode(e.charCode).toUpperCase();
    return KeyCodeUtils.fromString(char);
  }
  const keyCode = e.keyCode;
  if (keyCode === 3) {
    return 7;
  } else if (isFirefox$1) {
    switch (keyCode) {
      case 59:
        return 85;
      case 60:
        if (isLinux) {
          return 97;
        }
        break;
      case 61:
        return 86;
      case 107:
        return 109;
      case 109:
        return 111;
      case 173:
        return 88;
      case 224:
        if (isMacintosh) {
          return 57;
        }
        break;
    }
  } else if (isWebKit) {
    if (isMacintosh && keyCode === 93) {
      return 57;
    } else if (!isMacintosh && keyCode === 92) {
      return 57;
    }
  }
  return EVENT_KEY_CODE_MAP[keyCode] || 0;
}
const ctrlKeyMod$1 = isMacintosh ? 256 : 2048;
const altKeyMod = 512;
const shiftKeyMod = 1024;
const metaKeyMod = isMacintosh ? 2048 : 256;
class StandardKeyboardEvent {
  constructor(source) {
    this._standardKeyboardEventBrand = true;
    const e = source;
    this.browserEvent = e;
    this.target = e.target;
    this.ctrlKey = e.ctrlKey;
    this.shiftKey = e.shiftKey;
    this.altKey = e.altKey;
    this.metaKey = e.metaKey;
    this.altGraphKey = e.getModifierState("AltGraph");
    this.keyCode = extractKeyCode(e);
    this.code = e.code;
    this.ctrlKey = this.ctrlKey || this.keyCode === 5;
    this.altKey = this.altKey || this.keyCode === 6;
    this.shiftKey = this.shiftKey || this.keyCode === 4;
    this.metaKey = this.metaKey || this.keyCode === 57;
    this._asKeybinding = this._computeKeybinding();
    this._asKeyCodeChord = this._computeKeyCodeChord();
  }
  preventDefault() {
    if (this.browserEvent && this.browserEvent.preventDefault) {
      this.browserEvent.preventDefault();
    }
  }
  stopPropagation() {
    if (this.browserEvent && this.browserEvent.stopPropagation) {
      this.browserEvent.stopPropagation();
    }
  }
  toKeyCodeChord() {
    return this._asKeyCodeChord;
  }
  equals(other) {
    return this._asKeybinding === other;
  }
  _computeKeybinding() {
    let key = 0;
    if (this.keyCode !== 5 && this.keyCode !== 4 && this.keyCode !== 6 && this.keyCode !== 57) {
      key = this.keyCode;
    }
    let result2 = 0;
    if (this.ctrlKey) {
      result2 |= ctrlKeyMod$1;
    }
    if (this.altKey) {
      result2 |= altKeyMod;
    }
    if (this.shiftKey) {
      result2 |= shiftKeyMod;
    }
    if (this.metaKey) {
      result2 |= metaKeyMod;
    }
    result2 |= key;
    return result2;
  }
  _computeKeyCodeChord() {
    let key = 0;
    if (this.keyCode !== 5 && this.keyCode !== 4 && this.keyCode !== 6 && this.keyCode !== 57) {
      key = this.keyCode;
    }
    return new KeyCodeChord(this.ctrlKey, this.shiftKey, this.altKey, this.metaKey, key);
  }
}
let hasDifferentOriginAncestorFlag = false;
let sameOriginWindowChainCache = null;
function getParentWindowIfSameOrigin(w) {
  if (!w.parent || w.parent === w) {
    return null;
  }
  try {
    const location = w.location;
    const parentLocation = w.parent.location;
    if (location.origin !== "null" && parentLocation.origin !== "null" && location.origin !== parentLocation.origin) {
      hasDifferentOriginAncestorFlag = true;
      return null;
    }
  } catch (e) {
    hasDifferentOriginAncestorFlag = true;
    return null;
  }
  return w.parent;
}
class IframeUtils {
  /**
   * Returns a chain of embedded windows with the same origin (which can be accessed programmatically).
   * Having a chain of length 1 might mean that the current execution environment is running outside of an iframe or inside an iframe embedded in a window with a different origin.
   * To distinguish if at one point the current execution environment is running inside a window with a different origin, see hasDifferentOriginAncestor()
   */
  static getSameOriginWindowChain() {
    if (!sameOriginWindowChainCache) {
      sameOriginWindowChainCache = [];
      let w = window;
      let parent;
      do {
        parent = getParentWindowIfSameOrigin(w);
        if (parent) {
          sameOriginWindowChainCache.push({
            window: w,
            iframeElement: w.frameElement || null
          });
        } else {
          sameOriginWindowChainCache.push({
            window: w,
            iframeElement: null
          });
        }
        w = parent;
      } while (w);
    }
    return sameOriginWindowChainCache.slice(0);
  }
  /**
   * Returns the position of `childWindow` relative to `ancestorWindow`
   */
  static getPositionOfChildWindowRelativeToAncestorWindow(childWindow, ancestorWindow) {
    if (!ancestorWindow || childWindow === ancestorWindow) {
      return {
        top: 0,
        left: 0
      };
    }
    let top = 0, left = 0;
    const windowChain = this.getSameOriginWindowChain();
    for (const windowChainEl of windowChain) {
      top += windowChainEl.window.scrollY;
      left += windowChainEl.window.scrollX;
      if (windowChainEl.window === ancestorWindow) {
        break;
      }
      if (!windowChainEl.iframeElement) {
        break;
      }
      const boundingRect = windowChainEl.iframeElement.getBoundingClientRect();
      top += boundingRect.top;
      left += boundingRect.left;
    }
    return {
      top,
      left
    };
  }
}
class StandardMouseEvent {
  constructor(e) {
    this.timestamp = Date.now();
    this.browserEvent = e;
    this.leftButton = e.button === 0;
    this.middleButton = e.button === 1;
    this.rightButton = e.button === 2;
    this.buttons = e.buttons;
    this.target = e.target;
    this.detail = e.detail || 1;
    if (e.type === "dblclick") {
      this.detail = 2;
    }
    this.ctrlKey = e.ctrlKey;
    this.shiftKey = e.shiftKey;
    this.altKey = e.altKey;
    this.metaKey = e.metaKey;
    if (typeof e.pageX === "number") {
      this.posx = e.pageX;
      this.posy = e.pageY;
    } else {
      this.posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
      this.posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }
    const iframeOffsets = IframeUtils.getPositionOfChildWindowRelativeToAncestorWindow(window, e.view);
    this.posx -= iframeOffsets.left;
    this.posy -= iframeOffsets.top;
  }
  preventDefault() {
    this.browserEvent.preventDefault();
  }
  stopPropagation() {
    this.browserEvent.stopPropagation();
  }
}
class StandardWheelEvent {
  constructor(e, deltaX = 0, deltaY = 0) {
    this.browserEvent = e || null;
    this.target = e ? e.target || e.targetNode || e.srcElement : null;
    this.deltaY = deltaY;
    this.deltaX = deltaX;
    if (e) {
      const e1 = e;
      const e2 = e;
      if (typeof e1.wheelDeltaY !== "undefined") {
        this.deltaY = e1.wheelDeltaY / 120;
      } else if (typeof e2.VERTICAL_AXIS !== "undefined" && e2.axis === e2.VERTICAL_AXIS) {
        this.deltaY = -e2.detail / 3;
      } else if (e.type === "wheel") {
        const ev = e;
        if (ev.deltaMode === ev.DOM_DELTA_LINE) {
          if (isFirefox$1 && !isMacintosh) {
            this.deltaY = -e.deltaY / 3;
          } else {
            this.deltaY = -e.deltaY;
          }
        } else {
          this.deltaY = -e.deltaY / 40;
        }
      }
      if (typeof e1.wheelDeltaX !== "undefined") {
        if (isSafari$1 && isWindows) {
          this.deltaX = -(e1.wheelDeltaX / 120);
        } else {
          this.deltaX = e1.wheelDeltaX / 120;
        }
      } else if (typeof e2.HORIZONTAL_AXIS !== "undefined" && e2.axis === e2.HORIZONTAL_AXIS) {
        this.deltaX = -e.detail / 3;
      } else if (e.type === "wheel") {
        const ev = e;
        if (ev.deltaMode === ev.DOM_DELTA_LINE) {
          if (isFirefox$1 && !isMacintosh) {
            this.deltaX = -e.deltaX / 3;
          } else {
            this.deltaX = -e.deltaX;
          }
        } else {
          this.deltaX = -e.deltaX / 40;
        }
      }
      if (this.deltaY === 0 && this.deltaX === 0 && e.wheelDelta) {
        this.deltaY = e.wheelDelta / 120;
      }
    }
  }
  preventDefault() {
    var _a2;
    (_a2 = this.browserEvent) === null || _a2 === void 0 ? void 0 : _a2.preventDefault();
  }
  stopPropagation() {
    var _a2;
    (_a2 = this.browserEvent) === null || _a2 === void 0 ? void 0 : _a2.stopPropagation();
  }
}
/*! @license DOMPurify 2.3.1 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/2.3.1/LICENSE */
function _toConsumableArray(arr) {
  if (Array.isArray(arr)) {
    for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
      arr2[i] = arr[i];
    }
    return arr2;
  } else {
    return Array.from(arr);
  }
}
var hasOwnProperty$6 = Object.hasOwnProperty, setPrototypeOf = Object.setPrototypeOf, isFrozen = Object.isFrozen, getPrototypeOf = Object.getPrototypeOf, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var freeze$1 = Object.freeze, seal = Object.seal, create$1 = Object.create;
var _ref = typeof Reflect !== "undefined" && Reflect, apply = _ref.apply, construct = _ref.construct;
if (!apply) {
  apply = function apply2(fun, thisValue, args) {
    return fun.apply(thisValue, args);
  };
}
if (!freeze$1) {
  freeze$1 = function freeze2(x) {
    return x;
  };
}
if (!seal) {
  seal = function seal2(x) {
    return x;
  };
}
if (!construct) {
  construct = function construct2(Func, args) {
    return new (Function.prototype.bind.apply(Func, [null].concat(_toConsumableArray(args))))();
  };
}
var arrayForEach = unapply(Array.prototype.forEach);
var arrayPop = unapply(Array.prototype.pop);
var arrayPush = unapply(Array.prototype.push);
var stringToLowerCase = unapply(String.prototype.toLowerCase);
var stringMatch = unapply(String.prototype.match);
var stringReplace = unapply(String.prototype.replace);
var stringIndexOf = unapply(String.prototype.indexOf);
var stringTrim = unapply(String.prototype.trim);
var regExpTest = unapply(RegExp.prototype.test);
var typeErrorCreate = unconstruct(TypeError);
function unapply(func) {
  return function(thisArg) {
    for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
      args[_key - 1] = arguments[_key];
    }
    return apply(func, thisArg, args);
  };
}
function unconstruct(func) {
  return function() {
    for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
      args[_key2] = arguments[_key2];
    }
    return construct(func, args);
  };
}
function addToSet(set2, array2) {
  if (setPrototypeOf) {
    setPrototypeOf(set2, null);
  }
  var l = array2.length;
  while (l--) {
    var element = array2[l];
    if (typeof element === "string") {
      var lcElement = stringToLowerCase(element);
      if (lcElement !== element) {
        if (!isFrozen(array2)) {
          array2[l] = lcElement;
        }
        element = lcElement;
      }
    }
    set2[element] = true;
  }
  return set2;
}
function clone(object2) {
  var newObject = create$1(null);
  var property = void 0;
  for (property in object2) {
    if (apply(hasOwnProperty$6, object2, [property])) {
      newObject[property] = object2[property];
    }
  }
  return newObject;
}
function lookupGetter(object2, prop) {
  while (object2 !== null) {
    var desc = getOwnPropertyDescriptor(object2, prop);
    if (desc) {
      if (desc.get) {
        return unapply(desc.get);
      }
      if (typeof desc.value === "function") {
        return unapply(desc.value);
      }
    }
    object2 = getPrototypeOf(object2);
  }
  function fallbackValue(element) {
    console.warn("fallback value for", element);
    return null;
  }
  return fallbackValue;
}
var html = freeze$1(["a", "abbr", "acronym", "address", "area", "article", "aside", "audio", "b", "bdi", "bdo", "big", "blink", "blockquote", "body", "br", "button", "canvas", "caption", "center", "cite", "code", "col", "colgroup", "content", "data", "datalist", "dd", "decorator", "del", "details", "dfn", "dialog", "dir", "div", "dl", "dt", "element", "em", "fieldset", "figcaption", "figure", "font", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "i", "img", "input", "ins", "kbd", "label", "legend", "li", "main", "map", "mark", "marquee", "menu", "menuitem", "meter", "nav", "nobr", "ol", "optgroup", "option", "output", "p", "picture", "pre", "progress", "q", "rp", "rt", "ruby", "s", "samp", "section", "select", "shadow", "small", "source", "spacer", "span", "strike", "strong", "style", "sub", "summary", "sup", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "time", "tr", "track", "tt", "u", "ul", "var", "video", "wbr"]);
var svg = freeze$1(["svg", "a", "altglyph", "altglyphdef", "altglyphitem", "animatecolor", "animatemotion", "animatetransform", "circle", "clippath", "defs", "desc", "ellipse", "filter", "font", "g", "glyph", "glyphref", "hkern", "image", "line", "lineargradient", "marker", "mask", "metadata", "mpath", "path", "pattern", "polygon", "polyline", "radialgradient", "rect", "stop", "style", "switch", "symbol", "text", "textpath", "title", "tref", "tspan", "view", "vkern"]);
var svgFilters = freeze$1(["feBlend", "feColorMatrix", "feComponentTransfer", "feComposite", "feConvolveMatrix", "feDiffuseLighting", "feDisplacementMap", "feDistantLight", "feFlood", "feFuncA", "feFuncB", "feFuncG", "feFuncR", "feGaussianBlur", "feMerge", "feMergeNode", "feMorphology", "feOffset", "fePointLight", "feSpecularLighting", "feSpotLight", "feTile", "feTurbulence"]);
var svgDisallowed = freeze$1(["animate", "color-profile", "cursor", "discard", "fedropshadow", "feimage", "font-face", "font-face-format", "font-face-name", "font-face-src", "font-face-uri", "foreignobject", "hatch", "hatchpath", "mesh", "meshgradient", "meshpatch", "meshrow", "missing-glyph", "script", "set", "solidcolor", "unknown", "use"]);
var mathMl = freeze$1(["math", "menclose", "merror", "mfenced", "mfrac", "mglyph", "mi", "mlabeledtr", "mmultiscripts", "mn", "mo", "mover", "mpadded", "mphantom", "mroot", "mrow", "ms", "mspace", "msqrt", "mstyle", "msub", "msup", "msubsup", "mtable", "mtd", "mtext", "mtr", "munder", "munderover"]);
var mathMlDisallowed = freeze$1(["maction", "maligngroup", "malignmark", "mlongdiv", "mscarries", "mscarry", "msgroup", "mstack", "msline", "msrow", "semantics", "annotation", "annotation-xml", "mprescripts", "none"]);
var text = freeze$1(["#text"]);
var html$1 = freeze$1(["accept", "action", "align", "alt", "autocapitalize", "autocomplete", "autopictureinpicture", "autoplay", "background", "bgcolor", "border", "capture", "cellpadding", "cellspacing", "checked", "cite", "class", "clear", "color", "cols", "colspan", "controls", "controlslist", "coords", "crossorigin", "datetime", "decoding", "default", "dir", "disabled", "disablepictureinpicture", "disableremoteplayback", "download", "draggable", "enctype", "enterkeyhint", "face", "for", "headers", "height", "hidden", "high", "href", "hreflang", "id", "inputmode", "integrity", "ismap", "kind", "label", "lang", "list", "loading", "loop", "low", "max", "maxlength", "media", "method", "min", "minlength", "multiple", "muted", "name", "noshade", "novalidate", "nowrap", "open", "optimum", "pattern", "placeholder", "playsinline", "poster", "preload", "pubdate", "radiogroup", "readonly", "rel", "required", "rev", "reversed", "role", "rows", "rowspan", "spellcheck", "scope", "selected", "shape", "size", "sizes", "span", "srclang", "start", "src", "srcset", "step", "style", "summary", "tabindex", "title", "translate", "type", "usemap", "valign", "value", "width", "xmlns", "slot"]);
var svg$1 = freeze$1(["accent-height", "accumulate", "additive", "alignment-baseline", "ascent", "attributename", "attributetype", "azimuth", "basefrequency", "baseline-shift", "begin", "bias", "by", "class", "clip", "clippathunits", "clip-path", "clip-rule", "color", "color-interpolation", "color-interpolation-filters", "color-profile", "color-rendering", "cx", "cy", "d", "dx", "dy", "diffuseconstant", "direction", "display", "divisor", "dur", "edgemode", "elevation", "end", "fill", "fill-opacity", "fill-rule", "filter", "filterunits", "flood-color", "flood-opacity", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "fx", "fy", "g1", "g2", "glyph-name", "glyphref", "gradientunits", "gradienttransform", "height", "href", "id", "image-rendering", "in", "in2", "k", "k1", "k2", "k3", "k4", "kerning", "keypoints", "keysplines", "keytimes", "lang", "lengthadjust", "letter-spacing", "kernelmatrix", "kernelunitlength", "lighting-color", "local", "marker-end", "marker-mid", "marker-start", "markerheight", "markerunits", "markerwidth", "maskcontentunits", "maskunits", "max", "mask", "media", "method", "mode", "min", "name", "numoctaves", "offset", "operator", "opacity", "order", "orient", "orientation", "origin", "overflow", "paint-order", "path", "pathlength", "patterncontentunits", "patterntransform", "patternunits", "points", "preservealpha", "preserveaspectratio", "primitiveunits", "r", "rx", "ry", "radius", "refx", "refy", "repeatcount", "repeatdur", "restart", "result", "rotate", "scale", "seed", "shape-rendering", "specularconstant", "specularexponent", "spreadmethod", "startoffset", "stddeviation", "stitchtiles", "stop-color", "stop-opacity", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke", "stroke-width", "style", "surfacescale", "systemlanguage", "tabindex", "targetx", "targety", "transform", "text-anchor", "text-decoration", "text-rendering", "textlength", "type", "u1", "u2", "unicode", "values", "viewbox", "visibility", "version", "vert-adv-y", "vert-origin-x", "vert-origin-y", "width", "word-spacing", "wrap", "writing-mode", "xchannelselector", "ychannelselector", "x", "x1", "x2", "xmlns", "y", "y1", "y2", "z", "zoomandpan"]);
var mathMl$1 = freeze$1(["accent", "accentunder", "align", "bevelled", "close", "columnsalign", "columnlines", "columnspan", "denomalign", "depth", "dir", "display", "displaystyle", "encoding", "fence", "frame", "height", "href", "id", "largeop", "length", "linethickness", "lspace", "lquote", "mathbackground", "mathcolor", "mathsize", "mathvariant", "maxsize", "minsize", "movablelimits", "notation", "numalign", "open", "rowalign", "rowlines", "rowspacing", "rowspan", "rspace", "rquote", "scriptlevel", "scriptminsize", "scriptsizemultiplier", "selection", "separator", "separators", "stretchy", "subscriptshift", "supscriptshift", "symmetric", "voffset", "width", "xmlns"]);
var xml = freeze$1(["xlink:href", "xml:id", "xlink:title", "xml:space", "xmlns:xlink"]);
var MUSTACHE_EXPR = seal(/\{\{[\s\S]*|[\s\S]*\}\}/gm);
var ERB_EXPR = seal(/<%[\s\S]*|[\s\S]*%>/gm);
var DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]/);
var ARIA_ATTR = seal(/^aria-[\-\w]+$/);
var IS_ALLOWED_URI = seal(
  /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i
  // eslint-disable-line no-useless-escape
);
var IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
var ATTR_WHITESPACE = seal(
  /[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g
  // eslint-disable-line no-control-regex
);
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function(obj) {
  return typeof obj;
} : function(obj) {
  return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
function _toConsumableArray$1(arr) {
  if (Array.isArray(arr)) {
    for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
      arr2[i] = arr[i];
    }
    return arr2;
  } else {
    return Array.from(arr);
  }
}
var getGlobal = function getGlobal2() {
  return typeof window === "undefined" ? null : window;
};
var _createTrustedTypesPolicy = function _createTrustedTypesPolicy2(trustedTypes, document2) {
  if ((typeof trustedTypes === "undefined" ? "undefined" : _typeof(trustedTypes)) !== "object" || typeof trustedTypes.createPolicy !== "function") {
    return null;
  }
  var suffix = null;
  var ATTR_NAME = "data-tt-policy-suffix";
  if (document2.currentScript && document2.currentScript.hasAttribute(ATTR_NAME)) {
    suffix = document2.currentScript.getAttribute(ATTR_NAME);
  }
  var policyName = "dompurify" + (suffix ? "#" + suffix : "");
  try {
    return trustedTypes.createPolicy(policyName, {
      createHTML: function createHTML(html$$1) {
        return html$$1;
      }
    });
  } catch (_) {
    console.warn("TrustedTypes policy " + policyName + " could not be created.");
    return null;
  }
};
function createDOMPurify() {
  var window2 = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : getGlobal();
  var DOMPurify = function DOMPurify2(root3) {
    return createDOMPurify(root3);
  };
  DOMPurify.version = "2.3.1";
  DOMPurify.removed = [];
  if (!window2 || !window2.document || window2.document.nodeType !== 9) {
    DOMPurify.isSupported = false;
    return DOMPurify;
  }
  var originalDocument = window2.document;
  var document2 = window2.document;
  var DocumentFragment = window2.DocumentFragment, HTMLTemplateElement = window2.HTMLTemplateElement, Node6 = window2.Node, Element2 = window2.Element, NodeFilter = window2.NodeFilter, _window$NamedNodeMap = window2.NamedNodeMap, NamedNodeMap = _window$NamedNodeMap === void 0 ? window2.NamedNodeMap || window2.MozNamedAttrMap : _window$NamedNodeMap, Text2 = window2.Text, Comment3 = window2.Comment, DOMParser2 = window2.DOMParser, trustedTypes = window2.trustedTypes;
  var ElementPrototype = Element2.prototype;
  var cloneNode2 = lookupGetter(ElementPrototype, "cloneNode");
  var getNextSibling = lookupGetter(ElementPrototype, "nextSibling");
  var getChildNodes = lookupGetter(ElementPrototype, "childNodes");
  var getParentNode = lookupGetter(ElementPrototype, "parentNode");
  if (typeof HTMLTemplateElement === "function") {
    var template = document2.createElement("template");
    if (template.content && template.content.ownerDocument) {
      document2 = template.content.ownerDocument;
    }
  }
  var trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, originalDocument);
  var emptyHTML = trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML("") : "";
  var _document = document2, implementation = _document.implementation, createNodeIterator = _document.createNodeIterator, createDocumentFragment = _document.createDocumentFragment, getElementsByTagName = _document.getElementsByTagName;
  var importNode = originalDocument.importNode;
  var documentMode = {};
  try {
    documentMode = clone(document2).documentMode ? document2.documentMode : {};
  } catch (_) {
  }
  var hooks = {};
  DOMPurify.isSupported = typeof getParentNode === "function" && implementation && typeof implementation.createHTMLDocument !== "undefined" && documentMode !== 9;
  var MUSTACHE_EXPR$$1 = MUSTACHE_EXPR, ERB_EXPR$$1 = ERB_EXPR, DATA_ATTR$$1 = DATA_ATTR, ARIA_ATTR$$1 = ARIA_ATTR, IS_SCRIPT_OR_DATA$$1 = IS_SCRIPT_OR_DATA, ATTR_WHITESPACE$$1 = ATTR_WHITESPACE;
  var IS_ALLOWED_URI$$1 = IS_ALLOWED_URI;
  var ALLOWED_TAGS = null;
  var DEFAULT_ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray$1(html), _toConsumableArray$1(svg), _toConsumableArray$1(svgFilters), _toConsumableArray$1(mathMl), _toConsumableArray$1(text)));
  var ALLOWED_ATTR = null;
  var DEFAULT_ALLOWED_ATTR = addToSet({}, [].concat(_toConsumableArray$1(html$1), _toConsumableArray$1(svg$1), _toConsumableArray$1(mathMl$1), _toConsumableArray$1(xml)));
  var FORBID_TAGS = null;
  var FORBID_ATTR = null;
  var ALLOW_ARIA_ATTR = true;
  var ALLOW_DATA_ATTR = true;
  var ALLOW_UNKNOWN_PROTOCOLS = false;
  var SAFE_FOR_TEMPLATES = false;
  var WHOLE_DOCUMENT = false;
  var SET_CONFIG = false;
  var FORCE_BODY = false;
  var RETURN_DOM = false;
  var RETURN_DOM_FRAGMENT = false;
  var RETURN_DOM_IMPORT = true;
  var RETURN_TRUSTED_TYPE = false;
  var SANITIZE_DOM = true;
  var KEEP_CONTENT = true;
  var IN_PLACE = false;
  var USE_PROFILES = {};
  var FORBID_CONTENTS = null;
  var DEFAULT_FORBID_CONTENTS = addToSet({}, ["annotation-xml", "audio", "colgroup", "desc", "foreignobject", "head", "iframe", "math", "mi", "mn", "mo", "ms", "mtext", "noembed", "noframes", "noscript", "plaintext", "script", "style", "svg", "template", "thead", "title", "video", "xmp"]);
  var DATA_URI_TAGS = null;
  var DEFAULT_DATA_URI_TAGS = addToSet({}, ["audio", "video", "img", "source", "image", "track"]);
  var URI_SAFE_ATTRIBUTES = null;
  var DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ["alt", "class", "for", "id", "label", "name", "pattern", "placeholder", "role", "summary", "title", "value", "style", "xmlns"]);
  var MATHML_NAMESPACE = "http://www.w3.org/1998/Math/MathML";
  var SVG_NAMESPACE = "http://www.w3.org/2000/svg";
  var HTML_NAMESPACE = "http://www.w3.org/1999/xhtml";
  var NAMESPACE = HTML_NAMESPACE;
  var IS_EMPTY_INPUT = false;
  var CONFIG = null;
  var formElement = document2.createElement("form");
  var _parseConfig = function _parseConfig2(cfg) {
    if (CONFIG && CONFIG === cfg) {
      return;
    }
    if (!cfg || (typeof cfg === "undefined" ? "undefined" : _typeof(cfg)) !== "object") {
      cfg = {};
    }
    cfg = clone(cfg);
    ALLOWED_TAGS = "ALLOWED_TAGS" in cfg ? addToSet({}, cfg.ALLOWED_TAGS) : DEFAULT_ALLOWED_TAGS;
    ALLOWED_ATTR = "ALLOWED_ATTR" in cfg ? addToSet({}, cfg.ALLOWED_ATTR) : DEFAULT_ALLOWED_ATTR;
    URI_SAFE_ATTRIBUTES = "ADD_URI_SAFE_ATTR" in cfg ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR) : DEFAULT_URI_SAFE_ATTRIBUTES;
    DATA_URI_TAGS = "ADD_DATA_URI_TAGS" in cfg ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS) : DEFAULT_DATA_URI_TAGS;
    FORBID_CONTENTS = "FORBID_CONTENTS" in cfg ? addToSet({}, cfg.FORBID_CONTENTS) : DEFAULT_FORBID_CONTENTS;
    FORBID_TAGS = "FORBID_TAGS" in cfg ? addToSet({}, cfg.FORBID_TAGS) : {};
    FORBID_ATTR = "FORBID_ATTR" in cfg ? addToSet({}, cfg.FORBID_ATTR) : {};
    USE_PROFILES = "USE_PROFILES" in cfg ? cfg.USE_PROFILES : false;
    ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false;
    ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false;
    ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false;
    SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false;
    WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false;
    RETURN_DOM = cfg.RETURN_DOM || false;
    RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false;
    RETURN_DOM_IMPORT = cfg.RETURN_DOM_IMPORT !== false;
    RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false;
    FORCE_BODY = cfg.FORCE_BODY || false;
    SANITIZE_DOM = cfg.SANITIZE_DOM !== false;
    KEEP_CONTENT = cfg.KEEP_CONTENT !== false;
    IN_PLACE = cfg.IN_PLACE || false;
    IS_ALLOWED_URI$$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI$$1;
    NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
    if (SAFE_FOR_TEMPLATES) {
      ALLOW_DATA_ATTR = false;
    }
    if (RETURN_DOM_FRAGMENT) {
      RETURN_DOM = true;
    }
    if (USE_PROFILES) {
      ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray$1(text)));
      ALLOWED_ATTR = [];
      if (USE_PROFILES.html === true) {
        addToSet(ALLOWED_TAGS, html);
        addToSet(ALLOWED_ATTR, html$1);
      }
      if (USE_PROFILES.svg === true) {
        addToSet(ALLOWED_TAGS, svg);
        addToSet(ALLOWED_ATTR, svg$1);
        addToSet(ALLOWED_ATTR, xml);
      }
      if (USE_PROFILES.svgFilters === true) {
        addToSet(ALLOWED_TAGS, svgFilters);
        addToSet(ALLOWED_ATTR, svg$1);
        addToSet(ALLOWED_ATTR, xml);
      }
      if (USE_PROFILES.mathMl === true) {
        addToSet(ALLOWED_TAGS, mathMl);
        addToSet(ALLOWED_ATTR, mathMl$1);
        addToSet(ALLOWED_ATTR, xml);
      }
    }
    if (cfg.ADD_TAGS) {
      if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
        ALLOWED_TAGS = clone(ALLOWED_TAGS);
      }
      addToSet(ALLOWED_TAGS, cfg.ADD_TAGS);
    }
    if (cfg.ADD_ATTR) {
      if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
        ALLOWED_ATTR = clone(ALLOWED_ATTR);
      }
      addToSet(ALLOWED_ATTR, cfg.ADD_ATTR);
    }
    if (cfg.ADD_URI_SAFE_ATTR) {
      addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR);
    }
    if (cfg.FORBID_CONTENTS) {
      if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
        FORBID_CONTENTS = clone(FORBID_CONTENTS);
      }
      addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS);
    }
    if (KEEP_CONTENT) {
      ALLOWED_TAGS["#text"] = true;
    }
    if (WHOLE_DOCUMENT) {
      addToSet(ALLOWED_TAGS, ["html", "head", "body"]);
    }
    if (ALLOWED_TAGS.table) {
      addToSet(ALLOWED_TAGS, ["tbody"]);
      delete FORBID_TAGS.tbody;
    }
    if (freeze$1) {
      freeze$1(cfg);
    }
    CONFIG = cfg;
  };
  var MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ["mi", "mo", "mn", "ms", "mtext"]);
  var HTML_INTEGRATION_POINTS = addToSet({}, ["foreignobject", "desc", "title", "annotation-xml"]);
  var ALL_SVG_TAGS = addToSet({}, svg);
  addToSet(ALL_SVG_TAGS, svgFilters);
  addToSet(ALL_SVG_TAGS, svgDisallowed);
  var ALL_MATHML_TAGS = addToSet({}, mathMl);
  addToSet(ALL_MATHML_TAGS, mathMlDisallowed);
  var _checkValidNamespace = function _checkValidNamespace2(element) {
    var parent = getParentNode(element);
    if (!parent || !parent.tagName) {
      parent = {
        namespaceURI: HTML_NAMESPACE,
        tagName: "template"
      };
    }
    var tagName = stringToLowerCase(element.tagName);
    var parentTagName = stringToLowerCase(parent.tagName);
    if (element.namespaceURI === SVG_NAMESPACE) {
      if (parent.namespaceURI === HTML_NAMESPACE) {
        return tagName === "svg";
      }
      if (parent.namespaceURI === MATHML_NAMESPACE) {
        return tagName === "svg" && (parentTagName === "annotation-xml" || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
      }
      return Boolean(ALL_SVG_TAGS[tagName]);
    }
    if (element.namespaceURI === MATHML_NAMESPACE) {
      if (parent.namespaceURI === HTML_NAMESPACE) {
        return tagName === "math";
      }
      if (parent.namespaceURI === SVG_NAMESPACE) {
        return tagName === "math" && HTML_INTEGRATION_POINTS[parentTagName];
      }
      return Boolean(ALL_MATHML_TAGS[tagName]);
    }
    if (element.namespaceURI === HTML_NAMESPACE) {
      if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
        return false;
      }
      if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
        return false;
      }
      var commonSvgAndHTMLElements = addToSet({}, ["title", "style", "font", "a", "script"]);
      return !ALL_MATHML_TAGS[tagName] && (commonSvgAndHTMLElements[tagName] || !ALL_SVG_TAGS[tagName]);
    }
    return false;
  };
  var _forceRemove = function _forceRemove2(node2) {
    arrayPush(DOMPurify.removed, { element: node2 });
    try {
      node2.parentNode.removeChild(node2);
    } catch (_) {
      try {
        node2.outerHTML = emptyHTML;
      } catch (_2) {
        node2.remove();
      }
    }
  };
  var _removeAttribute = function _removeAttribute2(name, node2) {
    try {
      arrayPush(DOMPurify.removed, {
        attribute: node2.getAttributeNode(name),
        from: node2
      });
    } catch (_) {
      arrayPush(DOMPurify.removed, {
        attribute: null,
        from: node2
      });
    }
    node2.removeAttribute(name);
    if (name === "is" && !ALLOWED_ATTR[name]) {
      if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
        try {
          _forceRemove(node2);
        } catch (_) {
        }
      } else {
        try {
          node2.setAttribute(name, "");
        } catch (_) {
        }
      }
    }
  };
  var _initDocument = function _initDocument2(dirty) {
    var doc2 = void 0;
    var leadingWhitespace = void 0;
    if (FORCE_BODY) {
      dirty = "<remove></remove>" + dirty;
    } else {
      var matches = stringMatch(dirty, /^[\r\n\t ]+/);
      leadingWhitespace = matches && matches[0];
    }
    var dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
    if (NAMESPACE === HTML_NAMESPACE) {
      try {
        doc2 = new DOMParser2().parseFromString(dirtyPayload, "text/html");
      } catch (_) {
      }
    }
    if (!doc2 || !doc2.documentElement) {
      doc2 = implementation.createDocument(NAMESPACE, "template", null);
      try {
        doc2.documentElement.innerHTML = IS_EMPTY_INPUT ? "" : dirtyPayload;
      } catch (_) {
      }
    }
    var body = doc2.body || doc2.documentElement;
    if (dirty && leadingWhitespace) {
      body.insertBefore(document2.createTextNode(leadingWhitespace), body.childNodes[0] || null);
    }
    if (NAMESPACE === HTML_NAMESPACE) {
      return getElementsByTagName.call(doc2, WHOLE_DOCUMENT ? "html" : "body")[0];
    }
    return WHOLE_DOCUMENT ? doc2.documentElement : body;
  };
  var _createIterator = function _createIterator2(root3) {
    return createNodeIterator.call(root3.ownerDocument || root3, root3, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT, null, false);
  };
  var _isClobbered = function _isClobbered2(elm) {
    if (elm instanceof Text2 || elm instanceof Comment3) {
      return false;
    }
    if (typeof elm.nodeName !== "string" || typeof elm.textContent !== "string" || typeof elm.removeChild !== "function" || !(elm.attributes instanceof NamedNodeMap) || typeof elm.removeAttribute !== "function" || typeof elm.setAttribute !== "function" || typeof elm.namespaceURI !== "string" || typeof elm.insertBefore !== "function") {
      return true;
    }
    return false;
  };
  var _isNode = function _isNode2(object2) {
    return (typeof Node6 === "undefined" ? "undefined" : _typeof(Node6)) === "object" ? object2 instanceof Node6 : object2 && (typeof object2 === "undefined" ? "undefined" : _typeof(object2)) === "object" && typeof object2.nodeType === "number" && typeof object2.nodeName === "string";
  };
  var _executeHook = function _executeHook2(entryPoint, currentNode, data) {
    if (!hooks[entryPoint]) {
      return;
    }
    arrayForEach(hooks[entryPoint], function(hook) {
      hook.call(DOMPurify, currentNode, data, CONFIG);
    });
  };
  var _sanitizeElements = function _sanitizeElements2(currentNode) {
    var content = void 0;
    _executeHook("beforeSanitizeElements", currentNode, null);
    if (_isClobbered(currentNode)) {
      _forceRemove(currentNode);
      return true;
    }
    if (stringMatch(currentNode.nodeName, /[\u0080-\uFFFF]/)) {
      _forceRemove(currentNode);
      return true;
    }
    var tagName = stringToLowerCase(currentNode.nodeName);
    _executeHook("uponSanitizeElement", currentNode, {
      tagName,
      allowedTags: ALLOWED_TAGS
    });
    if (!_isNode(currentNode.firstElementChild) && (!_isNode(currentNode.content) || !_isNode(currentNode.content.firstElementChild)) && regExpTest(/<[/\w]/g, currentNode.innerHTML) && regExpTest(/<[/\w]/g, currentNode.textContent)) {
      _forceRemove(currentNode);
      return true;
    }
    if (tagName === "select" && regExpTest(/<template/i, currentNode.innerHTML)) {
      _forceRemove(currentNode);
      return true;
    }
    if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
      if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
        var parentNode = getParentNode(currentNode) || currentNode.parentNode;
        var childNodes = getChildNodes(currentNode) || currentNode.childNodes;
        if (childNodes && parentNode) {
          var childCount = childNodes.length;
          for (var i = childCount - 1; i >= 0; --i) {
            parentNode.insertBefore(cloneNode2(childNodes[i], true), getNextSibling(currentNode));
          }
        }
      }
      _forceRemove(currentNode);
      return true;
    }
    if (currentNode instanceof Element2 && !_checkValidNamespace(currentNode)) {
      _forceRemove(currentNode);
      return true;
    }
    if ((tagName === "noscript" || tagName === "noembed") && regExpTest(/<\/no(script|embed)/i, currentNode.innerHTML)) {
      _forceRemove(currentNode);
      return true;
    }
    if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) {
      content = currentNode.textContent;
      content = stringReplace(content, MUSTACHE_EXPR$$1, " ");
      content = stringReplace(content, ERB_EXPR$$1, " ");
      if (currentNode.textContent !== content) {
        arrayPush(DOMPurify.removed, { element: currentNode.cloneNode() });
        currentNode.textContent = content;
      }
    }
    _executeHook("afterSanitizeElements", currentNode, null);
    return false;
  };
  var _isValidAttribute = function _isValidAttribute2(lcTag, lcName, value) {
    if (SANITIZE_DOM && (lcName === "id" || lcName === "name") && (value in document2 || value in formElement)) {
      return false;
    }
    if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR$$1, lcName))
      ;
    else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$$1, lcName))
      ;
    else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
      return false;
    } else if (URI_SAFE_ATTRIBUTES[lcName])
      ;
    else if (regExpTest(IS_ALLOWED_URI$$1, stringReplace(value, ATTR_WHITESPACE$$1, "")))
      ;
    else if ((lcName === "src" || lcName === "xlink:href" || lcName === "href") && lcTag !== "script" && stringIndexOf(value, "data:") === 0 && DATA_URI_TAGS[lcTag])
      ;
    else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$$1, stringReplace(value, ATTR_WHITESPACE$$1, "")))
      ;
    else if (!value)
      ;
    else {
      return false;
    }
    return true;
  };
  var _sanitizeAttributes = function _sanitizeAttributes2(currentNode) {
    var attr = void 0;
    var value = void 0;
    var lcName = void 0;
    var l = void 0;
    _executeHook("beforeSanitizeAttributes", currentNode, null);
    var attributes = currentNode.attributes;
    if (!attributes) {
      return;
    }
    var hookEvent = {
      attrName: "",
      attrValue: "",
      keepAttr: true,
      allowedAttributes: ALLOWED_ATTR
    };
    l = attributes.length;
    while (l--) {
      attr = attributes[l];
      var _attr = attr, name = _attr.name, namespaceURI = _attr.namespaceURI;
      value = stringTrim(attr.value);
      lcName = stringToLowerCase(name);
      hookEvent.attrName = lcName;
      hookEvent.attrValue = value;
      hookEvent.keepAttr = true;
      hookEvent.forceKeepAttr = void 0;
      _executeHook("uponSanitizeAttribute", currentNode, hookEvent);
      value = hookEvent.attrValue;
      if (hookEvent.forceKeepAttr) {
        continue;
      }
      _removeAttribute(name, currentNode);
      if (!hookEvent.keepAttr) {
        continue;
      }
      if (regExpTest(/\/>/i, value)) {
        _removeAttribute(name, currentNode);
        continue;
      }
      if (SAFE_FOR_TEMPLATES) {
        value = stringReplace(value, MUSTACHE_EXPR$$1, " ");
        value = stringReplace(value, ERB_EXPR$$1, " ");
      }
      var lcTag = currentNode.nodeName.toLowerCase();
      if (!_isValidAttribute(lcTag, lcName, value)) {
        continue;
      }
      try {
        if (namespaceURI) {
          currentNode.setAttributeNS(namespaceURI, name, value);
        } else {
          currentNode.setAttribute(name, value);
        }
        arrayPop(DOMPurify.removed);
      } catch (_) {
      }
    }
    _executeHook("afterSanitizeAttributes", currentNode, null);
  };
  var _sanitizeShadowDOM = function _sanitizeShadowDOM2(fragment) {
    var shadowNode = void 0;
    var shadowIterator = _createIterator(fragment);
    _executeHook("beforeSanitizeShadowDOM", fragment, null);
    while (shadowNode = shadowIterator.nextNode()) {
      _executeHook("uponSanitizeShadowNode", shadowNode, null);
      if (_sanitizeElements(shadowNode)) {
        continue;
      }
      if (shadowNode.content instanceof DocumentFragment) {
        _sanitizeShadowDOM2(shadowNode.content);
      }
      _sanitizeAttributes(shadowNode);
    }
    _executeHook("afterSanitizeShadowDOM", fragment, null);
  };
  DOMPurify.sanitize = function(dirty, cfg) {
    var body = void 0;
    var importedNode = void 0;
    var currentNode = void 0;
    var oldNode = void 0;
    var returnNode = void 0;
    IS_EMPTY_INPUT = !dirty;
    if (IS_EMPTY_INPUT) {
      dirty = "<!-->";
    }
    if (typeof dirty !== "string" && !_isNode(dirty)) {
      if (typeof dirty.toString !== "function") {
        throw typeErrorCreate("toString is not a function");
      } else {
        dirty = dirty.toString();
        if (typeof dirty !== "string") {
          throw typeErrorCreate("dirty is not a string, aborting");
        }
      }
    }
    if (!DOMPurify.isSupported) {
      if (_typeof(window2.toStaticHTML) === "object" || typeof window2.toStaticHTML === "function") {
        if (typeof dirty === "string") {
          return window2.toStaticHTML(dirty);
        }
        if (_isNode(dirty)) {
          return window2.toStaticHTML(dirty.outerHTML);
        }
      }
      return dirty;
    }
    if (!SET_CONFIG) {
      _parseConfig(cfg);
    }
    DOMPurify.removed = [];
    if (typeof dirty === "string") {
      IN_PLACE = false;
    }
    if (IN_PLACE)
      ;
    else if (dirty instanceof Node6) {
      body = _initDocument("<!---->");
      importedNode = body.ownerDocument.importNode(dirty, true);
      if (importedNode.nodeType === 1 && importedNode.nodeName === "BODY") {
        body = importedNode;
      } else if (importedNode.nodeName === "HTML") {
        body = importedNode;
      } else {
        body.appendChild(importedNode);
      }
    } else {
      if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT && // eslint-disable-next-line unicorn/prefer-includes
      dirty.indexOf("<") === -1) {
        return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
      }
      body = _initDocument(dirty);
      if (!body) {
        return RETURN_DOM ? null : emptyHTML;
      }
    }
    if (body && FORCE_BODY) {
      _forceRemove(body.firstChild);
    }
    var nodeIterator = _createIterator(IN_PLACE ? dirty : body);
    while (currentNode = nodeIterator.nextNode()) {
      if (currentNode.nodeType === 3 && currentNode === oldNode) {
        continue;
      }
      if (_sanitizeElements(currentNode)) {
        continue;
      }
      if (currentNode.content instanceof DocumentFragment) {
        _sanitizeShadowDOM(currentNode.content);
      }
      _sanitizeAttributes(currentNode);
      oldNode = currentNode;
    }
    oldNode = null;
    if (IN_PLACE) {
      return dirty;
    }
    if (RETURN_DOM) {
      if (RETURN_DOM_FRAGMENT) {
        returnNode = createDocumentFragment.call(body.ownerDocument);
        while (body.firstChild) {
          returnNode.appendChild(body.firstChild);
        }
      } else {
        returnNode = body;
      }
      if (RETURN_DOM_IMPORT) {
        returnNode = importNode.call(originalDocument, returnNode, true);
      }
      return returnNode;
    }
    var serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
    if (SAFE_FOR_TEMPLATES) {
      serializedHTML = stringReplace(serializedHTML, MUSTACHE_EXPR$$1, " ");
      serializedHTML = stringReplace(serializedHTML, ERB_EXPR$$1, " ");
    }
    return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
  };
  DOMPurify.setConfig = function(cfg) {
    _parseConfig(cfg);
    SET_CONFIG = true;
  };
  DOMPurify.clearConfig = function() {
    CONFIG = null;
    SET_CONFIG = false;
  };
  DOMPurify.isValidAttribute = function(tag3, attr, value) {
    if (!CONFIG) {
      _parseConfig({});
    }
    var lcTag = stringToLowerCase(tag3);
    var lcName = stringToLowerCase(attr);
    return _isValidAttribute(lcTag, lcName, value);
  };
  DOMPurify.addHook = function(entryPoint, hookFunction) {
    if (typeof hookFunction !== "function") {
      return;
    }
    hooks[entryPoint] = hooks[entryPoint] || [];
    arrayPush(hooks[entryPoint], hookFunction);
  };
  DOMPurify.removeHook = function(entryPoint) {
    if (hooks[entryPoint]) {
      arrayPop(hooks[entryPoint]);
    }
  };
  DOMPurify.removeHooks = function(entryPoint) {
    if (hooks[entryPoint]) {
      hooks[entryPoint] = [];
    }
  };
  DOMPurify.removeAllHooks = function() {
    hooks = {};
  };
  return DOMPurify;
}
var purify = createDOMPurify();
purify.version;
purify.isSupported;
const sanitize$1 = purify.sanitize;
purify.setConfig;
purify.clearConfig;
purify.isValidAttribute;
const addHook = purify.addHook;
const removeHook = purify.removeHook;
purify.removeHooks;
purify.removeAllHooks;
let safeProcess;
if (typeof globals.vscode !== "undefined" && typeof globals.vscode.process !== "undefined") {
  const sandboxProcess = globals.vscode.process;
  safeProcess = {
    get platform() {
      return sandboxProcess.platform;
    },
    get arch() {
      return sandboxProcess.arch;
    },
    get env() {
      return sandboxProcess.env;
    },
    cwd() {
      return sandboxProcess.cwd();
    }
  };
} else if (typeof process !== "undefined") {
  safeProcess = {
    get platform() {
      return process.platform;
    },
    get arch() {
      return process.arch;
    },
    get env() {
      return process.env;
    },
    cwd() {
      return process.env["VSCODE_CWD"] || process.cwd();
    }
  };
} else {
  safeProcess = {
    // Supported
    get platform() {
      return isWindows ? "win32" : isMacintosh ? "darwin" : "linux";
    },
    get arch() {
      return void 0;
    },
    // Unsupported
    get env() {
      return {};
    },
    cwd() {
      return "/";
    }
  };
}
const cwd$1 = safeProcess.cwd;
const env$1 = safeProcess.env;
const platform$1 = safeProcess.platform;
const CHAR_UPPERCASE_A = 65;
const CHAR_LOWERCASE_A = 97;
const CHAR_UPPERCASE_Z = 90;
const CHAR_LOWERCASE_Z = 122;
const CHAR_DOT = 46;
const CHAR_FORWARD_SLASH = 47;
const CHAR_BACKWARD_SLASH = 92;
const CHAR_COLON = 58;
const CHAR_QUESTION_MARK = 63;
class ErrorInvalidArgType extends Error {
  constructor(name, expected, actual) {
    let determiner;
    if (typeof expected === "string" && expected.indexOf("not ") === 0) {
      determiner = "must not be";
      expected = expected.replace(/^not /, "");
    } else {
      determiner = "must be";
    }
    const type = name.indexOf(".") !== -1 ? "property" : "argument";
    let msg = `The "${name}" ${type} ${determiner} of type ${expected}`;
    msg += `. Received type ${typeof actual}`;
    super(msg);
    this.code = "ERR_INVALID_ARG_TYPE";
  }
}
function validateObject(pathObject, name) {
  if (pathObject === null || typeof pathObject !== "object") {
    throw new ErrorInvalidArgType(name, "Object", pathObject);
  }
}
function validateString(value, name) {
  if (typeof value !== "string") {
    throw new ErrorInvalidArgType(name, "string", value);
  }
}
const platformIsWin32 = platform$1 === "win32";
function isPathSeparator$1(code) {
  return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
}
function isPosixPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH;
}
function isWindowsDeviceRoot(code) {
  return code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z || code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z;
}
function normalizeString(path2, allowAboveRoot, separator, isPathSeparator2) {
  let res = "";
  let lastSegmentLength = 0;
  let lastSlash = -1;
  let dots = 0;
  let code = 0;
  for (let i = 0; i <= path2.length; ++i) {
    if (i < path2.length) {
      code = path2.charCodeAt(i);
    } else if (isPathSeparator2(code)) {
      break;
    } else {
      code = CHAR_FORWARD_SLASH;
    }
    if (isPathSeparator2(code)) {
      if (lastSlash === i - 1 || dots === 1)
        ;
      else if (dots === 2) {
        if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== CHAR_DOT || res.charCodeAt(res.length - 2) !== CHAR_DOT) {
          if (res.length > 2) {
            const lastSlashIndex = res.lastIndexOf(separator);
            if (lastSlashIndex === -1) {
              res = "";
              lastSegmentLength = 0;
            } else {
              res = res.slice(0, lastSlashIndex);
              lastSegmentLength = res.length - 1 - res.lastIndexOf(separator);
            }
            lastSlash = i;
            dots = 0;
            continue;
          } else if (res.length !== 0) {
            res = "";
            lastSegmentLength = 0;
            lastSlash = i;
            dots = 0;
            continue;
          }
        }
        if (allowAboveRoot) {
          res += res.length > 0 ? `${separator}..` : "..";
          lastSegmentLength = 2;
        }
      } else {
        if (res.length > 0) {
          res += `${separator}${path2.slice(lastSlash + 1, i)}`;
        } else {
          res = path2.slice(lastSlash + 1, i);
        }
        lastSegmentLength = i - lastSlash - 1;
      }
      lastSlash = i;
      dots = 0;
    } else if (code === CHAR_DOT && dots !== -1) {
      ++dots;
    } else {
      dots = -1;
    }
  }
  return res;
}
function _format(sep2, pathObject) {
  validateObject(pathObject, "pathObject");
  const dir = pathObject.dir || pathObject.root;
  const base2 = pathObject.base || `${pathObject.name || ""}${pathObject.ext || ""}`;
  if (!dir) {
    return base2;
  }
  return dir === pathObject.root ? `${dir}${base2}` : `${dir}${sep2}${base2}`;
}
const win32 = {
  // path.resolve([from ...], to)
  resolve(...pathSegments) {
    let resolvedDevice = "";
    let resolvedTail = "";
    let resolvedAbsolute = false;
    for (let i = pathSegments.length - 1; i >= -1; i--) {
      let path2;
      if (i >= 0) {
        path2 = pathSegments[i];
        validateString(path2, "path");
        if (path2.length === 0) {
          continue;
        }
      } else if (resolvedDevice.length === 0) {
        path2 = cwd$1();
      } else {
        path2 = env$1[`=${resolvedDevice}`] || cwd$1();
        if (path2 === void 0 || path2.slice(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() && path2.charCodeAt(2) === CHAR_BACKWARD_SLASH) {
          path2 = `${resolvedDevice}\\`;
        }
      }
      const len = path2.length;
      let rootEnd = 0;
      let device = "";
      let isAbsolute2 = false;
      const code = path2.charCodeAt(0);
      if (len === 1) {
        if (isPathSeparator$1(code)) {
          rootEnd = 1;
          isAbsolute2 = true;
        }
      } else if (isPathSeparator$1(code)) {
        isAbsolute2 = true;
        if (isPathSeparator$1(path2.charCodeAt(1))) {
          let j = 2;
          let last2 = j;
          while (j < len && !isPathSeparator$1(path2.charCodeAt(j))) {
            j++;
          }
          if (j < len && j !== last2) {
            const firstPart = path2.slice(last2, j);
            last2 = j;
            while (j < len && isPathSeparator$1(path2.charCodeAt(j))) {
              j++;
            }
            if (j < len && j !== last2) {
              last2 = j;
              while (j < len && !isPathSeparator$1(path2.charCodeAt(j))) {
                j++;
              }
              if (j === len || j !== last2) {
                device = `\\\\${firstPart}\\${path2.slice(last2, j)}`;
                rootEnd = j;
              }
            }
          }
        } else {
          rootEnd = 1;
        }
      } else if (isWindowsDeviceRoot(code) && path2.charCodeAt(1) === CHAR_COLON) {
        device = path2.slice(0, 2);
        rootEnd = 2;
        if (len > 2 && isPathSeparator$1(path2.charCodeAt(2))) {
          isAbsolute2 = true;
          rootEnd = 3;
        }
      }
      if (device.length > 0) {
        if (resolvedDevice.length > 0) {
          if (device.toLowerCase() !== resolvedDevice.toLowerCase()) {
            continue;
          }
        } else {
          resolvedDevice = device;
        }
      }
      if (resolvedAbsolute) {
        if (resolvedDevice.length > 0) {
          break;
        }
      } else {
        resolvedTail = `${path2.slice(rootEnd)}\\${resolvedTail}`;
        resolvedAbsolute = isAbsolute2;
        if (isAbsolute2 && resolvedDevice.length > 0) {
          break;
        }
      }
    }
    resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, "\\", isPathSeparator$1);
    return resolvedAbsolute ? `${resolvedDevice}\\${resolvedTail}` : `${resolvedDevice}${resolvedTail}` || ".";
  },
  normalize(path2) {
    validateString(path2, "path");
    const len = path2.length;
    if (len === 0) {
      return ".";
    }
    let rootEnd = 0;
    let device;
    let isAbsolute2 = false;
    const code = path2.charCodeAt(0);
    if (len === 1) {
      return isPosixPathSeparator(code) ? "\\" : path2;
    }
    if (isPathSeparator$1(code)) {
      isAbsolute2 = true;
      if (isPathSeparator$1(path2.charCodeAt(1))) {
        let j = 2;
        let last2 = j;
        while (j < len && !isPathSeparator$1(path2.charCodeAt(j))) {
          j++;
        }
        if (j < len && j !== last2) {
          const firstPart = path2.slice(last2, j);
          last2 = j;
          while (j < len && isPathSeparator$1(path2.charCodeAt(j))) {
            j++;
          }
          if (j < len && j !== last2) {
            last2 = j;
            while (j < len && !isPathSeparator$1(path2.charCodeAt(j))) {
              j++;
            }
            if (j === len) {
              return `\\\\${firstPart}\\${path2.slice(last2)}\\`;
            }
            if (j !== last2) {
              device = `\\\\${firstPart}\\${path2.slice(last2, j)}`;
              rootEnd = j;
            }
          }
        }
      } else {
        rootEnd = 1;
      }
    } else if (isWindowsDeviceRoot(code) && path2.charCodeAt(1) === CHAR_COLON) {
      device = path2.slice(0, 2);
      rootEnd = 2;
      if (len > 2 && isPathSeparator$1(path2.charCodeAt(2))) {
        isAbsolute2 = true;
        rootEnd = 3;
      }
    }
    let tail3 = rootEnd < len ? normalizeString(path2.slice(rootEnd), !isAbsolute2, "\\", isPathSeparator$1) : "";
    if (tail3.length === 0 && !isAbsolute2) {
      tail3 = ".";
    }
    if (tail3.length > 0 && isPathSeparator$1(path2.charCodeAt(len - 1))) {
      tail3 += "\\";
    }
    if (device === void 0) {
      return isAbsolute2 ? `\\${tail3}` : tail3;
    }
    return isAbsolute2 ? `${device}\\${tail3}` : `${device}${tail3}`;
  },
  isAbsolute(path2) {
    validateString(path2, "path");
    const len = path2.length;
    if (len === 0) {
      return false;
    }
    const code = path2.charCodeAt(0);
    return isPathSeparator$1(code) || // Possible device root
    len > 2 && isWindowsDeviceRoot(code) && path2.charCodeAt(1) === CHAR_COLON && isPathSeparator$1(path2.charCodeAt(2));
  },
  join(...paths) {
    if (paths.length === 0) {
      return ".";
    }
    let joined;
    let firstPart;
    for (let i = 0; i < paths.length; ++i) {
      const arg = paths[i];
      validateString(arg, "path");
      if (arg.length > 0) {
        if (joined === void 0) {
          joined = firstPart = arg;
        } else {
          joined += `\\${arg}`;
        }
      }
    }
    if (joined === void 0) {
      return ".";
    }
    let needsReplace = true;
    let slashCount = 0;
    if (typeof firstPart === "string" && isPathSeparator$1(firstPart.charCodeAt(0))) {
      ++slashCount;
      const firstLen = firstPart.length;
      if (firstLen > 1 && isPathSeparator$1(firstPart.charCodeAt(1))) {
        ++slashCount;
        if (firstLen > 2) {
          if (isPathSeparator$1(firstPart.charCodeAt(2))) {
            ++slashCount;
          } else {
            needsReplace = false;
          }
        }
      }
    }
    if (needsReplace) {
      while (slashCount < joined.length && isPathSeparator$1(joined.charCodeAt(slashCount))) {
        slashCount++;
      }
      if (slashCount >= 2) {
        joined = `\\${joined.slice(slashCount)}`;
      }
    }
    return win32.normalize(joined);
  },
  // It will solve the relative path from `from` to `to`, for instance:
  //  from = 'C:\\orandea\\test\\aaa'
  //  to = 'C:\\orandea\\impl\\bbb'
  // The output of the function should be: '..\\..\\impl\\bbb'
  relative(from2, to) {
    validateString(from2, "from");
    validateString(to, "to");
    if (from2 === to) {
      return "";
    }
    const fromOrig = win32.resolve(from2);
    const toOrig = win32.resolve(to);
    if (fromOrig === toOrig) {
      return "";
    }
    from2 = fromOrig.toLowerCase();
    to = toOrig.toLowerCase();
    if (from2 === to) {
      return "";
    }
    let fromStart = 0;
    while (fromStart < from2.length && from2.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) {
      fromStart++;
    }
    let fromEnd = from2.length;
    while (fromEnd - 1 > fromStart && from2.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) {
      fromEnd--;
    }
    const fromLen = fromEnd - fromStart;
    let toStart = 0;
    while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
      toStart++;
    }
    let toEnd = to.length;
    while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) {
      toEnd--;
    }
    const toLen = toEnd - toStart;
    const length2 = fromLen < toLen ? fromLen : toLen;
    let lastCommonSep = -1;
    let i = 0;
    for (; i < length2; i++) {
      const fromCode = from2.charCodeAt(fromStart + i);
      if (fromCode !== to.charCodeAt(toStart + i)) {
        break;
      } else if (fromCode === CHAR_BACKWARD_SLASH) {
        lastCommonSep = i;
      }
    }
    if (i !== length2) {
      if (lastCommonSep === -1) {
        return toOrig;
      }
    } else {
      if (toLen > length2) {
        if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) {
          return toOrig.slice(toStart + i + 1);
        }
        if (i === 2) {
          return toOrig.slice(toStart + i);
        }
      }
      if (fromLen > length2) {
        if (from2.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) {
          lastCommonSep = i;
        } else if (i === 2) {
          lastCommonSep = 3;
        }
      }
      if (lastCommonSep === -1) {
        lastCommonSep = 0;
      }
    }
    let out = "";
    for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
      if (i === fromEnd || from2.charCodeAt(i) === CHAR_BACKWARD_SLASH) {
        out += out.length === 0 ? ".." : "\\..";
      }
    }
    toStart += lastCommonSep;
    if (out.length > 0) {
      return `${out}${toOrig.slice(toStart, toEnd)}`;
    }
    if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
      ++toStart;
    }
    return toOrig.slice(toStart, toEnd);
  },
  toNamespacedPath(path2) {
    if (typeof path2 !== "string" || path2.length === 0) {
      return path2;
    }
    const resolvedPath = win32.resolve(path2);
    if (resolvedPath.length <= 2) {
      return path2;
    }
    if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
      if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
        const code = resolvedPath.charCodeAt(2);
        if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) {
          return `\\\\?\\UNC\\${resolvedPath.slice(2)}`;
        }
      }
    } else if (isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) && resolvedPath.charCodeAt(1) === CHAR_COLON && resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH) {
      return `\\\\?\\${resolvedPath}`;
    }
    return path2;
  },
  dirname(path2) {
    validateString(path2, "path");
    const len = path2.length;
    if (len === 0) {
      return ".";
    }
    let rootEnd = -1;
    let offset = 0;
    const code = path2.charCodeAt(0);
    if (len === 1) {
      return isPathSeparator$1(code) ? path2 : ".";
    }
    if (isPathSeparator$1(code)) {
      rootEnd = offset = 1;
      if (isPathSeparator$1(path2.charCodeAt(1))) {
        let j = 2;
        let last2 = j;
        while (j < len && !isPathSeparator$1(path2.charCodeAt(j))) {
          j++;
        }
        if (j < len && j !== last2) {
          last2 = j;
          while (j < len && isPathSeparator$1(path2.charCodeAt(j))) {
            j++;
          }
          if (j < len && j !== last2) {
            last2 = j;
            while (j < len && !isPathSeparator$1(path2.charCodeAt(j))) {
              j++;
            }
            if (j === len) {
              return path2;
            }
            if (j !== last2) {
              rootEnd = offset = j + 1;
            }
          }
        }
      }
    } else if (isWindowsDeviceRoot(code) && path2.charCodeAt(1) === CHAR_COLON) {
      rootEnd = len > 2 && isPathSeparator$1(path2.charCodeAt(2)) ? 3 : 2;
      offset = rootEnd;
    }
    let end = -1;
    let matchedSlash = true;
    for (let i = len - 1; i >= offset; --i) {
      if (isPathSeparator$1(path2.charCodeAt(i))) {
        if (!matchedSlash) {
          end = i;
          break;
        }
      } else {
        matchedSlash = false;
      }
    }
    if (end === -1) {
      if (rootEnd === -1) {
        return ".";
      }
      end = rootEnd;
    }
    return path2.slice(0, end);
  },
  basename(path2, ext) {
    if (ext !== void 0) {
      validateString(ext, "ext");
    }
    validateString(path2, "path");
    let start = 0;
    let end = -1;
    let matchedSlash = true;
    let i;
    if (path2.length >= 2 && isWindowsDeviceRoot(path2.charCodeAt(0)) && path2.charCodeAt(1) === CHAR_COLON) {
      start = 2;
    }
    if (ext !== void 0 && ext.length > 0 && ext.length <= path2.length) {
      if (ext === path2) {
        return "";
      }
      let extIdx = ext.length - 1;
      let firstNonSlashEnd = -1;
      for (i = path2.length - 1; i >= start; --i) {
        const code = path2.charCodeAt(i);
        if (isPathSeparator$1(code)) {
          if (!matchedSlash) {
            start = i + 1;
            break;
          }
        } else {
          if (firstNonSlashEnd === -1) {
            matchedSlash = false;
            firstNonSlashEnd = i + 1;
          }
          if (extIdx >= 0) {
            if (code === ext.charCodeAt(extIdx)) {
              if (--extIdx === -1) {
                end = i;
              }
            } else {
              extIdx = -1;
              end = firstNonSlashEnd;
            }
          }
        }
      }
      if (start === end) {
        end = firstNonSlashEnd;
      } else if (end === -1) {
        end = path2.length;
      }
      return path2.slice(start, end);
    }
    for (i = path2.length - 1; i >= start; --i) {
      if (isPathSeparator$1(path2.charCodeAt(i))) {
        if (!matchedSlash) {
          start = i + 1;
          break;
        }
      } else if (end === -1) {
        matchedSlash = false;
        end = i + 1;
      }
    }
    if (end === -1) {
      return "";
    }
    return path2.slice(start, end);
  },
  extname(path2) {
    validateString(path2, "path");
    let start = 0;
    let startDot = -1;
    let startPart = 0;
    let end = -1;
    let matchedSlash = true;
    let preDotState = 0;
    if (path2.length >= 2 && path2.charCodeAt(1) === CHAR_COLON && isWindowsDeviceRoot(path2.charCodeAt(0))) {
      start = startPart = 2;
    }
    for (let i = path2.length - 1; i >= start; --i) {
      const code = path2.charCodeAt(i);
      if (isPathSeparator$1(code)) {
        if (!matchedSlash) {
          startPart = i + 1;
          break;
        }
        continue;
      }
      if (end === -1) {
        matchedSlash = false;
        end = i + 1;
      }
      if (code === CHAR_DOT) {
        if (startDot === -1) {
          startDot = i;
        } else if (preDotState !== 1) {
          preDotState = 1;
        }
      } else if (startDot !== -1) {
        preDotState = -1;
      }
    }
    if (startDot === -1 || end === -1 || // We saw a non-dot character immediately before the dot
    preDotState === 0 || // The (right-most) trimmed path component is exactly '..'
    preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
      return "";
    }
    return path2.slice(startDot, end);
  },
  format: _format.bind(null, "\\"),
  parse(path2) {
    validateString(path2, "path");
    const ret = { root: "", dir: "", base: "", ext: "", name: "" };
    if (path2.length === 0) {
      return ret;
    }
    const len = path2.length;
    let rootEnd = 0;
    let code = path2.charCodeAt(0);
    if (len === 1) {
      if (isPathSeparator$1(code)) {
        ret.root = ret.dir = path2;
        return ret;
      }
      ret.base = ret.name = path2;
      return ret;
    }
    if (isPathSeparator$1(code)) {
      rootEnd = 1;
      if (isPathSeparator$1(path2.charCodeAt(1))) {
        let j = 2;
        let last2 = j;
        while (j < len && !isPathSeparator$1(path2.charCodeAt(j))) {
          j++;
        }
        if (j < len && j !== last2) {
          last2 = j;
          while (j < len && isPathSeparator$1(path2.charCodeAt(j))) {
            j++;
          }
          if (j < len && j !== last2) {
            last2 = j;
            while (j < len && !isPathSeparator$1(path2.charCodeAt(j))) {
              j++;
            }
            if (j === len) {
              rootEnd = j;
            } else if (j !== last2) {
              rootEnd = j + 1;
            }
          }
        }
      }
    } else if (isWindowsDeviceRoot(code) && path2.charCodeAt(1) === CHAR_COLON) {
      if (len <= 2) {
        ret.root = ret.dir = path2;
        return ret;
      }
      rootEnd = 2;
      if (isPathSeparator$1(path2.charCodeAt(2))) {
        if (len === 3) {
          ret.root = ret.dir = path2;
          return ret;
        }
        rootEnd = 3;
      }
    }
    if (rootEnd > 0) {
      ret.root = path2.slice(0, rootEnd);
    }
    let startDot = -1;
    let startPart = rootEnd;
    let end = -1;
    let matchedSlash = true;
    let i = path2.length - 1;
    let preDotState = 0;
    for (; i >= rootEnd; --i) {
      code = path2.charCodeAt(i);
      if (isPathSeparator$1(code)) {
        if (!matchedSlash) {
          startPart = i + 1;
          break;
        }
        continue;
      }
      if (end === -1) {
        matchedSlash = false;
        end = i + 1;
      }
      if (code === CHAR_DOT) {
        if (startDot === -1) {
          startDot = i;
        } else if (preDotState !== 1) {
          preDotState = 1;
        }
      } else if (startDot !== -1) {
        preDotState = -1;
      }
    }
    if (end !== -1) {
      if (startDot === -1 || // We saw a non-dot character immediately before the dot
      preDotState === 0 || // The (right-most) trimmed path component is exactly '..'
      preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
        ret.base = ret.name = path2.slice(startPart, end);
      } else {
        ret.name = path2.slice(startPart, startDot);
        ret.base = path2.slice(startPart, end);
        ret.ext = path2.slice(startDot, end);
      }
    }
    if (startPart > 0 && startPart !== rootEnd) {
      ret.dir = path2.slice(0, startPart - 1);
    } else {
      ret.dir = ret.root;
    }
    return ret;
  },
  sep: "\\",
  delimiter: ";",
  win32: null,
  posix: null
};
const posixCwd = (() => {
  if (platformIsWin32) {
    const regexp = /\\/g;
    return () => {
      const cwd2 = cwd$1().replace(regexp, "/");
      return cwd2.slice(cwd2.indexOf("/"));
    };
  }
  return () => cwd$1();
})();
const posix = {
  // path.resolve([from ...], to)
  resolve(...pathSegments) {
    let resolvedPath = "";
    let resolvedAbsolute = false;
    for (let i = pathSegments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
      const path2 = i >= 0 ? pathSegments[i] : posixCwd();
      validateString(path2, "path");
      if (path2.length === 0) {
        continue;
      }
      resolvedPath = `${path2}/${resolvedPath}`;
      resolvedAbsolute = path2.charCodeAt(0) === CHAR_FORWARD_SLASH;
    }
    resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, "/", isPosixPathSeparator);
    if (resolvedAbsolute) {
      return `/${resolvedPath}`;
    }
    return resolvedPath.length > 0 ? resolvedPath : ".";
  },
  normalize(path2) {
    validateString(path2, "path");
    if (path2.length === 0) {
      return ".";
    }
    const isAbsolute2 = path2.charCodeAt(0) === CHAR_FORWARD_SLASH;
    const trailingSeparator = path2.charCodeAt(path2.length - 1) === CHAR_FORWARD_SLASH;
    path2 = normalizeString(path2, !isAbsolute2, "/", isPosixPathSeparator);
    if (path2.length === 0) {
      if (isAbsolute2) {
        return "/";
      }
      return trailingSeparator ? "./" : ".";
    }
    if (trailingSeparator) {
      path2 += "/";
    }
    return isAbsolute2 ? `/${path2}` : path2;
  },
  isAbsolute(path2) {
    validateString(path2, "path");
    return path2.length > 0 && path2.charCodeAt(0) === CHAR_FORWARD_SLASH;
  },
  join(...paths) {
    if (paths.length === 0) {
      return ".";
    }
    let joined;
    for (let i = 0; i < paths.length; ++i) {
      const arg = paths[i];
      validateString(arg, "path");
      if (arg.length > 0) {
        if (joined === void 0) {
          joined = arg;
        } else {
          joined += `/${arg}`;
        }
      }
    }
    if (joined === void 0) {
      return ".";
    }
    return posix.normalize(joined);
  },
  relative(from2, to) {
    validateString(from2, "from");
    validateString(to, "to");
    if (from2 === to) {
      return "";
    }
    from2 = posix.resolve(from2);
    to = posix.resolve(to);
    if (from2 === to) {
      return "";
    }
    const fromStart = 1;
    const fromEnd = from2.length;
    const fromLen = fromEnd - fromStart;
    const toStart = 1;
    const toLen = to.length - toStart;
    const length2 = fromLen < toLen ? fromLen : toLen;
    let lastCommonSep = -1;
    let i = 0;
    for (; i < length2; i++) {
      const fromCode = from2.charCodeAt(fromStart + i);
      if (fromCode !== to.charCodeAt(toStart + i)) {
        break;
      } else if (fromCode === CHAR_FORWARD_SLASH) {
        lastCommonSep = i;
      }
    }
    if (i === length2) {
      if (toLen > length2) {
        if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
          return to.slice(toStart + i + 1);
        }
        if (i === 0) {
          return to.slice(toStart + i);
        }
      } else if (fromLen > length2) {
        if (from2.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
          lastCommonSep = i;
        } else if (i === 0) {
          lastCommonSep = 0;
        }
      }
    }
    let out = "";
    for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
      if (i === fromEnd || from2.charCodeAt(i) === CHAR_FORWARD_SLASH) {
        out += out.length === 0 ? ".." : "/..";
      }
    }
    return `${out}${to.slice(toStart + lastCommonSep)}`;
  },
  toNamespacedPath(path2) {
    return path2;
  },
  dirname(path2) {
    validateString(path2, "path");
    if (path2.length === 0) {
      return ".";
    }
    const hasRoot = path2.charCodeAt(0) === CHAR_FORWARD_SLASH;
    let end = -1;
    let matchedSlash = true;
    for (let i = path2.length - 1; i >= 1; --i) {
      if (path2.charCodeAt(i) === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          end = i;
          break;
        }
      } else {
        matchedSlash = false;
      }
    }
    if (end === -1) {
      return hasRoot ? "/" : ".";
    }
    if (hasRoot && end === 1) {
      return "//";
    }
    return path2.slice(0, end);
  },
  basename(path2, ext) {
    if (ext !== void 0) {
      validateString(ext, "ext");
    }
    validateString(path2, "path");
    let start = 0;
    let end = -1;
    let matchedSlash = true;
    let i;
    if (ext !== void 0 && ext.length > 0 && ext.length <= path2.length) {
      if (ext === path2) {
        return "";
      }
      let extIdx = ext.length - 1;
      let firstNonSlashEnd = -1;
      for (i = path2.length - 1; i >= 0; --i) {
        const code = path2.charCodeAt(i);
        if (code === CHAR_FORWARD_SLASH) {
          if (!matchedSlash) {
            start = i + 1;
            break;
          }
        } else {
          if (firstNonSlashEnd === -1) {
            matchedSlash = false;
            firstNonSlashEnd = i + 1;
          }
          if (extIdx >= 0) {
            if (code === ext.charCodeAt(extIdx)) {
              if (--extIdx === -1) {
                end = i;
              }
            } else {
              extIdx = -1;
              end = firstNonSlashEnd;
            }
          }
        }
      }
      if (start === end) {
        end = firstNonSlashEnd;
      } else if (end === -1) {
        end = path2.length;
      }
      return path2.slice(start, end);
    }
    for (i = path2.length - 1; i >= 0; --i) {
      if (path2.charCodeAt(i) === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          start = i + 1;
          break;
        }
      } else if (end === -1) {
        matchedSlash = false;
        end = i + 1;
      }
    }
    if (end === -1) {
      return "";
    }
    return path2.slice(start, end);
  },
  extname(path2) {
    validateString(path2, "path");
    let startDot = -1;
    let startPart = 0;
    let end = -1;
    let matchedSlash = true;
    let preDotState = 0;
    for (let i = path2.length - 1; i >= 0; --i) {
      const code = path2.charCodeAt(i);
      if (code === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          startPart = i + 1;
          break;
        }
        continue;
      }
      if (end === -1) {
        matchedSlash = false;
        end = i + 1;
      }
      if (code === CHAR_DOT) {
        if (startDot === -1) {
          startDot = i;
        } else if (preDotState !== 1) {
          preDotState = 1;
        }
      } else if (startDot !== -1) {
        preDotState = -1;
      }
    }
    if (startDot === -1 || end === -1 || // We saw a non-dot character immediately before the dot
    preDotState === 0 || // The (right-most) trimmed path component is exactly '..'
    preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
      return "";
    }
    return path2.slice(startDot, end);
  },
  format: _format.bind(null, "/"),
  parse(path2) {
    validateString(path2, "path");
    const ret = { root: "", dir: "", base: "", ext: "", name: "" };
    if (path2.length === 0) {
      return ret;
    }
    const isAbsolute2 = path2.charCodeAt(0) === CHAR_FORWARD_SLASH;
    let start;
    if (isAbsolute2) {
      ret.root = "/";
      start = 1;
    } else {
      start = 0;
    }
    let startDot = -1;
    let startPart = 0;
    let end = -1;
    let matchedSlash = true;
    let i = path2.length - 1;
    let preDotState = 0;
    for (; i >= start; --i) {
      const code = path2.charCodeAt(i);
      if (code === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          startPart = i + 1;
          break;
        }
        continue;
      }
      if (end === -1) {
        matchedSlash = false;
        end = i + 1;
      }
      if (code === CHAR_DOT) {
        if (startDot === -1) {
          startDot = i;
        } else if (preDotState !== 1) {
          preDotState = 1;
        }
      } else if (startDot !== -1) {
        preDotState = -1;
      }
    }
    if (end !== -1) {
      const start2 = startPart === 0 && isAbsolute2 ? 1 : startPart;
      if (startDot === -1 || // We saw a non-dot character immediately before the dot
      preDotState === 0 || // The (right-most) trimmed path component is exactly '..'
      preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
        ret.base = ret.name = path2.slice(start2, end);
      } else {
        ret.name = path2.slice(start2, startDot);
        ret.base = path2.slice(start2, end);
        ret.ext = path2.slice(startDot, end);
      }
    }
    if (startPart > 0) {
      ret.dir = path2.slice(0, startPart - 1);
    } else if (isAbsolute2) {
      ret.dir = "/";
    }
    return ret;
  },
  sep: "/",
  delimiter: ":",
  win32: null,
  posix: null
};
posix.win32 = win32.win32 = win32;
posix.posix = win32.posix = posix;
const normalize = platformIsWin32 ? win32.normalize : posix.normalize;
const resolve$3 = platformIsWin32 ? win32.resolve : posix.resolve;
const relative$2 = platformIsWin32 ? win32.relative : posix.relative;
const dirname$4 = platformIsWin32 ? win32.dirname : posix.dirname;
const basename$2 = platformIsWin32 ? win32.basename : posix.basename;
const extname$2 = platformIsWin32 ? win32.extname : posix.extname;
const sep$2 = platformIsWin32 ? win32.sep : posix.sep;
const _schemePattern = /^\w[\w\d+.-]*$/;
const _singleSlashStart = /^\//;
const _doubleSlashStart = /^\/\//;
function _validateUri(ret, _strict) {
  if (!ret.scheme && _strict) {
    throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${ret.authority}", path: "${ret.path}", query: "${ret.query}", fragment: "${ret.fragment}"}`);
  }
  if (ret.scheme && !_schemePattern.test(ret.scheme)) {
    throw new Error("[UriError]: Scheme contains illegal characters.");
  }
  if (ret.path) {
    if (ret.authority) {
      if (!_singleSlashStart.test(ret.path)) {
        throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character');
      }
    } else {
      if (_doubleSlashStart.test(ret.path)) {
        throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")');
      }
    }
  }
}
function _schemeFix(scheme, _strict) {
  if (!scheme && !_strict) {
    return "file";
  }
  return scheme;
}
function _referenceResolution(scheme, path2) {
  switch (scheme) {
    case "https":
    case "http":
    case "file":
      if (!path2) {
        path2 = _slash;
      } else if (path2[0] !== _slash) {
        path2 = _slash + path2;
      }
      break;
  }
  return path2;
}
const _empty = "";
const _slash = "/";
const _regexp = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
class URI {
  static isUri(thing) {
    if (thing instanceof URI) {
      return true;
    }
    if (!thing) {
      return false;
    }
    return typeof thing.authority === "string" && typeof thing.fragment === "string" && typeof thing.path === "string" && typeof thing.query === "string" && typeof thing.scheme === "string" && typeof thing.fsPath === "string" && typeof thing.with === "function" && typeof thing.toString === "function";
  }
  /**
   * @internal
   */
  constructor(schemeOrData, authority, path2, query, fragment, _strict = false) {
    if (typeof schemeOrData === "object") {
      this.scheme = schemeOrData.scheme || _empty;
      this.authority = schemeOrData.authority || _empty;
      this.path = schemeOrData.path || _empty;
      this.query = schemeOrData.query || _empty;
      this.fragment = schemeOrData.fragment || _empty;
    } else {
      this.scheme = _schemeFix(schemeOrData, _strict);
      this.authority = authority || _empty;
      this.path = _referenceResolution(this.scheme, path2 || _empty);
      this.query = query || _empty;
      this.fragment = fragment || _empty;
      _validateUri(this, _strict);
    }
  }
  // ---- filesystem path -----------------------
  /**
   * Returns a string representing the corresponding file system path of this URI.
   * Will handle UNC paths, normalizes windows drive letters to lower-case, and uses the
   * platform specific path separator.
   *
   * * Will *not* validate the path for invalid characters and semantics.
   * * Will *not* look at the scheme of this URI.
   * * The result shall *not* be used for display purposes but for accessing a file on disk.
   *
   *
   * The *difference* to `URI#path` is the use of the platform specific separator and the handling
   * of UNC paths. See the below sample of a file-uri with an authority (UNC path).
   *
   * ```ts
      const u = URI.parse('file://server/c$/folder/file.txt')
      u.authority === 'server'
      u.path === '/shares/c$/file.txt'
      u.fsPath === '\\server\c$\folder\file.txt'
  ```
   *
   * Using `URI#path` to read a file (using fs-apis) would not be enough because parts of the path,
   * namely the server name, would be missing. Therefore `URI#fsPath` exists - it's sugar to ease working
   * with URIs that represent files on disk (`file` scheme).
   */
  get fsPath() {
    return uriToFsPath(this, false);
  }
  // ---- modify to new -------------------------
  with(change) {
    if (!change) {
      return this;
    }
    let { scheme, authority, path: path2, query, fragment } = change;
    if (scheme === void 0) {
      scheme = this.scheme;
    } else if (scheme === null) {
      scheme = _empty;
    }
    if (authority === void 0) {
      authority = this.authority;
    } else if (authority === null) {
      authority = _empty;
    }
    if (path2 === void 0) {
      path2 = this.path;
    } else if (path2 === null) {
      path2 = _empty;
    }
    if (query === void 0) {
      query = this.query;
    } else if (query === null) {
      query = _empty;
    }
    if (fragment === void 0) {
      fragment = this.fragment;
    } else if (fragment === null) {
      fragment = _empty;
    }
    if (scheme === this.scheme && authority === this.authority && path2 === this.path && query === this.query && fragment === this.fragment) {
      return this;
    }
    return new Uri$1(scheme, authority, path2, query, fragment);
  }
  // ---- parse & validate ------------------------
  /**
   * Creates a new URI from a string, e.g. `http://www.example.com/some/path`,
   * `file:///usr/home`, or `scheme:with/path`.
   *
   * @param value A string which represents an URI (see `URI#toString`).
   */
  static parse(value, _strict = false) {
    const match2 = _regexp.exec(value);
    if (!match2) {
      return new Uri$1(_empty, _empty, _empty, _empty, _empty);
    }
    return new Uri$1(match2[2] || _empty, percentDecode(match2[4] || _empty), percentDecode(match2[5] || _empty), percentDecode(match2[7] || _empty), percentDecode(match2[9] || _empty), _strict);
  }
  /**
   * Creates a new URI from a file system path, e.g. `c:\my\files`,
   * `/usr/home`, or `\\server\share\some\path`.
   *
   * The *difference* between `URI#parse` and `URI#file` is that the latter treats the argument
   * as path, not as stringified-uri. E.g. `URI.file(path)` is **not the same as**
   * `URI.parse('file://' + path)` because the path might contain characters that are
   * interpreted (# and ?). See the following sample:
   * ```ts
  const good = URI.file('/coding/c#/project1');
  good.scheme === 'file';
  good.path === '/coding/c#/project1';
  good.fragment === '';
  const bad = URI.parse('file://' + '/coding/c#/project1');
  bad.scheme === 'file';
  bad.path === '/coding/c'; // path is now broken
  bad.fragment === '/project1';
  ```
   *
   * @param path A file system path (see `URI#fsPath`)
   */
  static file(path2) {
    let authority = _empty;
    if (isWindows) {
      path2 = path2.replace(/\\/g, _slash);
    }
    if (path2[0] === _slash && path2[1] === _slash) {
      const idx = path2.indexOf(_slash, 2);
      if (idx === -1) {
        authority = path2.substring(2);
        path2 = _slash;
      } else {
        authority = path2.substring(2, idx);
        path2 = path2.substring(idx) || _slash;
      }
    }
    return new Uri$1("file", authority, path2, _empty, _empty);
  }
  /**
   * Creates new URI from uri components.
   *
   * Unless `strict` is `true` the scheme is defaults to be `file`. This function performs
   * validation and should be used for untrusted uri components retrieved from storage,
   * user input, command arguments etc
   */
  static from(components, strict) {
    const result2 = new Uri$1(components.scheme, components.authority, components.path, components.query, components.fragment, strict);
    return result2;
  }
  /**
   * Join a URI path with path fragments and normalizes the resulting path.
   *
   * @param uri The input URI.
   * @param pathFragment The path fragment to add to the URI path.
   * @returns The resulting URI.
   */
  static joinPath(uri, ...pathFragment) {
    if (!uri.path) {
      throw new Error(`[UriError]: cannot call joinPath on URI without path`);
    }
    let newPath;
    if (isWindows && uri.scheme === "file") {
      newPath = URI.file(win32.join(uriToFsPath(uri, true), ...pathFragment)).path;
    } else {
      newPath = posix.join(uri.path, ...pathFragment);
    }
    return uri.with({ path: newPath });
  }
  // ---- printing/externalize ---------------------------
  /**
   * Creates a string representation for this URI. It's guaranteed that calling
   * `URI.parse` with the result of this function creates an URI which is equal
   * to this URI.
   *
   * * The result shall *not* be used for display purposes but for externalization or transport.
   * * The result will be encoded using the percentage encoding and encoding happens mostly
   * ignore the scheme-specific encoding rules.
   *
   * @param skipEncoding Do not encode the result, default is `false`
   */
  toString(skipEncoding = false) {
    return _asFormatted(this, skipEncoding);
  }
  toJSON() {
    return this;
  }
  static revive(data) {
    var _a2, _b2;
    if (!data) {
      return data;
    } else if (data instanceof URI) {
      return data;
    } else {
      const result2 = new Uri$1(data);
      result2._formatted = (_a2 = data.external) !== null && _a2 !== void 0 ? _a2 : null;
      result2._fsPath = data._sep === _pathSepMarker ? (_b2 = data.fsPath) !== null && _b2 !== void 0 ? _b2 : null : null;
      return result2;
    }
  }
}
const _pathSepMarker = isWindows ? 1 : void 0;
let Uri$1 = class Uri extends URI {
  constructor() {
    super(...arguments);
    this._formatted = null;
    this._fsPath = null;
  }
  get fsPath() {
    if (!this._fsPath) {
      this._fsPath = uriToFsPath(this, false);
    }
    return this._fsPath;
  }
  toString(skipEncoding = false) {
    if (!skipEncoding) {
      if (!this._formatted) {
        this._formatted = _asFormatted(this, false);
      }
      return this._formatted;
    } else {
      return _asFormatted(this, true);
    }
  }
  toJSON() {
    const res = {
      $mid: 1
      /* MarshalledId.Uri */
    };
    if (this._fsPath) {
      res.fsPath = this._fsPath;
      res._sep = _pathSepMarker;
    }
    if (this._formatted) {
      res.external = this._formatted;
    }
    if (this.path) {
      res.path = this.path;
    }
    if (this.scheme) {
      res.scheme = this.scheme;
    }
    if (this.authority) {
      res.authority = this.authority;
    }
    if (this.query) {
      res.query = this.query;
    }
    if (this.fragment) {
      res.fragment = this.fragment;
    }
    return res;
  }
};
const encodeTable = {
  [
    58
    /* CharCode.Colon */
  ]: "%3A",
  [
    47
    /* CharCode.Slash */
  ]: "%2F",
  [
    63
    /* CharCode.QuestionMark */
  ]: "%3F",
  [
    35
    /* CharCode.Hash */
  ]: "%23",
  [
    91
    /* CharCode.OpenSquareBracket */
  ]: "%5B",
  [
    93
    /* CharCode.CloseSquareBracket */
  ]: "%5D",
  [
    64
    /* CharCode.AtSign */
  ]: "%40",
  [
    33
    /* CharCode.ExclamationMark */
  ]: "%21",
  [
    36
    /* CharCode.DollarSign */
  ]: "%24",
  [
    38
    /* CharCode.Ampersand */
  ]: "%26",
  [
    39
    /* CharCode.SingleQuote */
  ]: "%27",
  [
    40
    /* CharCode.OpenParen */
  ]: "%28",
  [
    41
    /* CharCode.CloseParen */
  ]: "%29",
  [
    42
    /* CharCode.Asterisk */
  ]: "%2A",
  [
    43
    /* CharCode.Plus */
  ]: "%2B",
  [
    44
    /* CharCode.Comma */
  ]: "%2C",
  [
    59
    /* CharCode.Semicolon */
  ]: "%3B",
  [
    61
    /* CharCode.Equals */
  ]: "%3D",
  [
    32
    /* CharCode.Space */
  ]: "%20"
};
function encodeURIComponentFast(uriComponent, isPath, isAuthority) {
  let res = void 0;
  let nativeEncodePos = -1;
  for (let pos = 0; pos < uriComponent.length; pos++) {
    const code = uriComponent.charCodeAt(pos);
    if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57 || code === 45 || code === 46 || code === 95 || code === 126 || isPath && code === 47 || isAuthority && code === 91 || isAuthority && code === 93 || isAuthority && code === 58) {
      if (nativeEncodePos !== -1) {
        res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
        nativeEncodePos = -1;
      }
      if (res !== void 0) {
        res += uriComponent.charAt(pos);
      }
    } else {
      if (res === void 0) {
        res = uriComponent.substr(0, pos);
      }
      const escaped = encodeTable[code];
      if (escaped !== void 0) {
        if (nativeEncodePos !== -1) {
          res += encodeURIComponent(uriComponent.substring(nativeEncodePos, pos));
          nativeEncodePos = -1;
        }
        res += escaped;
      } else if (nativeEncodePos === -1) {
        nativeEncodePos = pos;
      }
    }
  }
  if (nativeEncodePos !== -1) {
    res += encodeURIComponent(uriComponent.substring(nativeEncodePos));
  }
  return res !== void 0 ? res : uriComponent;
}
function encodeURIComponentMinimal(path2) {
  let res = void 0;
  for (let pos = 0; pos < path2.length; pos++) {
    const code = path2.charCodeAt(pos);
    if (code === 35 || code === 63) {
      if (res === void 0) {
        res = path2.substr(0, pos);
      }
      res += encodeTable[code];
    } else {
      if (res !== void 0) {
        res += path2[pos];
      }
    }
  }
  return res !== void 0 ? res : path2;
}
function uriToFsPath(uri, keepDriveLetterCasing) {
  let value;
  if (uri.authority && uri.path.length > 1 && uri.scheme === "file") {
    value = `//${uri.authority}${uri.path}`;
  } else if (uri.path.charCodeAt(0) === 47 && (uri.path.charCodeAt(1) >= 65 && uri.path.charCodeAt(1) <= 90 || uri.path.charCodeAt(1) >= 97 && uri.path.charCodeAt(1) <= 122) && uri.path.charCodeAt(2) === 58) {
    if (!keepDriveLetterCasing) {
      value = uri.path[1].toLowerCase() + uri.path.substr(2);
    } else {
      value = uri.path.substr(1);
    }
  } else {
    value = uri.path;
  }
  if (isWindows) {
    value = value.replace(/\//g, "\\");
  }
  return value;
}
function _asFormatted(uri, skipEncoding) {
  const encoder = !skipEncoding ? encodeURIComponentFast : encodeURIComponentMinimal;
  let res = "";
  let { scheme, authority, path: path2, query, fragment } = uri;
  if (scheme) {
    res += scheme;
    res += ":";
  }
  if (authority || scheme === "file") {
    res += _slash;
    res += _slash;
  }
  if (authority) {
    let idx = authority.indexOf("@");
    if (idx !== -1) {
      const userinfo = authority.substr(0, idx);
      authority = authority.substr(idx + 1);
      idx = userinfo.lastIndexOf(":");
      if (idx === -1) {
        res += encoder(userinfo, false, false);
      } else {
        res += encoder(userinfo.substr(0, idx), false, false);
        res += ":";
        res += encoder(userinfo.substr(idx + 1), false, true);
      }
      res += "@";
    }
    authority = authority.toLowerCase();
    idx = authority.lastIndexOf(":");
    if (idx === -1) {
      res += encoder(authority, false, true);
    } else {
      res += encoder(authority.substr(0, idx), false, true);
      res += authority.substr(idx);
    }
  }
  if (path2) {
    if (path2.length >= 3 && path2.charCodeAt(0) === 47 && path2.charCodeAt(2) === 58) {
      const code = path2.charCodeAt(1);
      if (code >= 65 && code <= 90) {
        path2 = `/${String.fromCharCode(code + 32)}:${path2.substr(3)}`;
      }
    } else if (path2.length >= 2 && path2.charCodeAt(1) === 58) {
      const code = path2.charCodeAt(0);
      if (code >= 65 && code <= 90) {
        path2 = `${String.fromCharCode(code + 32)}:${path2.substr(2)}`;
      }
    }
    res += encoder(path2, true, false);
  }
  if (query) {
    res += "?";
    res += encoder(query, false, false);
  }
  if (fragment) {
    res += "#";
    res += !skipEncoding ? encodeURIComponentFast(fragment, false, false) : fragment;
  }
  return res;
}
function decodeURIComponentGraceful(str2) {
  try {
    return decodeURIComponent(str2);
  } catch (_a2) {
    if (str2.length > 3) {
      return str2.substr(0, 3) + decodeURIComponentGraceful(str2.substr(3));
    } else {
      return str2;
    }
  }
}
const _rEncodedAsHex = /(%[0-9A-Za-z][0-9A-Za-z])+/g;
function percentDecode(str2) {
  if (!str2.match(_rEncodedAsHex)) {
    return str2;
  }
  return str2.replace(_rEncodedAsHex, (match2) => decodeURIComponentGraceful(match2));
}
var Schemas;
(function(Schemas2) {
  Schemas2.inMemory = "inmemory";
  Schemas2.vscode = "vscode";
  Schemas2.internal = "private";
  Schemas2.walkThrough = "walkThrough";
  Schemas2.walkThroughSnippet = "walkThroughSnippet";
  Schemas2.http = "http";
  Schemas2.https = "https";
  Schemas2.file = "file";
  Schemas2.mailto = "mailto";
  Schemas2.untitled = "untitled";
  Schemas2.data = "data";
  Schemas2.command = "command";
  Schemas2.vscodeRemote = "vscode-remote";
  Schemas2.vscodeRemoteResource = "vscode-remote-resource";
  Schemas2.vscodeManagedRemoteResource = "vscode-managed-remote-resource";
  Schemas2.vscodeUserData = "vscode-userdata";
  Schemas2.vscodeCustomEditor = "vscode-custom-editor";
  Schemas2.vscodeNotebookCell = "vscode-notebook-cell";
  Schemas2.vscodeNotebookCellMetadata = "vscode-notebook-cell-metadata";
  Schemas2.vscodeNotebookCellOutput = "vscode-notebook-cell-output";
  Schemas2.vscodeInteractiveInput = "vscode-interactive-input";
  Schemas2.vscodeSettings = "vscode-settings";
  Schemas2.vscodeWorkspaceTrust = "vscode-workspace-trust";
  Schemas2.vscodeTerminal = "vscode-terminal";
  Schemas2.vscodeChatSesssion = "vscode-chat-editor";
  Schemas2.webviewPanel = "webview-panel";
  Schemas2.vscodeWebview = "vscode-webview";
  Schemas2.extension = "extension";
  Schemas2.vscodeFileResource = "vscode-file";
  Schemas2.tmp = "tmp";
  Schemas2.vsls = "vsls";
  Schemas2.vscodeSourceControl = "vscode-scm";
})(Schemas || (Schemas = {}));
const connectionTokenQueryName = "tkn";
class RemoteAuthoritiesImpl {
  constructor() {
    this._hosts = /* @__PURE__ */ Object.create(null);
    this._ports = /* @__PURE__ */ Object.create(null);
    this._connectionTokens = /* @__PURE__ */ Object.create(null);
    this._preferredWebSchema = "http";
    this._delegate = null;
    this._remoteResourcesPath = `/${Schemas.vscodeRemoteResource}`;
  }
  setPreferredWebSchema(schema) {
    this._preferredWebSchema = schema;
  }
  rewrite(uri) {
    if (this._delegate) {
      try {
        return this._delegate(uri);
      } catch (err) {
        onUnexpectedError(err);
        return uri;
      }
    }
    const authority = uri.authority;
    let host = this._hosts[authority];
    if (host && host.indexOf(":") !== -1 && host.indexOf("[") === -1) {
      host = `[${host}]`;
    }
    const port = this._ports[authority];
    const connectionToken = this._connectionTokens[authority];
    let query = `path=${encodeURIComponent(uri.path)}`;
    if (typeof connectionToken === "string") {
      query += `&${connectionTokenQueryName}=${encodeURIComponent(connectionToken)}`;
    }
    return URI.from({
      scheme: isWeb ? this._preferredWebSchema : Schemas.vscodeRemoteResource,
      authority: `${host}:${port}`,
      path: this._remoteResourcesPath,
      query
    });
  }
}
const RemoteAuthorities = new RemoteAuthoritiesImpl();
class FileAccessImpl {
  /**
   * Returns a URI to use in contexts where the browser is responsible
   * for loading (e.g. fetch()) or when used within the DOM.
   *
   * **Note:** use `dom.ts#asCSSUrl` whenever the URL is to be used in CSS context.
   */
  uriToBrowserUri(uri) {
    if (uri.scheme === Schemas.vscodeRemote) {
      return RemoteAuthorities.rewrite(uri);
    }
    if (
      // ...only ever for `file` resources
      uri.scheme === Schemas.file && // ...and we run in native environments
      (isNative || // ...or web worker extensions on desktop
      isWebWorker && globals.origin === `${Schemas.vscodeFileResource}://${FileAccessImpl.FALLBACK_AUTHORITY}`)
    ) {
      return uri.with({
        scheme: Schemas.vscodeFileResource,
        // We need to provide an authority here so that it can serve
        // as origin for network and loading matters in chromium.
        // If the URI is not coming with an authority already, we
        // add our own
        authority: uri.authority || FileAccessImpl.FALLBACK_AUTHORITY,
        query: null,
        fragment: null
      });
    }
    return uri;
  }
}
FileAccessImpl.FALLBACK_AUTHORITY = "vscode-app";
const FileAccess = new FileAccessImpl();
var COI;
(function(COI2) {
  const coiHeaders = /* @__PURE__ */ new Map([
    ["1", { "Cross-Origin-Opener-Policy": "same-origin" }],
    ["2", { "Cross-Origin-Embedder-Policy": "require-corp" }],
    ["3", { "Cross-Origin-Opener-Policy": "same-origin", "Cross-Origin-Embedder-Policy": "require-corp" }]
  ]);
  COI2.CoopAndCoep = Object.freeze(coiHeaders.get("3"));
  const coiSearchParamName = "vscode-coi";
  function getHeadersFromQuery(url) {
    let params;
    if (typeof url === "string") {
      params = new URL(url).searchParams;
    } else if (url instanceof URL) {
      params = url.searchParams;
    } else if (URI.isUri(url)) {
      params = new URL(url.toString(true)).searchParams;
    }
    const value = params === null || params === void 0 ? void 0 : params.get(coiSearchParamName);
    if (!value) {
      return void 0;
    }
    return coiHeaders.get(value);
  }
  COI2.getHeadersFromQuery = getHeadersFromQuery;
  function addSearchParam(urlOrSearch, coop, coep) {
    if (!globalThis.crossOriginIsolated) {
      return;
    }
    const value = coop && coep ? "3" : coep ? "2" : "1";
    if (urlOrSearch instanceof URLSearchParams) {
      urlOrSearch.set(coiSearchParamName, value);
    } else {
      urlOrSearch[coiSearchParamName] = value;
    }
  }
  COI2.addSearchParam = addSearchParam;
})(COI || (COI = {}));
function clearNode(node2) {
  while (node2.firstChild) {
    node2.firstChild.remove();
  }
}
function isInDOM(node2) {
  var _a2;
  return (_a2 = node2 === null || node2 === void 0 ? void 0 : node2.isConnected) !== null && _a2 !== void 0 ? _a2 : false;
}
class DomListener {
  constructor(node2, type, handler, options) {
    this._node = node2;
    this._type = type;
    this._handler = handler;
    this._options = options || false;
    this._node.addEventListener(this._type, this._handler, this._options);
  }
  dispose() {
    if (!this._handler) {
      return;
    }
    this._node.removeEventListener(this._type, this._handler, this._options);
    this._node = null;
    this._handler = null;
  }
}
function addDisposableListener(node2, type, handler, useCaptureOrOptions) {
  return new DomListener(node2, type, handler, useCaptureOrOptions);
}
function _wrapAsStandardMouseEvent(handler) {
  return function(e) {
    return handler(new StandardMouseEvent(e));
  };
}
function _wrapAsStandardKeyboardEvent(handler) {
  return function(e) {
    return handler(new StandardKeyboardEvent(e));
  };
}
const addStandardDisposableListener = function addStandardDisposableListener2(node2, type, handler, useCapture) {
  let wrapHandler = handler;
  if (type === "click" || type === "mousedown") {
    wrapHandler = _wrapAsStandardMouseEvent(handler);
  } else if (type === "keydown" || type === "keypress" || type === "keyup") {
    wrapHandler = _wrapAsStandardKeyboardEvent(handler);
  }
  return addDisposableListener(node2, type, wrapHandler, useCapture);
};
const addStandardDisposableGenericMouseDownListener = function addStandardDisposableListener3(node2, handler, useCapture) {
  const wrapHandler = _wrapAsStandardMouseEvent(handler);
  return addDisposableGenericMouseDownListener(node2, wrapHandler, useCapture);
};
function addDisposableGenericMouseDownListener(node2, handler, useCapture) {
  return addDisposableListener(node2, isIOS && BrowserFeatures.pointerEvents ? EventType$1.POINTER_DOWN : EventType$1.MOUSE_DOWN, handler, useCapture);
}
let runAtThisOrScheduleAtNextAnimationFrame;
let scheduleAtNextAnimationFrame;
class AnimationFrameQueueItem {
  constructor(runner, priority = 0) {
    this._runner = runner;
    this.priority = priority;
    this._canceled = false;
  }
  dispose() {
    this._canceled = true;
  }
  execute() {
    if (this._canceled) {
      return;
    }
    try {
      this._runner();
    } catch (e) {
      onUnexpectedError(e);
    }
  }
  // Sort by priority (largest to lowest)
  static sort(a, b) {
    return b.priority - a.priority;
  }
}
(function() {
  let NEXT_QUEUE = [];
  let CURRENT_QUEUE = null;
  let animFrameRequested = false;
  let inAnimationFrameRunner = false;
  const animationFrameRunner = () => {
    animFrameRequested = false;
    CURRENT_QUEUE = NEXT_QUEUE;
    NEXT_QUEUE = [];
    inAnimationFrameRunner = true;
    while (CURRENT_QUEUE.length > 0) {
      CURRENT_QUEUE.sort(AnimationFrameQueueItem.sort);
      const top = CURRENT_QUEUE.shift();
      top.execute();
    }
    inAnimationFrameRunner = false;
  };
  scheduleAtNextAnimationFrame = (runner, priority = 0) => {
    const item = new AnimationFrameQueueItem(runner, priority);
    NEXT_QUEUE.push(item);
    if (!animFrameRequested) {
      animFrameRequested = true;
      requestAnimationFrame(animationFrameRunner);
    }
    return item;
  };
  runAtThisOrScheduleAtNextAnimationFrame = (runner, priority) => {
    if (inAnimationFrameRunner) {
      const item = new AnimationFrameQueueItem(runner, priority);
      CURRENT_QUEUE.push(item);
      return item;
    } else {
      return scheduleAtNextAnimationFrame(runner, priority);
    }
  };
})();
function getComputedStyle$1(el) {
  return document.defaultView.getComputedStyle(el, null);
}
function getClientArea(element) {
  if (element !== document.body) {
    return new Dimension(element.clientWidth, element.clientHeight);
  }
  if (isIOS && window.visualViewport) {
    return new Dimension(window.visualViewport.width, window.visualViewport.height);
  }
  if (window.innerWidth && window.innerHeight) {
    return new Dimension(window.innerWidth, window.innerHeight);
  }
  if (document.body && document.body.clientWidth && document.body.clientHeight) {
    return new Dimension(document.body.clientWidth, document.body.clientHeight);
  }
  if (document.documentElement && document.documentElement.clientWidth && document.documentElement.clientHeight) {
    return new Dimension(document.documentElement.clientWidth, document.documentElement.clientHeight);
  }
  throw new Error("Unable to figure out browser width and height");
}
class SizeUtils {
  // Adapted from WinJS
  // Converts a CSS positioning string for the specified element to pixels.
  static convertToPixels(element, value) {
    return parseFloat(value) || 0;
  }
  static getDimension(element, cssPropertyName, jsPropertyName) {
    const computedStyle = getComputedStyle$1(element);
    const value = computedStyle ? computedStyle.getPropertyValue(cssPropertyName) : "0";
    return SizeUtils.convertToPixels(element, value);
  }
  static getBorderLeftWidth(element) {
    return SizeUtils.getDimension(element, "border-left-width", "borderLeftWidth");
  }
  static getBorderRightWidth(element) {
    return SizeUtils.getDimension(element, "border-right-width", "borderRightWidth");
  }
  static getBorderTopWidth(element) {
    return SizeUtils.getDimension(element, "border-top-width", "borderTopWidth");
  }
  static getBorderBottomWidth(element) {
    return SizeUtils.getDimension(element, "border-bottom-width", "borderBottomWidth");
  }
  static getPaddingLeft(element) {
    return SizeUtils.getDimension(element, "padding-left", "paddingLeft");
  }
  static getPaddingRight(element) {
    return SizeUtils.getDimension(element, "padding-right", "paddingRight");
  }
  static getPaddingTop(element) {
    return SizeUtils.getDimension(element, "padding-top", "paddingTop");
  }
  static getPaddingBottom(element) {
    return SizeUtils.getDimension(element, "padding-bottom", "paddingBottom");
  }
  static getMarginLeft(element) {
    return SizeUtils.getDimension(element, "margin-left", "marginLeft");
  }
  static getMarginTop(element) {
    return SizeUtils.getDimension(element, "margin-top", "marginTop");
  }
  static getMarginRight(element) {
    return SizeUtils.getDimension(element, "margin-right", "marginRight");
  }
  static getMarginBottom(element) {
    return SizeUtils.getDimension(element, "margin-bottom", "marginBottom");
  }
}
class Dimension {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }
  with(width = this.width, height = this.height) {
    if (width !== this.width || height !== this.height) {
      return new Dimension(width, height);
    } else {
      return this;
    }
  }
  static is(obj) {
    return typeof obj === "object" && typeof obj.height === "number" && typeof obj.width === "number";
  }
  static lift(obj) {
    if (obj instanceof Dimension) {
      return obj;
    } else {
      return new Dimension(obj.width, obj.height);
    }
  }
  static equals(a, b) {
    if (a === b) {
      return true;
    }
    if (!a || !b) {
      return false;
    }
    return a.width === b.width && a.height === b.height;
  }
}
Dimension.None = new Dimension(0, 0);
function getTopLeftOffset(element) {
  let offsetParent = element.offsetParent;
  let top = element.offsetTop;
  let left = element.offsetLeft;
  while ((element = element.parentNode) !== null && element !== document.body && element !== document.documentElement) {
    top -= element.scrollTop;
    const c = isShadowRoot(element) ? null : getComputedStyle$1(element);
    if (c) {
      left -= c.direction !== "rtl" ? element.scrollLeft : -element.scrollLeft;
    }
    if (element === offsetParent) {
      left += SizeUtils.getBorderLeftWidth(element);
      top += SizeUtils.getBorderTopWidth(element);
      top += element.offsetTop;
      left += element.offsetLeft;
      offsetParent = element.offsetParent;
    }
  }
  return {
    left,
    top
  };
}
function size(element, width, height) {
  if (typeof width === "number") {
    element.style.width = `${width}px`;
  }
  if (typeof height === "number") {
    element.style.height = `${height}px`;
  }
}
function getDomNodePagePosition(domNode) {
  const bb = domNode.getBoundingClientRect();
  return {
    left: bb.left + window.scrollX,
    top: bb.top + window.scrollY,
    width: bb.width,
    height: bb.height
  };
}
function getDomNodeZoomLevel(domNode) {
  let testElement = domNode;
  let zoom = 1;
  do {
    const elementZoomLevel = getComputedStyle$1(testElement).zoom;
    if (elementZoomLevel !== null && elementZoomLevel !== void 0 && elementZoomLevel !== "1") {
      zoom *= elementZoomLevel;
    }
    testElement = testElement.parentElement;
  } while (testElement !== null && testElement !== document.documentElement);
  return zoom;
}
function getTotalWidth(element) {
  const margin2 = SizeUtils.getMarginLeft(element) + SizeUtils.getMarginRight(element);
  return element.offsetWidth + margin2;
}
function getContentWidth(element) {
  const border = SizeUtils.getBorderLeftWidth(element) + SizeUtils.getBorderRightWidth(element);
  const padding = SizeUtils.getPaddingLeft(element) + SizeUtils.getPaddingRight(element);
  return element.offsetWidth - border - padding;
}
function getContentHeight(element) {
  const border = SizeUtils.getBorderTopWidth(element) + SizeUtils.getBorderBottomWidth(element);
  const padding = SizeUtils.getPaddingTop(element) + SizeUtils.getPaddingBottom(element);
  return element.offsetHeight - border - padding;
}
function getTotalHeight(element) {
  const margin2 = SizeUtils.getMarginTop(element) + SizeUtils.getMarginBottom(element);
  return element.offsetHeight + margin2;
}
function isAncestor$1(testChild, testAncestor) {
  while (testChild) {
    if (testChild === testAncestor) {
      return true;
    }
    testChild = testChild.parentNode;
  }
  return false;
}
function findParentWithClass(node2, clazz, stopAtClazzOrNode) {
  while (node2 && node2.nodeType === node2.ELEMENT_NODE) {
    if (node2.classList.contains(clazz)) {
      return node2;
    }
    if (stopAtClazzOrNode) {
      if (typeof stopAtClazzOrNode === "string") {
        if (node2.classList.contains(stopAtClazzOrNode)) {
          return null;
        }
      } else {
        if (node2 === stopAtClazzOrNode) {
          return null;
        }
      }
    }
    node2 = node2.parentNode;
  }
  return null;
}
function hasParentWithClass(node2, clazz, stopAtClazzOrNode) {
  return !!findParentWithClass(node2, clazz, stopAtClazzOrNode);
}
function isShadowRoot(node2) {
  return node2 && !!node2.host && !!node2.mode;
}
function isInShadowDOM(domNode) {
  return !!getShadowRoot(domNode);
}
function getShadowRoot(domNode) {
  while (domNode.parentNode) {
    if (domNode === document.body) {
      return null;
    }
    domNode = domNode.parentNode;
  }
  return isShadowRoot(domNode) ? domNode : null;
}
function getActiveElement() {
  let result2 = document.activeElement;
  while (result2 === null || result2 === void 0 ? void 0 : result2.shadowRoot) {
    result2 = result2.shadowRoot.activeElement;
  }
  return result2;
}
function createStyleSheet(container2 = document.getElementsByTagName("head")[0], beforeAppend) {
  const style2 = document.createElement("style");
  style2.type = "text/css";
  style2.media = "screen";
  beforeAppend === null || beforeAppend === void 0 ? void 0 : beforeAppend(style2);
  container2.appendChild(style2);
  return style2;
}
let _sharedStyleSheet = null;
function getSharedStyleSheet() {
  if (!_sharedStyleSheet) {
    _sharedStyleSheet = createStyleSheet();
  }
  return _sharedStyleSheet;
}
function getDynamicStyleSheetRules(style2) {
  var _a2, _b2;
  if ((_a2 = style2 === null || style2 === void 0 ? void 0 : style2.sheet) === null || _a2 === void 0 ? void 0 : _a2.rules) {
    return style2.sheet.rules;
  }
  if ((_b2 = style2 === null || style2 === void 0 ? void 0 : style2.sheet) === null || _b2 === void 0 ? void 0 : _b2.cssRules) {
    return style2.sheet.cssRules;
  }
  return [];
}
function createCSSRule(selector3, cssText, style2 = getSharedStyleSheet()) {
  if (!style2 || !cssText) {
    return;
  }
  style2.sheet.insertRule(selector3 + "{" + cssText + "}", 0);
}
function removeCSSRulesContainingSelector(ruleName, style2 = getSharedStyleSheet()) {
  if (!style2) {
    return;
  }
  const rules = getDynamicStyleSheetRules(style2);
  const toDelete = [];
  for (let i = 0; i < rules.length; i++) {
    const rule2 = rules[i];
    if (rule2.selectorText.indexOf(ruleName) !== -1) {
      toDelete.push(i);
    }
  }
  for (let i = toDelete.length - 1; i >= 0; i--) {
    style2.sheet.deleteRule(toDelete[i]);
  }
}
function isHTMLElement(o) {
  if (typeof HTMLElement === "object") {
    return o instanceof HTMLElement;
  }
  return o && typeof o === "object" && o.nodeType === 1 && typeof o.nodeName === "string";
}
const EventType$1 = {
  // Mouse
  CLICK: "click",
  AUXCLICK: "auxclick",
  DBLCLICK: "dblclick",
  MOUSE_UP: "mouseup",
  MOUSE_DOWN: "mousedown",
  MOUSE_OVER: "mouseover",
  MOUSE_MOVE: "mousemove",
  MOUSE_OUT: "mouseout",
  MOUSE_ENTER: "mouseenter",
  MOUSE_LEAVE: "mouseleave",
  MOUSE_WHEEL: "wheel",
  POINTER_UP: "pointerup",
  POINTER_DOWN: "pointerdown",
  POINTER_MOVE: "pointermove",
  POINTER_LEAVE: "pointerleave",
  CONTEXT_MENU: "contextmenu",
  WHEEL: "wheel",
  // Keyboard
  KEY_DOWN: "keydown",
  KEY_PRESS: "keypress",
  KEY_UP: "keyup",
  // HTML Document
  LOAD: "load",
  BEFORE_UNLOAD: "beforeunload",
  UNLOAD: "unload",
  PAGE_SHOW: "pageshow",
  PAGE_HIDE: "pagehide",
  ABORT: "abort",
  ERROR: "error",
  RESIZE: "resize",
  SCROLL: "scroll",
  FULLSCREEN_CHANGE: "fullscreenchange",
  WK_FULLSCREEN_CHANGE: "webkitfullscreenchange",
  // Form
  SELECT: "select",
  CHANGE: "change",
  SUBMIT: "submit",
  RESET: "reset",
  FOCUS: "focus",
  FOCUS_IN: "focusin",
  FOCUS_OUT: "focusout",
  BLUR: "blur",
  INPUT: "input",
  // Local Storage
  STORAGE: "storage",
  // Drag
  DRAG_START: "dragstart",
  DRAG: "drag",
  DRAG_ENTER: "dragenter",
  DRAG_LEAVE: "dragleave",
  DRAG_OVER: "dragover",
  DROP: "drop",
  DRAG_END: "dragend",
  // Animation
  ANIMATION_START: isWebKit ? "webkitAnimationStart" : "animationstart",
  ANIMATION_END: isWebKit ? "webkitAnimationEnd" : "animationend",
  ANIMATION_ITERATION: isWebKit ? "webkitAnimationIteration" : "animationiteration"
};
function isEventLike(obj) {
  const candidate = obj;
  return !!(candidate && typeof candidate.preventDefault === "function" && typeof candidate.stopPropagation === "function");
}
const EventHelper = {
  stop: (e, cancelBubble) => {
    e.preventDefault();
    if (cancelBubble) {
      e.stopPropagation();
    }
    return e;
  }
};
function saveParentsScrollTop(node2) {
  const r = [];
  for (let i = 0; node2 && node2.nodeType === node2.ELEMENT_NODE; i++) {
    r[i] = node2.scrollTop;
    node2 = node2.parentNode;
  }
  return r;
}
function restoreParentsScrollTop(node2, state) {
  for (let i = 0; node2 && node2.nodeType === node2.ELEMENT_NODE; i++) {
    if (node2.scrollTop !== state[i]) {
      node2.scrollTop = state[i];
    }
    node2 = node2.parentNode;
  }
}
class FocusTracker extends Disposable {
  static hasFocusWithin(element) {
    const shadowRoot = getShadowRoot(element);
    const activeElement = shadowRoot ? shadowRoot.activeElement : document.activeElement;
    return isAncestor$1(activeElement, element);
  }
  constructor(element) {
    super();
    this._onDidFocus = this._register(new Emitter$1());
    this.onDidFocus = this._onDidFocus.event;
    this._onDidBlur = this._register(new Emitter$1());
    this.onDidBlur = this._onDidBlur.event;
    let hasFocus = FocusTracker.hasFocusWithin(element);
    let loosingFocus = false;
    const onFocus = () => {
      loosingFocus = false;
      if (!hasFocus) {
        hasFocus = true;
        this._onDidFocus.fire();
      }
    };
    const onBlur = () => {
      if (hasFocus) {
        loosingFocus = true;
        window.setTimeout(() => {
          if (loosingFocus) {
            loosingFocus = false;
            hasFocus = false;
            this._onDidBlur.fire();
          }
        }, 0);
      }
    };
    this._refreshStateHandler = () => {
      const currentNodeHasFocus = FocusTracker.hasFocusWithin(element);
      if (currentNodeHasFocus !== hasFocus) {
        if (hasFocus) {
          onBlur();
        } else {
          onFocus();
        }
      }
    };
    this._register(addDisposableListener(element, EventType$1.FOCUS, onFocus, true));
    this._register(addDisposableListener(element, EventType$1.BLUR, onBlur, true));
    this._register(addDisposableListener(element, EventType$1.FOCUS_IN, () => this._refreshStateHandler()));
    this._register(addDisposableListener(element, EventType$1.FOCUS_OUT, () => this._refreshStateHandler()));
  }
}
function trackFocus(element) {
  return new FocusTracker(element);
}
function append$1(parent, ...children) {
  parent.append(...children);
  if (children.length === 1 && typeof children[0] !== "string") {
    return children[0];
  }
}
function prepend$1(parent, child) {
  parent.insertBefore(child, parent.firstChild);
  return child;
}
function reset(parent, ...children) {
  parent.innerText = "";
  append$1(parent, ...children);
}
const SELECTOR_REGEX = /([\w\-]+)?(#([\w\-]+))?((\.([\w\-]+))*)/;
var Namespace;
(function(Namespace2) {
  Namespace2["HTML"] = "http://www.w3.org/1999/xhtml";
  Namespace2["SVG"] = "http://www.w3.org/2000/svg";
})(Namespace || (Namespace = {}));
function _$(namespace2, description, attrs, ...children) {
  const match2 = SELECTOR_REGEX.exec(description);
  if (!match2) {
    throw new Error("Bad use of emmet");
  }
  const tagName = match2[1] || "div";
  let result2;
  if (namespace2 !== Namespace.HTML) {
    result2 = document.createElementNS(namespace2, tagName);
  } else {
    result2 = document.createElement(tagName);
  }
  if (match2[3]) {
    result2.id = match2[3];
  }
  if (match2[4]) {
    result2.className = match2[4].replace(/\./g, " ").trim();
  }
  if (attrs) {
    Object.entries(attrs).forEach(([name, value]) => {
      if (typeof value === "undefined") {
        return;
      }
      if (/^on\w+$/.test(name)) {
        result2[name] = value;
      } else if (name === "selected") {
        if (value) {
          result2.setAttribute(name, "true");
        }
      } else {
        result2.setAttribute(name, value);
      }
    });
  }
  result2.append(...children);
  return result2;
}
function $$d(description, attrs, ...children) {
  return _$(Namespace.HTML, description, attrs, ...children);
}
$$d.SVG = function(description, attrs, ...children) {
  return _$(Namespace.SVG, description, attrs, ...children);
};
function setVisibility(visible, ...elements) {
  if (visible) {
    show(...elements);
  } else {
    hide(...elements);
  }
}
function show(...elements) {
  for (const element of elements) {
    element.style.display = "";
    element.removeAttribute("aria-hidden");
  }
}
function hide(...elements) {
  for (const element of elements) {
    element.style.display = "none";
    element.setAttribute("aria-hidden", "true");
  }
}
function computeScreenAwareSize(cssPx) {
  const screenPx = window.devicePixelRatio * cssPx;
  return Math.max(1, Math.floor(screenPx)) / window.devicePixelRatio;
}
function windowOpenNoOpener(url) {
  window.open(url, "_blank", "noopener");
}
function animate(fn) {
  const step = () => {
    fn();
    stepDisposable = scheduleAtNextAnimationFrame(step);
  };
  let stepDisposable = scheduleAtNextAnimationFrame(step);
  return toDisposable(() => stepDisposable.dispose());
}
RemoteAuthorities.setPreferredWebSchema(/^https:/.test(window.location.href) ? "https" : "http");
function asCSSUrl(uri) {
  if (!uri) {
    return `url('')`;
  }
  return `url('${FileAccess.uriToBrowserUri(uri).toString(true).replace(/'/g, "%27")}')`;
}
function asCSSPropertyValue(value) {
  return `'${value.replace(/'/g, "%27")}'`;
}
function asCssValueWithDefault(cssPropertyValue, dflt) {
  if (cssPropertyValue !== void 0) {
    const variableMatch = cssPropertyValue.match(/^\s*var\((.+)\)$/);
    if (variableMatch) {
      const varArguments = variableMatch[1].split(",", 2);
      if (varArguments.length === 2) {
        dflt = asCssValueWithDefault(varArguments[1].trim(), dflt);
      }
      return `var(${varArguments[0]}, ${dflt})`;
    }
    return cssPropertyValue;
  }
  return dflt;
}
function hookDomPurifyHrefAndSrcSanitizer(allowedProtocols, allowDataImages = false) {
  const anchor = document.createElement("a");
  addHook("afterSanitizeAttributes", (node2) => {
    for (const attr of ["href", "src"]) {
      if (node2.hasAttribute(attr)) {
        const attrValue = node2.getAttribute(attr);
        if (attr === "href" && attrValue.startsWith("#")) {
          continue;
        }
        anchor.href = attrValue;
        if (!allowedProtocols.includes(anchor.protocol.replace(/:$/, ""))) {
          if (allowDataImages && attr === "src" && anchor.href.startsWith("data:")) {
            continue;
          }
          node2.removeAttribute(attr);
        }
      }
    }
  });
  return toDisposable(() => {
    removeHook("afterSanitizeAttributes");
  });
}
const basicMarkupHtmlTags = Object.freeze([
  "a",
  "abbr",
  "b",
  "bdo",
  "blockquote",
  "br",
  "caption",
  "cite",
  "code",
  "col",
  "colgroup",
  "dd",
  "del",
  "details",
  "dfn",
  "div",
  "dl",
  "dt",
  "em",
  "figcaption",
  "figure",
  "h1",
  "h2",
  "h3",
  "h4",
  "h5",
  "h6",
  "hr",
  "i",
  "img",
  "ins",
  "kbd",
  "label",
  "li",
  "mark",
  "ol",
  "p",
  "pre",
  "q",
  "rp",
  "rt",
  "ruby",
  "samp",
  "small",
  "small",
  "source",
  "span",
  "strike",
  "strong",
  "sub",
  "summary",
  "sup",
  "table",
  "tbody",
  "td",
  "tfoot",
  "th",
  "thead",
  "time",
  "tr",
  "tt",
  "u",
  "ul",
  "var",
  "video",
  "wbr"
]);
class ModifierKeyEmitter extends Emitter$1 {
  constructor() {
    super();
    this._subscriptions = new DisposableStore();
    this._keyStatus = {
      altKey: false,
      shiftKey: false,
      ctrlKey: false,
      metaKey: false
    };
    this._subscriptions.add(addDisposableListener(window, "keydown", (e) => {
      if (e.defaultPrevented) {
        return;
      }
      const event = new StandardKeyboardEvent(e);
      if (event.keyCode === 6 && e.repeat) {
        return;
      }
      if (e.altKey && !this._keyStatus.altKey) {
        this._keyStatus.lastKeyPressed = "alt";
      } else if (e.ctrlKey && !this._keyStatus.ctrlKey) {
        this._keyStatus.lastKeyPressed = "ctrl";
      } else if (e.metaKey && !this._keyStatus.metaKey) {
        this._keyStatus.lastKeyPressed = "meta";
      } else if (e.shiftKey && !this._keyStatus.shiftKey) {
        this._keyStatus.lastKeyPressed = "shift";
      } else if (event.keyCode !== 6) {
        this._keyStatus.lastKeyPressed = void 0;
      } else {
        return;
      }
      this._keyStatus.altKey = e.altKey;
      this._keyStatus.ctrlKey = e.ctrlKey;
      this._keyStatus.metaKey = e.metaKey;
      this._keyStatus.shiftKey = e.shiftKey;
      if (this._keyStatus.lastKeyPressed) {
        this._keyStatus.event = e;
        this.fire(this._keyStatus);
      }
    }, true));
    this._subscriptions.add(addDisposableListener(window, "keyup", (e) => {
      if (e.defaultPrevented) {
        return;
      }
      if (!e.altKey && this._keyStatus.altKey) {
        this._keyStatus.lastKeyReleased = "alt";
      } else if (!e.ctrlKey && this._keyStatus.ctrlKey) {
        this._keyStatus.lastKeyReleased = "ctrl";
      } else if (!e.metaKey && this._keyStatus.metaKey) {
        this._keyStatus.lastKeyReleased = "meta";
      } else if (!e.shiftKey && this._keyStatus.shiftKey) {
        this._keyStatus.lastKeyReleased = "shift";
      } else {
        this._keyStatus.lastKeyReleased = void 0;
      }
      if (this._keyStatus.lastKeyPressed !== this._keyStatus.lastKeyReleased) {
        this._keyStatus.lastKeyPressed = void 0;
      }
      this._keyStatus.altKey = e.altKey;
      this._keyStatus.ctrlKey = e.ctrlKey;
      this._keyStatus.metaKey = e.metaKey;
      this._keyStatus.shiftKey = e.shiftKey;
      if (this._keyStatus.lastKeyReleased) {
        this._keyStatus.event = e;
        this.fire(this._keyStatus);
      }
    }, true));
    this._subscriptions.add(addDisposableListener(document.body, "mousedown", () => {
      this._keyStatus.lastKeyPressed = void 0;
    }, true));
    this._subscriptions.add(addDisposableListener(document.body, "mouseup", () => {
      this._keyStatus.lastKeyPressed = void 0;
    }, true));
    this._subscriptions.add(addDisposableListener(document.body, "mousemove", (e) => {
      if (e.buttons) {
        this._keyStatus.lastKeyPressed = void 0;
      }
    }, true));
    this._subscriptions.add(addDisposableListener(window, "blur", () => {
      this.resetKeyStatus();
    }));
  }
  get keyStatus() {
    return this._keyStatus;
  }
  /**
   * Allows to explicitly reset the key status based on more knowledge (#109062)
   */
  resetKeyStatus() {
    this.doResetKeyStatus();
    this.fire(this._keyStatus);
  }
  doResetKeyStatus() {
    this._keyStatus = {
      altKey: false,
      shiftKey: false,
      ctrlKey: false,
      metaKey: false
    };
  }
  static getInstance() {
    if (!ModifierKeyEmitter.instance) {
      ModifierKeyEmitter.instance = new ModifierKeyEmitter();
    }
    return ModifierKeyEmitter.instance;
  }
  dispose() {
    super.dispose();
    this._subscriptions.dispose();
  }
}
class DragAndDropObserver extends Disposable {
  constructor(element, callbacks) {
    super();
    this.element = element;
    this.callbacks = callbacks;
    this.counter = 0;
    this.dragStartTime = 0;
    this.registerListeners();
  }
  registerListeners() {
    this._register(addDisposableListener(this.element, EventType$1.DRAG_ENTER, (e) => {
      this.counter++;
      this.dragStartTime = e.timeStamp;
      this.callbacks.onDragEnter(e);
    }));
    this._register(addDisposableListener(this.element, EventType$1.DRAG_OVER, (e) => {
      var _a2, _b2;
      e.preventDefault();
      (_b2 = (_a2 = this.callbacks).onDragOver) === null || _b2 === void 0 ? void 0 : _b2.call(_a2, e, e.timeStamp - this.dragStartTime);
    }));
    this._register(addDisposableListener(this.element, EventType$1.DRAG_LEAVE, (e) => {
      this.counter--;
      if (this.counter === 0) {
        this.dragStartTime = 0;
        this.callbacks.onDragLeave(e);
      }
    }));
    this._register(addDisposableListener(this.element, EventType$1.DRAG_END, (e) => {
      this.counter = 0;
      this.dragStartTime = 0;
      this.callbacks.onDragEnd(e);
    }));
    this._register(addDisposableListener(this.element, EventType$1.DROP, (e) => {
      this.counter = 0;
      this.dragStartTime = 0;
      this.callbacks.onDrop(e);
    }));
  }
}
const H_REGEX = /(?<tag>[\w\-]+)?(?:#(?<id>[\w\-]+))?(?<class>(?:\.(?:[\w\-]+))*)(?:@(?<name>(?:[\w\_])+))?/;
function h(tag3, ...args) {
  let attributes;
  let children;
  if (Array.isArray(args[0])) {
    attributes = {};
    children = args[0];
  } else {
    attributes = args[0] || {};
    children = args[1];
  }
  const match2 = H_REGEX.exec(tag3);
  if (!match2 || !match2.groups) {
    throw new Error("Bad use of h");
  }
  const tagName = match2.groups["tag"] || "div";
  const el = document.createElement(tagName);
  if (match2.groups["id"]) {
    el.id = match2.groups["id"];
  }
  const classNames = [];
  if (match2.groups["class"]) {
    for (const className3 of match2.groups["class"].split(".")) {
      if (className3 !== "") {
        classNames.push(className3);
      }
    }
  }
  if (attributes.className !== void 0) {
    for (const className3 of attributes.className.split(".")) {
      if (className3 !== "") {
        classNames.push(className3);
      }
    }
  }
  if (classNames.length > 0) {
    el.className = classNames.join(" ");
  }
  const result2 = {};
  if (match2.groups["name"]) {
    result2[match2.groups["name"]] = el;
  }
  if (children) {
    for (const c of children) {
      if (c instanceof HTMLElement) {
        el.appendChild(c);
      } else if (typeof c === "string") {
        el.append(c);
      } else if ("root" in c) {
        Object.assign(result2, c);
        el.appendChild(c.root);
      }
    }
  }
  for (const [key, value] of Object.entries(attributes)) {
    if (key === "className") {
      continue;
    } else if (key === "style") {
      for (const [cssKey, cssValue] of Object.entries(value)) {
        el.style.setProperty(camelCaseToHyphenCase(cssKey), typeof cssValue === "number" ? cssValue + "px" : "" + cssValue);
      }
    } else if (key === "tabIndex") {
      el.tabIndex = value;
    } else {
      el.setAttribute(camelCaseToHyphenCase(key), value.toString());
    }
  }
  result2["root"] = el;
  return result2;
}
function camelCaseToHyphenCase(str2) {
  return str2.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
}
const aria = "";
const MAX_MESSAGE_LENGTH = 2e4;
let ariaContainer;
let alertContainer;
let alertContainer2;
let statusContainer;
let statusContainer2;
function setARIAContainer(parent) {
  ariaContainer = document.createElement("div");
  ariaContainer.className = "monaco-aria-container";
  const createAlertContainer = () => {
    const element = document.createElement("div");
    element.className = "monaco-alert";
    element.setAttribute("role", "alert");
    element.setAttribute("aria-atomic", "true");
    ariaContainer.appendChild(element);
    return element;
  };
  alertContainer = createAlertContainer();
  alertContainer2 = createAlertContainer();
  const createStatusContainer = () => {
    const element = document.createElement("div");
    element.className = "monaco-status";
    element.setAttribute("aria-live", "polite");
    element.setAttribute("aria-atomic", "true");
    ariaContainer.appendChild(element);
    return element;
  };
  statusContainer = createStatusContainer();
  statusContainer2 = createStatusContainer();
  parent.appendChild(ariaContainer);
}
function alert(msg) {
  if (!ariaContainer) {
    return;
  }
  if (alertContainer.textContent !== msg) {
    clearNode(alertContainer2);
    insertMessage(alertContainer, msg);
  } else {
    clearNode(alertContainer);
    insertMessage(alertContainer2, msg);
  }
}
function status(msg) {
  if (!ariaContainer) {
    return;
  }
  if (statusContainer.textContent !== msg) {
    clearNode(statusContainer2);
    insertMessage(statusContainer, msg);
  } else {
    clearNode(statusContainer);
    insertMessage(statusContainer2, msg);
  }
}
function insertMessage(target, msg) {
  clearNode(target);
  if (msg.length > MAX_MESSAGE_LENGTH) {
    msg = msg.substr(0, MAX_MESSAGE_LENGTH);
  }
  target.textContent = msg;
  target.style.visibility = "hidden";
  target.style.visibility = "visible";
}
var _util;
(function(_util2) {
  _util2.serviceIds = /* @__PURE__ */ new Map();
  _util2.DI_TARGET = "$di$target";
  _util2.DI_DEPENDENCIES = "$di$dependencies";
  function getServiceDependencies(ctor) {
    return ctor[_util2.DI_DEPENDENCIES] || [];
  }
  _util2.getServiceDependencies = getServiceDependencies;
})(_util || (_util = {}));
const IInstantiationService = createDecorator("instantiationService");
function storeServiceDependency(id3, target, index) {
  if (target[_util.DI_TARGET] === target) {
    target[_util.DI_DEPENDENCIES].push({ id: id3, index });
  } else {
    target[_util.DI_DEPENDENCIES] = [{ id: id3, index }];
    target[_util.DI_TARGET] = target;
  }
}
function createDecorator(serviceId) {
  if (_util.serviceIds.has(serviceId)) {
    return _util.serviceIds.get(serviceId);
  }
  const id3 = function(target, key, index) {
    if (arguments.length !== 3) {
      throw new Error("@IServiceName-decorator can only be used to decorate a parameter");
    }
    storeServiceDependency(id3, target, index);
  };
  id3.toString = () => serviceId;
  _util.serviceIds.set(serviceId, id3);
  return id3;
}
const ICodeEditorService = createDecorator("codeEditorService");
let Position$2 = class Position {
  constructor(lineNumber, column) {
    this.lineNumber = lineNumber;
    this.column = column;
  }
  /**
   * Create a new position from this position.
   *
   * @param newLineNumber new line number
   * @param newColumn new column
   */
  with(newLineNumber = this.lineNumber, newColumn = this.column) {
    if (newLineNumber === this.lineNumber && newColumn === this.column) {
      return this;
    } else {
      return new Position(newLineNumber, newColumn);
    }
  }
  /**
   * Derive a new position from this position.
   *
   * @param deltaLineNumber line number delta
   * @param deltaColumn column delta
   */
  delta(deltaLineNumber = 0, deltaColumn = 0) {
    return this.with(this.lineNumber + deltaLineNumber, this.column + deltaColumn);
  }
  /**
   * Test if this position equals other position
   */
  equals(other) {
    return Position.equals(this, other);
  }
  /**
   * Test if position `a` equals position `b`
   */
  static equals(a, b) {
    if (!a && !b) {
      return true;
    }
    return !!a && !!b && a.lineNumber === b.lineNumber && a.column === b.column;
  }
  /**
   * Test if this position is before other position.
   * If the two positions are equal, the result will be false.
   */
  isBefore(other) {
    return Position.isBefore(this, other);
  }
  /**
   * Test if position `a` is before position `b`.
   * If the two positions are equal, the result will be false.
   */
  static isBefore(a, b) {
    if (a.lineNumber < b.lineNumber) {
      return true;
    }
    if (b.lineNumber < a.lineNumber) {
      return false;
    }
    return a.column < b.column;
  }
  /**
   * Test if this position is before other position.
   * If the two positions are equal, the result will be true.
   */
  isBeforeOrEqual(other) {
    return Position.isBeforeOrEqual(this, other);
  }
  /**
   * Test if position `a` is before position `b`.
   * If the two positions are equal, the result will be true.
   */
  static isBeforeOrEqual(a, b) {
    if (a.lineNumber < b.lineNumber) {
      return true;
    }
    if (b.lineNumber < a.lineNumber) {
      return false;
    }
    return a.column <= b.column;
  }
  /**
   * A function that compares positions, useful for sorting
   */
  static compare(a, b) {
    const aLineNumber = a.lineNumber | 0;
    const bLineNumber = b.lineNumber | 0;
    if (aLineNumber === bLineNumber) {
      const aColumn = a.column | 0;
      const bColumn = b.column | 0;
      return aColumn - bColumn;
    }
    return aLineNumber - bLineNumber;
  }
  /**
   * Clone this position.
   */
  clone() {
    return new Position(this.lineNumber, this.column);
  }
  /**
   * Convert to a human-readable representation.
   */
  toString() {
    return "(" + this.lineNumber + "," + this.column + ")";
  }
  // ---
  /**
   * Create a `Position` from an `IPosition`.
   */
  static lift(pos) {
    return new Position(pos.lineNumber, pos.column);
  }
  /**
   * Test if `obj` is an `IPosition`.
   */
  static isIPosition(obj) {
    return obj && typeof obj.lineNumber === "number" && typeof obj.column === "number";
  }
};
const IModelService = createDecorator("modelService");
const ITextModelService = createDecorator("textModelService");
var __awaiter$1A = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class Action extends Disposable {
  constructor(id3, label = "", cssClass = "", enabled = true, actionCallback) {
    super();
    this._onDidChange = this._register(new Emitter$1());
    this.onDidChange = this._onDidChange.event;
    this._enabled = true;
    this._id = id3;
    this._label = label;
    this._cssClass = cssClass;
    this._enabled = enabled;
    this._actionCallback = actionCallback;
  }
  get id() {
    return this._id;
  }
  get label() {
    return this._label;
  }
  set label(value) {
    this._setLabel(value);
  }
  _setLabel(value) {
    if (this._label !== value) {
      this._label = value;
      this._onDidChange.fire({ label: value });
    }
  }
  get tooltip() {
    return this._tooltip || "";
  }
  set tooltip(value) {
    this._setTooltip(value);
  }
  _setTooltip(value) {
    if (this._tooltip !== value) {
      this._tooltip = value;
      this._onDidChange.fire({ tooltip: value });
    }
  }
  get class() {
    return this._cssClass;
  }
  set class(value) {
    this._setClass(value);
  }
  _setClass(value) {
    if (this._cssClass !== value) {
      this._cssClass = value;
      this._onDidChange.fire({ class: value });
    }
  }
  get enabled() {
    return this._enabled;
  }
  set enabled(value) {
    this._setEnabled(value);
  }
  _setEnabled(value) {
    if (this._enabled !== value) {
      this._enabled = value;
      this._onDidChange.fire({ enabled: value });
    }
  }
  get checked() {
    return this._checked;
  }
  set checked(value) {
    this._setChecked(value);
  }
  _setChecked(value) {
    if (this._checked !== value) {
      this._checked = value;
      this._onDidChange.fire({ checked: value });
    }
  }
  run(event, data) {
    return __awaiter$1A(this, void 0, void 0, function* () {
      if (this._actionCallback) {
        yield this._actionCallback(event);
      }
    });
  }
}
class ActionRunner extends Disposable {
  constructor() {
    super(...arguments);
    this._onWillRun = this._register(new Emitter$1());
    this.onWillRun = this._onWillRun.event;
    this._onDidRun = this._register(new Emitter$1());
    this.onDidRun = this._onDidRun.event;
  }
  run(action, context) {
    return __awaiter$1A(this, void 0, void 0, function* () {
      if (!action.enabled) {
        return;
      }
      this._onWillRun.fire({ action });
      let error2 = void 0;
      try {
        yield this.runAction(action, context);
      } catch (e) {
        error2 = e;
      }
      this._onDidRun.fire({ action, error: error2 });
    });
  }
  runAction(action, context) {
    return __awaiter$1A(this, void 0, void 0, function* () {
      yield action.run(context);
    });
  }
}
class Separator {
  constructor() {
    this.id = Separator.ID;
    this.label = "";
    this.tooltip = "";
    this.class = "separator";
    this.enabled = false;
    this.checked = false;
  }
  /**
   * Joins all non-empty lists of actions with separators.
   */
  static join(...actionLists) {
    let out = [];
    for (const list2 of actionLists) {
      if (!list2.length)
        ;
      else if (out.length) {
        out = [...out, new Separator(), ...list2];
      } else {
        out = list2;
      }
    }
    return out;
  }
  run() {
    return __awaiter$1A(this, void 0, void 0, function* () {
    });
  }
}
Separator.ID = "vs.actions.separator";
class SubmenuAction {
  get actions() {
    return this._actions;
  }
  constructor(id3, label, actions, cssClass) {
    this.tooltip = "";
    this.enabled = true;
    this.checked = void 0;
    this.id = id3;
    this.label = label;
    this.class = cssClass;
    this._actions = actions;
  }
  run() {
    return __awaiter$1A(this, void 0, void 0, function* () {
    });
  }
}
class EmptySubmenuAction extends Action {
  constructor() {
    super(EmptySubmenuAction.ID, localize("submenu.empty", "(empty)"), void 0, false);
  }
}
EmptySubmenuAction.ID = "vs.actions.empty";
function toAction(props) {
  var _a2, _b2;
  return {
    id: props.id,
    label: props.label,
    class: void 0,
    enabled: (_a2 = props.enabled) !== null && _a2 !== void 0 ? _a2 : true,
    checked: (_b2 = props.checked) !== null && _b2 !== void 0 ? _b2 : false,
    run: () => __awaiter$1A(this, void 0, void 0, function* () {
      return props.run();
    }),
    tooltip: props.label
  };
}
const _codiconFontCharacters = /* @__PURE__ */ Object.create(null);
function register$2(id3, fontCharacter) {
  if (isString$4(fontCharacter)) {
    const val = _codiconFontCharacters[fontCharacter];
    if (val === void 0) {
      throw new Error(`${id3} references an unknown codicon: ${fontCharacter}`);
    }
    fontCharacter = val;
  }
  _codiconFontCharacters[id3] = fontCharacter;
  return { id: id3 };
}
function getCodiconFontCharacters() {
  return _codiconFontCharacters;
}
const Codicon = {
  // built-in icons, with image name
  add: register$2("add", 6e4),
  plus: register$2("plus", 6e4),
  gistNew: register$2("gist-new", 6e4),
  repoCreate: register$2("repo-create", 6e4),
  lightbulb: register$2("lightbulb", 60001),
  lightBulb: register$2("light-bulb", 60001),
  repo: register$2("repo", 60002),
  repoDelete: register$2("repo-delete", 60002),
  gistFork: register$2("gist-fork", 60003),
  repoForked: register$2("repo-forked", 60003),
  gitPullRequest: register$2("git-pull-request", 60004),
  gitPullRequestAbandoned: register$2("git-pull-request-abandoned", 60004),
  recordKeys: register$2("record-keys", 60005),
  keyboard: register$2("keyboard", 60005),
  tag: register$2("tag", 60006),
  tagAdd: register$2("tag-add", 60006),
  tagRemove: register$2("tag-remove", 60006),
  person: register$2("person", 60007),
  personFollow: register$2("person-follow", 60007),
  personOutline: register$2("person-outline", 60007),
  personFilled: register$2("person-filled", 60007),
  gitBranch: register$2("git-branch", 60008),
  gitBranchCreate: register$2("git-branch-create", 60008),
  gitBranchDelete: register$2("git-branch-delete", 60008),
  sourceControl: register$2("source-control", 60008),
  mirror: register$2("mirror", 60009),
  mirrorPublic: register$2("mirror-public", 60009),
  star: register$2("star", 60010),
  starAdd: register$2("star-add", 60010),
  starDelete: register$2("star-delete", 60010),
  starEmpty: register$2("star-empty", 60010),
  comment: register$2("comment", 60011),
  commentAdd: register$2("comment-add", 60011),
  alert: register$2("alert", 60012),
  warning: register$2("warning", 60012),
  search: register$2("search", 60013),
  searchSave: register$2("search-save", 60013),
  logOut: register$2("log-out", 60014),
  signOut: register$2("sign-out", 60014),
  logIn: register$2("log-in", 60015),
  signIn: register$2("sign-in", 60015),
  eye: register$2("eye", 60016),
  eyeUnwatch: register$2("eye-unwatch", 60016),
  eyeWatch: register$2("eye-watch", 60016),
  circleFilled: register$2("circle-filled", 60017),
  primitiveDot: register$2("primitive-dot", 60017),
  closeDirty: register$2("close-dirty", 60017),
  debugBreakpoint: register$2("debug-breakpoint", 60017),
  debugBreakpointDisabled: register$2("debug-breakpoint-disabled", 60017),
  debugHint: register$2("debug-hint", 60017),
  primitiveSquare: register$2("primitive-square", 60018),
  edit: register$2("edit", 60019),
  pencil: register$2("pencil", 60019),
  info: register$2("info", 60020),
  issueOpened: register$2("issue-opened", 60020),
  gistPrivate: register$2("gist-private", 60021),
  gitForkPrivate: register$2("git-fork-private", 60021),
  lock: register$2("lock", 60021),
  mirrorPrivate: register$2("mirror-private", 60021),
  close: register$2("close", 60022),
  removeClose: register$2("remove-close", 60022),
  x: register$2("x", 60022),
  repoSync: register$2("repo-sync", 60023),
  sync: register$2("sync", 60023),
  clone: register$2("clone", 60024),
  desktopDownload: register$2("desktop-download", 60024),
  beaker: register$2("beaker", 60025),
  microscope: register$2("microscope", 60025),
  vm: register$2("vm", 60026),
  deviceDesktop: register$2("device-desktop", 60026),
  file: register$2("file", 60027),
  fileText: register$2("file-text", 60027),
  more: register$2("more", 60028),
  ellipsis: register$2("ellipsis", 60028),
  kebabHorizontal: register$2("kebab-horizontal", 60028),
  mailReply: register$2("mail-reply", 60029),
  reply: register$2("reply", 60029),
  organization: register$2("organization", 60030),
  organizationFilled: register$2("organization-filled", 60030),
  organizationOutline: register$2("organization-outline", 60030),
  newFile: register$2("new-file", 60031),
  fileAdd: register$2("file-add", 60031),
  newFolder: register$2("new-folder", 60032),
  fileDirectoryCreate: register$2("file-directory-create", 60032),
  trash: register$2("trash", 60033),
  trashcan: register$2("trashcan", 60033),
  history: register$2("history", 60034),
  clock: register$2("clock", 60034),
  folder: register$2("folder", 60035),
  fileDirectory: register$2("file-directory", 60035),
  symbolFolder: register$2("symbol-folder", 60035),
  logoGithub: register$2("logo-github", 60036),
  markGithub: register$2("mark-github", 60036),
  github: register$2("github", 60036),
  terminal: register$2("terminal", 60037),
  console: register$2("console", 60037),
  repl: register$2("repl", 60037),
  zap: register$2("zap", 60038),
  symbolEvent: register$2("symbol-event", 60038),
  error: register$2("error", 60039),
  stop: register$2("stop", 60039),
  variable: register$2("variable", 60040),
  symbolVariable: register$2("symbol-variable", 60040),
  array: register$2("array", 60042),
  symbolArray: register$2("symbol-array", 60042),
  symbolModule: register$2("symbol-module", 60043),
  symbolPackage: register$2("symbol-package", 60043),
  symbolNamespace: register$2("symbol-namespace", 60043),
  symbolObject: register$2("symbol-object", 60043),
  symbolMethod: register$2("symbol-method", 60044),
  symbolFunction: register$2("symbol-function", 60044),
  symbolConstructor: register$2("symbol-constructor", 60044),
  symbolBoolean: register$2("symbol-boolean", 60047),
  symbolNull: register$2("symbol-null", 60047),
  symbolNumeric: register$2("symbol-numeric", 60048),
  symbolNumber: register$2("symbol-number", 60048),
  symbolStructure: register$2("symbol-structure", 60049),
  symbolStruct: register$2("symbol-struct", 60049),
  symbolParameter: register$2("symbol-parameter", 60050),
  symbolTypeParameter: register$2("symbol-type-parameter", 60050),
  symbolKey: register$2("symbol-key", 60051),
  symbolText: register$2("symbol-text", 60051),
  symbolReference: register$2("symbol-reference", 60052),
  goToFile: register$2("go-to-file", 60052),
  symbolEnum: register$2("symbol-enum", 60053),
  symbolValue: register$2("symbol-value", 60053),
  symbolRuler: register$2("symbol-ruler", 60054),
  symbolUnit: register$2("symbol-unit", 60054),
  activateBreakpoints: register$2("activate-breakpoints", 60055),
  archive: register$2("archive", 60056),
  arrowBoth: register$2("arrow-both", 60057),
  arrowDown: register$2("arrow-down", 60058),
  arrowLeft: register$2("arrow-left", 60059),
  arrowRight: register$2("arrow-right", 60060),
  arrowSmallDown: register$2("arrow-small-down", 60061),
  arrowSmallLeft: register$2("arrow-small-left", 60062),
  arrowSmallRight: register$2("arrow-small-right", 60063),
  arrowSmallUp: register$2("arrow-small-up", 60064),
  arrowUp: register$2("arrow-up", 60065),
  bell: register$2("bell", 60066),
  bold: register$2("bold", 60067),
  book: register$2("book", 60068),
  bookmark: register$2("bookmark", 60069),
  debugBreakpointConditionalUnverified: register$2("debug-breakpoint-conditional-unverified", 60070),
  debugBreakpointConditional: register$2("debug-breakpoint-conditional", 60071),
  debugBreakpointConditionalDisabled: register$2("debug-breakpoint-conditional-disabled", 60071),
  debugBreakpointDataUnverified: register$2("debug-breakpoint-data-unverified", 60072),
  debugBreakpointData: register$2("debug-breakpoint-data", 60073),
  debugBreakpointDataDisabled: register$2("debug-breakpoint-data-disabled", 60073),
  debugBreakpointLogUnverified: register$2("debug-breakpoint-log-unverified", 60074),
  debugBreakpointLog: register$2("debug-breakpoint-log", 60075),
  debugBreakpointLogDisabled: register$2("debug-breakpoint-log-disabled", 60075),
  briefcase: register$2("briefcase", 60076),
  broadcast: register$2("broadcast", 60077),
  browser: register$2("browser", 60078),
  bug: register$2("bug", 60079),
  calendar: register$2("calendar", 60080),
  caseSensitive: register$2("case-sensitive", 60081),
  check: register$2("check", 60082),
  checklist: register$2("checklist", 60083),
  chevronDown: register$2("chevron-down", 60084),
  dropDownButton: register$2("drop-down-button", 60084),
  chevronLeft: register$2("chevron-left", 60085),
  chevronRight: register$2("chevron-right", 60086),
  chevronUp: register$2("chevron-up", 60087),
  chromeClose: register$2("chrome-close", 60088),
  chromeMaximize: register$2("chrome-maximize", 60089),
  chromeMinimize: register$2("chrome-minimize", 60090),
  chromeRestore: register$2("chrome-restore", 60091),
  circle: register$2("circle", 60092),
  circleOutline: register$2("circle-outline", 60092),
  debugBreakpointUnverified: register$2("debug-breakpoint-unverified", 60092),
  circleSlash: register$2("circle-slash", 60093),
  circuitBoard: register$2("circuit-board", 60094),
  clearAll: register$2("clear-all", 60095),
  clippy: register$2("clippy", 60096),
  closeAll: register$2("close-all", 60097),
  cloudDownload: register$2("cloud-download", 60098),
  cloudUpload: register$2("cloud-upload", 60099),
  code: register$2("code", 60100),
  collapseAll: register$2("collapse-all", 60101),
  colorMode: register$2("color-mode", 60102),
  commentDiscussion: register$2("comment-discussion", 60103),
  compareChanges: register$2("compare-changes", 60157),
  creditCard: register$2("credit-card", 60105),
  dash: register$2("dash", 60108),
  dashboard: register$2("dashboard", 60109),
  database: register$2("database", 60110),
  debugContinue: register$2("debug-continue", 60111),
  debugDisconnect: register$2("debug-disconnect", 60112),
  debugPause: register$2("debug-pause", 60113),
  debugRestart: register$2("debug-restart", 60114),
  debugStart: register$2("debug-start", 60115),
  debugStepInto: register$2("debug-step-into", 60116),
  debugStepOut: register$2("debug-step-out", 60117),
  debugStepOver: register$2("debug-step-over", 60118),
  debugStop: register$2("debug-stop", 60119),
  debug: register$2("debug", 60120),
  deviceCameraVideo: register$2("device-camera-video", 60121),
  deviceCamera: register$2("device-camera", 60122),
  deviceMobile: register$2("device-mobile", 60123),
  diffAdded: register$2("diff-added", 60124),
  diffIgnored: register$2("diff-ignored", 60125),
  diffModified: register$2("diff-modified", 60126),
  diffRemoved: register$2("diff-removed", 60127),
  diffRenamed: register$2("diff-renamed", 60128),
  diff: register$2("diff", 60129),
  discard: register$2("discard", 60130),
  editorLayout: register$2("editor-layout", 60131),
  emptyWindow: register$2("empty-window", 60132),
  exclude: register$2("exclude", 60133),
  extensions: register$2("extensions", 60134),
  eyeClosed: register$2("eye-closed", 60135),
  fileBinary: register$2("file-binary", 60136),
  fileCode: register$2("file-code", 60137),
  fileMedia: register$2("file-media", 60138),
  filePdf: register$2("file-pdf", 60139),
  fileSubmodule: register$2("file-submodule", 60140),
  fileSymlinkDirectory: register$2("file-symlink-directory", 60141),
  fileSymlinkFile: register$2("file-symlink-file", 60142),
  fileZip: register$2("file-zip", 60143),
  files: register$2("files", 60144),
  filter: register$2("filter", 60145),
  flame: register$2("flame", 60146),
  foldDown: register$2("fold-down", 60147),
  foldUp: register$2("fold-up", 60148),
  fold: register$2("fold", 60149),
  folderActive: register$2("folder-active", 60150),
  folderOpened: register$2("folder-opened", 60151),
  gear: register$2("gear", 60152),
  gift: register$2("gift", 60153),
  gistSecret: register$2("gist-secret", 60154),
  gist: register$2("gist", 60155),
  gitCommit: register$2("git-commit", 60156),
  gitCompare: register$2("git-compare", 60157),
  gitMerge: register$2("git-merge", 60158),
  githubAction: register$2("github-action", 60159),
  githubAlt: register$2("github-alt", 60160),
  globe: register$2("globe", 60161),
  grabber: register$2("grabber", 60162),
  graph: register$2("graph", 60163),
  gripper: register$2("gripper", 60164),
  heart: register$2("heart", 60165),
  home: register$2("home", 60166),
  horizontalRule: register$2("horizontal-rule", 60167),
  hubot: register$2("hubot", 60168),
  inbox: register$2("inbox", 60169),
  issueClosed: register$2("issue-closed", 60324),
  issueReopened: register$2("issue-reopened", 60171),
  issues: register$2("issues", 60172),
  italic: register$2("italic", 60173),
  jersey: register$2("jersey", 60174),
  json: register$2("json", 60175),
  bracket: register$2("bracket", 60175),
  kebabVertical: register$2("kebab-vertical", 60176),
  key: register$2("key", 60177),
  law: register$2("law", 60178),
  lightbulbAutofix: register$2("lightbulb-autofix", 60179),
  linkExternal: register$2("link-external", 60180),
  link: register$2("link", 60181),
  listOrdered: register$2("list-ordered", 60182),
  listUnordered: register$2("list-unordered", 60183),
  liveShare: register$2("live-share", 60184),
  loading: register$2("loading", 60185),
  location: register$2("location", 60186),
  mailRead: register$2("mail-read", 60187),
  mail: register$2("mail", 60188),
  markdown: register$2("markdown", 60189),
  megaphone: register$2("megaphone", 60190),
  mention: register$2("mention", 60191),
  milestone: register$2("milestone", 60192),
  mortarBoard: register$2("mortar-board", 60193),
  move: register$2("move", 60194),
  multipleWindows: register$2("multiple-windows", 60195),
  mute: register$2("mute", 60196),
  noNewline: register$2("no-newline", 60197),
  note: register$2("note", 60198),
  octoface: register$2("octoface", 60199),
  openPreview: register$2("open-preview", 60200),
  package_: register$2("package", 60201),
  paintcan: register$2("paintcan", 60202),
  pin: register$2("pin", 60203),
  play: register$2("play", 60204),
  run: register$2("run", 60204),
  plug: register$2("plug", 60205),
  preserveCase: register$2("preserve-case", 60206),
  preview: register$2("preview", 60207),
  project: register$2("project", 60208),
  pulse: register$2("pulse", 60209),
  question: register$2("question", 60210),
  quote: register$2("quote", 60211),
  radioTower: register$2("radio-tower", 60212),
  reactions: register$2("reactions", 60213),
  references: register$2("references", 60214),
  refresh: register$2("refresh", 60215),
  regex: register$2("regex", 60216),
  remoteExplorer: register$2("remote-explorer", 60217),
  remote: register$2("remote", 60218),
  remove: register$2("remove", 60219),
  replaceAll: register$2("replace-all", 60220),
  replace: register$2("replace", 60221),
  repoClone: register$2("repo-clone", 60222),
  repoForcePush: register$2("repo-force-push", 60223),
  repoPull: register$2("repo-pull", 60224),
  repoPush: register$2("repo-push", 60225),
  report: register$2("report", 60226),
  requestChanges: register$2("request-changes", 60227),
  rocket: register$2("rocket", 60228),
  rootFolderOpened: register$2("root-folder-opened", 60229),
  rootFolder: register$2("root-folder", 60230),
  rss: register$2("rss", 60231),
  ruby: register$2("ruby", 60232),
  saveAll: register$2("save-all", 60233),
  saveAs: register$2("save-as", 60234),
  save: register$2("save", 60235),
  screenFull: register$2("screen-full", 60236),
  screenNormal: register$2("screen-normal", 60237),
  searchStop: register$2("search-stop", 60238),
  server: register$2("server", 60240),
  settingsGear: register$2("settings-gear", 60241),
  settings: register$2("settings", 60242),
  shield: register$2("shield", 60243),
  smiley: register$2("smiley", 60244),
  sortPrecedence: register$2("sort-precedence", 60245),
  splitHorizontal: register$2("split-horizontal", 60246),
  splitVertical: register$2("split-vertical", 60247),
  squirrel: register$2("squirrel", 60248),
  starFull: register$2("star-full", 60249),
  starHalf: register$2("star-half", 60250),
  symbolClass: register$2("symbol-class", 60251),
  symbolColor: register$2("symbol-color", 60252),
  symbolCustomColor: register$2("symbol-customcolor", 60252),
  symbolConstant: register$2("symbol-constant", 60253),
  symbolEnumMember: register$2("symbol-enum-member", 60254),
  symbolField: register$2("symbol-field", 60255),
  symbolFile: register$2("symbol-file", 60256),
  symbolInterface: register$2("symbol-interface", 60257),
  symbolKeyword: register$2("symbol-keyword", 60258),
  symbolMisc: register$2("symbol-misc", 60259),
  symbolOperator: register$2("symbol-operator", 60260),
  symbolProperty: register$2("symbol-property", 60261),
  wrench: register$2("wrench", 60261),
  wrenchSubaction: register$2("wrench-subaction", 60261),
  symbolSnippet: register$2("symbol-snippet", 60262),
  tasklist: register$2("tasklist", 60263),
  telescope: register$2("telescope", 60264),
  textSize: register$2("text-size", 60265),
  threeBars: register$2("three-bars", 60266),
  thumbsdown: register$2("thumbsdown", 60267),
  thumbsup: register$2("thumbsup", 60268),
  tools: register$2("tools", 60269),
  triangleDown: register$2("triangle-down", 60270),
  triangleLeft: register$2("triangle-left", 60271),
  triangleRight: register$2("triangle-right", 60272),
  triangleUp: register$2("triangle-up", 60273),
  twitter: register$2("twitter", 60274),
  unfold: register$2("unfold", 60275),
  unlock: register$2("unlock", 60276),
  unmute: register$2("unmute", 60277),
  unverified: register$2("unverified", 60278),
  verified: register$2("verified", 60279),
  versions: register$2("versions", 60280),
  vmActive: register$2("vm-active", 60281),
  vmOutline: register$2("vm-outline", 60282),
  vmRunning: register$2("vm-running", 60283),
  watch: register$2("watch", 60284),
  whitespace: register$2("whitespace", 60285),
  wholeWord: register$2("whole-word", 60286),
  window: register$2("window", 60287),
  wordWrap: register$2("word-wrap", 60288),
  zoomIn: register$2("zoom-in", 60289),
  zoomOut: register$2("zoom-out", 60290),
  listFilter: register$2("list-filter", 60291),
  listFlat: register$2("list-flat", 60292),
  listSelection: register$2("list-selection", 60293),
  selection: register$2("selection", 60293),
  listTree: register$2("list-tree", 60294),
  debugBreakpointFunctionUnverified: register$2("debug-breakpoint-function-unverified", 60295),
  debugBreakpointFunction: register$2("debug-breakpoint-function", 60296),
  debugBreakpointFunctionDisabled: register$2("debug-breakpoint-function-disabled", 60296),
  debugStackframeActive: register$2("debug-stackframe-active", 60297),
  circleSmallFilled: register$2("circle-small-filled", 60298),
  debugStackframeDot: register$2("debug-stackframe-dot", 60298),
  debugStackframe: register$2("debug-stackframe", 60299),
  debugStackframeFocused: register$2("debug-stackframe-focused", 60299),
  debugBreakpointUnsupported: register$2("debug-breakpoint-unsupported", 60300),
  symbolString: register$2("symbol-string", 60301),
  debugReverseContinue: register$2("debug-reverse-continue", 60302),
  debugStepBack: register$2("debug-step-back", 60303),
  debugRestartFrame: register$2("debug-restart-frame", 60304),
  callIncoming: register$2("call-incoming", 60306),
  callOutgoing: register$2("call-outgoing", 60307),
  menu: register$2("menu", 60308),
  expandAll: register$2("expand-all", 60309),
  feedback: register$2("feedback", 60310),
  groupByRefType: register$2("group-by-ref-type", 60311),
  ungroupByRefType: register$2("ungroup-by-ref-type", 60312),
  account: register$2("account", 60313),
  bellDot: register$2("bell-dot", 60314),
  debugConsole: register$2("debug-console", 60315),
  library: register$2("library", 60316),
  output: register$2("output", 60317),
  runAll: register$2("run-all", 60318),
  syncIgnored: register$2("sync-ignored", 60319),
  pinned: register$2("pinned", 60320),
  githubInverted: register$2("github-inverted", 60321),
  debugAlt: register$2("debug-alt", 60305),
  serverProcess: register$2("server-process", 60322),
  serverEnvironment: register$2("server-environment", 60323),
  pass: register$2("pass", 60324),
  stopCircle: register$2("stop-circle", 60325),
  playCircle: register$2("play-circle", 60326),
  record: register$2("record", 60327),
  debugAltSmall: register$2("debug-alt-small", 60328),
  vmConnect: register$2("vm-connect", 60329),
  cloud: register$2("cloud", 60330),
  merge: register$2("merge", 60331),
  exportIcon: register$2("export", 60332),
  graphLeft: register$2("graph-left", 60333),
  magnet: register$2("magnet", 60334),
  notebook: register$2("notebook", 60335),
  redo: register$2("redo", 60336),
  checkAll: register$2("check-all", 60337),
  pinnedDirty: register$2("pinned-dirty", 60338),
  passFilled: register$2("pass-filled", 60339),
  circleLargeFilled: register$2("circle-large-filled", 60340),
  circleLarge: register$2("circle-large", 60341),
  circleLargeOutline: register$2("circle-large-outline", 60341),
  combine: register$2("combine", 60342),
  gather: register$2("gather", 60342),
  table: register$2("table", 60343),
  variableGroup: register$2("variable-group", 60344),
  typeHierarchy: register$2("type-hierarchy", 60345),
  typeHierarchySub: register$2("type-hierarchy-sub", 60346),
  typeHierarchySuper: register$2("type-hierarchy-super", 60347),
  gitPullRequestCreate: register$2("git-pull-request-create", 60348),
  runAbove: register$2("run-above", 60349),
  runBelow: register$2("run-below", 60350),
  notebookTemplate: register$2("notebook-template", 60351),
  debugRerun: register$2("debug-rerun", 60352),
  workspaceTrusted: register$2("workspace-trusted", 60353),
  workspaceUntrusted: register$2("workspace-untrusted", 60354),
  workspaceUnspecified: register$2("workspace-unspecified", 60355),
  terminalCmd: register$2("terminal-cmd", 60356),
  terminalDebian: register$2("terminal-debian", 60357),
  terminalLinux: register$2("terminal-linux", 60358),
  terminalPowershell: register$2("terminal-powershell", 60359),
  terminalTmux: register$2("terminal-tmux", 60360),
  terminalUbuntu: register$2("terminal-ubuntu", 60361),
  terminalBash: register$2("terminal-bash", 60362),
  arrowSwap: register$2("arrow-swap", 60363),
  copy: register$2("copy", 60364),
  personAdd: register$2("person-add", 60365),
  filterFilled: register$2("filter-filled", 60366),
  wand: register$2("wand", 60367),
  debugLineByLine: register$2("debug-line-by-line", 60368),
  inspect: register$2("inspect", 60369),
  layers: register$2("layers", 60370),
  layersDot: register$2("layers-dot", 60371),
  layersActive: register$2("layers-active", 60372),
  compass: register$2("compass", 60373),
  compassDot: register$2("compass-dot", 60374),
  compassActive: register$2("compass-active", 60375),
  azure: register$2("azure", 60376),
  issueDraft: register$2("issue-draft", 60377),
  gitPullRequestClosed: register$2("git-pull-request-closed", 60378),
  gitPullRequestDraft: register$2("git-pull-request-draft", 60379),
  debugAll: register$2("debug-all", 60380),
  debugCoverage: register$2("debug-coverage", 60381),
  runErrors: register$2("run-errors", 60382),
  folderLibrary: register$2("folder-library", 60383),
  debugContinueSmall: register$2("debug-continue-small", 60384),
  beakerStop: register$2("beaker-stop", 60385),
  graphLine: register$2("graph-line", 60386),
  graphScatter: register$2("graph-scatter", 60387),
  pieChart: register$2("pie-chart", 60388),
  bracketDot: register$2("bracket-dot", 60389),
  bracketError: register$2("bracket-error", 60390),
  lockSmall: register$2("lock-small", 60391),
  azureDevops: register$2("azure-devops", 60392),
  verifiedFilled: register$2("verified-filled", 60393),
  newLine: register$2("newline", 60394),
  layout: register$2("layout", 60395),
  layoutActivitybarLeft: register$2("layout-activitybar-left", 60396),
  layoutActivitybarRight: register$2("layout-activitybar-right", 60397),
  layoutPanelLeft: register$2("layout-panel-left", 60398),
  layoutPanelCenter: register$2("layout-panel-center", 60399),
  layoutPanelJustify: register$2("layout-panel-justify", 60400),
  layoutPanelRight: register$2("layout-panel-right", 60401),
  layoutPanel: register$2("layout-panel", 60402),
  layoutSidebarLeft: register$2("layout-sidebar-left", 60403),
  layoutSidebarRight: register$2("layout-sidebar-right", 60404),
  layoutStatusbar: register$2("layout-statusbar", 60405),
  layoutMenubar: register$2("layout-menubar", 60406),
  layoutCentered: register$2("layout-centered", 60407),
  layoutSidebarRightOff: register$2("layout-sidebar-right-off", 60416),
  layoutPanelOff: register$2("layout-panel-off", 60417),
  layoutSidebarLeftOff: register$2("layout-sidebar-left-off", 60418),
  target: register$2("target", 60408),
  indent: register$2("indent", 60409),
  recordSmall: register$2("record-small", 60410),
  errorSmall: register$2("error-small", 60411),
  arrowCircleDown: register$2("arrow-circle-down", 60412),
  arrowCircleLeft: register$2("arrow-circle-left", 60413),
  arrowCircleRight: register$2("arrow-circle-right", 60414),
  arrowCircleUp: register$2("arrow-circle-up", 60415),
  heartFilled: register$2("heart-filled", 60420),
  map: register$2("map", 60421),
  mapFilled: register$2("map-filled", 60422),
  circleSmall: register$2("circle-small", 60423),
  bellSlash: register$2("bell-slash", 60424),
  bellSlashDot: register$2("bell-slash-dot", 60425),
  commentUnresolved: register$2("comment-unresolved", 60426),
  gitPullRequestGoToChanges: register$2("git-pull-request-go-to-changes", 60427),
  gitPullRequestNewChanges: register$2("git-pull-request-new-changes", 60428),
  searchFuzzy: register$2("search-fuzzy", 60429),
  commentDraft: register$2("comment-draft", 60430),
  send: register$2("send", 60431),
  sparkle: register$2("sparkle", 60432),
  insert: register$2("insert", 60433),
  // derived icons, that could become separate icons
  dialogError: register$2("dialog-error", "error"),
  dialogWarning: register$2("dialog-warning", "warning"),
  dialogInfo: register$2("dialog-info", "info"),
  dialogClose: register$2("dialog-close", "close"),
  treeItemExpanded: register$2("tree-item-expanded", "chevron-down"),
  treeFilterOnTypeOn: register$2("tree-filter-on-type-on", "list-filter"),
  treeFilterOnTypeOff: register$2("tree-filter-on-type-off", "list-selection"),
  treeFilterClear: register$2("tree-filter-clear", "close"),
  treeItemLoading: register$2("tree-item-loading", "loading"),
  menuSelection: register$2("menu-selection", "check"),
  menuSubmenu: register$2("menu-submenu", "chevron-right"),
  menuBarMore: register$2("menubar-more", "more"),
  scrollbarButtonLeft: register$2("scrollbar-button-left", "triangle-left"),
  scrollbarButtonRight: register$2("scrollbar-button-right", "triangle-right"),
  scrollbarButtonUp: register$2("scrollbar-button-up", "triangle-up"),
  scrollbarButtonDown: register$2("scrollbar-button-down", "triangle-down"),
  toolBarMore: register$2("toolbar-more", "more"),
  quickInputBack: register$2("quick-input-back", "arrow-left")
};
var ThemeColor;
(function(ThemeColor2) {
  function isThemeColor(obj) {
    return obj && typeof obj === "object" && typeof obj.id === "string";
  }
  ThemeColor2.isThemeColor = isThemeColor;
})(ThemeColor || (ThemeColor = {}));
var ThemeIcon;
(function(ThemeIcon2) {
  ThemeIcon2.iconNameSegment = "[A-Za-z0-9]+";
  ThemeIcon2.iconNameExpression = "[A-Za-z0-9-]+";
  ThemeIcon2.iconModifierExpression = "~[A-Za-z]+";
  ThemeIcon2.iconNameCharacter = "[A-Za-z0-9~-]";
  const ThemeIconIdRegex = new RegExp(`^(${ThemeIcon2.iconNameExpression})(${ThemeIcon2.iconModifierExpression})?$`);
  function asClassNameArray(icon) {
    const match2 = ThemeIconIdRegex.exec(icon.id);
    if (!match2) {
      return asClassNameArray(Codicon.error);
    }
    const [, id3, modifier] = match2;
    const classNames = ["codicon", "codicon-" + id3];
    if (modifier) {
      classNames.push("codicon-modifier-" + modifier.substring(1));
    }
    return classNames;
  }
  ThemeIcon2.asClassNameArray = asClassNameArray;
  function asClassName(icon) {
    return asClassNameArray(icon).join(" ");
  }
  ThemeIcon2.asClassName = asClassName;
  function asCSSSelector(icon) {
    return "." + asClassNameArray(icon).join(".");
  }
  ThemeIcon2.asCSSSelector = asCSSSelector;
  function isThemeIcon(obj) {
    return obj && typeof obj === "object" && typeof obj.id === "string" && (typeof obj.color === "undefined" || ThemeColor.isThemeColor(obj.color));
  }
  ThemeIcon2.isThemeIcon = isThemeIcon;
  const _regexFromString = new RegExp(`^\\$\\((${ThemeIcon2.iconNameExpression}(?:${ThemeIcon2.iconModifierExpression})?)\\)$`);
  function fromString2(str2) {
    const match2 = _regexFromString.exec(str2);
    if (!match2) {
      return void 0;
    }
    const [, name] = match2;
    return { id: name };
  }
  ThemeIcon2.fromString = fromString2;
  function fromId(id3) {
    return { id: id3 };
  }
  ThemeIcon2.fromId = fromId;
  function modify(icon, modifier) {
    let id3 = icon.id;
    const tildeIndex = id3.lastIndexOf("~");
    if (tildeIndex !== -1) {
      id3 = id3.substring(0, tildeIndex);
    }
    if (modifier) {
      id3 = `${id3}~${modifier}`;
    }
    return { id: id3 };
  }
  ThemeIcon2.modify = modify;
  function getModifier(icon) {
    const tildeIndex = icon.id.lastIndexOf("~");
    if (tildeIndex !== -1) {
      return icon.id.substring(tildeIndex + 1);
    }
    return void 0;
  }
  ThemeIcon2.getModifier = getModifier;
  function isEqual2(ti1, ti2) {
    var _a2, _b2;
    return ti1.id === ti2.id && ((_a2 = ti1.color) === null || _a2 === void 0 ? void 0 : _a2.id) === ((_b2 = ti2.color) === null || _b2 === void 0 ? void 0 : _b2.id);
  }
  ThemeIcon2.isEqual = isEqual2;
})(ThemeIcon || (ThemeIcon = {}));
const ICommandService = createDecorator("commandService");
const CommandsRegistry = new class {
  constructor() {
    this._commands = /* @__PURE__ */ new Map();
    this._onDidRegisterCommand = new Emitter$1();
    this.onDidRegisterCommand = this._onDidRegisterCommand.event;
  }
  registerCommand(idOrCommand, handler) {
    if (!idOrCommand) {
      throw new Error(`invalid command`);
    }
    if (typeof idOrCommand === "string") {
      if (!handler) {
        throw new Error(`invalid command`);
      }
      return this.registerCommand({ id: idOrCommand, handler });
    }
    if (idOrCommand.description) {
      const constraints = [];
      for (const arg of idOrCommand.description.args) {
        constraints.push(arg.constraint);
      }
      const actualHandler = idOrCommand.handler;
      idOrCommand.handler = function(accessor, ...args) {
        validateConstraints(args, constraints);
        return actualHandler(accessor, ...args);
      };
    }
    const { id: id3 } = idOrCommand;
    let commands = this._commands.get(id3);
    if (!commands) {
      commands = new LinkedList();
      this._commands.set(id3, commands);
    }
    const removeFn = commands.unshift(idOrCommand);
    const ret = toDisposable(() => {
      removeFn();
      const command = this._commands.get(id3);
      if (command === null || command === void 0 ? void 0 : command.isEmpty()) {
        this._commands.delete(id3);
      }
    });
    this._onDidRegisterCommand.fire(id3);
    return ret;
  }
  registerCommandAlias(oldId, newId) {
    return CommandsRegistry.registerCommand(oldId, (accessor, ...args) => accessor.get(ICommandService).executeCommand(newId, ...args));
  }
  getCommand(id3) {
    const list2 = this._commands.get(id3);
    if (!list2 || list2.isEmpty()) {
      return void 0;
    }
    return Iterable.first(list2);
  }
  getCommands() {
    const result2 = /* @__PURE__ */ new Map();
    for (const key of this._commands.keys()) {
      const command = this.getCommand(key);
      if (command) {
        result2.set(key, command);
      }
    }
    return result2;
  }
}();
CommandsRegistry.registerCommand("noop", () => {
});
class LRUCachedFunction {
  constructor(fn) {
    this.fn = fn;
    this.lastCache = void 0;
    this.lastArgKey = void 0;
  }
  get(arg) {
    const key = JSON.stringify(arg);
    if (this.lastArgKey !== key) {
      this.lastArgKey = key;
      this.lastCache = this.fn(arg);
    }
    return this.lastCache;
  }
}
class CachedFunction {
  get cachedValues() {
    return this._map;
  }
  constructor(fn) {
    this.fn = fn;
    this._map = /* @__PURE__ */ new Map();
  }
  get(arg) {
    if (this._map.has(arg)) {
      return this._map.get(arg);
    }
    const value = this.fn(arg);
    this._map.set(arg, value);
    return value;
  }
}
class Lazy {
  constructor(executor) {
    this.executor = executor;
    this._didRun = false;
  }
  /**
   * Get the wrapped value.
   *
   * This will force evaluation of the lazy value if it has not been resolved yet. Lazy values are only
   * resolved once. `getValue` will re-throw exceptions that are hit while resolving the value
   */
  get value() {
    if (!this._didRun) {
      try {
        this._value = this.executor();
      } catch (err) {
        this._error = err;
      } finally {
        this._didRun = true;
      }
    }
    if (this._error) {
      throw this._error;
    }
    return this._value;
  }
  /**
   * Get the wrapped value without forcing evaluation.
   */
  get rawValue() {
    return this._value;
  }
}
var _a$3;
function isFalsyOrWhitespace(str2) {
  if (!str2 || typeof str2 !== "string") {
    return true;
  }
  return str2.trim().length === 0;
}
const _formatRegexp = /{(\d+)}/g;
function format$2(value, ...args) {
  if (args.length === 0) {
    return value;
  }
  return value.replace(_formatRegexp, function(match2, group2) {
    const idx = parseInt(group2, 10);
    return isNaN(idx) || idx < 0 || idx >= args.length ? match2 : args[idx];
  });
}
function escape$1(html2) {
  return html2.replace(/[<>&]/g, function(match2) {
    switch (match2) {
      case "<":
        return "&lt;";
      case ">":
        return "&gt;";
      case "&":
        return "&amp;";
      default:
        return match2;
    }
  });
}
function escapeRegExpCharacters(value) {
  return value.replace(/[\\\{\}\*\+\?\|\^\$\.\[\]\(\)]/g, "\\$&");
}
function trim$1(haystack, needle = " ") {
  const trimmed = ltrim(haystack, needle);
  return rtrim(trimmed, needle);
}
function ltrim(haystack, needle) {
  if (!haystack || !needle) {
    return haystack;
  }
  const needleLen = needle.length;
  if (needleLen === 0 || haystack.length === 0) {
    return haystack;
  }
  let offset = 0;
  while (haystack.indexOf(needle, offset) === offset) {
    offset = offset + needleLen;
  }
  return haystack.substring(offset);
}
function rtrim(haystack, needle) {
  if (!haystack || !needle) {
    return haystack;
  }
  const needleLen = needle.length, haystackLen = haystack.length;
  if (needleLen === 0 || haystackLen === 0) {
    return haystack;
  }
  let offset = haystackLen, idx = -1;
  while (true) {
    idx = haystack.lastIndexOf(needle, offset - 1);
    if (idx === -1 || idx + needleLen !== offset) {
      break;
    }
    if (idx === 0) {
      return "";
    }
    offset = idx;
  }
  return haystack.substring(0, offset);
}
function convertSimple2RegExpPattern(pattern) {
  return pattern.replace(/[\-\\\{\}\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, "\\$&").replace(/[\*]/g, ".*");
}
function stripWildcards(pattern) {
  return pattern.replace(/\*/g, "");
}
function createRegExp(searchString, isRegex, options = {}) {
  if (!searchString) {
    throw new Error("Cannot create regex from empty string");
  }
  if (!isRegex) {
    searchString = escapeRegExpCharacters(searchString);
  }
  if (options.wholeWord) {
    if (!/\B/.test(searchString.charAt(0))) {
      searchString = "\\b" + searchString;
    }
    if (!/\B/.test(searchString.charAt(searchString.length - 1))) {
      searchString = searchString + "\\b";
    }
  }
  let modifiers = "";
  if (options.global) {
    modifiers += "g";
  }
  if (!options.matchCase) {
    modifiers += "i";
  }
  if (options.multiline) {
    modifiers += "m";
  }
  if (options.unicode) {
    modifiers += "u";
  }
  return new RegExp(searchString, modifiers);
}
function regExpLeadsToEndlessLoop(regexp) {
  if (regexp.source === "^" || regexp.source === "^$" || regexp.source === "$" || regexp.source === "^\\s*$") {
    return false;
  }
  const match2 = regexp.exec("");
  return !!(match2 && regexp.lastIndex === 0);
}
function regExpFlags(regexp) {
  return (regexp.global ? "g" : "") + (regexp.ignoreCase ? "i" : "") + (regexp.multiline ? "m" : "") + (regexp.unicode ? "u" : "");
}
function splitLines(str2) {
  return str2.split(/\r\n|\r|\n/);
}
function firstNonWhitespaceIndex(str2) {
  for (let i = 0, len = str2.length; i < len; i++) {
    const chCode = str2.charCodeAt(i);
    if (chCode !== 32 && chCode !== 9) {
      return i;
    }
  }
  return -1;
}
function getLeadingWhitespace(str2, start = 0, end = str2.length) {
  for (let i = start; i < end; i++) {
    const chCode = str2.charCodeAt(i);
    if (chCode !== 32 && chCode !== 9) {
      return str2.substring(start, i);
    }
  }
  return str2.substring(start, end);
}
function lastNonWhitespaceIndex(str2, startIndex = str2.length - 1) {
  for (let i = startIndex; i >= 0; i--) {
    const chCode = str2.charCodeAt(i);
    if (chCode !== 32 && chCode !== 9) {
      return i;
    }
  }
  return -1;
}
function compare(a, b) {
  if (a < b) {
    return -1;
  } else if (a > b) {
    return 1;
  } else {
    return 0;
  }
}
function compareSubstring(a, b, aStart = 0, aEnd = a.length, bStart = 0, bEnd = b.length) {
  for (; aStart < aEnd && bStart < bEnd; aStart++, bStart++) {
    const codeA = a.charCodeAt(aStart);
    const codeB = b.charCodeAt(bStart);
    if (codeA < codeB) {
      return -1;
    } else if (codeA > codeB) {
      return 1;
    }
  }
  const aLen = aEnd - aStart;
  const bLen = bEnd - bStart;
  if (aLen < bLen) {
    return -1;
  } else if (aLen > bLen) {
    return 1;
  }
  return 0;
}
function compareIgnoreCase(a, b) {
  return compareSubstringIgnoreCase(a, b, 0, a.length, 0, b.length);
}
function compareSubstringIgnoreCase(a, b, aStart = 0, aEnd = a.length, bStart = 0, bEnd = b.length) {
  for (; aStart < aEnd && bStart < bEnd; aStart++, bStart++) {
    let codeA = a.charCodeAt(aStart);
    let codeB = b.charCodeAt(bStart);
    if (codeA === codeB) {
      continue;
    }
    if (codeA >= 128 || codeB >= 128) {
      return compareSubstring(a.toLowerCase(), b.toLowerCase(), aStart, aEnd, bStart, bEnd);
    }
    if (isLowerAsciiLetter(codeA)) {
      codeA -= 32;
    }
    if (isLowerAsciiLetter(codeB)) {
      codeB -= 32;
    }
    const diff = codeA - codeB;
    if (diff === 0) {
      continue;
    }
    return diff;
  }
  const aLen = aEnd - aStart;
  const bLen = bEnd - bStart;
  if (aLen < bLen) {
    return -1;
  } else if (aLen > bLen) {
    return 1;
  }
  return 0;
}
function isAsciiDigit(code) {
  return code >= 48 && code <= 57;
}
function isLowerAsciiLetter(code) {
  return code >= 97 && code <= 122;
}
function isUpperAsciiLetter(code) {
  return code >= 65 && code <= 90;
}
function equalsIgnoreCase(a, b) {
  return a.length === b.length && compareSubstringIgnoreCase(a, b) === 0;
}
function startsWithIgnoreCase(str2, candidate) {
  const candidateLength = candidate.length;
  if (candidate.length > str2.length) {
    return false;
  }
  return compareSubstringIgnoreCase(str2, candidate, 0, candidateLength) === 0;
}
function commonPrefixLength(a, b) {
  const len = Math.min(a.length, b.length);
  let i;
  for (i = 0; i < len; i++) {
    if (a.charCodeAt(i) !== b.charCodeAt(i)) {
      return i;
    }
  }
  return len;
}
function commonSuffixLength(a, b) {
  const len = Math.min(a.length, b.length);
  let i;
  const aLastIndex = a.length - 1;
  const bLastIndex = b.length - 1;
  for (i = 0; i < len; i++) {
    if (a.charCodeAt(aLastIndex - i) !== b.charCodeAt(bLastIndex - i)) {
      return i;
    }
  }
  return len;
}
function isHighSurrogate(charCode) {
  return 55296 <= charCode && charCode <= 56319;
}
function isLowSurrogate(charCode) {
  return 56320 <= charCode && charCode <= 57343;
}
function computeCodePoint(highSurrogate, lowSurrogate) {
  return (highSurrogate - 55296 << 10) + (lowSurrogate - 56320) + 65536;
}
function getNextCodePoint(str2, len, offset) {
  const charCode = str2.charCodeAt(offset);
  if (isHighSurrogate(charCode) && offset + 1 < len) {
    const nextCharCode = str2.charCodeAt(offset + 1);
    if (isLowSurrogate(nextCharCode)) {
      return computeCodePoint(charCode, nextCharCode);
    }
  }
  return charCode;
}
function getPrevCodePoint(str2, offset) {
  const charCode = str2.charCodeAt(offset - 1);
  if (isLowSurrogate(charCode) && offset > 1) {
    const prevCharCode = str2.charCodeAt(offset - 2);
    if (isHighSurrogate(prevCharCode)) {
      return computeCodePoint(prevCharCode, charCode);
    }
  }
  return charCode;
}
class CodePointIterator {
  get offset() {
    return this._offset;
  }
  constructor(str2, offset = 0) {
    this._str = str2;
    this._len = str2.length;
    this._offset = offset;
  }
  setOffset(offset) {
    this._offset = offset;
  }
  prevCodePoint() {
    const codePoint = getPrevCodePoint(this._str, this._offset);
    this._offset -= codePoint >= 65536 ? 2 : 1;
    return codePoint;
  }
  nextCodePoint() {
    const codePoint = getNextCodePoint(this._str, this._len, this._offset);
    this._offset += codePoint >= 65536 ? 2 : 1;
    return codePoint;
  }
  eol() {
    return this._offset >= this._len;
  }
}
class GraphemeIterator {
  get offset() {
    return this._iterator.offset;
  }
  constructor(str2, offset = 0) {
    this._iterator = new CodePointIterator(str2, offset);
  }
  nextGraphemeLength() {
    const graphemeBreakTree = GraphemeBreakTree.getInstance();
    const iterator2 = this._iterator;
    const initialOffset = iterator2.offset;
    let graphemeBreakType = graphemeBreakTree.getGraphemeBreakType(iterator2.nextCodePoint());
    while (!iterator2.eol()) {
      const offset = iterator2.offset;
      const nextGraphemeBreakType = graphemeBreakTree.getGraphemeBreakType(iterator2.nextCodePoint());
      if (breakBetweenGraphemeBreakType(graphemeBreakType, nextGraphemeBreakType)) {
        iterator2.setOffset(offset);
        break;
      }
      graphemeBreakType = nextGraphemeBreakType;
    }
    return iterator2.offset - initialOffset;
  }
  prevGraphemeLength() {
    const graphemeBreakTree = GraphemeBreakTree.getInstance();
    const iterator2 = this._iterator;
    const initialOffset = iterator2.offset;
    let graphemeBreakType = graphemeBreakTree.getGraphemeBreakType(iterator2.prevCodePoint());
    while (iterator2.offset > 0) {
      const offset = iterator2.offset;
      const prevGraphemeBreakType = graphemeBreakTree.getGraphemeBreakType(iterator2.prevCodePoint());
      if (breakBetweenGraphemeBreakType(prevGraphemeBreakType, graphemeBreakType)) {
        iterator2.setOffset(offset);
        break;
      }
      graphemeBreakType = prevGraphemeBreakType;
    }
    return initialOffset - iterator2.offset;
  }
  eol() {
    return this._iterator.eol();
  }
}
function nextCharLength(str2, initialOffset) {
  const iterator2 = new GraphemeIterator(str2, initialOffset);
  return iterator2.nextGraphemeLength();
}
function prevCharLength(str2, initialOffset) {
  const iterator2 = new GraphemeIterator(str2, initialOffset);
  return iterator2.prevGraphemeLength();
}
function getCharContainingOffset(str2, offset) {
  if (offset > 0 && isLowSurrogate(str2.charCodeAt(offset))) {
    offset--;
  }
  const endOffset = offset + nextCharLength(str2, offset);
  const startOffset = endOffset - prevCharLength(str2, endOffset);
  return [startOffset, endOffset];
}
let CONTAINS_RTL = void 0;
function makeContainsRtl() {
  return /(?:[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05F4\u0608\u060B\u060D\u061B-\u064A\u066D-\u066F\u0671-\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u0710\u0712-\u072F\u074D-\u07A5\u07B1-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u0858\u085E-\u088E\u08A0-\u08C9\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFD3D\uFD50-\uFDC7\uFDF0-\uFDFC\uFE70-\uFEFC]|\uD802[\uDC00-\uDD1B\uDD20-\uDE00\uDE10-\uDE35\uDE40-\uDEE4\uDEEB-\uDF35\uDF40-\uDFFF]|\uD803[\uDC00-\uDD23\uDE80-\uDEA9\uDEAD-\uDF45\uDF51-\uDF81\uDF86-\uDFF6]|\uD83A[\uDC00-\uDCCF\uDD00-\uDD43\uDD4B-\uDFFF]|\uD83B[\uDC00-\uDEBB])/;
}
function containsRTL(str2) {
  if (!CONTAINS_RTL) {
    CONTAINS_RTL = makeContainsRtl();
  }
  return CONTAINS_RTL.test(str2);
}
const IS_BASIC_ASCII = /^[\t\n\r\x20-\x7E]*$/;
function isBasicASCII(str2) {
  return IS_BASIC_ASCII.test(str2);
}
const UNUSUAL_LINE_TERMINATORS = /[\u2028\u2029]/;
function containsUnusualLineTerminators(str2) {
  return UNUSUAL_LINE_TERMINATORS.test(str2);
}
function isFullWidthCharacter(charCode) {
  return charCode >= 11904 && charCode <= 55215 || charCode >= 63744 && charCode <= 64255 || charCode >= 65281 && charCode <= 65374;
}
function isEmojiImprecise(x) {
  return x >= 127462 && x <= 127487 || x === 8986 || x === 8987 || x === 9200 || x === 9203 || x >= 9728 && x <= 10175 || x === 11088 || x === 11093 || x >= 127744 && x <= 128591 || x >= 128640 && x <= 128764 || x >= 128992 && x <= 129008 || x >= 129280 && x <= 129535 || x >= 129648 && x <= 129782;
}
const UTF8_BOM_CHARACTER = String.fromCharCode(
  65279
  /* CharCode.UTF8_BOM */
);
function startsWithUTF8BOM(str2) {
  return !!(str2 && str2.length > 0 && str2.charCodeAt(0) === 65279);
}
function containsUppercaseCharacter(target, ignoreEscapedChars = false) {
  if (!target) {
    return false;
  }
  if (ignoreEscapedChars) {
    target = target.replace(/\\./g, "");
  }
  return target.toLowerCase() !== target;
}
function singleLetterHash(n2) {
  const LETTERS_CNT = 90 - 65 + 1;
  n2 = n2 % (2 * LETTERS_CNT);
  if (n2 < LETTERS_CNT) {
    return String.fromCharCode(97 + n2);
  }
  return String.fromCharCode(65 + n2 - LETTERS_CNT);
}
function breakBetweenGraphemeBreakType(breakTypeA, breakTypeB) {
  if (breakTypeA === 0) {
    return breakTypeB !== 5 && breakTypeB !== 7;
  }
  if (breakTypeA === 2) {
    if (breakTypeB === 3) {
      return false;
    }
  }
  if (breakTypeA === 4 || breakTypeA === 2 || breakTypeA === 3) {
    return true;
  }
  if (breakTypeB === 4 || breakTypeB === 2 || breakTypeB === 3) {
    return true;
  }
  if (breakTypeA === 8) {
    if (breakTypeB === 8 || breakTypeB === 9 || breakTypeB === 11 || breakTypeB === 12) {
      return false;
    }
  }
  if (breakTypeA === 11 || breakTypeA === 9) {
    if (breakTypeB === 9 || breakTypeB === 10) {
      return false;
    }
  }
  if (breakTypeA === 12 || breakTypeA === 10) {
    if (breakTypeB === 10) {
      return false;
    }
  }
  if (breakTypeB === 5 || breakTypeB === 13) {
    return false;
  }
  if (breakTypeB === 7) {
    return false;
  }
  if (breakTypeA === 1) {
    return false;
  }
  if (breakTypeA === 13 && breakTypeB === 14) {
    return false;
  }
  if (breakTypeA === 6 && breakTypeB === 6) {
    return false;
  }
  return true;
}
class GraphemeBreakTree {
  static getInstance() {
    if (!GraphemeBreakTree._INSTANCE) {
      GraphemeBreakTree._INSTANCE = new GraphemeBreakTree();
    }
    return GraphemeBreakTree._INSTANCE;
  }
  constructor() {
    this._data = getGraphemeBreakRawData();
  }
  getGraphemeBreakType(codePoint) {
    if (codePoint < 32) {
      if (codePoint === 10) {
        return 3;
      }
      if (codePoint === 13) {
        return 2;
      }
      return 4;
    }
    if (codePoint < 127) {
      return 0;
    }
    const data = this._data;
    const nodeCount = data.length / 3;
    let nodeIndex = 1;
    while (nodeIndex <= nodeCount) {
      if (codePoint < data[3 * nodeIndex]) {
        nodeIndex = 2 * nodeIndex;
      } else if (codePoint > data[3 * nodeIndex + 1]) {
        nodeIndex = 2 * nodeIndex + 1;
      } else {
        return data[3 * nodeIndex + 2];
      }
    }
    return 0;
  }
}
GraphemeBreakTree._INSTANCE = null;
function getGraphemeBreakRawData() {
  return JSON.parse("[0,0,0,51229,51255,12,44061,44087,12,127462,127487,6,7083,7085,5,47645,47671,12,54813,54839,12,128678,128678,14,3270,3270,5,9919,9923,14,45853,45879,12,49437,49463,12,53021,53047,12,71216,71218,7,128398,128399,14,129360,129374,14,2519,2519,5,4448,4519,9,9742,9742,14,12336,12336,14,44957,44983,12,46749,46775,12,48541,48567,12,50333,50359,12,52125,52151,12,53917,53943,12,69888,69890,5,73018,73018,5,127990,127990,14,128558,128559,14,128759,128760,14,129653,129655,14,2027,2035,5,2891,2892,7,3761,3761,5,6683,6683,5,8293,8293,4,9825,9826,14,9999,9999,14,43452,43453,5,44509,44535,12,45405,45431,12,46301,46327,12,47197,47223,12,48093,48119,12,48989,49015,12,49885,49911,12,50781,50807,12,51677,51703,12,52573,52599,12,53469,53495,12,54365,54391,12,65279,65279,4,70471,70472,7,72145,72147,7,119173,119179,5,127799,127818,14,128240,128244,14,128512,128512,14,128652,128652,14,128721,128722,14,129292,129292,14,129445,129450,14,129734,129743,14,1476,1477,5,2366,2368,7,2750,2752,7,3076,3076,5,3415,3415,5,4141,4144,5,6109,6109,5,6964,6964,5,7394,7400,5,9197,9198,14,9770,9770,14,9877,9877,14,9968,9969,14,10084,10084,14,43052,43052,5,43713,43713,5,44285,44311,12,44733,44759,12,45181,45207,12,45629,45655,12,46077,46103,12,46525,46551,12,46973,46999,12,47421,47447,12,47869,47895,12,48317,48343,12,48765,48791,12,49213,49239,12,49661,49687,12,50109,50135,12,50557,50583,12,51005,51031,12,51453,51479,12,51901,51927,12,52349,52375,12,52797,52823,12,53245,53271,12,53693,53719,12,54141,54167,12,54589,54615,12,55037,55063,12,69506,69509,5,70191,70193,5,70841,70841,7,71463,71467,5,72330,72342,5,94031,94031,5,123628,123631,5,127763,127765,14,127941,127941,14,128043,128062,14,128302,128317,14,128465,128467,14,128539,128539,14,128640,128640,14,128662,128662,14,128703,128703,14,128745,128745,14,129004,129007,14,129329,129330,14,129402,129402,14,129483,129483,14,129686,129704,14,130048,131069,14,173,173,4,1757,1757,1,2200,2207,5,2434,2435,7,2631,2632,5,2817,2817,5,3008,3008,5,3201,3201,5,3387,3388,5,3542,3542,5,3902,3903,7,4190,4192,5,6002,6003,5,6439,6440,5,6765,6770,7,7019,7027,5,7154,7155,7,8205,8205,13,8505,8505,14,9654,9654,14,9757,9757,14,9792,9792,14,9852,9853,14,9890,9894,14,9937,9937,14,9981,9981,14,10035,10036,14,11035,11036,14,42654,42655,5,43346,43347,7,43587,43587,5,44006,44007,7,44173,44199,12,44397,44423,12,44621,44647,12,44845,44871,12,45069,45095,12,45293,45319,12,45517,45543,12,45741,45767,12,45965,45991,12,46189,46215,12,46413,46439,12,46637,46663,12,46861,46887,12,47085,47111,12,47309,47335,12,47533,47559,12,47757,47783,12,47981,48007,12,48205,48231,12,48429,48455,12,48653,48679,12,48877,48903,12,49101,49127,12,49325,49351,12,49549,49575,12,49773,49799,12,49997,50023,12,50221,50247,12,50445,50471,12,50669,50695,12,50893,50919,12,51117,51143,12,51341,51367,12,51565,51591,12,51789,51815,12,52013,52039,12,52237,52263,12,52461,52487,12,52685,52711,12,52909,52935,12,53133,53159,12,53357,53383,12,53581,53607,12,53805,53831,12,54029,54055,12,54253,54279,12,54477,54503,12,54701,54727,12,54925,54951,12,55149,55175,12,68101,68102,5,69762,69762,7,70067,70069,7,70371,70378,5,70720,70721,7,71087,71087,5,71341,71341,5,71995,71996,5,72249,72249,7,72850,72871,5,73109,73109,5,118576,118598,5,121505,121519,5,127245,127247,14,127568,127569,14,127777,127777,14,127872,127891,14,127956,127967,14,128015,128016,14,128110,128172,14,128259,128259,14,128367,128368,14,128424,128424,14,128488,128488,14,128530,128532,14,128550,128551,14,128566,128566,14,128647,128647,14,128656,128656,14,128667,128673,14,128691,128693,14,128715,128715,14,128728,128732,14,128752,128752,14,128765,128767,14,129096,129103,14,129311,129311,14,129344,129349,14,129394,129394,14,129413,129425,14,129466,129471,14,129511,129535,14,129664,129666,14,129719,129722,14,129760,129767,14,917536,917631,5,13,13,2,1160,1161,5,1564,1564,4,1807,1807,1,2085,2087,5,2307,2307,7,2382,2383,7,2497,2500,5,2563,2563,7,2677,2677,5,2763,2764,7,2879,2879,5,2914,2915,5,3021,3021,5,3142,3144,5,3263,3263,5,3285,3286,5,3398,3400,7,3530,3530,5,3633,3633,5,3864,3865,5,3974,3975,5,4155,4156,7,4229,4230,5,5909,5909,7,6078,6085,7,6277,6278,5,6451,6456,7,6744,6750,5,6846,6846,5,6972,6972,5,7074,7077,5,7146,7148,7,7222,7223,5,7416,7417,5,8234,8238,4,8417,8417,5,9000,9000,14,9203,9203,14,9730,9731,14,9748,9749,14,9762,9763,14,9776,9783,14,9800,9811,14,9831,9831,14,9872,9873,14,9882,9882,14,9900,9903,14,9929,9933,14,9941,9960,14,9974,9974,14,9989,9989,14,10006,10006,14,10062,10062,14,10160,10160,14,11647,11647,5,12953,12953,14,43019,43019,5,43232,43249,5,43443,43443,5,43567,43568,7,43696,43696,5,43765,43765,7,44013,44013,5,44117,44143,12,44229,44255,12,44341,44367,12,44453,44479,12,44565,44591,12,44677,44703,12,44789,44815,12,44901,44927,12,45013,45039,12,45125,45151,12,45237,45263,12,45349,45375,12,45461,45487,12,45573,45599,12,45685,45711,12,45797,45823,12,45909,45935,12,46021,46047,12,46133,46159,12,46245,46271,12,46357,46383,12,46469,46495,12,46581,46607,12,46693,46719,12,46805,46831,12,46917,46943,12,47029,47055,12,47141,47167,12,47253,47279,12,47365,47391,12,47477,47503,12,47589,47615,12,47701,47727,12,47813,47839,12,47925,47951,12,48037,48063,12,48149,48175,12,48261,48287,12,48373,48399,12,48485,48511,12,48597,48623,12,48709,48735,12,48821,48847,12,48933,48959,12,49045,49071,12,49157,49183,12,49269,49295,12,49381,49407,12,49493,49519,12,49605,49631,12,49717,49743,12,49829,49855,12,49941,49967,12,50053,50079,12,50165,50191,12,50277,50303,12,50389,50415,12,50501,50527,12,50613,50639,12,50725,50751,12,50837,50863,12,50949,50975,12,51061,51087,12,51173,51199,12,51285,51311,12,51397,51423,12,51509,51535,12,51621,51647,12,51733,51759,12,51845,51871,12,51957,51983,12,52069,52095,12,52181,52207,12,52293,52319,12,52405,52431,12,52517,52543,12,52629,52655,12,52741,52767,12,52853,52879,12,52965,52991,12,53077,53103,12,53189,53215,12,53301,53327,12,53413,53439,12,53525,53551,12,53637,53663,12,53749,53775,12,53861,53887,12,53973,53999,12,54085,54111,12,54197,54223,12,54309,54335,12,54421,54447,12,54533,54559,12,54645,54671,12,54757,54783,12,54869,54895,12,54981,55007,12,55093,55119,12,55243,55291,10,66045,66045,5,68325,68326,5,69688,69702,5,69817,69818,5,69957,69958,7,70089,70092,5,70198,70199,5,70462,70462,5,70502,70508,5,70750,70750,5,70846,70846,7,71100,71101,5,71230,71230,7,71351,71351,5,71737,71738,5,72000,72000,7,72160,72160,5,72273,72278,5,72752,72758,5,72882,72883,5,73031,73031,5,73461,73462,7,94192,94193,7,119149,119149,7,121403,121452,5,122915,122916,5,126980,126980,14,127358,127359,14,127535,127535,14,127759,127759,14,127771,127771,14,127792,127793,14,127825,127867,14,127897,127899,14,127945,127945,14,127985,127986,14,128000,128007,14,128021,128021,14,128066,128100,14,128184,128235,14,128249,128252,14,128266,128276,14,128335,128335,14,128379,128390,14,128407,128419,14,128444,128444,14,128481,128481,14,128499,128499,14,128526,128526,14,128536,128536,14,128543,128543,14,128556,128556,14,128564,128564,14,128577,128580,14,128643,128645,14,128649,128649,14,128654,128654,14,128660,128660,14,128664,128664,14,128675,128675,14,128686,128689,14,128695,128696,14,128705,128709,14,128717,128719,14,128725,128725,14,128736,128741,14,128747,128748,14,128755,128755,14,128762,128762,14,128981,128991,14,129009,129023,14,129160,129167,14,129296,129304,14,129320,129327,14,129340,129342,14,129356,129356,14,129388,129392,14,129399,129400,14,129404,129407,14,129432,129442,14,129454,129455,14,129473,129474,14,129485,129487,14,129648,129651,14,129659,129660,14,129671,129679,14,129709,129711,14,129728,129730,14,129751,129753,14,129776,129782,14,917505,917505,4,917760,917999,5,10,10,3,127,159,4,768,879,5,1471,1471,5,1536,1541,1,1648,1648,5,1767,1768,5,1840,1866,5,2070,2073,5,2137,2139,5,2274,2274,1,2363,2363,7,2377,2380,7,2402,2403,5,2494,2494,5,2507,2508,7,2558,2558,5,2622,2624,7,2641,2641,5,2691,2691,7,2759,2760,5,2786,2787,5,2876,2876,5,2881,2884,5,2901,2902,5,3006,3006,5,3014,3016,7,3072,3072,5,3134,3136,5,3157,3158,5,3260,3260,5,3266,3266,5,3274,3275,7,3328,3329,5,3391,3392,7,3405,3405,5,3457,3457,5,3536,3537,7,3551,3551,5,3636,3642,5,3764,3772,5,3895,3895,5,3967,3967,7,3993,4028,5,4146,4151,5,4182,4183,7,4226,4226,5,4253,4253,5,4957,4959,5,5940,5940,7,6070,6070,7,6087,6088,7,6158,6158,4,6432,6434,5,6448,6449,7,6679,6680,5,6742,6742,5,6754,6754,5,6783,6783,5,6912,6915,5,6966,6970,5,6978,6978,5,7042,7042,7,7080,7081,5,7143,7143,7,7150,7150,7,7212,7219,5,7380,7392,5,7412,7412,5,8203,8203,4,8232,8232,4,8265,8265,14,8400,8412,5,8421,8432,5,8617,8618,14,9167,9167,14,9200,9200,14,9410,9410,14,9723,9726,14,9733,9733,14,9745,9745,14,9752,9752,14,9760,9760,14,9766,9766,14,9774,9774,14,9786,9786,14,9794,9794,14,9823,9823,14,9828,9828,14,9833,9850,14,9855,9855,14,9875,9875,14,9880,9880,14,9885,9887,14,9896,9897,14,9906,9916,14,9926,9927,14,9935,9935,14,9939,9939,14,9962,9962,14,9972,9972,14,9978,9978,14,9986,9986,14,9997,9997,14,10002,10002,14,10017,10017,14,10055,10055,14,10071,10071,14,10133,10135,14,10548,10549,14,11093,11093,14,12330,12333,5,12441,12442,5,42608,42610,5,43010,43010,5,43045,43046,5,43188,43203,7,43302,43309,5,43392,43394,5,43446,43449,5,43493,43493,5,43571,43572,7,43597,43597,7,43703,43704,5,43756,43757,5,44003,44004,7,44009,44010,7,44033,44059,12,44089,44115,12,44145,44171,12,44201,44227,12,44257,44283,12,44313,44339,12,44369,44395,12,44425,44451,12,44481,44507,12,44537,44563,12,44593,44619,12,44649,44675,12,44705,44731,12,44761,44787,12,44817,44843,12,44873,44899,12,44929,44955,12,44985,45011,12,45041,45067,12,45097,45123,12,45153,45179,12,45209,45235,12,45265,45291,12,45321,45347,12,45377,45403,12,45433,45459,12,45489,45515,12,45545,45571,12,45601,45627,12,45657,45683,12,45713,45739,12,45769,45795,12,45825,45851,12,45881,45907,12,45937,45963,12,45993,46019,12,46049,46075,12,46105,46131,12,46161,46187,12,46217,46243,12,46273,46299,12,46329,46355,12,46385,46411,12,46441,46467,12,46497,46523,12,46553,46579,12,46609,46635,12,46665,46691,12,46721,46747,12,46777,46803,12,46833,46859,12,46889,46915,12,46945,46971,12,47001,47027,12,47057,47083,12,47113,47139,12,47169,47195,12,47225,47251,12,47281,47307,12,47337,47363,12,47393,47419,12,47449,47475,12,47505,47531,12,47561,47587,12,47617,47643,12,47673,47699,12,47729,47755,12,47785,47811,12,47841,47867,12,47897,47923,12,47953,47979,12,48009,48035,12,48065,48091,12,48121,48147,12,48177,48203,12,48233,48259,12,48289,48315,12,48345,48371,12,48401,48427,12,48457,48483,12,48513,48539,12,48569,48595,12,48625,48651,12,48681,48707,12,48737,48763,12,48793,48819,12,48849,48875,12,48905,48931,12,48961,48987,12,49017,49043,12,49073,49099,12,49129,49155,12,49185,49211,12,49241,49267,12,49297,49323,12,49353,49379,12,49409,49435,12,49465,49491,12,49521,49547,12,49577,49603,12,49633,49659,12,49689,49715,12,49745,49771,12,49801,49827,12,49857,49883,12,49913,49939,12,49969,49995,12,50025,50051,12,50081,50107,12,50137,50163,12,50193,50219,12,50249,50275,12,50305,50331,12,50361,50387,12,50417,50443,12,50473,50499,12,50529,50555,12,50585,50611,12,50641,50667,12,50697,50723,12,50753,50779,12,50809,50835,12,50865,50891,12,50921,50947,12,50977,51003,12,51033,51059,12,51089,51115,12,51145,51171,12,51201,51227,12,51257,51283,12,51313,51339,12,51369,51395,12,51425,51451,12,51481,51507,12,51537,51563,12,51593,51619,12,51649,51675,12,51705,51731,12,51761,51787,12,51817,51843,12,51873,51899,12,51929,51955,12,51985,52011,12,52041,52067,12,52097,52123,12,52153,52179,12,52209,52235,12,52265,52291,12,52321,52347,12,52377,52403,12,52433,52459,12,52489,52515,12,52545,52571,12,52601,52627,12,52657,52683,12,52713,52739,12,52769,52795,12,52825,52851,12,52881,52907,12,52937,52963,12,52993,53019,12,53049,53075,12,53105,53131,12,53161,53187,12,53217,53243,12,53273,53299,12,53329,53355,12,53385,53411,12,53441,53467,12,53497,53523,12,53553,53579,12,53609,53635,12,53665,53691,12,53721,53747,12,53777,53803,12,53833,53859,12,53889,53915,12,53945,53971,12,54001,54027,12,54057,54083,12,54113,54139,12,54169,54195,12,54225,54251,12,54281,54307,12,54337,54363,12,54393,54419,12,54449,54475,12,54505,54531,12,54561,54587,12,54617,54643,12,54673,54699,12,54729,54755,12,54785,54811,12,54841,54867,12,54897,54923,12,54953,54979,12,55009,55035,12,55065,55091,12,55121,55147,12,55177,55203,12,65024,65039,5,65520,65528,4,66422,66426,5,68152,68154,5,69291,69292,5,69633,69633,5,69747,69748,5,69811,69814,5,69826,69826,5,69932,69932,7,70016,70017,5,70079,70080,7,70095,70095,5,70196,70196,5,70367,70367,5,70402,70403,7,70464,70464,5,70487,70487,5,70709,70711,7,70725,70725,7,70833,70834,7,70843,70844,7,70849,70849,7,71090,71093,5,71103,71104,5,71227,71228,7,71339,71339,5,71344,71349,5,71458,71461,5,71727,71735,5,71985,71989,7,71998,71998,5,72002,72002,7,72154,72155,5,72193,72202,5,72251,72254,5,72281,72283,5,72344,72345,5,72766,72766,7,72874,72880,5,72885,72886,5,73023,73029,5,73104,73105,5,73111,73111,5,92912,92916,5,94095,94098,5,113824,113827,4,119142,119142,7,119155,119162,4,119362,119364,5,121476,121476,5,122888,122904,5,123184,123190,5,125252,125258,5,127183,127183,14,127340,127343,14,127377,127386,14,127491,127503,14,127548,127551,14,127744,127756,14,127761,127761,14,127769,127769,14,127773,127774,14,127780,127788,14,127796,127797,14,127820,127823,14,127869,127869,14,127894,127895,14,127902,127903,14,127943,127943,14,127947,127950,14,127972,127972,14,127988,127988,14,127992,127994,14,128009,128011,14,128019,128019,14,128023,128041,14,128064,128064,14,128102,128107,14,128174,128181,14,128238,128238,14,128246,128247,14,128254,128254,14,128264,128264,14,128278,128299,14,128329,128330,14,128348,128359,14,128371,128377,14,128392,128393,14,128401,128404,14,128421,128421,14,128433,128434,14,128450,128452,14,128476,128478,14,128483,128483,14,128495,128495,14,128506,128506,14,128519,128520,14,128528,128528,14,128534,128534,14,128538,128538,14,128540,128542,14,128544,128549,14,128552,128555,14,128557,128557,14,128560,128563,14,128565,128565,14,128567,128576,14,128581,128591,14,128641,128642,14,128646,128646,14,128648,128648,14,128650,128651,14,128653,128653,14,128655,128655,14,128657,128659,14,128661,128661,14,128663,128663,14,128665,128666,14,128674,128674,14,128676,128677,14,128679,128685,14,128690,128690,14,128694,128694,14,128697,128702,14,128704,128704,14,128710,128714,14,128716,128716,14,128720,128720,14,128723,128724,14,128726,128727,14,128733,128735,14,128742,128744,14,128746,128746,14,128749,128751,14,128753,128754,14,128756,128758,14,128761,128761,14,128763,128764,14,128884,128895,14,128992,129003,14,129008,129008,14,129036,129039,14,129114,129119,14,129198,129279,14,129293,129295,14,129305,129310,14,129312,129319,14,129328,129328,14,129331,129338,14,129343,129343,14,129351,129355,14,129357,129359,14,129375,129387,14,129393,129393,14,129395,129398,14,129401,129401,14,129403,129403,14,129408,129412,14,129426,129431,14,129443,129444,14,129451,129453,14,129456,129465,14,129472,129472,14,129475,129482,14,129484,129484,14,129488,129510,14,129536,129647,14,129652,129652,14,129656,129658,14,129661,129663,14,129667,129670,14,129680,129685,14,129705,129708,14,129712,129718,14,129723,129727,14,129731,129733,14,129744,129750,14,129754,129759,14,129768,129775,14,129783,129791,14,917504,917504,4,917506,917535,4,917632,917759,4,918000,921599,4,0,9,4,11,12,4,14,31,4,169,169,14,174,174,14,1155,1159,5,1425,1469,5,1473,1474,5,1479,1479,5,1552,1562,5,1611,1631,5,1750,1756,5,1759,1764,5,1770,1773,5,1809,1809,5,1958,1968,5,2045,2045,5,2075,2083,5,2089,2093,5,2192,2193,1,2250,2273,5,2275,2306,5,2362,2362,5,2364,2364,5,2369,2376,5,2381,2381,5,2385,2391,5,2433,2433,5,2492,2492,5,2495,2496,7,2503,2504,7,2509,2509,5,2530,2531,5,2561,2562,5,2620,2620,5,2625,2626,5,2635,2637,5,2672,2673,5,2689,2690,5,2748,2748,5,2753,2757,5,2761,2761,7,2765,2765,5,2810,2815,5,2818,2819,7,2878,2878,5,2880,2880,7,2887,2888,7,2893,2893,5,2903,2903,5,2946,2946,5,3007,3007,7,3009,3010,7,3018,3020,7,3031,3031,5,3073,3075,7,3132,3132,5,3137,3140,7,3146,3149,5,3170,3171,5,3202,3203,7,3262,3262,7,3264,3265,7,3267,3268,7,3271,3272,7,3276,3277,5,3298,3299,5,3330,3331,7,3390,3390,5,3393,3396,5,3402,3404,7,3406,3406,1,3426,3427,5,3458,3459,7,3535,3535,5,3538,3540,5,3544,3550,7,3570,3571,7,3635,3635,7,3655,3662,5,3763,3763,7,3784,3789,5,3893,3893,5,3897,3897,5,3953,3966,5,3968,3972,5,3981,3991,5,4038,4038,5,4145,4145,7,4153,4154,5,4157,4158,5,4184,4185,5,4209,4212,5,4228,4228,7,4237,4237,5,4352,4447,8,4520,4607,10,5906,5908,5,5938,5939,5,5970,5971,5,6068,6069,5,6071,6077,5,6086,6086,5,6089,6099,5,6155,6157,5,6159,6159,5,6313,6313,5,6435,6438,7,6441,6443,7,6450,6450,5,6457,6459,5,6681,6682,7,6741,6741,7,6743,6743,7,6752,6752,5,6757,6764,5,6771,6780,5,6832,6845,5,6847,6862,5,6916,6916,7,6965,6965,5,6971,6971,7,6973,6977,7,6979,6980,7,7040,7041,5,7073,7073,7,7078,7079,7,7082,7082,7,7142,7142,5,7144,7145,5,7149,7149,5,7151,7153,5,7204,7211,7,7220,7221,7,7376,7378,5,7393,7393,7,7405,7405,5,7415,7415,7,7616,7679,5,8204,8204,5,8206,8207,4,8233,8233,4,8252,8252,14,8288,8292,4,8294,8303,4,8413,8416,5,8418,8420,5,8482,8482,14,8596,8601,14,8986,8987,14,9096,9096,14,9193,9196,14,9199,9199,14,9201,9202,14,9208,9210,14,9642,9643,14,9664,9664,14,9728,9729,14,9732,9732,14,9735,9741,14,9743,9744,14,9746,9746,14,9750,9751,14,9753,9756,14,9758,9759,14,9761,9761,14,9764,9765,14,9767,9769,14,9771,9773,14,9775,9775,14,9784,9785,14,9787,9791,14,9793,9793,14,9795,9799,14,9812,9822,14,9824,9824,14,9827,9827,14,9829,9830,14,9832,9832,14,9851,9851,14,9854,9854,14,9856,9861,14,9874,9874,14,9876,9876,14,9878,9879,14,9881,9881,14,9883,9884,14,9888,9889,14,9895,9895,14,9898,9899,14,9904,9905,14,9917,9918,14,9924,9925,14,9928,9928,14,9934,9934,14,9936,9936,14,9938,9938,14,9940,9940,14,9961,9961,14,9963,9967,14,9970,9971,14,9973,9973,14,9975,9977,14,9979,9980,14,9982,9985,14,9987,9988,14,9992,9996,14,9998,9998,14,10000,10001,14,10004,10004,14,10013,10013,14,10024,10024,14,10052,10052,14,10060,10060,14,10067,10069,14,10083,10083,14,10085,10087,14,10145,10145,14,10175,10175,14,11013,11015,14,11088,11088,14,11503,11505,5,11744,11775,5,12334,12335,5,12349,12349,14,12951,12951,14,42607,42607,5,42612,42621,5,42736,42737,5,43014,43014,5,43043,43044,7,43047,43047,7,43136,43137,7,43204,43205,5,43263,43263,5,43335,43345,5,43360,43388,8,43395,43395,7,43444,43445,7,43450,43451,7,43454,43456,7,43561,43566,5,43569,43570,5,43573,43574,5,43596,43596,5,43644,43644,5,43698,43700,5,43710,43711,5,43755,43755,7,43758,43759,7,43766,43766,5,44005,44005,5,44008,44008,5,44012,44012,7,44032,44032,11,44060,44060,11,44088,44088,11,44116,44116,11,44144,44144,11,44172,44172,11,44200,44200,11,44228,44228,11,44256,44256,11,44284,44284,11,44312,44312,11,44340,44340,11,44368,44368,11,44396,44396,11,44424,44424,11,44452,44452,11,44480,44480,11,44508,44508,11,44536,44536,11,44564,44564,11,44592,44592,11,44620,44620,11,44648,44648,11,44676,44676,11,44704,44704,11,44732,44732,11,44760,44760,11,44788,44788,11,44816,44816,11,44844,44844,11,44872,44872,11,44900,44900,11,44928,44928,11,44956,44956,11,44984,44984,11,45012,45012,11,45040,45040,11,45068,45068,11,45096,45096,11,45124,45124,11,45152,45152,11,45180,45180,11,45208,45208,11,45236,45236,11,45264,45264,11,45292,45292,11,45320,45320,11,45348,45348,11,45376,45376,11,45404,45404,11,45432,45432,11,45460,45460,11,45488,45488,11,45516,45516,11,45544,45544,11,45572,45572,11,45600,45600,11,45628,45628,11,45656,45656,11,45684,45684,11,45712,45712,11,45740,45740,11,45768,45768,11,45796,45796,11,45824,45824,11,45852,45852,11,45880,45880,11,45908,45908,11,45936,45936,11,45964,45964,11,45992,45992,11,46020,46020,11,46048,46048,11,46076,46076,11,46104,46104,11,46132,46132,11,46160,46160,11,46188,46188,11,46216,46216,11,46244,46244,11,46272,46272,11,46300,46300,11,46328,46328,11,46356,46356,11,46384,46384,11,46412,46412,11,46440,46440,11,46468,46468,11,46496,46496,11,46524,46524,11,46552,46552,11,46580,46580,11,46608,46608,11,46636,46636,11,46664,46664,11,46692,46692,11,46720,46720,11,46748,46748,11,46776,46776,11,46804,46804,11,46832,46832,11,46860,46860,11,46888,46888,11,46916,46916,11,46944,46944,11,46972,46972,11,47000,47000,11,47028,47028,11,47056,47056,11,47084,47084,11,47112,47112,11,47140,47140,11,47168,47168,11,47196,47196,11,47224,47224,11,47252,47252,11,47280,47280,11,47308,47308,11,47336,47336,11,47364,47364,11,47392,47392,11,47420,47420,11,47448,47448,11,47476,47476,11,47504,47504,11,47532,47532,11,47560,47560,11,47588,47588,11,47616,47616,11,47644,47644,11,47672,47672,11,47700,47700,11,47728,47728,11,47756,47756,11,47784,47784,11,47812,47812,11,47840,47840,11,47868,47868,11,47896,47896,11,47924,47924,11,47952,47952,11,47980,47980,11,48008,48008,11,48036,48036,11,48064,48064,11,48092,48092,11,48120,48120,11,48148,48148,11,48176,48176,11,48204,48204,11,48232,48232,11,48260,48260,11,48288,48288,11,48316,48316,11,48344,48344,11,48372,48372,11,48400,48400,11,48428,48428,11,48456,48456,11,48484,48484,11,48512,48512,11,48540,48540,11,48568,48568,11,48596,48596,11,48624,48624,11,48652,48652,11,48680,48680,11,48708,48708,11,48736,48736,11,48764,48764,11,48792,48792,11,48820,48820,11,48848,48848,11,48876,48876,11,48904,48904,11,48932,48932,11,48960,48960,11,48988,48988,11,49016,49016,11,49044,49044,11,49072,49072,11,49100,49100,11,49128,49128,11,49156,49156,11,49184,49184,11,49212,49212,11,49240,49240,11,49268,49268,11,49296,49296,11,49324,49324,11,49352,49352,11,49380,49380,11,49408,49408,11,49436,49436,11,49464,49464,11,49492,49492,11,49520,49520,11,49548,49548,11,49576,49576,11,49604,49604,11,49632,49632,11,49660,49660,11,49688,49688,11,49716,49716,11,49744,49744,11,49772,49772,11,49800,49800,11,49828,49828,11,49856,49856,11,49884,49884,11,49912,49912,11,49940,49940,11,49968,49968,11,49996,49996,11,50024,50024,11,50052,50052,11,50080,50080,11,50108,50108,11,50136,50136,11,50164,50164,11,50192,50192,11,50220,50220,11,50248,50248,11,50276,50276,11,50304,50304,11,50332,50332,11,50360,50360,11,50388,50388,11,50416,50416,11,50444,50444,11,50472,50472,11,50500,50500,11,50528,50528,11,50556,50556,11,50584,50584,11,50612,50612,11,50640,50640,11,50668,50668,11,50696,50696,11,50724,50724,11,50752,50752,11,50780,50780,11,50808,50808,11,50836,50836,11,50864,50864,11,50892,50892,11,50920,50920,11,50948,50948,11,50976,50976,11,51004,51004,11,51032,51032,11,51060,51060,11,51088,51088,11,51116,51116,11,51144,51144,11,51172,51172,11,51200,51200,11,51228,51228,11,51256,51256,11,51284,51284,11,51312,51312,11,51340,51340,11,51368,51368,11,51396,51396,11,51424,51424,11,51452,51452,11,51480,51480,11,51508,51508,11,51536,51536,11,51564,51564,11,51592,51592,11,51620,51620,11,51648,51648,11,51676,51676,11,51704,51704,11,51732,51732,11,51760,51760,11,51788,51788,11,51816,51816,11,51844,51844,11,51872,51872,11,51900,51900,11,51928,51928,11,51956,51956,11,51984,51984,11,52012,52012,11,52040,52040,11,52068,52068,11,52096,52096,11,52124,52124,11,52152,52152,11,52180,52180,11,52208,52208,11,52236,52236,11,52264,52264,11,52292,52292,11,52320,52320,11,52348,52348,11,52376,52376,11,52404,52404,11,52432,52432,11,52460,52460,11,52488,52488,11,52516,52516,11,52544,52544,11,52572,52572,11,52600,52600,11,52628,52628,11,52656,52656,11,52684,52684,11,52712,52712,11,52740,52740,11,52768,52768,11,52796,52796,11,52824,52824,11,52852,52852,11,52880,52880,11,52908,52908,11,52936,52936,11,52964,52964,11,52992,52992,11,53020,53020,11,53048,53048,11,53076,53076,11,53104,53104,11,53132,53132,11,53160,53160,11,53188,53188,11,53216,53216,11,53244,53244,11,53272,53272,11,53300,53300,11,53328,53328,11,53356,53356,11,53384,53384,11,53412,53412,11,53440,53440,11,53468,53468,11,53496,53496,11,53524,53524,11,53552,53552,11,53580,53580,11,53608,53608,11,53636,53636,11,53664,53664,11,53692,53692,11,53720,53720,11,53748,53748,11,53776,53776,11,53804,53804,11,53832,53832,11,53860,53860,11,53888,53888,11,53916,53916,11,53944,53944,11,53972,53972,11,54000,54000,11,54028,54028,11,54056,54056,11,54084,54084,11,54112,54112,11,54140,54140,11,54168,54168,11,54196,54196,11,54224,54224,11,54252,54252,11,54280,54280,11,54308,54308,11,54336,54336,11,54364,54364,11,54392,54392,11,54420,54420,11,54448,54448,11,54476,54476,11,54504,54504,11,54532,54532,11,54560,54560,11,54588,54588,11,54616,54616,11,54644,54644,11,54672,54672,11,54700,54700,11,54728,54728,11,54756,54756,11,54784,54784,11,54812,54812,11,54840,54840,11,54868,54868,11,54896,54896,11,54924,54924,11,54952,54952,11,54980,54980,11,55008,55008,11,55036,55036,11,55064,55064,11,55092,55092,11,55120,55120,11,55148,55148,11,55176,55176,11,55216,55238,9,64286,64286,5,65056,65071,5,65438,65439,5,65529,65531,4,66272,66272,5,68097,68099,5,68108,68111,5,68159,68159,5,68900,68903,5,69446,69456,5,69632,69632,7,69634,69634,7,69744,69744,5,69759,69761,5,69808,69810,7,69815,69816,7,69821,69821,1,69837,69837,1,69927,69931,5,69933,69940,5,70003,70003,5,70018,70018,7,70070,70078,5,70082,70083,1,70094,70094,7,70188,70190,7,70194,70195,7,70197,70197,7,70206,70206,5,70368,70370,7,70400,70401,5,70459,70460,5,70463,70463,7,70465,70468,7,70475,70477,7,70498,70499,7,70512,70516,5,70712,70719,5,70722,70724,5,70726,70726,5,70832,70832,5,70835,70840,5,70842,70842,5,70845,70845,5,70847,70848,5,70850,70851,5,71088,71089,7,71096,71099,7,71102,71102,7,71132,71133,5,71219,71226,5,71229,71229,5,71231,71232,5,71340,71340,7,71342,71343,7,71350,71350,7,71453,71455,5,71462,71462,7,71724,71726,7,71736,71736,7,71984,71984,5,71991,71992,7,71997,71997,7,71999,71999,1,72001,72001,1,72003,72003,5,72148,72151,5,72156,72159,7,72164,72164,7,72243,72248,5,72250,72250,1,72263,72263,5,72279,72280,7,72324,72329,1,72343,72343,7,72751,72751,7,72760,72765,5,72767,72767,5,72873,72873,7,72881,72881,7,72884,72884,7,73009,73014,5,73020,73021,5,73030,73030,1,73098,73102,7,73107,73108,7,73110,73110,7,73459,73460,5,78896,78904,4,92976,92982,5,94033,94087,7,94180,94180,5,113821,113822,5,118528,118573,5,119141,119141,5,119143,119145,5,119150,119154,5,119163,119170,5,119210,119213,5,121344,121398,5,121461,121461,5,121499,121503,5,122880,122886,5,122907,122913,5,122918,122922,5,123566,123566,5,125136,125142,5,126976,126979,14,126981,127182,14,127184,127231,14,127279,127279,14,127344,127345,14,127374,127374,14,127405,127461,14,127489,127490,14,127514,127514,14,127538,127546,14,127561,127567,14,127570,127743,14,127757,127758,14,127760,127760,14,127762,127762,14,127766,127768,14,127770,127770,14,127772,127772,14,127775,127776,14,127778,127779,14,127789,127791,14,127794,127795,14,127798,127798,14,127819,127819,14,127824,127824,14,127868,127868,14,127870,127871,14,127892,127893,14,127896,127896,14,127900,127901,14,127904,127940,14,127942,127942,14,127944,127944,14,127946,127946,14,127951,127955,14,127968,127971,14,127973,127984,14,127987,127987,14,127989,127989,14,127991,127991,14,127995,127999,5,128008,128008,14,128012,128014,14,128017,128018,14,128020,128020,14,128022,128022,14,128042,128042,14,128063,128063,14,128065,128065,14,128101,128101,14,128108,128109,14,128173,128173,14,128182,128183,14,128236,128237,14,128239,128239,14,128245,128245,14,128248,128248,14,128253,128253,14,128255,128258,14,128260,128263,14,128265,128265,14,128277,128277,14,128300,128301,14,128326,128328,14,128331,128334,14,128336,128347,14,128360,128366,14,128369,128370,14,128378,128378,14,128391,128391,14,128394,128397,14,128400,128400,14,128405,128406,14,128420,128420,14,128422,128423,14,128425,128432,14,128435,128443,14,128445,128449,14,128453,128464,14,128468,128475,14,128479,128480,14,128482,128482,14,128484,128487,14,128489,128494,14,128496,128498,14,128500,128505,14,128507,128511,14,128513,128518,14,128521,128525,14,128527,128527,14,128529,128529,14,128533,128533,14,128535,128535,14,128537,128537,14]");
}
function getLeftDeleteOffset(offset, str2) {
  if (offset === 0) {
    return 0;
  }
  const emojiOffset = getOffsetBeforeLastEmojiComponent(offset, str2);
  if (emojiOffset !== void 0) {
    return emojiOffset;
  }
  const iterator2 = new CodePointIterator(str2, offset);
  iterator2.prevCodePoint();
  return iterator2.offset;
}
function getOffsetBeforeLastEmojiComponent(initialOffset, str2) {
  const iterator2 = new CodePointIterator(str2, initialOffset);
  let codePoint = iterator2.prevCodePoint();
  while (isEmojiModifier(codePoint) || codePoint === 65039 || codePoint === 8419) {
    if (iterator2.offset === 0) {
      return void 0;
    }
    codePoint = iterator2.prevCodePoint();
  }
  if (!isEmojiImprecise(codePoint)) {
    return void 0;
  }
  let resultOffset = iterator2.offset;
  if (resultOffset > 0) {
    const optionalZwjCodePoint = iterator2.prevCodePoint();
    if (optionalZwjCodePoint === 8205) {
      resultOffset = iterator2.offset;
    }
  }
  return resultOffset;
}
function isEmojiModifier(codePoint) {
  return 127995 <= codePoint && codePoint <= 127999;
}
const noBreakWhitespace = " ";
class AmbiguousCharacters {
  static getInstance(locales) {
    return AmbiguousCharacters.cache.get(Array.from(locales));
  }
  static getLocales() {
    return AmbiguousCharacters._locales.value;
  }
  constructor(confusableDictionary) {
    this.confusableDictionary = confusableDictionary;
  }
  isAmbiguous(codePoint) {
    return this.confusableDictionary.has(codePoint);
  }
  /**
   * Returns the non basic ASCII code point that the given code point can be confused,
   * or undefined if such code point does note exist.
   */
  getPrimaryConfusable(codePoint) {
    return this.confusableDictionary.get(codePoint);
  }
  getConfusableCodePoints() {
    return new Set(this.confusableDictionary.keys());
  }
}
_a$3 = AmbiguousCharacters;
AmbiguousCharacters.ambiguousCharacterData = new Lazy(() => {
  return JSON.parse('{"_common":[8232,32,8233,32,5760,32,8192,32,8193,32,8194,32,8195,32,8196,32,8197,32,8198,32,8200,32,8201,32,8202,32,8287,32,8199,32,8239,32,2042,95,65101,95,65102,95,65103,95,8208,45,8209,45,8210,45,65112,45,1748,45,8259,45,727,45,8722,45,10134,45,11450,45,1549,44,1643,44,8218,44,184,44,42233,44,894,59,2307,58,2691,58,1417,58,1795,58,1796,58,5868,58,65072,58,6147,58,6153,58,8282,58,1475,58,760,58,42889,58,8758,58,720,58,42237,58,451,33,11601,33,660,63,577,63,2429,63,5038,63,42731,63,119149,46,8228,46,1793,46,1794,46,42510,46,68176,46,1632,46,1776,46,42232,46,1373,96,65287,96,8219,96,8242,96,1370,96,1523,96,8175,96,65344,96,900,96,8189,96,8125,96,8127,96,8190,96,697,96,884,96,712,96,714,96,715,96,756,96,699,96,701,96,700,96,702,96,42892,96,1497,96,2036,96,2037,96,5194,96,5836,96,94033,96,94034,96,65339,91,10088,40,10098,40,12308,40,64830,40,65341,93,10089,41,10099,41,12309,41,64831,41,10100,123,119060,123,10101,125,65342,94,8270,42,1645,42,8727,42,66335,42,5941,47,8257,47,8725,47,8260,47,9585,47,10187,47,10744,47,119354,47,12755,47,12339,47,11462,47,20031,47,12035,47,65340,92,65128,92,8726,92,10189,92,10741,92,10745,92,119311,92,119355,92,12756,92,20022,92,12034,92,42872,38,708,94,710,94,5869,43,10133,43,66203,43,8249,60,10094,60,706,60,119350,60,5176,60,5810,60,5120,61,11840,61,12448,61,42239,61,8250,62,10095,62,707,62,119351,62,5171,62,94015,62,8275,126,732,126,8128,126,8764,126,65372,124,65293,45,120784,50,120794,50,120804,50,120814,50,120824,50,130034,50,42842,50,423,50,1000,50,42564,50,5311,50,42735,50,119302,51,120785,51,120795,51,120805,51,120815,51,120825,51,130035,51,42923,51,540,51,439,51,42858,51,11468,51,1248,51,94011,51,71882,51,120786,52,120796,52,120806,52,120816,52,120826,52,130036,52,5070,52,71855,52,120787,53,120797,53,120807,53,120817,53,120827,53,130037,53,444,53,71867,53,120788,54,120798,54,120808,54,120818,54,120828,54,130038,54,11474,54,5102,54,71893,54,119314,55,120789,55,120799,55,120809,55,120819,55,120829,55,130039,55,66770,55,71878,55,2819,56,2538,56,2666,56,125131,56,120790,56,120800,56,120810,56,120820,56,120830,56,130040,56,547,56,546,56,66330,56,2663,57,2920,57,2541,57,3437,57,120791,57,120801,57,120811,57,120821,57,120831,57,130041,57,42862,57,11466,57,71884,57,71852,57,71894,57,9082,97,65345,97,119834,97,119886,97,119938,97,119990,97,120042,97,120094,97,120146,97,120198,97,120250,97,120302,97,120354,97,120406,97,120458,97,593,97,945,97,120514,97,120572,97,120630,97,120688,97,120746,97,65313,65,119808,65,119860,65,119912,65,119964,65,120016,65,120068,65,120120,65,120172,65,120224,65,120276,65,120328,65,120380,65,120432,65,913,65,120488,65,120546,65,120604,65,120662,65,120720,65,5034,65,5573,65,42222,65,94016,65,66208,65,119835,98,119887,98,119939,98,119991,98,120043,98,120095,98,120147,98,120199,98,120251,98,120303,98,120355,98,120407,98,120459,98,388,98,5071,98,5234,98,5551,98,65314,66,8492,66,119809,66,119861,66,119913,66,120017,66,120069,66,120121,66,120173,66,120225,66,120277,66,120329,66,120381,66,120433,66,42932,66,914,66,120489,66,120547,66,120605,66,120663,66,120721,66,5108,66,5623,66,42192,66,66178,66,66209,66,66305,66,65347,99,8573,99,119836,99,119888,99,119940,99,119992,99,120044,99,120096,99,120148,99,120200,99,120252,99,120304,99,120356,99,120408,99,120460,99,7428,99,1010,99,11429,99,43951,99,66621,99,128844,67,71922,67,71913,67,65315,67,8557,67,8450,67,8493,67,119810,67,119862,67,119914,67,119966,67,120018,67,120174,67,120226,67,120278,67,120330,67,120382,67,120434,67,1017,67,11428,67,5087,67,42202,67,66210,67,66306,67,66581,67,66844,67,8574,100,8518,100,119837,100,119889,100,119941,100,119993,100,120045,100,120097,100,120149,100,120201,100,120253,100,120305,100,120357,100,120409,100,120461,100,1281,100,5095,100,5231,100,42194,100,8558,68,8517,68,119811,68,119863,68,119915,68,119967,68,120019,68,120071,68,120123,68,120175,68,120227,68,120279,68,120331,68,120383,68,120435,68,5024,68,5598,68,5610,68,42195,68,8494,101,65349,101,8495,101,8519,101,119838,101,119890,101,119942,101,120046,101,120098,101,120150,101,120202,101,120254,101,120306,101,120358,101,120410,101,120462,101,43826,101,1213,101,8959,69,65317,69,8496,69,119812,69,119864,69,119916,69,120020,69,120072,69,120124,69,120176,69,120228,69,120280,69,120332,69,120384,69,120436,69,917,69,120492,69,120550,69,120608,69,120666,69,120724,69,11577,69,5036,69,42224,69,71846,69,71854,69,66182,69,119839,102,119891,102,119943,102,119995,102,120047,102,120099,102,120151,102,120203,102,120255,102,120307,102,120359,102,120411,102,120463,102,43829,102,42905,102,383,102,7837,102,1412,102,119315,70,8497,70,119813,70,119865,70,119917,70,120021,70,120073,70,120125,70,120177,70,120229,70,120281,70,120333,70,120385,70,120437,70,42904,70,988,70,120778,70,5556,70,42205,70,71874,70,71842,70,66183,70,66213,70,66853,70,65351,103,8458,103,119840,103,119892,103,119944,103,120048,103,120100,103,120152,103,120204,103,120256,103,120308,103,120360,103,120412,103,120464,103,609,103,7555,103,397,103,1409,103,119814,71,119866,71,119918,71,119970,71,120022,71,120074,71,120126,71,120178,71,120230,71,120282,71,120334,71,120386,71,120438,71,1292,71,5056,71,5107,71,42198,71,65352,104,8462,104,119841,104,119945,104,119997,104,120049,104,120101,104,120153,104,120205,104,120257,104,120309,104,120361,104,120413,104,120465,104,1211,104,1392,104,5058,104,65320,72,8459,72,8460,72,8461,72,119815,72,119867,72,119919,72,120023,72,120179,72,120231,72,120283,72,120335,72,120387,72,120439,72,919,72,120494,72,120552,72,120610,72,120668,72,120726,72,11406,72,5051,72,5500,72,42215,72,66255,72,731,105,9075,105,65353,105,8560,105,8505,105,8520,105,119842,105,119894,105,119946,105,119998,105,120050,105,120102,105,120154,105,120206,105,120258,105,120310,105,120362,105,120414,105,120466,105,120484,105,618,105,617,105,953,105,8126,105,890,105,120522,105,120580,105,120638,105,120696,105,120754,105,1110,105,42567,105,1231,105,43893,105,5029,105,71875,105,65354,106,8521,106,119843,106,119895,106,119947,106,119999,106,120051,106,120103,106,120155,106,120207,106,120259,106,120311,106,120363,106,120415,106,120467,106,1011,106,1112,106,65322,74,119817,74,119869,74,119921,74,119973,74,120025,74,120077,74,120129,74,120181,74,120233,74,120285,74,120337,74,120389,74,120441,74,42930,74,895,74,1032,74,5035,74,5261,74,42201,74,119844,107,119896,107,119948,107,120000,107,120052,107,120104,107,120156,107,120208,107,120260,107,120312,107,120364,107,120416,107,120468,107,8490,75,65323,75,119818,75,119870,75,119922,75,119974,75,120026,75,120078,75,120130,75,120182,75,120234,75,120286,75,120338,75,120390,75,120442,75,922,75,120497,75,120555,75,120613,75,120671,75,120729,75,11412,75,5094,75,5845,75,42199,75,66840,75,1472,108,8739,73,9213,73,65512,73,1633,108,1777,73,66336,108,125127,108,120783,73,120793,73,120803,73,120813,73,120823,73,130033,73,65321,73,8544,73,8464,73,8465,73,119816,73,119868,73,119920,73,120024,73,120128,73,120180,73,120232,73,120284,73,120336,73,120388,73,120440,73,65356,108,8572,73,8467,108,119845,108,119897,108,119949,108,120001,108,120053,108,120105,73,120157,73,120209,73,120261,73,120313,73,120365,73,120417,73,120469,73,448,73,120496,73,120554,73,120612,73,120670,73,120728,73,11410,73,1030,73,1216,73,1493,108,1503,108,1575,108,126464,108,126592,108,65166,108,65165,108,1994,108,11599,73,5825,73,42226,73,93992,73,66186,124,66313,124,119338,76,8556,76,8466,76,119819,76,119871,76,119923,76,120027,76,120079,76,120131,76,120183,76,120235,76,120287,76,120339,76,120391,76,120443,76,11472,76,5086,76,5290,76,42209,76,93974,76,71843,76,71858,76,66587,76,66854,76,65325,77,8559,77,8499,77,119820,77,119872,77,119924,77,120028,77,120080,77,120132,77,120184,77,120236,77,120288,77,120340,77,120392,77,120444,77,924,77,120499,77,120557,77,120615,77,120673,77,120731,77,1018,77,11416,77,5047,77,5616,77,5846,77,42207,77,66224,77,66321,77,119847,110,119899,110,119951,110,120003,110,120055,110,120107,110,120159,110,120211,110,120263,110,120315,110,120367,110,120419,110,120471,110,1400,110,1404,110,65326,78,8469,78,119821,78,119873,78,119925,78,119977,78,120029,78,120081,78,120185,78,120237,78,120289,78,120341,78,120393,78,120445,78,925,78,120500,78,120558,78,120616,78,120674,78,120732,78,11418,78,42208,78,66835,78,3074,111,3202,111,3330,111,3458,111,2406,111,2662,111,2790,111,3046,111,3174,111,3302,111,3430,111,3664,111,3792,111,4160,111,1637,111,1781,111,65359,111,8500,111,119848,111,119900,111,119952,111,120056,111,120108,111,120160,111,120212,111,120264,111,120316,111,120368,111,120420,111,120472,111,7439,111,7441,111,43837,111,959,111,120528,111,120586,111,120644,111,120702,111,120760,111,963,111,120532,111,120590,111,120648,111,120706,111,120764,111,11423,111,4351,111,1413,111,1505,111,1607,111,126500,111,126564,111,126596,111,65259,111,65260,111,65258,111,65257,111,1726,111,64428,111,64429,111,64427,111,64426,111,1729,111,64424,111,64425,111,64423,111,64422,111,1749,111,3360,111,4125,111,66794,111,71880,111,71895,111,66604,111,1984,79,2534,79,2918,79,12295,79,70864,79,71904,79,120782,79,120792,79,120802,79,120812,79,120822,79,130032,79,65327,79,119822,79,119874,79,119926,79,119978,79,120030,79,120082,79,120134,79,120186,79,120238,79,120290,79,120342,79,120394,79,120446,79,927,79,120502,79,120560,79,120618,79,120676,79,120734,79,11422,79,1365,79,11604,79,4816,79,2848,79,66754,79,42227,79,71861,79,66194,79,66219,79,66564,79,66838,79,9076,112,65360,112,119849,112,119901,112,119953,112,120005,112,120057,112,120109,112,120161,112,120213,112,120265,112,120317,112,120369,112,120421,112,120473,112,961,112,120530,112,120544,112,120588,112,120602,112,120646,112,120660,112,120704,112,120718,112,120762,112,120776,112,11427,112,65328,80,8473,80,119823,80,119875,80,119927,80,119979,80,120031,80,120083,80,120187,80,120239,80,120291,80,120343,80,120395,80,120447,80,929,80,120504,80,120562,80,120620,80,120678,80,120736,80,11426,80,5090,80,5229,80,42193,80,66197,80,119850,113,119902,113,119954,113,120006,113,120058,113,120110,113,120162,113,120214,113,120266,113,120318,113,120370,113,120422,113,120474,113,1307,113,1379,113,1382,113,8474,81,119824,81,119876,81,119928,81,119980,81,120032,81,120084,81,120188,81,120240,81,120292,81,120344,81,120396,81,120448,81,11605,81,119851,114,119903,114,119955,114,120007,114,120059,114,120111,114,120163,114,120215,114,120267,114,120319,114,120371,114,120423,114,120475,114,43847,114,43848,114,7462,114,11397,114,43905,114,119318,82,8475,82,8476,82,8477,82,119825,82,119877,82,119929,82,120033,82,120189,82,120241,82,120293,82,120345,82,120397,82,120449,82,422,82,5025,82,5074,82,66740,82,5511,82,42211,82,94005,82,65363,115,119852,115,119904,115,119956,115,120008,115,120060,115,120112,115,120164,115,120216,115,120268,115,120320,115,120372,115,120424,115,120476,115,42801,115,445,115,1109,115,43946,115,71873,115,66632,115,65331,83,119826,83,119878,83,119930,83,119982,83,120034,83,120086,83,120138,83,120190,83,120242,83,120294,83,120346,83,120398,83,120450,83,1029,83,1359,83,5077,83,5082,83,42210,83,94010,83,66198,83,66592,83,119853,116,119905,116,119957,116,120009,116,120061,116,120113,116,120165,116,120217,116,120269,116,120321,116,120373,116,120425,116,120477,116,8868,84,10201,84,128872,84,65332,84,119827,84,119879,84,119931,84,119983,84,120035,84,120087,84,120139,84,120191,84,120243,84,120295,84,120347,84,120399,84,120451,84,932,84,120507,84,120565,84,120623,84,120681,84,120739,84,11430,84,5026,84,42196,84,93962,84,71868,84,66199,84,66225,84,66325,84,119854,117,119906,117,119958,117,120010,117,120062,117,120114,117,120166,117,120218,117,120270,117,120322,117,120374,117,120426,117,120478,117,42911,117,7452,117,43854,117,43858,117,651,117,965,117,120534,117,120592,117,120650,117,120708,117,120766,117,1405,117,66806,117,71896,117,8746,85,8899,85,119828,85,119880,85,119932,85,119984,85,120036,85,120088,85,120140,85,120192,85,120244,85,120296,85,120348,85,120400,85,120452,85,1357,85,4608,85,66766,85,5196,85,42228,85,94018,85,71864,85,8744,118,8897,118,65366,118,8564,118,119855,118,119907,118,119959,118,120011,118,120063,118,120115,118,120167,118,120219,118,120271,118,120323,118,120375,118,120427,118,120479,118,7456,118,957,118,120526,118,120584,118,120642,118,120700,118,120758,118,1141,118,1496,118,71430,118,43945,118,71872,118,119309,86,1639,86,1783,86,8548,86,119829,86,119881,86,119933,86,119985,86,120037,86,120089,86,120141,86,120193,86,120245,86,120297,86,120349,86,120401,86,120453,86,1140,86,11576,86,5081,86,5167,86,42719,86,42214,86,93960,86,71840,86,66845,86,623,119,119856,119,119908,119,119960,119,120012,119,120064,119,120116,119,120168,119,120220,119,120272,119,120324,119,120376,119,120428,119,120480,119,7457,119,1121,119,1309,119,1377,119,71434,119,71438,119,71439,119,43907,119,71919,87,71910,87,119830,87,119882,87,119934,87,119986,87,120038,87,120090,87,120142,87,120194,87,120246,87,120298,87,120350,87,120402,87,120454,87,1308,87,5043,87,5076,87,42218,87,5742,120,10539,120,10540,120,10799,120,65368,120,8569,120,119857,120,119909,120,119961,120,120013,120,120065,120,120117,120,120169,120,120221,120,120273,120,120325,120,120377,120,120429,120,120481,120,5441,120,5501,120,5741,88,9587,88,66338,88,71916,88,65336,88,8553,88,119831,88,119883,88,119935,88,119987,88,120039,88,120091,88,120143,88,120195,88,120247,88,120299,88,120351,88,120403,88,120455,88,42931,88,935,88,120510,88,120568,88,120626,88,120684,88,120742,88,11436,88,11613,88,5815,88,42219,88,66192,88,66228,88,66327,88,66855,88,611,121,7564,121,65369,121,119858,121,119910,121,119962,121,120014,121,120066,121,120118,121,120170,121,120222,121,120274,121,120326,121,120378,121,120430,121,120482,121,655,121,7935,121,43866,121,947,121,8509,121,120516,121,120574,121,120632,121,120690,121,120748,121,1199,121,4327,121,71900,121,65337,89,119832,89,119884,89,119936,89,119988,89,120040,89,120092,89,120144,89,120196,89,120248,89,120300,89,120352,89,120404,89,120456,89,933,89,978,89,120508,89,120566,89,120624,89,120682,89,120740,89,11432,89,1198,89,5033,89,5053,89,42220,89,94019,89,71844,89,66226,89,119859,122,119911,122,119963,122,120015,122,120067,122,120119,122,120171,122,120223,122,120275,122,120327,122,120379,122,120431,122,120483,122,7458,122,43923,122,71876,122,66293,90,71909,90,65338,90,8484,90,8488,90,119833,90,119885,90,119937,90,119989,90,120041,90,120197,90,120249,90,120301,90,120353,90,120405,90,120457,90,918,90,120493,90,120551,90,120609,90,120667,90,120725,90,5059,90,42204,90,71849,90,65282,34,65284,36,65285,37,65286,38,65290,42,65291,43,65294,46,65295,47,65296,48,65297,49,65298,50,65299,51,65300,52,65301,53,65302,54,65303,55,65304,56,65305,57,65308,60,65309,61,65310,62,65312,64,65316,68,65318,70,65319,71,65324,76,65329,81,65330,82,65333,85,65334,86,65335,87,65343,95,65346,98,65348,100,65350,102,65355,107,65357,109,65358,110,65361,113,65362,114,65364,116,65365,117,65367,119,65370,122,65371,123,65373,125,119846,109],"_default":[160,32,8211,45,65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],"cs":[65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],"de":[65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],"es":[8211,45,65374,126,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],"fr":[65374,126,65306,58,65281,33,8216,96,8245,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],"it":[160,32,8211,45,65374,126,65306,58,65281,33,8216,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],"ja":[8211,45,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65292,44,65307,59],"ko":[8211,45,65374,126,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],"pl":[65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],"pt-BR":[65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],"qps-ploc":[160,32,8211,45,65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],"ru":[65374,126,65306,58,65281,33,8216,96,8217,96,8245,96,180,96,12494,47,305,105,921,73,1009,112,215,120,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],"tr":[160,32,8211,45,65374,126,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65288,40,65289,41,65292,44,65307,59,65311,63],"zh-hans":[65374,126,65306,58,65281,33,8245,96,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65288,40,65289,41],"zh-hant":[8211,45,65374,126,180,96,12494,47,1047,51,1073,54,1072,97,1040,65,1068,98,1042,66,1089,99,1057,67,1077,101,1045,69,1053,72,305,105,1050,75,921,73,1052,77,1086,111,1054,79,1009,112,1088,112,1056,80,1075,114,1058,84,215,120,1093,120,1061,88,1091,121,1059,89,65283,35,65307,59]}');
});
AmbiguousCharacters.cache = new LRUCachedFunction((locales) => {
  function arrayToMap(arr) {
    const result2 = /* @__PURE__ */ new Map();
    for (let i = 0; i < arr.length; i += 2) {
      result2.set(arr[i], arr[i + 1]);
    }
    return result2;
  }
  function mergeMaps(map1, map22) {
    const result2 = new Map(map1);
    for (const [key, value] of map22) {
      result2.set(key, value);
    }
    return result2;
  }
  function intersectMaps(map1, map22) {
    if (!map1) {
      return map22;
    }
    const result2 = /* @__PURE__ */ new Map();
    for (const [key, value] of map1) {
      if (map22.has(key)) {
        result2.set(key, value);
      }
    }
    return result2;
  }
  const data = _a$3.ambiguousCharacterData.value;
  let filteredLocales = locales.filter((l) => !l.startsWith("_") && l in data);
  if (filteredLocales.length === 0) {
    filteredLocales = ["_default"];
  }
  let languageSpecificMap = void 0;
  for (const locale of filteredLocales) {
    const map3 = arrayToMap(data[locale]);
    languageSpecificMap = intersectMaps(languageSpecificMap, map3);
  }
  const commonMap = arrayToMap(data["_common"]);
  const map2 = mergeMaps(commonMap, languageSpecificMap);
  return new AmbiguousCharacters(map2);
});
AmbiguousCharacters._locales = new Lazy(() => Object.keys(AmbiguousCharacters.ambiguousCharacterData.value).filter((k) => !k.startsWith("_")));
class InvisibleCharacters {
  static getRawData() {
    return JSON.parse("[9,10,11,12,13,32,127,160,173,847,1564,4447,4448,6068,6069,6155,6156,6157,6158,7355,7356,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8203,8204,8205,8206,8207,8234,8235,8236,8237,8238,8239,8287,8288,8289,8290,8291,8292,8293,8294,8295,8296,8297,8298,8299,8300,8301,8302,8303,10240,12288,12644,65024,65025,65026,65027,65028,65029,65030,65031,65032,65033,65034,65035,65036,65037,65038,65039,65279,65440,65520,65521,65522,65523,65524,65525,65526,65527,65528,65532,78844,119155,119156,119157,119158,119159,119160,119161,119162,917504,917505,917506,917507,917508,917509,917510,917511,917512,917513,917514,917515,917516,917517,917518,917519,917520,917521,917522,917523,917524,917525,917526,917527,917528,917529,917530,917531,917532,917533,917534,917535,917536,917537,917538,917539,917540,917541,917542,917543,917544,917545,917546,917547,917548,917549,917550,917551,917552,917553,917554,917555,917556,917557,917558,917559,917560,917561,917562,917563,917564,917565,917566,917567,917568,917569,917570,917571,917572,917573,917574,917575,917576,917577,917578,917579,917580,917581,917582,917583,917584,917585,917586,917587,917588,917589,917590,917591,917592,917593,917594,917595,917596,917597,917598,917599,917600,917601,917602,917603,917604,917605,917606,917607,917608,917609,917610,917611,917612,917613,917614,917615,917616,917617,917618,917619,917620,917621,917622,917623,917624,917625,917626,917627,917628,917629,917630,917631,917760,917761,917762,917763,917764,917765,917766,917767,917768,917769,917770,917771,917772,917773,917774,917775,917776,917777,917778,917779,917780,917781,917782,917783,917784,917785,917786,917787,917788,917789,917790,917791,917792,917793,917794,917795,917796,917797,917798,917799,917800,917801,917802,917803,917804,917805,917806,917807,917808,917809,917810,917811,917812,917813,917814,917815,917816,917817,917818,917819,917820,917821,917822,917823,917824,917825,917826,917827,917828,917829,917830,917831,917832,917833,917834,917835,917836,917837,917838,917839,917840,917841,917842,917843,917844,917845,917846,917847,917848,917849,917850,917851,917852,917853,917854,917855,917856,917857,917858,917859,917860,917861,917862,917863,917864,917865,917866,917867,917868,917869,917870,917871,917872,917873,917874,917875,917876,917877,917878,917879,917880,917881,917882,917883,917884,917885,917886,917887,917888,917889,917890,917891,917892,917893,917894,917895,917896,917897,917898,917899,917900,917901,917902,917903,917904,917905,917906,917907,917908,917909,917910,917911,917912,917913,917914,917915,917916,917917,917918,917919,917920,917921,917922,917923,917924,917925,917926,917927,917928,917929,917930,917931,917932,917933,917934,917935,917936,917937,917938,917939,917940,917941,917942,917943,917944,917945,917946,917947,917948,917949,917950,917951,917952,917953,917954,917955,917956,917957,917958,917959,917960,917961,917962,917963,917964,917965,917966,917967,917968,917969,917970,917971,917972,917973,917974,917975,917976,917977,917978,917979,917980,917981,917982,917983,917984,917985,917986,917987,917988,917989,917990,917991,917992,917993,917994,917995,917996,917997,917998,917999]");
  }
  static getData() {
    if (!this._data) {
      this._data = new Set(InvisibleCharacters.getRawData());
    }
    return this._data;
  }
  static isInvisibleCharacter(codePoint) {
    return InvisibleCharacters.getData().has(codePoint);
  }
  static get codePoints() {
    return InvisibleCharacters.getData();
  }
}
InvisibleCharacters._data = void 0;
function hintDidYouMean(...meant) {
  switch (meant.length) {
    case 1:
      return localize("contextkey.scanner.hint.didYouMean1", "Did you mean {0}?", meant[0]);
    case 2:
      return localize("contextkey.scanner.hint.didYouMean2", "Did you mean {0} or {1}?", meant[0], meant[1]);
    case 3:
      return localize("contextkey.scanner.hint.didYouMean3", "Did you mean {0}, {1} or {2}?", meant[0], meant[1], meant[2]);
    default:
      return void 0;
  }
}
const hintDidYouForgetToOpenOrCloseQuote = localize("contextkey.scanner.hint.didYouForgetToOpenOrCloseQuote", "Did you forget to open or close the quote?");
const hintDidYouForgetToEscapeSlash = localize("contextkey.scanner.hint.didYouForgetToEscapeSlash", "Did you forget to escape the '/' (slash) character? Put two backslashes before it to escape, e.g., '\\\\/'.");
let Scanner$1 = class Scanner {
  constructor() {
    this._input = "";
    this._start = 0;
    this._current = 0;
    this._tokens = [];
    this._errors = [];
    this.stringRe = /[a-zA-Z0-9_<>\-\./\\:\*\?\+\[\]\^,#@;"%\$\p{L}-]+/uy;
  }
  static getLexeme(token) {
    switch (token.type) {
      case 0:
        return "(";
      case 1:
        return ")";
      case 2:
        return "!";
      case 3:
        return token.isTripleEq ? "===" : "==";
      case 4:
        return token.isTripleEq ? "!==" : "!=";
      case 5:
        return "<";
      case 6:
        return "<=";
      case 7:
        return ">=";
      case 8:
        return ">=";
      case 9:
        return "=~";
      case 10:
        return token.lexeme;
      case 11:
        return "true";
      case 12:
        return "false";
      case 13:
        return "in";
      case 14:
        return "not";
      case 15:
        return "&&";
      case 16:
        return "||";
      case 17:
        return token.lexeme;
      case 18:
        return token.lexeme;
      case 19:
        return token.lexeme;
      case 20:
        return "EOF";
      default:
        throw illegalState(`unhandled token type: ${JSON.stringify(token)}; have you forgotten to add a case?`);
    }
  }
  reset(value) {
    this._input = value;
    this._start = 0;
    this._current = 0;
    this._tokens = [];
    this._errors = [];
    return this;
  }
  scan() {
    while (!this._isAtEnd()) {
      this._start = this._current;
      const ch = this._advance();
      switch (ch) {
        case 40:
          this._addToken(
            0
            /* TokenType.LParen */
          );
          break;
        case 41:
          this._addToken(
            1
            /* TokenType.RParen */
          );
          break;
        case 33:
          if (this._match(
            61
            /* CharCode.Equals */
          )) {
            const isTripleEq = this._match(
              61
              /* CharCode.Equals */
            );
            this._tokens.push({ type: 4, offset: this._start, isTripleEq });
          } else {
            this._addToken(
              2
              /* TokenType.Neg */
            );
          }
          break;
        case 39:
          this._quotedString();
          break;
        case 47:
          this._regex();
          break;
        case 61:
          if (this._match(
            61
            /* CharCode.Equals */
          )) {
            const isTripleEq = this._match(
              61
              /* CharCode.Equals */
            );
            this._tokens.push({ type: 3, offset: this._start, isTripleEq });
          } else if (this._match(
            126
            /* CharCode.Tilde */
          )) {
            this._addToken(
              9
              /* TokenType.RegexOp */
            );
          } else {
            this._error(hintDidYouMean("==", "=~"));
          }
          break;
        case 60:
          this._addToken(
            this._match(
              61
              /* CharCode.Equals */
            ) ? 6 : 5
            /* TokenType.Lt */
          );
          break;
        case 62:
          this._addToken(
            this._match(
              61
              /* CharCode.Equals */
            ) ? 8 : 7
            /* TokenType.Gt */
          );
          break;
        case 38:
          if (this._match(
            38
            /* CharCode.Ampersand */
          )) {
            this._addToken(
              15
              /* TokenType.And */
            );
          } else {
            this._error(hintDidYouMean("&&"));
          }
          break;
        case 124:
          if (this._match(
            124
            /* CharCode.Pipe */
          )) {
            this._addToken(
              16
              /* TokenType.Or */
            );
          } else {
            this._error(hintDidYouMean("||"));
          }
          break;
        case 32:
        case 13:
        case 9:
        case 10:
        case 160:
          break;
        default:
          this._string();
      }
    }
    this._start = this._current;
    this._addToken(
      20
      /* TokenType.EOF */
    );
    return Array.from(this._tokens);
  }
  _match(expected) {
    if (this._isAtEnd()) {
      return false;
    }
    if (this._input.charCodeAt(this._current) !== expected) {
      return false;
    }
    this._current++;
    return true;
  }
  _advance() {
    return this._input.charCodeAt(this._current++);
  }
  _peek() {
    return this._isAtEnd() ? 0 : this._input.charCodeAt(this._current);
  }
  _addToken(type) {
    this._tokens.push({ type, offset: this._start });
  }
  _error(additional) {
    const offset = this._start;
    const lexeme = this._input.substring(this._start, this._current);
    const errToken = { type: 19, offset: this._start, lexeme };
    this._errors.push({ offset, lexeme, additionalInfo: additional });
    this._tokens.push(errToken);
  }
  _string() {
    this.stringRe.lastIndex = this._start;
    const match2 = this.stringRe.exec(this._input);
    if (match2) {
      this._current = this._start + match2[0].length;
      const lexeme = this._input.substring(this._start, this._current);
      const keyword = Scanner._keywords.get(lexeme);
      if (keyword) {
        this._addToken(keyword);
      } else {
        this._tokens.push({ type: 17, lexeme, offset: this._start });
      }
    }
  }
  // captures the lexeme without the leading and trailing '
  _quotedString() {
    while (this._peek() !== 39 && !this._isAtEnd()) {
      this._advance();
    }
    if (this._isAtEnd()) {
      this._error(hintDidYouForgetToOpenOrCloseQuote);
      return;
    }
    this._advance();
    this._tokens.push({ type: 18, lexeme: this._input.substring(this._start + 1, this._current - 1), offset: this._start + 1 });
  }
  /*
   * Lexing a regex expression: /.../[igsmyu]*
   * Based on https://github.com/microsoft/TypeScript/blob/9247ef115e617805983740ba795d7a8164babf89/src/compiler/scanner.ts#L2129-L2181
   *
   * Note that we want slashes within a regex to be escaped, e.g., /file:\\/\\/\\// should match `file:///`
   */
  _regex() {
    let p2 = this._current;
    let inEscape = false;
    let inCharacterClass = false;
    while (true) {
      if (p2 >= this._input.length) {
        this._current = p2;
        this._error(hintDidYouForgetToEscapeSlash);
        return;
      }
      const ch = this._input.charCodeAt(p2);
      if (inEscape) {
        inEscape = false;
      } else if (ch === 47 && !inCharacterClass) {
        p2++;
        break;
      } else if (ch === 91) {
        inCharacterClass = true;
      } else if (ch === 92) {
        inEscape = true;
      } else if (ch === 93) {
        inCharacterClass = false;
      }
      p2++;
    }
    while (p2 < this._input.length && Scanner._regexFlags.has(this._input.charCodeAt(p2))) {
      p2++;
    }
    this._current = p2;
    const lexeme = this._input.substring(this._start, this._current);
    this._tokens.push({ type: 10, lexeme, offset: this._start });
  }
  _isAtEnd() {
    return this._current >= this._input.length;
  }
};
Scanner$1._regexFlags = new Set(["i", "g", "s", "m", "y", "u"].map((ch) => ch.charCodeAt(0)));
Scanner$1._keywords = /* @__PURE__ */ new Map([
  [
    "not",
    14
    /* TokenType.Not */
  ],
  [
    "in",
    13
    /* TokenType.In */
  ],
  [
    "false",
    12
    /* TokenType.False */
  ],
  [
    "true",
    11
    /* TokenType.True */
  ]
]);
const CONSTANT_VALUES = /* @__PURE__ */ new Map();
CONSTANT_VALUES.set("false", false);
CONSTANT_VALUES.set("true", true);
CONSTANT_VALUES.set("isMac", isMacintosh);
CONSTANT_VALUES.set("isLinux", isLinux);
CONSTANT_VALUES.set("isWindows", isWindows);
CONSTANT_VALUES.set("isWeb", isWeb);
CONSTANT_VALUES.set("isMacNative", isMacintosh && !isWeb);
CONSTANT_VALUES.set("isEdge", isEdge);
CONSTANT_VALUES.set("isFirefox", isFirefox);
CONSTANT_VALUES.set("isChrome", isChrome);
CONSTANT_VALUES.set("isSafari", isSafari);
const hasOwnProperty$5 = Object.prototype.hasOwnProperty;
const defaultConfig = {
  regexParsingWithErrorRecovery: true
};
const errorEmptyString = localize("contextkey.parser.error.emptyString", "Empty context key expression");
const hintEmptyString = localize("contextkey.parser.error.emptyString.hint", "Did you forget to write an expression? You can also put 'false' or 'true' to always evaluate to false or true, respectively.");
const errorNoInAfterNot = localize("contextkey.parser.error.noInAfterNot", "'in' after 'not'.");
const errorClosingParenthesis = localize("contextkey.parser.error.closingParenthesis", "closing parenthesis ')'");
const errorUnexpectedToken = localize("contextkey.parser.error.unexpectedToken", "Unexpected token");
const hintUnexpectedToken = localize("contextkey.parser.error.unexpectedToken.hint", "Did you forget to put && or || before the token?");
const errorUnexpectedEOF = localize("contextkey.parser.error.unexpectedEOF", "Unexpected end of expression");
const hintUnexpectedEOF = localize("contextkey.parser.error.unexpectedEOF.hint", "Did you forget to put a context key?");
let Parser$4 = class Parser {
  constructor(_config = defaultConfig) {
    this._config = _config;
    this._scanner = new Scanner$1();
    this._tokens = [];
    this._current = 0;
    this._parsingErrors = [];
    this._flagsGYRe = /g|y/g;
  }
  /**
   * Parse a context key expression.
   *
   * @param input the expression to parse
   * @returns the parsed expression or `undefined` if there's an error - call `lexingErrors` and `parsingErrors` to see the errors
   */
  parse(input2) {
    if (input2 === "") {
      this._parsingErrors.push({ message: errorEmptyString, offset: 0, lexeme: "", additionalInfo: hintEmptyString });
      return void 0;
    }
    this._tokens = this._scanner.reset(input2).scan();
    this._current = 0;
    this._parsingErrors = [];
    try {
      const expr = this._expr();
      if (!this._isAtEnd()) {
        const peek = this._peek();
        const additionalInfo = peek.type === 17 ? hintUnexpectedToken : void 0;
        this._parsingErrors.push({ message: errorUnexpectedToken, offset: peek.offset, lexeme: Scanner$1.getLexeme(peek), additionalInfo });
        throw Parser._parseError;
      }
      return expr;
    } catch (e) {
      if (!(e === Parser._parseError)) {
        throw e;
      }
      return void 0;
    }
  }
  _expr() {
    return this._or();
  }
  _or() {
    const expr = [this._and()];
    while (this._matchOne(
      16
      /* TokenType.Or */
    )) {
      const right = this._and();
      expr.push(right);
    }
    return expr.length === 1 ? expr[0] : ContextKeyExpr.or(...expr);
  }
  _and() {
    const expr = [this._term()];
    while (this._matchOne(
      15
      /* TokenType.And */
    )) {
      const right = this._term();
      expr.push(right);
    }
    return expr.length === 1 ? expr[0] : ContextKeyExpr.and(...expr);
  }
  _term() {
    if (this._matchOne(
      2
      /* TokenType.Neg */
    )) {
      const peek = this._peek();
      switch (peek.type) {
        case 11:
          this._advance();
          return ContextKeyFalseExpr.INSTANCE;
        case 12:
          this._advance();
          return ContextKeyTrueExpr.INSTANCE;
        case 0: {
          this._advance();
          const expr = this._expr();
          this._consume(1, errorClosingParenthesis);
          return expr === null || expr === void 0 ? void 0 : expr.negate();
        }
        case 17:
          this._advance();
          return ContextKeyNotExpr.create(peek.lexeme);
        default:
          throw this._errExpectedButGot(`KEY | true | false | '(' expression ')'`, peek);
      }
    }
    return this._primary();
  }
  _primary() {
    const peek = this._peek();
    switch (peek.type) {
      case 11:
        this._advance();
        return ContextKeyExpr.true();
      case 12:
        this._advance();
        return ContextKeyExpr.false();
      case 0: {
        this._advance();
        const expr = this._expr();
        this._consume(1, errorClosingParenthesis);
        return expr;
      }
      case 17: {
        const key = peek.lexeme;
        this._advance();
        if (this._matchOne(
          9
          /* TokenType.RegexOp */
        )) {
          const expr = this._peek();
          if (!this._config.regexParsingWithErrorRecovery) {
            this._advance();
            if (expr.type !== 10) {
              throw this._errExpectedButGot(`REGEX`, expr);
            }
            const regexLexeme = expr.lexeme;
            const closingSlashIndex = regexLexeme.lastIndexOf("/");
            const flags = closingSlashIndex === regexLexeme.length - 1 ? void 0 : this._removeFlagsGY(regexLexeme.substring(closingSlashIndex + 1));
            let regexp;
            try {
              regexp = new RegExp(regexLexeme.substring(1, closingSlashIndex), flags);
            } catch (e) {
              throw this._errExpectedButGot(`REGEX`, expr);
            }
            return ContextKeyRegexExpr.create(key, regexp);
          }
          switch (expr.type) {
            case 10:
            case 19: {
              const lexemeReconstruction = [expr.lexeme];
              this._advance();
              let followingToken = this._peek();
              let parenBalance = 0;
              for (let i = 0; i < expr.lexeme.length; i++) {
                if (expr.lexeme.charCodeAt(i) === 40) {
                  parenBalance++;
                } else if (expr.lexeme.charCodeAt(i) === 41) {
                  parenBalance--;
                }
              }
              while (!this._isAtEnd() && followingToken.type !== 15 && followingToken.type !== 16) {
                switch (followingToken.type) {
                  case 0:
                    parenBalance++;
                    break;
                  case 1:
                    parenBalance--;
                    break;
                  case 10:
                  case 18:
                    for (let i = 0; i < followingToken.lexeme.length; i++) {
                      if (followingToken.lexeme.charCodeAt(i) === 40) {
                        parenBalance++;
                      } else if (expr.lexeme.charCodeAt(i) === 41) {
                        parenBalance--;
                      }
                    }
                }
                if (parenBalance < 0) {
                  break;
                }
                lexemeReconstruction.push(Scanner$1.getLexeme(followingToken));
                this._advance();
                followingToken = this._peek();
              }
              const regexLexeme = lexemeReconstruction.join("");
              const closingSlashIndex = regexLexeme.lastIndexOf("/");
              const flags = closingSlashIndex === regexLexeme.length - 1 ? void 0 : this._removeFlagsGY(regexLexeme.substring(closingSlashIndex + 1));
              let regexp;
              try {
                regexp = new RegExp(regexLexeme.substring(1, closingSlashIndex), flags);
              } catch (e) {
                throw this._errExpectedButGot(`REGEX`, expr);
              }
              return ContextKeyExpr.regex(key, regexp);
            }
            case 18: {
              const serializedValue = expr.lexeme;
              this._advance();
              let regex = null;
              if (!isFalsyOrWhitespace(serializedValue)) {
                const start = serializedValue.indexOf("/");
                const end = serializedValue.lastIndexOf("/");
                if (start !== end && start >= 0) {
                  const value = serializedValue.slice(start + 1, end);
                  const caseIgnoreFlag = serializedValue[end + 1] === "i" ? "i" : "";
                  try {
                    regex = new RegExp(value, caseIgnoreFlag);
                  } catch (_e2) {
                    throw this._errExpectedButGot(`REGEX`, expr);
                  }
                }
              }
              if (regex === null) {
                throw this._errExpectedButGot("REGEX", expr);
              }
              return ContextKeyRegexExpr.create(key, regex);
            }
            default:
              throw this._errExpectedButGot("REGEX", this._peek());
          }
        }
        if (this._matchOne(
          14
          /* TokenType.Not */
        )) {
          this._consume(13, errorNoInAfterNot);
          const right = this._value();
          return ContextKeyExpr.notIn(key, right);
        }
        const maybeOp = this._peek().type;
        switch (maybeOp) {
          case 3: {
            this._advance();
            const right = this._value();
            if (this._previous().type === 18) {
              return ContextKeyExpr.equals(key, right);
            }
            switch (right) {
              case "true":
                return ContextKeyExpr.has(key);
              case "false":
                return ContextKeyExpr.not(key);
              default:
                return ContextKeyExpr.equals(key, right);
            }
          }
          case 4: {
            this._advance();
            const right = this._value();
            if (this._previous().type === 18) {
              return ContextKeyExpr.notEquals(key, right);
            }
            switch (right) {
              case "true":
                return ContextKeyExpr.not(key);
              case "false":
                return ContextKeyExpr.has(key);
              default:
                return ContextKeyExpr.notEquals(key, right);
            }
          }
          case 5:
            this._advance();
            return ContextKeySmallerExpr.create(key, this._value());
          case 6:
            this._advance();
            return ContextKeySmallerEqualsExpr.create(key, this._value());
          case 7:
            this._advance();
            return ContextKeyGreaterExpr.create(key, this._value());
          case 8:
            this._advance();
            return ContextKeyGreaterEqualsExpr.create(key, this._value());
          case 13:
            this._advance();
            return ContextKeyExpr.in(key, this._value());
          default:
            return ContextKeyExpr.has(key);
        }
      }
      case 20:
        this._parsingErrors.push({ message: errorUnexpectedEOF, offset: peek.offset, lexeme: "", additionalInfo: hintUnexpectedEOF });
        throw Parser._parseError;
      default:
        throw this._errExpectedButGot(`true | false | KEY 
	| KEY '=~' REGEX 
	| KEY ('==' | '!=' | '<' | '<=' | '>' | '>=' | 'in' | 'not' 'in') value`, this._peek());
    }
  }
  _value() {
    const token = this._peek();
    switch (token.type) {
      case 17:
      case 18:
        this._advance();
        return token.lexeme;
      case 11:
        this._advance();
        return "true";
      case 12:
        this._advance();
        return "false";
      case 13:
        this._advance();
        return "in";
      default:
        return "";
    }
  }
  _removeFlagsGY(flags) {
    return flags.replaceAll(this._flagsGYRe, "");
  }
  // careful: this can throw if current token is the initial one (ie index = 0)
  _previous() {
    return this._tokens[this._current - 1];
  }
  _matchOne(token) {
    if (this._check(token)) {
      this._advance();
      return true;
    }
    return false;
  }
  _advance() {
    if (!this._isAtEnd()) {
      this._current++;
    }
    return this._previous();
  }
  _consume(type, message) {
    if (this._check(type)) {
      return this._advance();
    }
    throw this._errExpectedButGot(message, this._peek());
  }
  _errExpectedButGot(expected, got, additionalInfo) {
    const message = localize("contextkey.parser.error.expectedButGot", "Expected: {0}\nReceived: '{1}'.", expected, Scanner$1.getLexeme(got));
    const offset = got.offset;
    const lexeme = Scanner$1.getLexeme(got);
    this._parsingErrors.push({ message, offset, lexeme, additionalInfo });
    return Parser._parseError;
  }
  _check(type) {
    return this._peek().type === type;
  }
  _peek() {
    return this._tokens[this._current];
  }
  _isAtEnd() {
    return this._peek().type === 20;
  }
};
Parser$4._parseError = new Error();
class ContextKeyExpr {
  static false() {
    return ContextKeyFalseExpr.INSTANCE;
  }
  static true() {
    return ContextKeyTrueExpr.INSTANCE;
  }
  static has(key) {
    return ContextKeyDefinedExpr.create(key);
  }
  static equals(key, value) {
    return ContextKeyEqualsExpr.create(key, value);
  }
  static notEquals(key, value) {
    return ContextKeyNotEqualsExpr.create(key, value);
  }
  static regex(key, value) {
    return ContextKeyRegexExpr.create(key, value);
  }
  static in(key, value) {
    return ContextKeyInExpr.create(key, value);
  }
  static notIn(key, value) {
    return ContextKeyNotInExpr.create(key, value);
  }
  static not(key) {
    return ContextKeyNotExpr.create(key);
  }
  static and(...expr) {
    return ContextKeyAndExpr.create(expr, null, true);
  }
  static or(...expr) {
    return ContextKeyOrExpr.create(expr, null, true);
  }
  static deserialize(serialized) {
    if (serialized === void 0 || serialized === null) {
      return void 0;
    }
    const expr = this._parser.parse(serialized);
    return expr;
  }
}
ContextKeyExpr._parser = new Parser$4({ regexParsingWithErrorRecovery: false });
function expressionsAreEqualWithConstantSubstitution(a, b) {
  const aExpr = a ? a.substituteConstants() : void 0;
  const bExpr = b ? b.substituteConstants() : void 0;
  if (!aExpr && !bExpr) {
    return true;
  }
  if (!aExpr || !bExpr) {
    return false;
  }
  return aExpr.equals(bExpr);
}
function cmp(a, b) {
  return a.cmp(b);
}
class ContextKeyFalseExpr {
  constructor() {
    this.type = 0;
  }
  cmp(other) {
    return this.type - other.type;
  }
  equals(other) {
    return other.type === this.type;
  }
  substituteConstants() {
    return this;
  }
  evaluate(context) {
    return false;
  }
  serialize() {
    return "false";
  }
  keys() {
    return [];
  }
  negate() {
    return ContextKeyTrueExpr.INSTANCE;
  }
}
ContextKeyFalseExpr.INSTANCE = new ContextKeyFalseExpr();
class ContextKeyTrueExpr {
  constructor() {
    this.type = 1;
  }
  cmp(other) {
    return this.type - other.type;
  }
  equals(other) {
    return other.type === this.type;
  }
  substituteConstants() {
    return this;
  }
  evaluate(context) {
    return true;
  }
  serialize() {
    return "true";
  }
  keys() {
    return [];
  }
  negate() {
    return ContextKeyFalseExpr.INSTANCE;
  }
}
ContextKeyTrueExpr.INSTANCE = new ContextKeyTrueExpr();
class ContextKeyDefinedExpr {
  static create(key, negated = null) {
    const constantValue = CONSTANT_VALUES.get(key);
    if (typeof constantValue === "boolean") {
      return constantValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE;
    }
    return new ContextKeyDefinedExpr(key, negated);
  }
  constructor(key, negated) {
    this.key = key;
    this.negated = negated;
    this.type = 2;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return cmp1(this.key, other.key);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.key === other.key;
    }
    return false;
  }
  substituteConstants() {
    const constantValue = CONSTANT_VALUES.get(this.key);
    if (typeof constantValue === "boolean") {
      return constantValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE;
    }
    return this;
  }
  evaluate(context) {
    return !!context.getValue(this.key);
  }
  serialize() {
    return this.key;
  }
  keys() {
    return [this.key];
  }
  negate() {
    if (!this.negated) {
      this.negated = ContextKeyNotExpr.create(this.key, this);
    }
    return this.negated;
  }
}
class ContextKeyEqualsExpr {
  static create(key, value, negated = null) {
    if (typeof value === "boolean") {
      return value ? ContextKeyDefinedExpr.create(key, negated) : ContextKeyNotExpr.create(key, negated);
    }
    const constantValue = CONSTANT_VALUES.get(key);
    if (typeof constantValue === "boolean") {
      const trueValue = constantValue ? "true" : "false";
      return value === trueValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE;
    }
    return new ContextKeyEqualsExpr(key, value, negated);
  }
  constructor(key, value, negated) {
    this.key = key;
    this.value = value;
    this.negated = negated;
    this.type = 4;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return cmp2(this.key, this.value, other.key, other.value);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.key === other.key && this.value === other.value;
    }
    return false;
  }
  substituteConstants() {
    const constantValue = CONSTANT_VALUES.get(this.key);
    if (typeof constantValue === "boolean") {
      const trueValue = constantValue ? "true" : "false";
      return this.value === trueValue ? ContextKeyTrueExpr.INSTANCE : ContextKeyFalseExpr.INSTANCE;
    }
    return this;
  }
  evaluate(context) {
    return context.getValue(this.key) == this.value;
  }
  serialize() {
    return `${this.key} == '${this.value}'`;
  }
  keys() {
    return [this.key];
  }
  negate() {
    if (!this.negated) {
      this.negated = ContextKeyNotEqualsExpr.create(this.key, this.value, this);
    }
    return this.negated;
  }
}
class ContextKeyInExpr {
  static create(key, valueKey) {
    return new ContextKeyInExpr(key, valueKey);
  }
  constructor(key, valueKey) {
    this.key = key;
    this.valueKey = valueKey;
    this.type = 10;
    this.negated = null;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return cmp2(this.key, this.valueKey, other.key, other.valueKey);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.key === other.key && this.valueKey === other.valueKey;
    }
    return false;
  }
  substituteConstants() {
    return this;
  }
  evaluate(context) {
    const source = context.getValue(this.valueKey);
    const item = context.getValue(this.key);
    if (Array.isArray(source)) {
      return source.includes(item);
    }
    if (typeof item === "string" && typeof source === "object" && source !== null) {
      return hasOwnProperty$5.call(source, item);
    }
    return false;
  }
  serialize() {
    return `${this.key} in '${this.valueKey}'`;
  }
  keys() {
    return [this.key, this.valueKey];
  }
  negate() {
    if (!this.negated) {
      this.negated = ContextKeyNotInExpr.create(this.key, this.valueKey);
    }
    return this.negated;
  }
}
class ContextKeyNotInExpr {
  static create(key, valueKey) {
    return new ContextKeyNotInExpr(key, valueKey);
  }
  constructor(key, valueKey) {
    this.key = key;
    this.valueKey = valueKey;
    this.type = 11;
    this._negated = ContextKeyInExpr.create(key, valueKey);
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return this._negated.cmp(other._negated);
  }
  equals(other) {
    if (other.type === this.type) {
      return this._negated.equals(other._negated);
    }
    return false;
  }
  substituteConstants() {
    return this;
  }
  evaluate(context) {
    return !this._negated.evaluate(context);
  }
  serialize() {
    return `${this.key} not in '${this.valueKey}'`;
  }
  keys() {
    return this._negated.keys();
  }
  negate() {
    return this._negated;
  }
}
class ContextKeyNotEqualsExpr {
  static create(key, value, negated = null) {
    if (typeof value === "boolean") {
      if (value) {
        return ContextKeyNotExpr.create(key, negated);
      }
      return ContextKeyDefinedExpr.create(key, negated);
    }
    const constantValue = CONSTANT_VALUES.get(key);
    if (typeof constantValue === "boolean") {
      const falseValue = constantValue ? "true" : "false";
      return value === falseValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE;
    }
    return new ContextKeyNotEqualsExpr(key, value, negated);
  }
  constructor(key, value, negated) {
    this.key = key;
    this.value = value;
    this.negated = negated;
    this.type = 5;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return cmp2(this.key, this.value, other.key, other.value);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.key === other.key && this.value === other.value;
    }
    return false;
  }
  substituteConstants() {
    const constantValue = CONSTANT_VALUES.get(this.key);
    if (typeof constantValue === "boolean") {
      const falseValue = constantValue ? "true" : "false";
      return this.value === falseValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE;
    }
    return this;
  }
  evaluate(context) {
    return context.getValue(this.key) != this.value;
  }
  serialize() {
    return `${this.key} != '${this.value}'`;
  }
  keys() {
    return [this.key];
  }
  negate() {
    if (!this.negated) {
      this.negated = ContextKeyEqualsExpr.create(this.key, this.value, this);
    }
    return this.negated;
  }
}
class ContextKeyNotExpr {
  static create(key, negated = null) {
    const constantValue = CONSTANT_VALUES.get(key);
    if (typeof constantValue === "boolean") {
      return constantValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE;
    }
    return new ContextKeyNotExpr(key, negated);
  }
  constructor(key, negated) {
    this.key = key;
    this.negated = negated;
    this.type = 3;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return cmp1(this.key, other.key);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.key === other.key;
    }
    return false;
  }
  substituteConstants() {
    const constantValue = CONSTANT_VALUES.get(this.key);
    if (typeof constantValue === "boolean") {
      return constantValue ? ContextKeyFalseExpr.INSTANCE : ContextKeyTrueExpr.INSTANCE;
    }
    return this;
  }
  evaluate(context) {
    return !context.getValue(this.key);
  }
  serialize() {
    return `!${this.key}`;
  }
  keys() {
    return [this.key];
  }
  negate() {
    if (!this.negated) {
      this.negated = ContextKeyDefinedExpr.create(this.key, this);
    }
    return this.negated;
  }
}
function withFloatOrStr(value, callback) {
  if (typeof value === "string") {
    const n2 = parseFloat(value);
    if (!isNaN(n2)) {
      value = n2;
    }
  }
  if (typeof value === "string" || typeof value === "number") {
    return callback(value);
  }
  return ContextKeyFalseExpr.INSTANCE;
}
class ContextKeyGreaterExpr {
  static create(key, _value, negated = null) {
    return withFloatOrStr(_value, (value) => new ContextKeyGreaterExpr(key, value, negated));
  }
  constructor(key, value, negated) {
    this.key = key;
    this.value = value;
    this.negated = negated;
    this.type = 12;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return cmp2(this.key, this.value, other.key, other.value);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.key === other.key && this.value === other.value;
    }
    return false;
  }
  substituteConstants() {
    return this;
  }
  evaluate(context) {
    if (typeof this.value === "string") {
      return false;
    }
    return parseFloat(context.getValue(this.key)) > this.value;
  }
  serialize() {
    return `${this.key} > ${this.value}`;
  }
  keys() {
    return [this.key];
  }
  negate() {
    if (!this.negated) {
      this.negated = ContextKeySmallerEqualsExpr.create(this.key, this.value, this);
    }
    return this.negated;
  }
}
class ContextKeyGreaterEqualsExpr {
  static create(key, _value, negated = null) {
    return withFloatOrStr(_value, (value) => new ContextKeyGreaterEqualsExpr(key, value, negated));
  }
  constructor(key, value, negated) {
    this.key = key;
    this.value = value;
    this.negated = negated;
    this.type = 13;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return cmp2(this.key, this.value, other.key, other.value);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.key === other.key && this.value === other.value;
    }
    return false;
  }
  substituteConstants() {
    return this;
  }
  evaluate(context) {
    if (typeof this.value === "string") {
      return false;
    }
    return parseFloat(context.getValue(this.key)) >= this.value;
  }
  serialize() {
    return `${this.key} >= ${this.value}`;
  }
  keys() {
    return [this.key];
  }
  negate() {
    if (!this.negated) {
      this.negated = ContextKeySmallerExpr.create(this.key, this.value, this);
    }
    return this.negated;
  }
}
class ContextKeySmallerExpr {
  static create(key, _value, negated = null) {
    return withFloatOrStr(_value, (value) => new ContextKeySmallerExpr(key, value, negated));
  }
  constructor(key, value, negated) {
    this.key = key;
    this.value = value;
    this.negated = negated;
    this.type = 14;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return cmp2(this.key, this.value, other.key, other.value);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.key === other.key && this.value === other.value;
    }
    return false;
  }
  substituteConstants() {
    return this;
  }
  evaluate(context) {
    if (typeof this.value === "string") {
      return false;
    }
    return parseFloat(context.getValue(this.key)) < this.value;
  }
  serialize() {
    return `${this.key} < ${this.value}`;
  }
  keys() {
    return [this.key];
  }
  negate() {
    if (!this.negated) {
      this.negated = ContextKeyGreaterEqualsExpr.create(this.key, this.value, this);
    }
    return this.negated;
  }
}
class ContextKeySmallerEqualsExpr {
  static create(key, _value, negated = null) {
    return withFloatOrStr(_value, (value) => new ContextKeySmallerEqualsExpr(key, value, negated));
  }
  constructor(key, value, negated) {
    this.key = key;
    this.value = value;
    this.negated = negated;
    this.type = 15;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return cmp2(this.key, this.value, other.key, other.value);
  }
  equals(other) {
    if (other.type === this.type) {
      return this.key === other.key && this.value === other.value;
    }
    return false;
  }
  substituteConstants() {
    return this;
  }
  evaluate(context) {
    if (typeof this.value === "string") {
      return false;
    }
    return parseFloat(context.getValue(this.key)) <= this.value;
  }
  serialize() {
    return `${this.key} <= ${this.value}`;
  }
  keys() {
    return [this.key];
  }
  negate() {
    if (!this.negated) {
      this.negated = ContextKeyGreaterExpr.create(this.key, this.value, this);
    }
    return this.negated;
  }
}
class ContextKeyRegexExpr {
  static create(key, regexp) {
    return new ContextKeyRegexExpr(key, regexp);
  }
  constructor(key, regexp) {
    this.key = key;
    this.regexp = regexp;
    this.type = 7;
    this.negated = null;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    if (this.key < other.key) {
      return -1;
    }
    if (this.key > other.key) {
      return 1;
    }
    const thisSource = this.regexp ? this.regexp.source : "";
    const otherSource = other.regexp ? other.regexp.source : "";
    if (thisSource < otherSource) {
      return -1;
    }
    if (thisSource > otherSource) {
      return 1;
    }
    return 0;
  }
  equals(other) {
    if (other.type === this.type) {
      const thisSource = this.regexp ? this.regexp.source : "";
      const otherSource = other.regexp ? other.regexp.source : "";
      return this.key === other.key && thisSource === otherSource;
    }
    return false;
  }
  substituteConstants() {
    return this;
  }
  evaluate(context) {
    const value = context.getValue(this.key);
    return this.regexp ? this.regexp.test(value) : false;
  }
  serialize() {
    const value = this.regexp ? `/${this.regexp.source}/${this.regexp.flags}` : "/invalid/";
    return `${this.key} =~ ${value}`;
  }
  keys() {
    return [this.key];
  }
  negate() {
    if (!this.negated) {
      this.negated = ContextKeyNotRegexExpr.create(this);
    }
    return this.negated;
  }
}
class ContextKeyNotRegexExpr {
  static create(actual) {
    return new ContextKeyNotRegexExpr(actual);
  }
  constructor(_actual) {
    this._actual = _actual;
    this.type = 8;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    return this._actual.cmp(other._actual);
  }
  equals(other) {
    if (other.type === this.type) {
      return this._actual.equals(other._actual);
    }
    return false;
  }
  substituteConstants() {
    return this;
  }
  evaluate(context) {
    return !this._actual.evaluate(context);
  }
  serialize() {
    return `!(${this._actual.serialize()})`;
  }
  keys() {
    return this._actual.keys();
  }
  negate() {
    return this._actual;
  }
}
function eliminateConstantsInArray(arr) {
  let newArr = null;
  for (let i = 0, len = arr.length; i < len; i++) {
    const newExpr = arr[i].substituteConstants();
    if (arr[i] !== newExpr) {
      if (newArr === null) {
        newArr = [];
        for (let j = 0; j < i; j++) {
          newArr[j] = arr[j];
        }
      }
    }
    if (newArr !== null) {
      newArr[i] = newExpr;
    }
  }
  if (newArr === null) {
    return arr;
  }
  return newArr;
}
class ContextKeyAndExpr {
  static create(_expr, negated, extraRedundantCheck) {
    return ContextKeyAndExpr._normalizeArr(_expr, negated, extraRedundantCheck);
  }
  constructor(expr, negated) {
    this.expr = expr;
    this.negated = negated;
    this.type = 6;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    if (this.expr.length < other.expr.length) {
      return -1;
    }
    if (this.expr.length > other.expr.length) {
      return 1;
    }
    for (let i = 0, len = this.expr.length; i < len; i++) {
      const r = cmp(this.expr[i], other.expr[i]);
      if (r !== 0) {
        return r;
      }
    }
    return 0;
  }
  equals(other) {
    if (other.type === this.type) {
      if (this.expr.length !== other.expr.length) {
        return false;
      }
      for (let i = 0, len = this.expr.length; i < len; i++) {
        if (!this.expr[i].equals(other.expr[i])) {
          return false;
        }
      }
      return true;
    }
    return false;
  }
  substituteConstants() {
    const exprArr = eliminateConstantsInArray(this.expr);
    if (exprArr === this.expr) {
      return this;
    }
    return ContextKeyAndExpr.create(exprArr, this.negated, false);
  }
  evaluate(context) {
    for (let i = 0, len = this.expr.length; i < len; i++) {
      if (!this.expr[i].evaluate(context)) {
        return false;
      }
    }
    return true;
  }
  static _normalizeArr(arr, negated, extraRedundantCheck) {
    const expr = [];
    let hasTrue = false;
    for (const e of arr) {
      if (!e) {
        continue;
      }
      if (e.type === 1) {
        hasTrue = true;
        continue;
      }
      if (e.type === 0) {
        return ContextKeyFalseExpr.INSTANCE;
      }
      if (e.type === 6) {
        expr.push(...e.expr);
        continue;
      }
      expr.push(e);
    }
    if (expr.length === 0 && hasTrue) {
      return ContextKeyTrueExpr.INSTANCE;
    }
    if (expr.length === 0) {
      return void 0;
    }
    if (expr.length === 1) {
      return expr[0];
    }
    expr.sort(cmp);
    for (let i = 1; i < expr.length; i++) {
      if (expr[i - 1].equals(expr[i])) {
        expr.splice(i, 1);
        i--;
      }
    }
    if (expr.length === 1) {
      return expr[0];
    }
    while (expr.length > 1) {
      const lastElement = expr[expr.length - 1];
      if (lastElement.type !== 9) {
        break;
      }
      expr.pop();
      const secondToLastElement = expr.pop();
      const isFinished = expr.length === 0;
      const resultElement = ContextKeyOrExpr.create(lastElement.expr.map((el) => ContextKeyAndExpr.create([el, secondToLastElement], null, extraRedundantCheck)), null, isFinished);
      if (resultElement) {
        expr.push(resultElement);
        expr.sort(cmp);
      }
    }
    if (expr.length === 1) {
      return expr[0];
    }
    if (extraRedundantCheck) {
      for (let i = 0; i < expr.length; i++) {
        for (let j = i + 1; j < expr.length; j++) {
          if (expr[i].negate().equals(expr[j])) {
            return ContextKeyFalseExpr.INSTANCE;
          }
        }
      }
      if (expr.length === 1) {
        return expr[0];
      }
    }
    return new ContextKeyAndExpr(expr, negated);
  }
  serialize() {
    return this.expr.map((e) => e.serialize()).join(" && ");
  }
  keys() {
    const result2 = [];
    for (const expr of this.expr) {
      result2.push(...expr.keys());
    }
    return result2;
  }
  negate() {
    if (!this.negated) {
      const result2 = [];
      for (const expr of this.expr) {
        result2.push(expr.negate());
      }
      this.negated = ContextKeyOrExpr.create(result2, this, true);
    }
    return this.negated;
  }
}
class ContextKeyOrExpr {
  static create(_expr, negated, extraRedundantCheck) {
    return ContextKeyOrExpr._normalizeArr(_expr, negated, extraRedundantCheck);
  }
  constructor(expr, negated) {
    this.expr = expr;
    this.negated = negated;
    this.type = 9;
  }
  cmp(other) {
    if (other.type !== this.type) {
      return this.type - other.type;
    }
    if (this.expr.length < other.expr.length) {
      return -1;
    }
    if (this.expr.length > other.expr.length) {
      return 1;
    }
    for (let i = 0, len = this.expr.length; i < len; i++) {
      const r = cmp(this.expr[i], other.expr[i]);
      if (r !== 0) {
        return r;
      }
    }
    return 0;
  }
  equals(other) {
    if (other.type === this.type) {
      if (this.expr.length !== other.expr.length) {
        return false;
      }
      for (let i = 0, len = this.expr.length; i < len; i++) {
        if (!this.expr[i].equals(other.expr[i])) {
          return false;
        }
      }
      return true;
    }
    return false;
  }
  substituteConstants() {
    const exprArr = eliminateConstantsInArray(this.expr);
    if (exprArr === this.expr) {
      return this;
    }
    return ContextKeyOrExpr.create(exprArr, this.negated, false);
  }
  evaluate(context) {
    for (let i = 0, len = this.expr.length; i < len; i++) {
      if (this.expr[i].evaluate(context)) {
        return true;
      }
    }
    return false;
  }
  static _normalizeArr(arr, negated, extraRedundantCheck) {
    let expr = [];
    let hasFalse = false;
    if (arr) {
      for (let i = 0, len = arr.length; i < len; i++) {
        const e = arr[i];
        if (!e) {
          continue;
        }
        if (e.type === 0) {
          hasFalse = true;
          continue;
        }
        if (e.type === 1) {
          return ContextKeyTrueExpr.INSTANCE;
        }
        if (e.type === 9) {
          expr = expr.concat(e.expr);
          continue;
        }
        expr.push(e);
      }
      if (expr.length === 0 && hasFalse) {
        return ContextKeyFalseExpr.INSTANCE;
      }
      expr.sort(cmp);
    }
    if (expr.length === 0) {
      return void 0;
    }
    if (expr.length === 1) {
      return expr[0];
    }
    for (let i = 1; i < expr.length; i++) {
      if (expr[i - 1].equals(expr[i])) {
        expr.splice(i, 1);
        i--;
      }
    }
    if (expr.length === 1) {
      return expr[0];
    }
    if (extraRedundantCheck) {
      for (let i = 0; i < expr.length; i++) {
        for (let j = i + 1; j < expr.length; j++) {
          if (expr[i].negate().equals(expr[j])) {
            return ContextKeyTrueExpr.INSTANCE;
          }
        }
      }
      if (expr.length === 1) {
        return expr[0];
      }
    }
    return new ContextKeyOrExpr(expr, negated);
  }
  serialize() {
    return this.expr.map((e) => e.serialize()).join(" || ");
  }
  keys() {
    const result2 = [];
    for (const expr of this.expr) {
      result2.push(...expr.keys());
    }
    return result2;
  }
  negate() {
    if (!this.negated) {
      const result2 = [];
      for (const expr of this.expr) {
        result2.push(expr.negate());
      }
      while (result2.length > 1) {
        const LEFT = result2.shift();
        const RIGHT = result2.shift();
        const all = [];
        for (const left of getTerminals(LEFT)) {
          for (const right of getTerminals(RIGHT)) {
            all.push(ContextKeyAndExpr.create([left, right], null, false));
          }
        }
        result2.unshift(ContextKeyOrExpr.create(all, null, false));
      }
      this.negated = ContextKeyOrExpr.create(result2, this, true);
    }
    return this.negated;
  }
}
class RawContextKey extends ContextKeyDefinedExpr {
  static all() {
    return RawContextKey._info.values();
  }
  constructor(key, defaultValue, metaOrHide) {
    super(key, null);
    this._defaultValue = defaultValue;
    if (typeof metaOrHide === "object") {
      RawContextKey._info.push(Object.assign(Object.assign({}, metaOrHide), { key }));
    } else if (metaOrHide !== true) {
      RawContextKey._info.push({ key, description: metaOrHide, type: defaultValue !== null && defaultValue !== void 0 ? typeof defaultValue : void 0 });
    }
  }
  bindTo(target) {
    return target.createKey(this.key, this._defaultValue);
  }
  getValue(target) {
    return target.getContextKeyValue(this.key);
  }
  toNegated() {
    return this.negate();
  }
  isEqualTo(value) {
    return ContextKeyEqualsExpr.create(this.key, value);
  }
}
RawContextKey._info = [];
const IContextKeyService = createDecorator("contextKeyService");
function cmp1(key1, key2) {
  if (key1 < key2) {
    return -1;
  }
  if (key1 > key2) {
    return 1;
  }
  return 0;
}
function cmp2(key1, value1, key2, value2) {
  if (key1 < key2) {
    return -1;
  }
  if (key1 > key2) {
    return 1;
  }
  if (value1 < value2) {
    return -1;
  }
  if (value1 > value2) {
    return 1;
  }
  return 0;
}
function implies(p2, q) {
  if (p2.type === 0 || q.type === 1) {
    return true;
  }
  if (p2.type === 9) {
    if (q.type === 9) {
      return allElementsIncluded(p2.expr, q.expr);
    }
    return false;
  }
  if (q.type === 9) {
    for (const element of q.expr) {
      if (implies(p2, element)) {
        return true;
      }
    }
    return false;
  }
  if (p2.type === 6) {
    if (q.type === 6) {
      return allElementsIncluded(q.expr, p2.expr);
    }
    for (const element of p2.expr) {
      if (implies(element, q)) {
        return true;
      }
    }
    return false;
  }
  return p2.equals(q);
}
function allElementsIncluded(p2, q) {
  let pIndex = 0;
  let qIndex = 0;
  while (pIndex < p2.length && qIndex < q.length) {
    const cmp3 = p2[pIndex].cmp(q[qIndex]);
    if (cmp3 < 0) {
      return false;
    } else if (cmp3 === 0) {
      pIndex++;
      qIndex++;
    } else {
      qIndex++;
    }
  }
  return pIndex === p2.length;
}
function getTerminals(node2) {
  if (node2.type === 9) {
    return node2.expr;
  }
  return [node2];
}
function ok(value, message) {
  if (!value) {
    throw new Error(message ? `Assertion failed (${message})` : "Assertion Failed");
  }
}
function assertNever(value, message = "Unreachable") {
  throw new Error(message);
}
function assertFn(condition) {
  if (!condition()) {
    debugger;
    condition();
    onUnexpectedError(new BugIndicatingError("Assertion Failed"));
  }
}
function checkAdjacentItems(items, predicate) {
  let i = 0;
  while (i < items.length - 1) {
    const a = items[i];
    const b = items[i + 1];
    if (!predicate(a, b)) {
      return false;
    }
    i++;
  }
  return true;
}
class RegistryImpl {
  constructor() {
    this.data = /* @__PURE__ */ new Map();
  }
  add(id3, data) {
    ok(isString$4(id3));
    ok(isObject$4(data));
    ok(!this.data.has(id3), "There is already an extension with this id");
    this.data.set(id3, data);
  }
  as(id3) {
    return this.data.get(id3) || null;
  }
}
const Registry = new RegistryImpl();
class KeybindingsRegistryImpl {
  constructor() {
    this._coreKeybindings = new LinkedList();
    this._extensionKeybindings = [];
    this._cachedMergedKeybindings = null;
  }
  /**
   * Take current platform into account and reduce to primary & secondary.
   */
  static bindToCurrentPlatform(kb) {
    if (OS === 1) {
      if (kb && kb.win) {
        return kb.win;
      }
    } else if (OS === 2) {
      if (kb && kb.mac) {
        return kb.mac;
      }
    } else {
      if (kb && kb.linux) {
        return kb.linux;
      }
    }
    return kb;
  }
  registerKeybindingRule(rule2) {
    const actualKb = KeybindingsRegistryImpl.bindToCurrentPlatform(rule2);
    const result2 = new DisposableStore();
    if (actualKb && actualKb.primary) {
      const kk = decodeKeybinding(actualKb.primary, OS);
      if (kk) {
        result2.add(this._registerDefaultKeybinding(kk, rule2.id, rule2.args, rule2.weight, 0, rule2.when));
      }
    }
    if (actualKb && Array.isArray(actualKb.secondary)) {
      for (let i = 0, len = actualKb.secondary.length; i < len; i++) {
        const k = actualKb.secondary[i];
        const kk = decodeKeybinding(k, OS);
        if (kk) {
          result2.add(this._registerDefaultKeybinding(kk, rule2.id, rule2.args, rule2.weight, -i - 1, rule2.when));
        }
      }
    }
    return result2;
  }
  registerCommandAndKeybindingRule(desc) {
    return combinedDisposable(this.registerKeybindingRule(desc), CommandsRegistry.registerCommand(desc));
  }
  _registerDefaultKeybinding(keybinding, commandId, commandArgs, weight1, weight2, when) {
    const remove2 = this._coreKeybindings.push({
      keybinding,
      command: commandId,
      commandArgs,
      when,
      weight1,
      weight2,
      extensionId: null,
      isBuiltinExtension: false
    });
    this._cachedMergedKeybindings = null;
    return toDisposable(() => {
      remove2();
      this._cachedMergedKeybindings = null;
    });
  }
  getDefaultKeybindings() {
    if (!this._cachedMergedKeybindings) {
      this._cachedMergedKeybindings = Array.from(this._coreKeybindings).concat(this._extensionKeybindings);
      this._cachedMergedKeybindings.sort(sorter);
    }
    return this._cachedMergedKeybindings.slice(0);
  }
}
const KeybindingsRegistry = new KeybindingsRegistryImpl();
const Extensions$9 = {
  EditorModes: "platform.keybindingsRegistry"
};
Registry.add(Extensions$9.EditorModes, KeybindingsRegistry);
function sorter(a, b) {
  if (a.weight1 !== b.weight1) {
    return a.weight1 - b.weight1;
  }
  if (a.command && b.command) {
    if (a.command < b.command) {
      return -1;
    }
    if (a.command > b.command) {
      return 1;
    }
  }
  return a.weight2 - b.weight2;
}
var __decorate$2b = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$24 = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __rest = globalThis && globalThis.__rest || function(s, e) {
  var t = {};
  for (var p2 in s)
    if (Object.prototype.hasOwnProperty.call(s, p2) && e.indexOf(p2) < 0)
      t[p2] = s[p2];
  if (s != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i = 0, p2 = Object.getOwnPropertySymbols(s); i < p2.length; i++) {
      if (e.indexOf(p2[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p2[i]))
        t[p2[i]] = s[p2[i]];
    }
  return t;
};
function isIMenuItem(item) {
  return item.command !== void 0;
}
function isISubmenuItem(item) {
  return item.submenu !== void 0;
}
class MenuId {
  /**
   * Create a new `MenuId` with the unique identifier. Will throw if a menu
   * with the identifier already exists, use `MenuId.for(ident)` or a unique
   * identifier
   */
  constructor(identifier) {
    if (MenuId._instances.has(identifier)) {
      throw new TypeError(`MenuId with identifier '${identifier}' already exists. Use MenuId.for(ident) or a unique identifier`);
    }
    MenuId._instances.set(identifier, this);
    this.id = identifier;
  }
}
MenuId._instances = /* @__PURE__ */ new Map();
MenuId.CommandPalette = new MenuId("CommandPalette");
MenuId.DebugBreakpointsContext = new MenuId("DebugBreakpointsContext");
MenuId.DebugCallStackContext = new MenuId("DebugCallStackContext");
MenuId.DebugConsoleContext = new MenuId("DebugConsoleContext");
MenuId.DebugVariablesContext = new MenuId("DebugVariablesContext");
MenuId.DebugWatchContext = new MenuId("DebugWatchContext");
MenuId.DebugToolBar = new MenuId("DebugToolBar");
MenuId.DebugToolBarStop = new MenuId("DebugToolBarStop");
MenuId.EditorContext = new MenuId("EditorContext");
MenuId.SimpleEditorContext = new MenuId("SimpleEditorContext");
MenuId.EditorContent = new MenuId("EditorContent");
MenuId.EditorLineNumberContext = new MenuId("EditorLineNumberContext");
MenuId.EditorContextCopy = new MenuId("EditorContextCopy");
MenuId.EditorContextPeek = new MenuId("EditorContextPeek");
MenuId.EditorContextShare = new MenuId("EditorContextShare");
MenuId.EditorTitle = new MenuId("EditorTitle");
MenuId.EditorTitleRun = new MenuId("EditorTitleRun");
MenuId.EditorTitleContext = new MenuId("EditorTitleContext");
MenuId.EditorTitleContextShare = new MenuId("EditorTitleContextShare");
MenuId.EmptyEditorGroup = new MenuId("EmptyEditorGroup");
MenuId.EmptyEditorGroupContext = new MenuId("EmptyEditorGroupContext");
MenuId.EditorTabsBarContext = new MenuId("EditorTabsBarContext");
MenuId.ExplorerContext = new MenuId("ExplorerContext");
MenuId.ExplorerContextShare = new MenuId("ExplorerContextShare");
MenuId.ExtensionContext = new MenuId("ExtensionContext");
MenuId.GlobalActivity = new MenuId("GlobalActivity");
MenuId.CommandCenter = new MenuId("CommandCenter");
MenuId.LayoutControlMenuSubmenu = new MenuId("LayoutControlMenuSubmenu");
MenuId.LayoutControlMenu = new MenuId("LayoutControlMenu");
MenuId.MenubarMainMenu = new MenuId("MenubarMainMenu");
MenuId.MenubarAppearanceMenu = new MenuId("MenubarAppearanceMenu");
MenuId.MenubarDebugMenu = new MenuId("MenubarDebugMenu");
MenuId.MenubarEditMenu = new MenuId("MenubarEditMenu");
MenuId.MenubarCopy = new MenuId("MenubarCopy");
MenuId.MenubarFileMenu = new MenuId("MenubarFileMenu");
MenuId.MenubarGoMenu = new MenuId("MenubarGoMenu");
MenuId.MenubarHelpMenu = new MenuId("MenubarHelpMenu");
MenuId.MenubarLayoutMenu = new MenuId("MenubarLayoutMenu");
MenuId.MenubarNewBreakpointMenu = new MenuId("MenubarNewBreakpointMenu");
MenuId.PanelAlignmentMenu = new MenuId("PanelAlignmentMenu");
MenuId.PanelPositionMenu = new MenuId("PanelPositionMenu");
MenuId.MenubarPreferencesMenu = new MenuId("MenubarPreferencesMenu");
MenuId.MenubarRecentMenu = new MenuId("MenubarRecentMenu");
MenuId.MenubarSelectionMenu = new MenuId("MenubarSelectionMenu");
MenuId.MenubarShare = new MenuId("MenubarShare");
MenuId.MenubarSwitchEditorMenu = new MenuId("MenubarSwitchEditorMenu");
MenuId.MenubarSwitchGroupMenu = new MenuId("MenubarSwitchGroupMenu");
MenuId.MenubarTerminalMenu = new MenuId("MenubarTerminalMenu");
MenuId.MenubarViewMenu = new MenuId("MenubarViewMenu");
MenuId.MenubarHomeMenu = new MenuId("MenubarHomeMenu");
MenuId.OpenEditorsContext = new MenuId("OpenEditorsContext");
MenuId.OpenEditorsContextShare = new MenuId("OpenEditorsContextShare");
MenuId.ProblemsPanelContext = new MenuId("ProblemsPanelContext");
MenuId.SCMChangeContext = new MenuId("SCMChangeContext");
MenuId.SCMResourceContext = new MenuId("SCMResourceContext");
MenuId.SCMResourceContextShare = new MenuId("SCMResourceContextShare");
MenuId.SCMResourceFolderContext = new MenuId("SCMResourceFolderContext");
MenuId.SCMResourceGroupContext = new MenuId("SCMResourceGroupContext");
MenuId.SCMSourceControl = new MenuId("SCMSourceControl");
MenuId.SCMTitle = new MenuId("SCMTitle");
MenuId.SearchContext = new MenuId("SearchContext");
MenuId.SearchActionMenu = new MenuId("SearchActionContext");
MenuId.StatusBarWindowIndicatorMenu = new MenuId("StatusBarWindowIndicatorMenu");
MenuId.StatusBarRemoteIndicatorMenu = new MenuId("StatusBarRemoteIndicatorMenu");
MenuId.StickyScrollContext = new MenuId("StickyScrollContext");
MenuId.TestItem = new MenuId("TestItem");
MenuId.TestItemGutter = new MenuId("TestItemGutter");
MenuId.TestPeekElement = new MenuId("TestPeekElement");
MenuId.TestPeekTitle = new MenuId("TestPeekTitle");
MenuId.TouchBarContext = new MenuId("TouchBarContext");
MenuId.TitleBarContext = new MenuId("TitleBarContext");
MenuId.TitleBarTitleContext = new MenuId("TitleBarTitleContext");
MenuId.TunnelContext = new MenuId("TunnelContext");
MenuId.TunnelPrivacy = new MenuId("TunnelPrivacy");
MenuId.TunnelProtocol = new MenuId("TunnelProtocol");
MenuId.TunnelPortInline = new MenuId("TunnelInline");
MenuId.TunnelTitle = new MenuId("TunnelTitle");
MenuId.TunnelLocalAddressInline = new MenuId("TunnelLocalAddressInline");
MenuId.TunnelOriginInline = new MenuId("TunnelOriginInline");
MenuId.ViewItemContext = new MenuId("ViewItemContext");
MenuId.ViewContainerTitle = new MenuId("ViewContainerTitle");
MenuId.ViewContainerTitleContext = new MenuId("ViewContainerTitleContext");
MenuId.ViewTitle = new MenuId("ViewTitle");
MenuId.ViewTitleContext = new MenuId("ViewTitleContext");
MenuId.CommentEditorActions = new MenuId("CommentEditorActions");
MenuId.CommentThreadTitle = new MenuId("CommentThreadTitle");
MenuId.CommentThreadActions = new MenuId("CommentThreadActions");
MenuId.CommentThreadAdditionalActions = new MenuId("CommentThreadAdditionalActions");
MenuId.CommentThreadTitleContext = new MenuId("CommentThreadTitleContext");
MenuId.CommentThreadCommentContext = new MenuId("CommentThreadCommentContext");
MenuId.CommentTitle = new MenuId("CommentTitle");
MenuId.CommentActions = new MenuId("CommentActions");
MenuId.InteractiveToolbar = new MenuId("InteractiveToolbar");
MenuId.InteractiveCellTitle = new MenuId("InteractiveCellTitle");
MenuId.InteractiveCellDelete = new MenuId("InteractiveCellDelete");
MenuId.InteractiveCellExecute = new MenuId("InteractiveCellExecute");
MenuId.InteractiveInputExecute = new MenuId("InteractiveInputExecute");
MenuId.NotebookToolbar = new MenuId("NotebookToolbar");
MenuId.NotebookStickyScrollContext = new MenuId("NotebookStickyScrollContext");
MenuId.NotebookCellTitle = new MenuId("NotebookCellTitle");
MenuId.NotebookCellDelete = new MenuId("NotebookCellDelete");
MenuId.NotebookCellInsert = new MenuId("NotebookCellInsert");
MenuId.NotebookCellBetween = new MenuId("NotebookCellBetween");
MenuId.NotebookCellListTop = new MenuId("NotebookCellTop");
MenuId.NotebookCellExecute = new MenuId("NotebookCellExecute");
MenuId.NotebookCellExecutePrimary = new MenuId("NotebookCellExecutePrimary");
MenuId.NotebookDiffCellInputTitle = new MenuId("NotebookDiffCellInputTitle");
MenuId.NotebookDiffCellMetadataTitle = new MenuId("NotebookDiffCellMetadataTitle");
MenuId.NotebookDiffCellOutputsTitle = new MenuId("NotebookDiffCellOutputsTitle");
MenuId.NotebookOutputToolbar = new MenuId("NotebookOutputToolbar");
MenuId.NotebookEditorLayoutConfigure = new MenuId("NotebookEditorLayoutConfigure");
MenuId.NotebookKernelSource = new MenuId("NotebookKernelSource");
MenuId.BulkEditTitle = new MenuId("BulkEditTitle");
MenuId.BulkEditContext = new MenuId("BulkEditContext");
MenuId.TimelineItemContext = new MenuId("TimelineItemContext");
MenuId.TimelineTitle = new MenuId("TimelineTitle");
MenuId.TimelineTitleContext = new MenuId("TimelineTitleContext");
MenuId.TimelineFilterSubMenu = new MenuId("TimelineFilterSubMenu");
MenuId.AccountsContext = new MenuId("AccountsContext");
MenuId.PanelTitle = new MenuId("PanelTitle");
MenuId.AuxiliaryBarTitle = new MenuId("AuxiliaryBarTitle");
MenuId.TerminalInstanceContext = new MenuId("TerminalInstanceContext");
MenuId.TerminalEditorInstanceContext = new MenuId("TerminalEditorInstanceContext");
MenuId.TerminalNewDropdownContext = new MenuId("TerminalNewDropdownContext");
MenuId.TerminalTabContext = new MenuId("TerminalTabContext");
MenuId.TerminalTabEmptyAreaContext = new MenuId("TerminalTabEmptyAreaContext");
MenuId.TerminalInlineTabContext = new MenuId("TerminalInlineTabContext");
MenuId.WebviewContext = new MenuId("WebviewContext");
MenuId.InlineCompletionsActions = new MenuId("InlineCompletionsActions");
MenuId.NewFile = new MenuId("NewFile");
MenuId.MergeInput1Toolbar = new MenuId("MergeToolbar1Toolbar");
MenuId.MergeInput2Toolbar = new MenuId("MergeToolbar2Toolbar");
MenuId.MergeBaseToolbar = new MenuId("MergeBaseToolbar");
MenuId.MergeInputResultToolbar = new MenuId("MergeToolbarResultToolbar");
MenuId.InlineSuggestionToolbar = new MenuId("InlineSuggestionToolbar");
MenuId.ChatContext = new MenuId("ChatContext");
MenuId.ChatCodeBlock = new MenuId("ChatCodeblock");
MenuId.ChatMessageTitle = new MenuId("ChatMessageTitle");
MenuId.ChatExecute = new MenuId("ChatExecute");
const IMenuService = createDecorator("menuService");
class MenuRegistryChangeEvent {
  static for(id3) {
    let value = this._all.get(id3);
    if (!value) {
      value = new MenuRegistryChangeEvent(id3);
      this._all.set(id3, value);
    }
    return value;
  }
  static merge(events) {
    const ids = /* @__PURE__ */ new Set();
    for (const item of events) {
      if (item instanceof MenuRegistryChangeEvent) {
        ids.add(item.id);
      }
    }
    return ids;
  }
  constructor(id3) {
    this.id = id3;
    this.has = (candidate) => candidate === id3;
  }
}
MenuRegistryChangeEvent._all = /* @__PURE__ */ new Map();
const MenuRegistry = new class {
  constructor() {
    this._commands = /* @__PURE__ */ new Map();
    this._menuItems = /* @__PURE__ */ new Map();
    this._onDidChangeMenu = new MicrotaskEmitter({
      merge: MenuRegistryChangeEvent.merge
    });
    this.onDidChangeMenu = this._onDidChangeMenu.event;
  }
  addCommand(command) {
    this._commands.set(command.id, command);
    this._onDidChangeMenu.fire(MenuRegistryChangeEvent.for(MenuId.CommandPalette));
    return toDisposable(() => {
      if (this._commands.delete(command.id)) {
        this._onDidChangeMenu.fire(MenuRegistryChangeEvent.for(MenuId.CommandPalette));
      }
    });
  }
  getCommand(id3) {
    return this._commands.get(id3);
  }
  getCommands() {
    const map2 = /* @__PURE__ */ new Map();
    this._commands.forEach((value, key) => map2.set(key, value));
    return map2;
  }
  appendMenuItem(id3, item) {
    let list2 = this._menuItems.get(id3);
    if (!list2) {
      list2 = new LinkedList();
      this._menuItems.set(id3, list2);
    }
    const rm = list2.push(item);
    this._onDidChangeMenu.fire(MenuRegistryChangeEvent.for(id3));
    return toDisposable(rm);
  }
  appendMenuItems(items) {
    const result2 = new DisposableStore();
    for (const { id: id3, item } of items) {
      result2.add(this.appendMenuItem(id3, item));
    }
    return result2;
  }
  getMenuItems(id3) {
    let result2;
    if (this._menuItems.has(id3)) {
      result2 = [...this._menuItems.get(id3)];
    } else {
      result2 = [];
    }
    if (id3 === MenuId.CommandPalette) {
      this._appendImplicitItems(result2);
    }
    return result2;
  }
  _appendImplicitItems(result2) {
    const set2 = /* @__PURE__ */ new Set();
    for (const item of result2) {
      if (isIMenuItem(item)) {
        set2.add(item.command.id);
        if (item.alt) {
          set2.add(item.alt.id);
        }
      }
    }
    this._commands.forEach((command, id3) => {
      if (!set2.has(id3)) {
        result2.push({ command });
      }
    });
  }
}();
class SubmenuItemAction extends SubmenuAction {
  constructor(item, hideActions, actions) {
    super(`submenuitem.${item.submenu.id}`, typeof item.title === "string" ? item.title : item.title.value, actions, "submenu");
    this.item = item;
    this.hideActions = hideActions;
  }
}
let MenuItemAction = class MenuItemAction2 {
  static label(action, options) {
    return (options === null || options === void 0 ? void 0 : options.renderShortTitle) && action.shortTitle ? typeof action.shortTitle === "string" ? action.shortTitle : action.shortTitle.value : typeof action.title === "string" ? action.title : action.title.value;
  }
  constructor(item, alt, options, hideActions, contextKeyService, _commandService) {
    var _a2, _b2;
    this.hideActions = hideActions;
    this._commandService = _commandService;
    this.id = item.id;
    this.label = MenuItemAction2.label(item, options);
    this.tooltip = (_b2 = typeof item.tooltip === "string" ? item.tooltip : (_a2 = item.tooltip) === null || _a2 === void 0 ? void 0 : _a2.value) !== null && _b2 !== void 0 ? _b2 : "";
    this.enabled = !item.precondition || contextKeyService.contextMatchesRules(item.precondition);
    this.checked = void 0;
    let icon;
    if (item.toggled) {
      const toggled = item.toggled.condition ? item.toggled : { condition: item.toggled };
      this.checked = contextKeyService.contextMatchesRules(toggled.condition);
      if (this.checked && toggled.tooltip) {
        this.tooltip = typeof toggled.tooltip === "string" ? toggled.tooltip : toggled.tooltip.value;
      }
      if (this.checked && ThemeIcon.isThemeIcon(toggled.icon)) {
        icon = toggled.icon;
      }
      if (this.checked && toggled.title) {
        this.label = typeof toggled.title === "string" ? toggled.title : toggled.title.value;
      }
    }
    if (!icon) {
      icon = ThemeIcon.isThemeIcon(item.icon) ? item.icon : void 0;
    }
    this.item = item;
    this.alt = alt ? new MenuItemAction2(alt, void 0, options, hideActions, contextKeyService, _commandService) : void 0;
    this._options = options;
    this.class = icon && ThemeIcon.asClassName(icon);
  }
  run(...args) {
    var _a2, _b2;
    let runArgs = [];
    if ((_a2 = this._options) === null || _a2 === void 0 ? void 0 : _a2.arg) {
      runArgs = [...runArgs, this._options.arg];
    }
    if ((_b2 = this._options) === null || _b2 === void 0 ? void 0 : _b2.shouldForwardArgs) {
      runArgs = [...runArgs, ...args];
    }
    return this._commandService.executeCommand(this.id, ...runArgs);
  }
};
MenuItemAction = __decorate$2b([
  __param$24(4, IContextKeyService),
  __param$24(5, ICommandService)
], MenuItemAction);
class Action2 {
  constructor(desc) {
    this.desc = desc;
  }
}
function registerAction2(ctor) {
  const disposables = new DisposableStore();
  const action = new ctor();
  const _a2 = action.desc, { f1, menu, keybinding, description } = _a2, command = __rest(_a2, ["f1", "menu", "keybinding", "description"]);
  disposables.add(CommandsRegistry.registerCommand({
    id: command.id,
    handler: (accessor, ...args) => action.run(accessor, ...args),
    description
  }));
  if (Array.isArray(menu)) {
    for (const item of menu) {
      disposables.add(MenuRegistry.appendMenuItem(item.id, Object.assign({ command: Object.assign(Object.assign({}, command), { precondition: item.precondition === null ? void 0 : command.precondition }) }, item)));
    }
  } else if (menu) {
    disposables.add(MenuRegistry.appendMenuItem(menu.id, Object.assign({ command: Object.assign(Object.assign({}, command), { precondition: menu.precondition === null ? void 0 : command.precondition }) }, menu)));
  }
  if (f1) {
    disposables.add(MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command, when: command.precondition }));
    disposables.add(MenuRegistry.addCommand(command));
  }
  if (Array.isArray(keybinding)) {
    for (const item of keybinding) {
      disposables.add(KeybindingsRegistry.registerKeybindingRule(Object.assign(Object.assign({}, item), { id: command.id, when: command.precondition ? ContextKeyExpr.and(command.precondition, item.when) : item.when })));
    }
  } else if (keybinding) {
    disposables.add(KeybindingsRegistry.registerKeybindingRule(Object.assign(Object.assign({}, keybinding), { id: command.id, when: command.precondition ? ContextKeyExpr.and(command.precondition, keybinding.when) : keybinding.when })));
  }
  return disposables;
}
const ITelemetryService = createDecorator("telemetryService");
const ILogService = createDecorator("logService");
var LogLevel;
(function(LogLevel2) {
  LogLevel2[LogLevel2["Off"] = 0] = "Off";
  LogLevel2[LogLevel2["Trace"] = 1] = "Trace";
  LogLevel2[LogLevel2["Debug"] = 2] = "Debug";
  LogLevel2[LogLevel2["Info"] = 3] = "Info";
  LogLevel2[LogLevel2["Warning"] = 4] = "Warning";
  LogLevel2[LogLevel2["Error"] = 5] = "Error";
})(LogLevel || (LogLevel = {}));
const DEFAULT_LOG_LEVEL = LogLevel.Info;
class AbstractLogger extends Disposable {
  constructor() {
    super(...arguments);
    this.level = DEFAULT_LOG_LEVEL;
    this._onDidChangeLogLevel = this._register(new Emitter$1());
    this.onDidChangeLogLevel = this._onDidChangeLogLevel.event;
  }
  setLevel(level) {
    if (this.level !== level) {
      this.level = level;
      this._onDidChangeLogLevel.fire(this.level);
    }
  }
  getLevel() {
    return this.level;
  }
  checkLogLevel(level) {
    return this.level !== LogLevel.Off && this.level <= level;
  }
}
class ConsoleLogger extends AbstractLogger {
  constructor(logLevel = DEFAULT_LOG_LEVEL, useColors = true) {
    super();
    this.useColors = useColors;
    this.setLevel(logLevel);
  }
  trace(message, ...args) {
    if (this.checkLogLevel(LogLevel.Trace)) {
      if (this.useColors) {
        console.log("%cTRACE", "color: #888", message, ...args);
      } else {
        console.log(message, ...args);
      }
    }
  }
  debug(message, ...args) {
    if (this.checkLogLevel(LogLevel.Debug)) {
      if (this.useColors) {
        console.log("%cDEBUG", "background: #eee; color: #888", message, ...args);
      } else {
        console.log(message, ...args);
      }
    }
  }
  info(message, ...args) {
    if (this.checkLogLevel(LogLevel.Info)) {
      if (this.useColors) {
        console.log("%c INFO", "color: #33f", message, ...args);
      } else {
        console.log(message, ...args);
      }
    }
  }
  warn(message, ...args) {
    if (this.checkLogLevel(LogLevel.Warning)) {
      if (this.useColors) {
        console.log("%c WARN", "color: #993", message, ...args);
      } else {
        console.log(message, ...args);
      }
    }
  }
  error(message, ...args) {
    if (this.checkLogLevel(LogLevel.Error)) {
      if (this.useColors) {
        console.log("%c  ERR", "color: #f33", message, ...args);
      } else {
        console.error(message, ...args);
      }
    }
  }
  dispose() {
  }
}
class MultiplexLogger extends AbstractLogger {
  constructor(loggers) {
    super();
    this.loggers = loggers;
    if (loggers.length) {
      this.setLevel(loggers[0].getLevel());
    }
  }
  setLevel(level) {
    for (const logger of this.loggers) {
      logger.setLevel(level);
    }
    super.setLevel(level);
  }
  trace(message, ...args) {
    for (const logger of this.loggers) {
      logger.trace(message, ...args);
    }
  }
  debug(message, ...args) {
    for (const logger of this.loggers) {
      logger.debug(message, ...args);
    }
  }
  info(message, ...args) {
    for (const logger of this.loggers) {
      logger.info(message, ...args);
    }
  }
  warn(message, ...args) {
    for (const logger of this.loggers) {
      logger.warn(message, ...args);
    }
  }
  error(message, ...args) {
    for (const logger of this.loggers) {
      logger.error(message, ...args);
    }
  }
  dispose() {
    for (const logger of this.loggers) {
      logger.dispose();
    }
  }
}
function LogLevelToString(logLevel) {
  switch (logLevel) {
    case LogLevel.Trace:
      return "trace";
    case LogLevel.Debug:
      return "debug";
    case LogLevel.Info:
      return "info";
    case LogLevel.Warning:
      return "warn";
    case LogLevel.Error:
      return "error";
    case LogLevel.Off:
      return "off";
  }
}
new RawContextKey("logLevel", LogLevelToString(LogLevel.Info));
let Command$1 = class Command {
  constructor(opts) {
    this.id = opts.id;
    this.precondition = opts.precondition;
    this._kbOpts = opts.kbOpts;
    this._menuOpts = opts.menuOpts;
    this._description = opts.description;
  }
  register() {
    if (Array.isArray(this._menuOpts)) {
      this._menuOpts.forEach(this._registerMenuItem, this);
    } else if (this._menuOpts) {
      this._registerMenuItem(this._menuOpts);
    }
    if (this._kbOpts) {
      const kbOptsArr = Array.isArray(this._kbOpts) ? this._kbOpts : [this._kbOpts];
      for (const kbOpts of kbOptsArr) {
        let kbWhen = kbOpts.kbExpr;
        if (this.precondition) {
          if (kbWhen) {
            kbWhen = ContextKeyExpr.and(kbWhen, this.precondition);
          } else {
            kbWhen = this.precondition;
          }
        }
        const desc = {
          id: this.id,
          weight: kbOpts.weight,
          args: kbOpts.args,
          when: kbWhen,
          primary: kbOpts.primary,
          secondary: kbOpts.secondary,
          win: kbOpts.win,
          linux: kbOpts.linux,
          mac: kbOpts.mac
        };
        KeybindingsRegistry.registerKeybindingRule(desc);
      }
    }
    CommandsRegistry.registerCommand({
      id: this.id,
      handler: (accessor, args) => this.runCommand(accessor, args),
      description: this._description
    });
  }
  _registerMenuItem(item) {
    MenuRegistry.appendMenuItem(item.menuId, {
      group: item.group,
      command: {
        id: this.id,
        title: item.title,
        icon: item.icon,
        precondition: this.precondition
      },
      when: item.when,
      order: item.order
    });
  }
};
class MultiCommand extends Command$1 {
  constructor() {
    super(...arguments);
    this._implementations = [];
  }
  /**
   * A higher priority gets to be looked at first
   */
  addImplementation(priority, name, implementation, when) {
    this._implementations.push({ priority, name, implementation, when });
    this._implementations.sort((a, b) => b.priority - a.priority);
    return {
      dispose: () => {
        for (let i = 0; i < this._implementations.length; i++) {
          if (this._implementations[i].implementation === implementation) {
            this._implementations.splice(i, 1);
            return;
          }
        }
      }
    };
  }
  runCommand(accessor, args) {
    const logService = accessor.get(ILogService);
    const contextKeyService = accessor.get(IContextKeyService);
    logService.trace(`Executing Command '${this.id}' which has ${this._implementations.length} bound.`);
    for (const impl of this._implementations) {
      if (impl.when) {
        const context = contextKeyService.getContext(document.activeElement);
        const value = impl.when.evaluate(context);
        if (!value) {
          continue;
        }
      }
      const result2 = impl.implementation(accessor, args);
      if (result2) {
        logService.trace(`Command '${this.id}' was handled by '${impl.name}'.`);
        if (typeof result2 === "boolean") {
          return;
        }
        return result2;
      }
    }
    logService.trace(`The Command '${this.id}' was not handled by any implementation.`);
  }
}
class ProxyCommand extends Command$1 {
  constructor(command, opts) {
    super(opts);
    this.command = command;
  }
  runCommand(accessor, args) {
    return this.command.runCommand(accessor, args);
  }
}
class EditorCommand extends Command$1 {
  /**
   * Create a command class that is bound to a certain editor contribution.
   */
  static bindToContribution(controllerGetter) {
    return class EditorControllerCommandImpl extends EditorCommand {
      constructor(opts) {
        super(opts);
        this._callback = opts.handler;
      }
      runEditorCommand(accessor, editor2, args) {
        const controller = controllerGetter(editor2);
        if (controller) {
          this._callback(controller, args);
        }
      }
    };
  }
  static runEditorCommand(accessor, args, precondition, runner) {
    const codeEditorService = accessor.get(ICodeEditorService);
    const editor2 = codeEditorService.getFocusedCodeEditor() || codeEditorService.getActiveCodeEditor();
    if (!editor2) {
      return;
    }
    return editor2.invokeWithinContext((editorAccessor) => {
      const kbService = editorAccessor.get(IContextKeyService);
      if (!kbService.contextMatchesRules(withNullAsUndefined(precondition))) {
        return;
      }
      return runner(editorAccessor, editor2, args);
    });
  }
  runCommand(accessor, args) {
    return EditorCommand.runEditorCommand(accessor, args, this.precondition, (accessor2, editor2, args2) => this.runEditorCommand(accessor2, editor2, args2));
  }
}
class EditorAction extends EditorCommand {
  static convertOptions(opts) {
    let menuOpts;
    if (Array.isArray(opts.menuOpts)) {
      menuOpts = opts.menuOpts;
    } else if (opts.menuOpts) {
      menuOpts = [opts.menuOpts];
    } else {
      menuOpts = [];
    }
    function withDefaults(item) {
      if (!item.menuId) {
        item.menuId = MenuId.EditorContext;
      }
      if (!item.title) {
        item.title = opts.label;
      }
      item.when = ContextKeyExpr.and(opts.precondition, item.when);
      return item;
    }
    if (Array.isArray(opts.contextMenuOpts)) {
      menuOpts.push(...opts.contextMenuOpts.map(withDefaults));
    } else if (opts.contextMenuOpts) {
      menuOpts.push(withDefaults(opts.contextMenuOpts));
    }
    opts.menuOpts = menuOpts;
    return opts;
  }
  constructor(opts) {
    super(EditorAction.convertOptions(opts));
    this.label = opts.label;
    this.alias = opts.alias;
  }
  runEditorCommand(accessor, editor2, args) {
    this.reportTelemetry(accessor, editor2);
    return this.run(accessor, editor2, args || {});
  }
  reportTelemetry(accessor, editor2) {
    accessor.get(ITelemetryService).publicLog2("editorActionInvoked", { name: this.label, id: this.id });
  }
}
class MultiEditorAction extends EditorAction {
  constructor() {
    super(...arguments);
    this._implementations = [];
  }
  /**
   * A higher priority gets to be looked at first
   */
  addImplementation(priority, implementation) {
    this._implementations.push([priority, implementation]);
    this._implementations.sort((a, b) => b[0] - a[0]);
    return {
      dispose: () => {
        for (let i = 0; i < this._implementations.length; i++) {
          if (this._implementations[i][1] === implementation) {
            this._implementations.splice(i, 1);
            return;
          }
        }
      }
    };
  }
  run(accessor, editor2, args) {
    for (const impl of this._implementations) {
      const result2 = impl[1](accessor, editor2, args);
      if (result2) {
        if (typeof result2 === "boolean") {
          return;
        }
        return result2;
      }
    }
  }
}
class EditorAction2 extends Action2 {
  run(accessor, ...args) {
    const codeEditorService = accessor.get(ICodeEditorService);
    const editor2 = codeEditorService.getFocusedCodeEditor() || codeEditorService.getActiveCodeEditor();
    if (!editor2) {
      return;
    }
    return editor2.invokeWithinContext((editorAccessor) => {
      var _a2;
      const kbService = editorAccessor.get(IContextKeyService);
      const logService = editorAccessor.get(ILogService);
      const enabled = kbService.contextMatchesRules(withNullAsUndefined(this.desc.precondition));
      if (!enabled) {
        logService.debug(`[EditorAction2] NOT running command because its precondition is FALSE`, this.desc.id, (_a2 = this.desc.precondition) === null || _a2 === void 0 ? void 0 : _a2.serialize());
        return;
      }
      return this.runEditorCommand(editorAccessor, editor2, ...args);
    });
  }
}
function registerModelAndPositionCommand(id3, handler) {
  CommandsRegistry.registerCommand(id3, function(accessor, ...args) {
    const instaService = accessor.get(IInstantiationService);
    const [resource, position] = args;
    assertType(URI.isUri(resource));
    assertType(Position$2.isIPosition(position));
    const model = accessor.get(IModelService).getModel(resource);
    if (model) {
      const editorPosition = Position$2.lift(position);
      return instaService.invokeFunction(handler, model, editorPosition, ...args.slice(2));
    }
    return accessor.get(ITextModelService).createModelReference(resource).then((reference) => {
      return new Promise((resolve2, reject) => {
        try {
          const result2 = instaService.invokeFunction(handler, reference.object.textEditorModel, Position$2.lift(position), args.slice(2));
          resolve2(result2);
        } catch (err) {
          reject(err);
        }
      }).finally(() => {
        reference.dispose();
      });
    });
  });
}
function registerEditorCommand(editorCommand) {
  EditorContributionRegistry.INSTANCE.registerEditorCommand(editorCommand);
  return editorCommand;
}
function registerEditorAction(ctor) {
  const action = new ctor();
  EditorContributionRegistry.INSTANCE.registerEditorAction(action);
  return action;
}
function registerMultiEditorAction(action) {
  EditorContributionRegistry.INSTANCE.registerEditorAction(action);
  return action;
}
function registerInstantiatedEditorAction(editorAction) {
  EditorContributionRegistry.INSTANCE.registerEditorAction(editorAction);
}
function registerEditorContribution(id3, ctor, instantiation) {
  EditorContributionRegistry.INSTANCE.registerEditorContribution(id3, ctor, instantiation);
}
var EditorExtensionsRegistry;
(function(EditorExtensionsRegistry2) {
  function getEditorCommand(commandId) {
    return EditorContributionRegistry.INSTANCE.getEditorCommand(commandId);
  }
  EditorExtensionsRegistry2.getEditorCommand = getEditorCommand;
  function getEditorActions() {
    return EditorContributionRegistry.INSTANCE.getEditorActions();
  }
  EditorExtensionsRegistry2.getEditorActions = getEditorActions;
  function getEditorContributions() {
    return EditorContributionRegistry.INSTANCE.getEditorContributions();
  }
  EditorExtensionsRegistry2.getEditorContributions = getEditorContributions;
  function getSomeEditorContributions(ids) {
    return EditorContributionRegistry.INSTANCE.getEditorContributions().filter((c) => ids.indexOf(c.id) >= 0);
  }
  EditorExtensionsRegistry2.getSomeEditorContributions = getSomeEditorContributions;
  function getDiffEditorContributions() {
    return EditorContributionRegistry.INSTANCE.getDiffEditorContributions();
  }
  EditorExtensionsRegistry2.getDiffEditorContributions = getDiffEditorContributions;
})(EditorExtensionsRegistry || (EditorExtensionsRegistry = {}));
const Extensions$8 = {
  EditorCommonContributions: "editor.contributions"
};
class EditorContributionRegistry {
  constructor() {
    this.editorContributions = [];
    this.diffEditorContributions = [];
    this.editorActions = [];
    this.editorCommands = /* @__PURE__ */ Object.create(null);
  }
  registerEditorContribution(id3, ctor, instantiation) {
    this.editorContributions.push({ id: id3, ctor, instantiation });
  }
  getEditorContributions() {
    return this.editorContributions.slice(0);
  }
  getDiffEditorContributions() {
    return this.diffEditorContributions.slice(0);
  }
  registerEditorAction(action) {
    action.register();
    this.editorActions.push(action);
  }
  getEditorActions() {
    return this.editorActions;
  }
  registerEditorCommand(editorCommand) {
    editorCommand.register();
    this.editorCommands[editorCommand.id] = editorCommand;
  }
  getEditorCommand(commandId) {
    return this.editorCommands[commandId] || null;
  }
}
EditorContributionRegistry.INSTANCE = new EditorContributionRegistry();
Registry.add(Extensions$8.EditorCommonContributions, EditorContributionRegistry.INSTANCE);
function registerCommand$3(command) {
  command.register();
  return command;
}
const UndoCommand = registerCommand$3(new MultiCommand({
  id: "undo",
  precondition: void 0,
  kbOpts: {
    weight: 0,
    primary: 2048 | 56
    /* KeyCode.KeyZ */
  },
  menuOpts: [{
    menuId: MenuId.MenubarEditMenu,
    group: "1_do",
    title: localize({ key: "miUndo", comment: ["&& denotes a mnemonic"] }, "&&Undo"),
    order: 1
  }, {
    menuId: MenuId.CommandPalette,
    group: "",
    title: localize("undo", "Undo"),
    order: 1
  }]
}));
registerCommand$3(new ProxyCommand(UndoCommand, { id: "default:undo", precondition: void 0 }));
const RedoCommand = registerCommand$3(new MultiCommand({
  id: "redo",
  precondition: void 0,
  kbOpts: {
    weight: 0,
    primary: 2048 | 55,
    secondary: [
      2048 | 1024 | 56
      /* KeyCode.KeyZ */
    ],
    mac: {
      primary: 2048 | 1024 | 56
      /* KeyCode.KeyZ */
    }
  },
  menuOpts: [{
    menuId: MenuId.MenubarEditMenu,
    group: "1_do",
    title: localize({ key: "miRedo", comment: ["&& denotes a mnemonic"] }, "&&Redo"),
    order: 2
  }, {
    menuId: MenuId.CommandPalette,
    group: "",
    title: localize("redo", "Redo"),
    order: 1
  }]
}));
registerCommand$3(new ProxyCommand(RedoCommand, { id: "default:redo", precondition: void 0 }));
const SelectAllCommand = registerCommand$3(new MultiCommand({
  id: "editor.action.selectAll",
  precondition: void 0,
  kbOpts: {
    weight: 0,
    kbExpr: null,
    primary: 2048 | 31
    /* KeyCode.KeyA */
  },
  menuOpts: [{
    menuId: MenuId.MenubarSelectionMenu,
    group: "1_basic",
    title: localize({ key: "miSelectAll", comment: ["&& denotes a mnemonic"] }, "&&Select All"),
    order: 1
  }, {
    menuId: MenuId.CommandPalette,
    group: "",
    title: localize("selectAll", "Select All"),
    order: 1
  }]
}));
let Range$2 = class Range {
  constructor(startLineNumber, startColumn, endLineNumber, endColumn) {
    if (startLineNumber > endLineNumber || startLineNumber === endLineNumber && startColumn > endColumn) {
      this.startLineNumber = endLineNumber;
      this.startColumn = endColumn;
      this.endLineNumber = startLineNumber;
      this.endColumn = startColumn;
    } else {
      this.startLineNumber = startLineNumber;
      this.startColumn = startColumn;
      this.endLineNumber = endLineNumber;
      this.endColumn = endColumn;
    }
  }
  /**
   * Test if this range is empty.
   */
  isEmpty() {
    return Range.isEmpty(this);
  }
  /**
   * Test if `range` is empty.
   */
  static isEmpty(range2) {
    return range2.startLineNumber === range2.endLineNumber && range2.startColumn === range2.endColumn;
  }
  /**
   * Test if position is in this range. If the position is at the edges, will return true.
   */
  containsPosition(position) {
    return Range.containsPosition(this, position);
  }
  /**
   * Test if `position` is in `range`. If the position is at the edges, will return true.
   */
  static containsPosition(range2, position) {
    if (position.lineNumber < range2.startLineNumber || position.lineNumber > range2.endLineNumber) {
      return false;
    }
    if (position.lineNumber === range2.startLineNumber && position.column < range2.startColumn) {
      return false;
    }
    if (position.lineNumber === range2.endLineNumber && position.column > range2.endColumn) {
      return false;
    }
    return true;
  }
  /**
   * Test if `position` is in `range`. If the position is at the edges, will return false.
   * @internal
   */
  static strictContainsPosition(range2, position) {
    if (position.lineNumber < range2.startLineNumber || position.lineNumber > range2.endLineNumber) {
      return false;
    }
    if (position.lineNumber === range2.startLineNumber && position.column <= range2.startColumn) {
      return false;
    }
    if (position.lineNumber === range2.endLineNumber && position.column >= range2.endColumn) {
      return false;
    }
    return true;
  }
  /**
   * Test if range is in this range. If the range is equal to this range, will return true.
   */
  containsRange(range2) {
    return Range.containsRange(this, range2);
  }
  /**
   * Test if `otherRange` is in `range`. If the ranges are equal, will return true.
   */
  static containsRange(range2, otherRange) {
    if (otherRange.startLineNumber < range2.startLineNumber || otherRange.endLineNumber < range2.startLineNumber) {
      return false;
    }
    if (otherRange.startLineNumber > range2.endLineNumber || otherRange.endLineNumber > range2.endLineNumber) {
      return false;
    }
    if (otherRange.startLineNumber === range2.startLineNumber && otherRange.startColumn < range2.startColumn) {
      return false;
    }
    if (otherRange.endLineNumber === range2.endLineNumber && otherRange.endColumn > range2.endColumn) {
      return false;
    }
    return true;
  }
  /**
   * Test if `range` is strictly in this range. `range` must start after and end before this range for the result to be true.
   */
  strictContainsRange(range2) {
    return Range.strictContainsRange(this, range2);
  }
  /**
   * Test if `otherRange` is strictly in `range` (must start after, and end before). If the ranges are equal, will return false.
   */
  static strictContainsRange(range2, otherRange) {
    if (otherRange.startLineNumber < range2.startLineNumber || otherRange.endLineNumber < range2.startLineNumber) {
      return false;
    }
    if (otherRange.startLineNumber > range2.endLineNumber || otherRange.endLineNumber > range2.endLineNumber) {
      return false;
    }
    if (otherRange.startLineNumber === range2.startLineNumber && otherRange.startColumn <= range2.startColumn) {
      return false;
    }
    if (otherRange.endLineNumber === range2.endLineNumber && otherRange.endColumn >= range2.endColumn) {
      return false;
    }
    return true;
  }
  /**
   * A reunion of the two ranges.
   * The smallest position will be used as the start point, and the largest one as the end point.
   */
  plusRange(range2) {
    return Range.plusRange(this, range2);
  }
  /**
   * A reunion of the two ranges.
   * The smallest position will be used as the start point, and the largest one as the end point.
   */
  static plusRange(a, b) {
    let startLineNumber;
    let startColumn;
    let endLineNumber;
    let endColumn;
    if (b.startLineNumber < a.startLineNumber) {
      startLineNumber = b.startLineNumber;
      startColumn = b.startColumn;
    } else if (b.startLineNumber === a.startLineNumber) {
      startLineNumber = b.startLineNumber;
      startColumn = Math.min(b.startColumn, a.startColumn);
    } else {
      startLineNumber = a.startLineNumber;
      startColumn = a.startColumn;
    }
    if (b.endLineNumber > a.endLineNumber) {
      endLineNumber = b.endLineNumber;
      endColumn = b.endColumn;
    } else if (b.endLineNumber === a.endLineNumber) {
      endLineNumber = b.endLineNumber;
      endColumn = Math.max(b.endColumn, a.endColumn);
    } else {
      endLineNumber = a.endLineNumber;
      endColumn = a.endColumn;
    }
    return new Range(startLineNumber, startColumn, endLineNumber, endColumn);
  }
  /**
   * A intersection of the two ranges.
   */
  intersectRanges(range2) {
    return Range.intersectRanges(this, range2);
  }
  /**
   * A intersection of the two ranges.
   */
  static intersectRanges(a, b) {
    let resultStartLineNumber = a.startLineNumber;
    let resultStartColumn = a.startColumn;
    let resultEndLineNumber = a.endLineNumber;
    let resultEndColumn = a.endColumn;
    const otherStartLineNumber = b.startLineNumber;
    const otherStartColumn = b.startColumn;
    const otherEndLineNumber = b.endLineNumber;
    const otherEndColumn = b.endColumn;
    if (resultStartLineNumber < otherStartLineNumber) {
      resultStartLineNumber = otherStartLineNumber;
      resultStartColumn = otherStartColumn;
    } else if (resultStartLineNumber === otherStartLineNumber) {
      resultStartColumn = Math.max(resultStartColumn, otherStartColumn);
    }
    if (resultEndLineNumber > otherEndLineNumber) {
      resultEndLineNumber = otherEndLineNumber;
      resultEndColumn = otherEndColumn;
    } else if (resultEndLineNumber === otherEndLineNumber) {
      resultEndColumn = Math.min(resultEndColumn, otherEndColumn);
    }
    if (resultStartLineNumber > resultEndLineNumber) {
      return null;
    }
    if (resultStartLineNumber === resultEndLineNumber && resultStartColumn > resultEndColumn) {
      return null;
    }
    return new Range(resultStartLineNumber, resultStartColumn, resultEndLineNumber, resultEndColumn);
  }
  /**
   * Test if this range equals other.
   */
  equalsRange(other) {
    return Range.equalsRange(this, other);
  }
  /**
   * Test if range `a` equals `b`.
   */
  static equalsRange(a, b) {
    if (!a && !b) {
      return true;
    }
    return !!a && !!b && a.startLineNumber === b.startLineNumber && a.startColumn === b.startColumn && a.endLineNumber === b.endLineNumber && a.endColumn === b.endColumn;
  }
  /**
   * Return the end position (which will be after or equal to the start position)
   */
  getEndPosition() {
    return Range.getEndPosition(this);
  }
  /**
   * Return the end position (which will be after or equal to the start position)
   */
  static getEndPosition(range2) {
    return new Position$2(range2.endLineNumber, range2.endColumn);
  }
  /**
   * Return the start position (which will be before or equal to the end position)
   */
  getStartPosition() {
    return Range.getStartPosition(this);
  }
  /**
   * Return the start position (which will be before or equal to the end position)
   */
  static getStartPosition(range2) {
    return new Position$2(range2.startLineNumber, range2.startColumn);
  }
  /**
   * Transform to a user presentable string representation.
   */
  toString() {
    return "[" + this.startLineNumber + "," + this.startColumn + " -> " + this.endLineNumber + "," + this.endColumn + "]";
  }
  /**
   * Create a new range using this range's start position, and using endLineNumber and endColumn as the end position.
   */
  setEndPosition(endLineNumber, endColumn) {
    return new Range(this.startLineNumber, this.startColumn, endLineNumber, endColumn);
  }
  /**
   * Create a new range using this range's end position, and using startLineNumber and startColumn as the start position.
   */
  setStartPosition(startLineNumber, startColumn) {
    return new Range(startLineNumber, startColumn, this.endLineNumber, this.endColumn);
  }
  /**
   * Create a new empty range using this range's start position.
   */
  collapseToStart() {
    return Range.collapseToStart(this);
  }
  /**
   * Create a new empty range using this range's start position.
   */
  static collapseToStart(range2) {
    return new Range(range2.startLineNumber, range2.startColumn, range2.startLineNumber, range2.startColumn);
  }
  /**
   * Create a new empty range using this range's end position.
   */
  collapseToEnd() {
    return Range.collapseToEnd(this);
  }
  /**
   * Create a new empty range using this range's end position.
   */
  static collapseToEnd(range2) {
    return new Range(range2.endLineNumber, range2.endColumn, range2.endLineNumber, range2.endColumn);
  }
  /**
   * Moves the range by the given amount of lines.
   */
  delta(lineCount) {
    return new Range(this.startLineNumber + lineCount, this.startColumn, this.endLineNumber + lineCount, this.endColumn);
  }
  // ---
  static fromPositions(start, end = start) {
    return new Range(start.lineNumber, start.column, end.lineNumber, end.column);
  }
  static lift(range2) {
    if (!range2) {
      return null;
    }
    return new Range(range2.startLineNumber, range2.startColumn, range2.endLineNumber, range2.endColumn);
  }
  /**
   * Test if `obj` is an `IRange`.
   */
  static isIRange(obj) {
    return obj && typeof obj.startLineNumber === "number" && typeof obj.startColumn === "number" && typeof obj.endLineNumber === "number" && typeof obj.endColumn === "number";
  }
  /**
   * Test if the two ranges are touching in any way.
   */
  static areIntersectingOrTouching(a, b) {
    if (a.endLineNumber < b.startLineNumber || a.endLineNumber === b.startLineNumber && a.endColumn < b.startColumn) {
      return false;
    }
    if (b.endLineNumber < a.startLineNumber || b.endLineNumber === a.startLineNumber && b.endColumn < a.startColumn) {
      return false;
    }
    return true;
  }
  /**
   * Test if the two ranges are intersecting. If the ranges are touching it returns true.
   */
  static areIntersecting(a, b) {
    if (a.endLineNumber < b.startLineNumber || a.endLineNumber === b.startLineNumber && a.endColumn <= b.startColumn) {
      return false;
    }
    if (b.endLineNumber < a.startLineNumber || b.endLineNumber === a.startLineNumber && b.endColumn <= a.startColumn) {
      return false;
    }
    return true;
  }
  /**
   * A function that compares ranges, useful for sorting ranges
   * It will first compare ranges on the startPosition and then on the endPosition
   */
  static compareRangesUsingStarts(a, b) {
    if (a && b) {
      const aStartLineNumber = a.startLineNumber | 0;
      const bStartLineNumber = b.startLineNumber | 0;
      if (aStartLineNumber === bStartLineNumber) {
        const aStartColumn = a.startColumn | 0;
        const bStartColumn = b.startColumn | 0;
        if (aStartColumn === bStartColumn) {
          const aEndLineNumber = a.endLineNumber | 0;
          const bEndLineNumber = b.endLineNumber | 0;
          if (aEndLineNumber === bEndLineNumber) {
            const aEndColumn = a.endColumn | 0;
            const bEndColumn = b.endColumn | 0;
            return aEndColumn - bEndColumn;
          }
          return aEndLineNumber - bEndLineNumber;
        }
        return aStartColumn - bStartColumn;
      }
      return aStartLineNumber - bStartLineNumber;
    }
    const aExists = a ? 1 : 0;
    const bExists = b ? 1 : 0;
    return aExists - bExists;
  }
  /**
   * A function that compares ranges, useful for sorting ranges
   * It will first compare ranges on the endPosition and then on the startPosition
   */
  static compareRangesUsingEnds(a, b) {
    if (a.endLineNumber === b.endLineNumber) {
      if (a.endColumn === b.endColumn) {
        if (a.startLineNumber === b.startLineNumber) {
          return a.startColumn - b.startColumn;
        }
        return a.startLineNumber - b.startLineNumber;
      }
      return a.endColumn - b.endColumn;
    }
    return a.endLineNumber - b.endLineNumber;
  }
  /**
   * Test if the range spans multiple lines.
   */
  static spansMultipleLines(range2) {
    return range2.endLineNumber > range2.startLineNumber;
  }
  toJSON() {
    return this;
  }
};
let Selection$1 = class Selection extends Range$2 {
  constructor(selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn) {
    super(selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn);
    this.selectionStartLineNumber = selectionStartLineNumber;
    this.selectionStartColumn = selectionStartColumn;
    this.positionLineNumber = positionLineNumber;
    this.positionColumn = positionColumn;
  }
  /**
   * Transform to a human-readable representation.
   */
  toString() {
    return "[" + this.selectionStartLineNumber + "," + this.selectionStartColumn + " -> " + this.positionLineNumber + "," + this.positionColumn + "]";
  }
  /**
   * Test if equals other selection.
   */
  equalsSelection(other) {
    return Selection.selectionsEqual(this, other);
  }
  /**
   * Test if the two selections are equal.
   */
  static selectionsEqual(a, b) {
    return a.selectionStartLineNumber === b.selectionStartLineNumber && a.selectionStartColumn === b.selectionStartColumn && a.positionLineNumber === b.positionLineNumber && a.positionColumn === b.positionColumn;
  }
  /**
   * Get directions (LTR or RTL).
   */
  getDirection() {
    if (this.selectionStartLineNumber === this.startLineNumber && this.selectionStartColumn === this.startColumn) {
      return 0;
    }
    return 1;
  }
  /**
   * Create a new selection with a different `positionLineNumber` and `positionColumn`.
   */
  setEndPosition(endLineNumber, endColumn) {
    if (this.getDirection() === 0) {
      return new Selection(this.startLineNumber, this.startColumn, endLineNumber, endColumn);
    }
    return new Selection(endLineNumber, endColumn, this.startLineNumber, this.startColumn);
  }
  /**
   * Get the position at `positionLineNumber` and `positionColumn`.
   */
  getPosition() {
    return new Position$2(this.positionLineNumber, this.positionColumn);
  }
  /**
   * Get the position at the start of the selection.
  */
  getSelectionStart() {
    return new Position$2(this.selectionStartLineNumber, this.selectionStartColumn);
  }
  /**
   * Create a new selection with a different `selectionStartLineNumber` and `selectionStartColumn`.
   */
  setStartPosition(startLineNumber, startColumn) {
    if (this.getDirection() === 0) {
      return new Selection(startLineNumber, startColumn, this.endLineNumber, this.endColumn);
    }
    return new Selection(this.endLineNumber, this.endColumn, startLineNumber, startColumn);
  }
  // ----
  /**
   * Create a `Selection` from one or two positions
   */
  static fromPositions(start, end = start) {
    return new Selection(start.lineNumber, start.column, end.lineNumber, end.column);
  }
  /**
   * Creates a `Selection` from a range, given a direction.
   */
  static fromRange(range2, direction) {
    if (direction === 0) {
      return new Selection(range2.startLineNumber, range2.startColumn, range2.endLineNumber, range2.endColumn);
    } else {
      return new Selection(range2.endLineNumber, range2.endColumn, range2.startLineNumber, range2.startColumn);
    }
  }
  /**
   * Create a `Selection` from an `ISelection`.
   */
  static liftSelection(sel) {
    return new Selection(sel.selectionStartLineNumber, sel.selectionStartColumn, sel.positionLineNumber, sel.positionColumn);
  }
  /**
   * `a` equals `b`.
   */
  static selectionsArrEqual(a, b) {
    if (a && !b || !a && b) {
      return false;
    }
    if (!a && !b) {
      return true;
    }
    if (a.length !== b.length) {
      return false;
    }
    for (let i = 0, len = a.length; i < len; i++) {
      if (!this.selectionsEqual(a[i], b[i])) {
        return false;
      }
    }
    return true;
  }
  /**
   * Test if `obj` is an `ISelection`.
   */
  static isISelection(obj) {
    return obj && typeof obj.selectionStartLineNumber === "number" && typeof obj.selectionStartColumn === "number" && typeof obj.positionLineNumber === "number" && typeof obj.positionColumn === "number";
  }
  /**
   * Create with a direction.
   */
  static createWithDirection(startLineNumber, startColumn, endLineNumber, endColumn, direction) {
    if (direction === 0) {
      return new Selection(startLineNumber, startColumn, endLineNumber, endColumn);
    }
    return new Selection(endLineNumber, endColumn, startLineNumber, startColumn);
  }
};
function createScopedLineTokens(context, offset) {
  const tokenCount = context.getCount();
  const tokenIndex = context.findTokenIndexAtOffset(offset);
  const desiredLanguageId = context.getLanguageId(tokenIndex);
  let lastTokenIndex = tokenIndex;
  while (lastTokenIndex + 1 < tokenCount && context.getLanguageId(lastTokenIndex + 1) === desiredLanguageId) {
    lastTokenIndex++;
  }
  let firstTokenIndex = tokenIndex;
  while (firstTokenIndex > 0 && context.getLanguageId(firstTokenIndex - 1) === desiredLanguageId) {
    firstTokenIndex--;
  }
  return new ScopedLineTokens(context, desiredLanguageId, firstTokenIndex, lastTokenIndex + 1, context.getStartOffset(firstTokenIndex), context.getEndOffset(lastTokenIndex));
}
class ScopedLineTokens {
  constructor(actual, languageId, firstTokenIndex, lastTokenIndex, firstCharOffset, lastCharOffset) {
    this._scopedLineTokensBrand = void 0;
    this._actual = actual;
    this.languageId = languageId;
    this._firstTokenIndex = firstTokenIndex;
    this._lastTokenIndex = lastTokenIndex;
    this.firstCharOffset = firstCharOffset;
    this._lastCharOffset = lastCharOffset;
  }
  getLineContent() {
    const actualLineContent = this._actual.getLineContent();
    return actualLineContent.substring(this.firstCharOffset, this._lastCharOffset);
  }
  getActualLineContentBefore(offset) {
    const actualLineContent = this._actual.getLineContent();
    return actualLineContent.substring(0, this.firstCharOffset + offset);
  }
  getTokenCount() {
    return this._lastTokenIndex - this._firstTokenIndex;
  }
  findTokenIndexAtOffset(offset) {
    return this._actual.findTokenIndexAtOffset(offset + this.firstCharOffset) - this._firstTokenIndex;
  }
  getStandardTokenType(tokenIndex) {
    return this._actual.getStandardTokenType(tokenIndex + this._firstTokenIndex);
  }
}
function ignoreBracketsInToken(standardTokenType) {
  return (standardTokenType & 3) !== 0;
}
class CursorColumns {
  static _nextVisibleColumn(codePoint, visibleColumn, tabSize) {
    if (codePoint === 9) {
      return CursorColumns.nextRenderTabStop(visibleColumn, tabSize);
    }
    if (isFullWidthCharacter(codePoint) || isEmojiImprecise(codePoint)) {
      return visibleColumn + 2;
    }
    return visibleColumn + 1;
  }
  /**
   * Returns a visible column from a column.
   * @see {@link CursorColumns}
   */
  static visibleColumnFromColumn(lineContent, column, tabSize) {
    const textLen = Math.min(column - 1, lineContent.length);
    const text2 = lineContent.substring(0, textLen);
    const iterator2 = new GraphemeIterator(text2);
    let result2 = 0;
    while (!iterator2.eol()) {
      const codePoint = getNextCodePoint(text2, textLen, iterator2.offset);
      iterator2.nextGraphemeLength();
      result2 = this._nextVisibleColumn(codePoint, result2, tabSize);
    }
    return result2;
  }
  /**
   * Returns a column from a visible column.
   * @see {@link CursorColumns}
   */
  static columnFromVisibleColumn(lineContent, visibleColumn, tabSize) {
    if (visibleColumn <= 0) {
      return 1;
    }
    const lineContentLength = lineContent.length;
    const iterator2 = new GraphemeIterator(lineContent);
    let beforeVisibleColumn = 0;
    let beforeColumn = 1;
    while (!iterator2.eol()) {
      const codePoint = getNextCodePoint(lineContent, lineContentLength, iterator2.offset);
      iterator2.nextGraphemeLength();
      const afterVisibleColumn = this._nextVisibleColumn(codePoint, beforeVisibleColumn, tabSize);
      const afterColumn = iterator2.offset + 1;
      if (afterVisibleColumn >= visibleColumn) {
        const beforeDelta = visibleColumn - beforeVisibleColumn;
        const afterDelta = afterVisibleColumn - visibleColumn;
        if (afterDelta < beforeDelta) {
          return afterColumn;
        } else {
          return beforeColumn;
        }
      }
      beforeVisibleColumn = afterVisibleColumn;
      beforeColumn = afterColumn;
    }
    return lineContentLength + 1;
  }
  /**
   * ATTENTION: This works with 0-based columns (as opposed to the regular 1-based columns)
   * @see {@link CursorColumns}
   */
  static nextRenderTabStop(visibleColumn, tabSize) {
    return visibleColumn + tabSize - visibleColumn % tabSize;
  }
  /**
   * ATTENTION: This works with 0-based columns (as opposed to the regular 1-based columns)
   * @see {@link CursorColumns}
   */
  static nextIndentTabStop(visibleColumn, indentSize) {
    return visibleColumn + indentSize - visibleColumn % indentSize;
  }
  /**
   * ATTENTION: This works with 0-based columns (as opposed to the regular 1-based columns)
   * @see {@link CursorColumns}
   */
  static prevRenderTabStop(column, tabSize) {
    return Math.max(0, column - 1 - (column - 1) % tabSize);
  }
  /**
   * ATTENTION: This works with 0-based columns (as opposed to the regular 1-based columns)
   * @see {@link CursorColumns}
   */
  static prevIndentTabStop(column, indentSize) {
    return Math.max(0, column - 1 - (column - 1) % indentSize);
  }
}
function _normalizeIndentationFromWhitespace(str2, indentSize, insertSpaces) {
  let spacesCnt = 0;
  for (let i = 0; i < str2.length; i++) {
    if (str2.charAt(i) === "	") {
      spacesCnt = CursorColumns.nextIndentTabStop(spacesCnt, indentSize);
    } else {
      spacesCnt++;
    }
  }
  let result2 = "";
  if (!insertSpaces) {
    const tabsCnt = Math.floor(spacesCnt / indentSize);
    spacesCnt = spacesCnt % indentSize;
    for (let i = 0; i < tabsCnt; i++) {
      result2 += "	";
    }
  }
  for (let i = 0; i < spacesCnt; i++) {
    result2 += " ";
  }
  return result2;
}
function normalizeIndentation(str2, indentSize, insertSpaces) {
  let firstNonWhitespaceIndex$1 = firstNonWhitespaceIndex(str2);
  if (firstNonWhitespaceIndex$1 === -1) {
    firstNonWhitespaceIndex$1 = str2.length;
  }
  return _normalizeIndentationFromWhitespace(str2.substring(0, firstNonWhitespaceIndex$1), indentSize, insertSpaces) + str2.substring(firstNonWhitespaceIndex$1);
}
const autoCloseAlways = () => true;
const autoCloseNever = () => false;
const autoCloseBeforeWhitespace = (chr) => chr === " " || chr === "	";
class CursorConfiguration {
  static shouldRecreate(e) {
    return e.hasChanged(
      142
      /* EditorOption.layoutInfo */
    ) || e.hasChanged(
      128
      /* EditorOption.wordSeparators */
    ) || e.hasChanged(
      36
      /* EditorOption.emptySelectionClipboard */
    ) || e.hasChanged(
      75
      /* EditorOption.multiCursorMergeOverlapping */
    ) || e.hasChanged(
      77
      /* EditorOption.multiCursorPaste */
    ) || e.hasChanged(
      78
      /* EditorOption.multiCursorLimit */
    ) || e.hasChanged(
      6
      /* EditorOption.autoClosingBrackets */
    ) || e.hasChanged(
      10
      /* EditorOption.autoClosingQuotes */
    ) || e.hasChanged(
      8
      /* EditorOption.autoClosingDelete */
    ) || e.hasChanged(
      9
      /* EditorOption.autoClosingOvertype */
    ) || e.hasChanged(
      13
      /* EditorOption.autoSurround */
    ) || e.hasChanged(
      126
      /* EditorOption.useTabStops */
    ) || e.hasChanged(
      49
      /* EditorOption.fontInfo */
    ) || e.hasChanged(
      89
      /* EditorOption.readOnly */
    );
  }
  constructor(languageId, modelOptions, configuration, languageConfigurationService) {
    this.languageConfigurationService = languageConfigurationService;
    this._cursorMoveConfigurationBrand = void 0;
    this._languageId = languageId;
    const options = configuration.options;
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    const fontInfo = options.get(
      49
      /* EditorOption.fontInfo */
    );
    this.readOnly = options.get(
      89
      /* EditorOption.readOnly */
    );
    this.tabSize = modelOptions.tabSize;
    this.indentSize = modelOptions.indentSize;
    this.insertSpaces = modelOptions.insertSpaces;
    this.stickyTabStops = options.get(
      114
      /* EditorOption.stickyTabStops */
    );
    this.lineHeight = fontInfo.lineHeight;
    this.typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
    this.pageSize = Math.max(1, Math.floor(layoutInfo.height / this.lineHeight) - 2);
    this.useTabStops = options.get(
      126
      /* EditorOption.useTabStops */
    );
    this.wordSeparators = options.get(
      128
      /* EditorOption.wordSeparators */
    );
    this.emptySelectionClipboard = options.get(
      36
      /* EditorOption.emptySelectionClipboard */
    );
    this.copyWithSyntaxHighlighting = options.get(
      24
      /* EditorOption.copyWithSyntaxHighlighting */
    );
    this.multiCursorMergeOverlapping = options.get(
      75
      /* EditorOption.multiCursorMergeOverlapping */
    );
    this.multiCursorPaste = options.get(
      77
      /* EditorOption.multiCursorPaste */
    );
    this.multiCursorLimit = options.get(
      78
      /* EditorOption.multiCursorLimit */
    );
    this.autoClosingBrackets = options.get(
      6
      /* EditorOption.autoClosingBrackets */
    );
    this.autoClosingQuotes = options.get(
      10
      /* EditorOption.autoClosingQuotes */
    );
    this.autoClosingDelete = options.get(
      8
      /* EditorOption.autoClosingDelete */
    );
    this.autoClosingOvertype = options.get(
      9
      /* EditorOption.autoClosingOvertype */
    );
    this.autoSurround = options.get(
      13
      /* EditorOption.autoSurround */
    );
    this.autoIndent = options.get(
      11
      /* EditorOption.autoIndent */
    );
    this.surroundingPairs = {};
    this._electricChars = null;
    this.shouldAutoCloseBefore = {
      quote: this._getShouldAutoClose(languageId, this.autoClosingQuotes, true),
      bracket: this._getShouldAutoClose(languageId, this.autoClosingBrackets, false)
    };
    this.autoClosingPairs = this.languageConfigurationService.getLanguageConfiguration(languageId).getAutoClosingPairs();
    const surroundingPairs = this.languageConfigurationService.getLanguageConfiguration(languageId).getSurroundingPairs();
    if (surroundingPairs) {
      for (const pair of surroundingPairs) {
        this.surroundingPairs[pair.open] = pair.close;
      }
    }
  }
  get electricChars() {
    var _a2;
    if (!this._electricChars) {
      this._electricChars = {};
      const electricChars = (_a2 = this.languageConfigurationService.getLanguageConfiguration(this._languageId).electricCharacter) === null || _a2 === void 0 ? void 0 : _a2.getElectricCharacters();
      if (electricChars) {
        for (const char of electricChars) {
          this._electricChars[char] = true;
        }
      }
    }
    return this._electricChars;
  }
  /**
   * Should return opening bracket type to match indentation with
   */
  onElectricCharacter(character, context, column) {
    const scopedLineTokens = createScopedLineTokens(context, column - 1);
    const electricCharacterSupport = this.languageConfigurationService.getLanguageConfiguration(scopedLineTokens.languageId).electricCharacter;
    if (!electricCharacterSupport) {
      return null;
    }
    return electricCharacterSupport.onElectricCharacter(character, scopedLineTokens, column - scopedLineTokens.firstCharOffset);
  }
  normalizeIndentation(str2) {
    return normalizeIndentation(str2, this.indentSize, this.insertSpaces);
  }
  _getShouldAutoClose(languageId, autoCloseConfig, forQuotes) {
    switch (autoCloseConfig) {
      case "beforeWhitespace":
        return autoCloseBeforeWhitespace;
      case "languageDefined":
        return this._getLanguageDefinedShouldAutoClose(languageId, forQuotes);
      case "always":
        return autoCloseAlways;
      case "never":
        return autoCloseNever;
    }
  }
  _getLanguageDefinedShouldAutoClose(languageId, forQuotes) {
    const autoCloseBeforeSet = this.languageConfigurationService.getLanguageConfiguration(languageId).getAutoCloseBeforeSet(forQuotes);
    return (c) => autoCloseBeforeSet.indexOf(c) !== -1;
  }
  /**
   * Returns a visible column from a column.
   * @see {@link CursorColumns}
   */
  visibleColumnFromColumn(model, position) {
    return CursorColumns.visibleColumnFromColumn(model.getLineContent(position.lineNumber), position.column, this.tabSize);
  }
  /**
   * Returns a visible column from a column.
   * @see {@link CursorColumns}
   */
  columnFromVisibleColumn(model, lineNumber, visibleColumn) {
    const result2 = CursorColumns.columnFromVisibleColumn(model.getLineContent(lineNumber), visibleColumn, this.tabSize);
    const minColumn = model.getLineMinColumn(lineNumber);
    if (result2 < minColumn) {
      return minColumn;
    }
    const maxColumn = model.getLineMaxColumn(lineNumber);
    if (result2 > maxColumn) {
      return maxColumn;
    }
    return result2;
  }
}
let CursorState$1 = class CursorState {
  static fromModelState(modelState) {
    return new PartialModelCursorState(modelState);
  }
  static fromViewState(viewState) {
    return new PartialViewCursorState(viewState);
  }
  static fromModelSelection(modelSelection) {
    const selection = Selection$1.liftSelection(modelSelection);
    const modelState = new SingleCursorState(Range$2.fromPositions(selection.getSelectionStart()), 0, 0, selection.getPosition(), 0);
    return CursorState.fromModelState(modelState);
  }
  static fromModelSelections(modelSelections) {
    const states = [];
    for (let i = 0, len = modelSelections.length; i < len; i++) {
      states[i] = this.fromModelSelection(modelSelections[i]);
    }
    return states;
  }
  constructor(modelState, viewState) {
    this._cursorStateBrand = void 0;
    this.modelState = modelState;
    this.viewState = viewState;
  }
  equals(other) {
    return this.viewState.equals(other.viewState) && this.modelState.equals(other.modelState);
  }
};
class PartialModelCursorState {
  constructor(modelState) {
    this.modelState = modelState;
    this.viewState = null;
  }
}
class PartialViewCursorState {
  constructor(viewState) {
    this.modelState = null;
    this.viewState = viewState;
  }
}
class SingleCursorState {
  constructor(selectionStart, selectionStartKind, selectionStartLeftoverVisibleColumns, position, leftoverVisibleColumns) {
    this.selectionStart = selectionStart;
    this.selectionStartKind = selectionStartKind;
    this.selectionStartLeftoverVisibleColumns = selectionStartLeftoverVisibleColumns;
    this.position = position;
    this.leftoverVisibleColumns = leftoverVisibleColumns;
    this._singleCursorStateBrand = void 0;
    this.selection = SingleCursorState._computeSelection(this.selectionStart, this.position);
  }
  equals(other) {
    return this.selectionStartLeftoverVisibleColumns === other.selectionStartLeftoverVisibleColumns && this.leftoverVisibleColumns === other.leftoverVisibleColumns && this.selectionStartKind === other.selectionStartKind && this.position.equals(other.position) && this.selectionStart.equalsRange(other.selectionStart);
  }
  hasSelection() {
    return !this.selection.isEmpty() || !this.selectionStart.isEmpty();
  }
  move(inSelectionMode, lineNumber, column, leftoverVisibleColumns) {
    if (inSelectionMode) {
      return new SingleCursorState(this.selectionStart, this.selectionStartKind, this.selectionStartLeftoverVisibleColumns, new Position$2(lineNumber, column), leftoverVisibleColumns);
    } else {
      return new SingleCursorState(new Range$2(lineNumber, column, lineNumber, column), 0, leftoverVisibleColumns, new Position$2(lineNumber, column), leftoverVisibleColumns);
    }
  }
  static _computeSelection(selectionStart, position) {
    if (selectionStart.isEmpty() || !position.isBeforeOrEqual(selectionStart.getStartPosition())) {
      return Selection$1.fromPositions(selectionStart.getStartPosition(), position);
    } else {
      return Selection$1.fromPositions(selectionStart.getEndPosition(), position);
    }
  }
}
class EditOperationResult {
  constructor(type, commands, opts) {
    this._editOperationResultBrand = void 0;
    this.type = type;
    this.commands = commands;
    this.shouldPushStackElementBefore = opts.shouldPushStackElementBefore;
    this.shouldPushStackElementAfter = opts.shouldPushStackElementAfter;
  }
}
function isQuote(ch) {
  return ch === "'" || ch === '"' || ch === "`";
}
class ColumnSelection {
  static columnSelect(config2, model, fromLineNumber, fromVisibleColumn, toLineNumber, toVisibleColumn) {
    const lineCount = Math.abs(toLineNumber - fromLineNumber) + 1;
    const reversed = fromLineNumber > toLineNumber;
    const isRTL = fromVisibleColumn > toVisibleColumn;
    const isLTR = fromVisibleColumn < toVisibleColumn;
    const result2 = [];
    for (let i = 0; i < lineCount; i++) {
      const lineNumber = fromLineNumber + (reversed ? -i : i);
      const startColumn = config2.columnFromVisibleColumn(model, lineNumber, fromVisibleColumn);
      const endColumn = config2.columnFromVisibleColumn(model, lineNumber, toVisibleColumn);
      const visibleStartColumn = config2.visibleColumnFromColumn(model, new Position$2(lineNumber, startColumn));
      const visibleEndColumn = config2.visibleColumnFromColumn(model, new Position$2(lineNumber, endColumn));
      if (isLTR) {
        if (visibleStartColumn > toVisibleColumn) {
          continue;
        }
        if (visibleEndColumn < fromVisibleColumn) {
          continue;
        }
      }
      if (isRTL) {
        if (visibleEndColumn > fromVisibleColumn) {
          continue;
        }
        if (visibleStartColumn < toVisibleColumn) {
          continue;
        }
      }
      result2.push(new SingleCursorState(new Range$2(lineNumber, startColumn, lineNumber, startColumn), 0, 0, new Position$2(lineNumber, endColumn), 0));
    }
    if (result2.length === 0) {
      for (let i = 0; i < lineCount; i++) {
        const lineNumber = fromLineNumber + (reversed ? -i : i);
        const maxColumn = model.getLineMaxColumn(lineNumber);
        result2.push(new SingleCursorState(new Range$2(lineNumber, maxColumn, lineNumber, maxColumn), 0, 0, new Position$2(lineNumber, maxColumn), 0));
      }
    }
    return {
      viewStates: result2,
      reversed,
      fromLineNumber,
      fromVisualColumn: fromVisibleColumn,
      toLineNumber,
      toVisualColumn: toVisibleColumn
    };
  }
  static columnSelectLeft(config2, model, prevColumnSelectData) {
    let toViewVisualColumn = prevColumnSelectData.toViewVisualColumn;
    if (toViewVisualColumn > 0) {
      toViewVisualColumn--;
    }
    return ColumnSelection.columnSelect(config2, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, prevColumnSelectData.toViewLineNumber, toViewVisualColumn);
  }
  static columnSelectRight(config2, model, prevColumnSelectData) {
    let maxVisualViewColumn = 0;
    const minViewLineNumber = Math.min(prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.toViewLineNumber);
    const maxViewLineNumber = Math.max(prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.toViewLineNumber);
    for (let lineNumber = minViewLineNumber; lineNumber <= maxViewLineNumber; lineNumber++) {
      const lineMaxViewColumn = model.getLineMaxColumn(lineNumber);
      const lineMaxVisualViewColumn = config2.visibleColumnFromColumn(model, new Position$2(lineNumber, lineMaxViewColumn));
      maxVisualViewColumn = Math.max(maxVisualViewColumn, lineMaxVisualViewColumn);
    }
    let toViewVisualColumn = prevColumnSelectData.toViewVisualColumn;
    if (toViewVisualColumn < maxVisualViewColumn) {
      toViewVisualColumn++;
    }
    return this.columnSelect(config2, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, prevColumnSelectData.toViewLineNumber, toViewVisualColumn);
  }
  static columnSelectUp(config2, model, prevColumnSelectData, isPaged) {
    const linesCount = isPaged ? config2.pageSize : 1;
    const toViewLineNumber = Math.max(1, prevColumnSelectData.toViewLineNumber - linesCount);
    return this.columnSelect(config2, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, toViewLineNumber, prevColumnSelectData.toViewVisualColumn);
  }
  static columnSelectDown(config2, model, prevColumnSelectData, isPaged) {
    const linesCount = isPaged ? config2.pageSize : 1;
    const toViewLineNumber = Math.min(model.getLineCount(), prevColumnSelectData.toViewLineNumber + linesCount);
    return this.columnSelect(config2, model, prevColumnSelectData.fromViewLineNumber, prevColumnSelectData.fromViewVisualColumn, toViewLineNumber, prevColumnSelectData.toViewVisualColumn);
  }
}
class ReplaceCommand {
  constructor(range2, text2, insertsAutoWhitespace = false) {
    this._range = range2;
    this._text = text2;
    this.insertsAutoWhitespace = insertsAutoWhitespace;
  }
  getEditOperations(model, builder) {
    builder.addTrackedEditOperation(this._range, this._text);
  }
  computeCursorState(model, helper) {
    const inverseEditOperations = helper.getInverseEditOperations();
    const srcRange = inverseEditOperations[0].range;
    return Selection$1.fromPositions(srcRange.getEndPosition());
  }
}
class ReplaceCommandThatSelectsText {
  constructor(range2, text2) {
    this._range = range2;
    this._text = text2;
  }
  getEditOperations(model, builder) {
    builder.addTrackedEditOperation(this._range, this._text);
  }
  computeCursorState(model, helper) {
    const inverseEditOperations = helper.getInverseEditOperations();
    const srcRange = inverseEditOperations[0].range;
    return Selection$1.fromRange(
      srcRange,
      0
      /* SelectionDirection.LTR */
    );
  }
}
class ReplaceCommandWithoutChangingPosition {
  constructor(range2, text2, insertsAutoWhitespace = false) {
    this._range = range2;
    this._text = text2;
    this.insertsAutoWhitespace = insertsAutoWhitespace;
  }
  getEditOperations(model, builder) {
    builder.addTrackedEditOperation(this._range, this._text);
  }
  computeCursorState(model, helper) {
    const inverseEditOperations = helper.getInverseEditOperations();
    const srcRange = inverseEditOperations[0].range;
    return Selection$1.fromPositions(srcRange.getStartPosition());
  }
}
class ReplaceCommandWithOffsetCursorState {
  constructor(range2, text2, lineNumberDeltaOffset, columnDeltaOffset, insertsAutoWhitespace = false) {
    this._range = range2;
    this._text = text2;
    this._columnDeltaOffset = columnDeltaOffset;
    this._lineNumberDeltaOffset = lineNumberDeltaOffset;
    this.insertsAutoWhitespace = insertsAutoWhitespace;
  }
  getEditOperations(model, builder) {
    builder.addTrackedEditOperation(this._range, this._text);
  }
  computeCursorState(model, helper) {
    const inverseEditOperations = helper.getInverseEditOperations();
    const srcRange = inverseEditOperations[0].range;
    return Selection$1.fromPositions(srcRange.getEndPosition().delta(this._lineNumberDeltaOffset, this._columnDeltaOffset));
  }
}
class ReplaceCommandThatPreservesSelection {
  constructor(editRange, text2, initialSelection, forceMoveMarkers = false) {
    this._range = editRange;
    this._text = text2;
    this._initialSelection = initialSelection;
    this._forceMoveMarkers = forceMoveMarkers;
    this._selectionId = null;
  }
  getEditOperations(model, builder) {
    builder.addTrackedEditOperation(this._range, this._text, this._forceMoveMarkers);
    this._selectionId = builder.trackSelection(this._initialSelection);
  }
  computeCursorState(model, helper) {
    return helper.getTrackedSelection(this._selectionId);
  }
}
class AtomicTabMoveOperations {
  /**
   * Get the visible column at the position. If we get to a non-whitespace character first
   * or past the end of string then return -1.
   *
   * **Note** `position` and the return value are 0-based.
   */
  static whitespaceVisibleColumn(lineContent, position, tabSize) {
    const lineLength = lineContent.length;
    let visibleColumn = 0;
    let prevTabStopPosition = -1;
    let prevTabStopVisibleColumn = -1;
    for (let i = 0; i < lineLength; i++) {
      if (i === position) {
        return [prevTabStopPosition, prevTabStopVisibleColumn, visibleColumn];
      }
      if (visibleColumn % tabSize === 0) {
        prevTabStopPosition = i;
        prevTabStopVisibleColumn = visibleColumn;
      }
      const chCode = lineContent.charCodeAt(i);
      switch (chCode) {
        case 32:
          visibleColumn += 1;
          break;
        case 9:
          visibleColumn = CursorColumns.nextRenderTabStop(visibleColumn, tabSize);
          break;
        default:
          return [-1, -1, -1];
      }
    }
    if (position === lineLength) {
      return [prevTabStopPosition, prevTabStopVisibleColumn, visibleColumn];
    }
    return [-1, -1, -1];
  }
  /**
   * Return the position that should result from a move left, right or to the
   * nearest tab, if atomic tabs are enabled. Left and right are used for the
   * arrow key movements, nearest is used for mouse selection. It returns
   * -1 if atomic tabs are not relevant and you should fall back to normal
   * behaviour.
   *
   * **Note**: `position` and the return value are 0-based.
   */
  static atomicPosition(lineContent, position, tabSize, direction) {
    const lineLength = lineContent.length;
    const [prevTabStopPosition, prevTabStopVisibleColumn, visibleColumn] = AtomicTabMoveOperations.whitespaceVisibleColumn(lineContent, position, tabSize);
    if (visibleColumn === -1) {
      return -1;
    }
    let left;
    switch (direction) {
      case 0:
        left = true;
        break;
      case 1:
        left = false;
        break;
      case 2:
        if (visibleColumn % tabSize === 0) {
          return position;
        }
        left = visibleColumn % tabSize <= tabSize / 2;
        break;
    }
    if (left) {
      if (prevTabStopPosition === -1) {
        return -1;
      }
      let currentVisibleColumn2 = prevTabStopVisibleColumn;
      for (let i = prevTabStopPosition; i < lineLength; ++i) {
        if (currentVisibleColumn2 === prevTabStopVisibleColumn + tabSize) {
          return prevTabStopPosition;
        }
        const chCode = lineContent.charCodeAt(i);
        switch (chCode) {
          case 32:
            currentVisibleColumn2 += 1;
            break;
          case 9:
            currentVisibleColumn2 = CursorColumns.nextRenderTabStop(currentVisibleColumn2, tabSize);
            break;
          default:
            return -1;
        }
      }
      if (currentVisibleColumn2 === prevTabStopVisibleColumn + tabSize) {
        return prevTabStopPosition;
      }
      return -1;
    }
    const targetVisibleColumn = CursorColumns.nextRenderTabStop(visibleColumn, tabSize);
    let currentVisibleColumn = visibleColumn;
    for (let i = position; i < lineLength; i++) {
      if (currentVisibleColumn === targetVisibleColumn) {
        return i;
      }
      const chCode = lineContent.charCodeAt(i);
      switch (chCode) {
        case 32:
          currentVisibleColumn += 1;
          break;
        case 9:
          currentVisibleColumn = CursorColumns.nextRenderTabStop(currentVisibleColumn, tabSize);
          break;
        default:
          return -1;
      }
    }
    if (currentVisibleColumn === targetVisibleColumn) {
      return lineLength;
    }
    return -1;
  }
}
class CursorPosition {
  constructor(lineNumber, column, leftoverVisibleColumns) {
    this._cursorPositionBrand = void 0;
    this.lineNumber = lineNumber;
    this.column = column;
    this.leftoverVisibleColumns = leftoverVisibleColumns;
  }
}
class MoveOperations {
  static leftPosition(model, position) {
    if (position.column > model.getLineMinColumn(position.lineNumber)) {
      return position.delta(void 0, -prevCharLength(model.getLineContent(position.lineNumber), position.column - 1));
    } else if (position.lineNumber > 1) {
      const newLineNumber = position.lineNumber - 1;
      return new Position$2(newLineNumber, model.getLineMaxColumn(newLineNumber));
    } else {
      return position;
    }
  }
  static leftPositionAtomicSoftTabs(model, position, tabSize) {
    if (position.column <= model.getLineIndentColumn(position.lineNumber)) {
      const minColumn = model.getLineMinColumn(position.lineNumber);
      const lineContent = model.getLineContent(position.lineNumber);
      const newPosition = AtomicTabMoveOperations.atomicPosition(
        lineContent,
        position.column - 1,
        tabSize,
        0
        /* Direction.Left */
      );
      if (newPosition !== -1 && newPosition + 1 >= minColumn) {
        return new Position$2(position.lineNumber, newPosition + 1);
      }
    }
    return this.leftPosition(model, position);
  }
  static left(config2, model, position) {
    const pos = config2.stickyTabStops ? MoveOperations.leftPositionAtomicSoftTabs(model, position, config2.tabSize) : MoveOperations.leftPosition(model, position);
    return new CursorPosition(pos.lineNumber, pos.column, 0);
  }
  /**
   * @param noOfColumns Must be either `1`
   * or `Math.round(viewModel.getLineContent(viewLineNumber).length / 2)` (for half lines).
  */
  static moveLeft(config2, model, cursor, inSelectionMode, noOfColumns) {
    let lineNumber, column;
    if (cursor.hasSelection() && !inSelectionMode) {
      lineNumber = cursor.selection.startLineNumber;
      column = cursor.selection.startColumn;
    } else {
      const pos = cursor.position.delta(void 0, -(noOfColumns - 1));
      const normalizedPos = model.normalizePosition(
        MoveOperations.clipPositionColumn(pos, model),
        0
        /* PositionAffinity.Left */
      );
      const p2 = MoveOperations.left(config2, model, normalizedPos);
      lineNumber = p2.lineNumber;
      column = p2.column;
    }
    return cursor.move(inSelectionMode, lineNumber, column, 0);
  }
  /**
   * Adjusts the column so that it is within min/max of the line.
  */
  static clipPositionColumn(position, model) {
    return new Position$2(position.lineNumber, MoveOperations.clipRange(position.column, model.getLineMinColumn(position.lineNumber), model.getLineMaxColumn(position.lineNumber)));
  }
  static clipRange(value, min, max) {
    if (value < min) {
      return min;
    }
    if (value > max) {
      return max;
    }
    return value;
  }
  static rightPosition(model, lineNumber, column) {
    if (column < model.getLineMaxColumn(lineNumber)) {
      column = column + nextCharLength(model.getLineContent(lineNumber), column - 1);
    } else if (lineNumber < model.getLineCount()) {
      lineNumber = lineNumber + 1;
      column = model.getLineMinColumn(lineNumber);
    }
    return new Position$2(lineNumber, column);
  }
  static rightPositionAtomicSoftTabs(model, lineNumber, column, tabSize, indentSize) {
    if (column < model.getLineIndentColumn(lineNumber)) {
      const lineContent = model.getLineContent(lineNumber);
      const newPosition = AtomicTabMoveOperations.atomicPosition(
        lineContent,
        column - 1,
        tabSize,
        1
        /* Direction.Right */
      );
      if (newPosition !== -1) {
        return new Position$2(lineNumber, newPosition + 1);
      }
    }
    return this.rightPosition(model, lineNumber, column);
  }
  static right(config2, model, position) {
    const pos = config2.stickyTabStops ? MoveOperations.rightPositionAtomicSoftTabs(model, position.lineNumber, position.column, config2.tabSize, config2.indentSize) : MoveOperations.rightPosition(model, position.lineNumber, position.column);
    return new CursorPosition(pos.lineNumber, pos.column, 0);
  }
  static moveRight(config2, model, cursor, inSelectionMode, noOfColumns) {
    let lineNumber, column;
    if (cursor.hasSelection() && !inSelectionMode) {
      lineNumber = cursor.selection.endLineNumber;
      column = cursor.selection.endColumn;
    } else {
      const pos = cursor.position.delta(void 0, noOfColumns - 1);
      const normalizedPos = model.normalizePosition(
        MoveOperations.clipPositionColumn(pos, model),
        1
        /* PositionAffinity.Right */
      );
      const r = MoveOperations.right(config2, model, normalizedPos);
      lineNumber = r.lineNumber;
      column = r.column;
    }
    return cursor.move(inSelectionMode, lineNumber, column, 0);
  }
  static vertical(config2, model, lineNumber, column, leftoverVisibleColumns, newLineNumber, allowMoveOnEdgeLine, normalizationAffinity) {
    const currentVisibleColumn = CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config2.tabSize) + leftoverVisibleColumns;
    const lineCount = model.getLineCount();
    const wasOnFirstPosition = lineNumber === 1 && column === 1;
    const wasOnLastPosition = lineNumber === lineCount && column === model.getLineMaxColumn(lineNumber);
    const wasAtEdgePosition = newLineNumber < lineNumber ? wasOnFirstPosition : wasOnLastPosition;
    lineNumber = newLineNumber;
    if (lineNumber < 1) {
      lineNumber = 1;
      if (allowMoveOnEdgeLine) {
        column = model.getLineMinColumn(lineNumber);
      } else {
        column = Math.min(model.getLineMaxColumn(lineNumber), column);
      }
    } else if (lineNumber > lineCount) {
      lineNumber = lineCount;
      if (allowMoveOnEdgeLine) {
        column = model.getLineMaxColumn(lineNumber);
      } else {
        column = Math.min(model.getLineMaxColumn(lineNumber), column);
      }
    } else {
      column = config2.columnFromVisibleColumn(model, lineNumber, currentVisibleColumn);
    }
    if (wasAtEdgePosition) {
      leftoverVisibleColumns = 0;
    } else {
      leftoverVisibleColumns = currentVisibleColumn - CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config2.tabSize);
    }
    if (normalizationAffinity !== void 0) {
      const position = new Position$2(lineNumber, column);
      const newPosition = model.normalizePosition(position, normalizationAffinity);
      leftoverVisibleColumns = leftoverVisibleColumns + (column - newPosition.column);
      lineNumber = newPosition.lineNumber;
      column = newPosition.column;
    }
    return new CursorPosition(lineNumber, column, leftoverVisibleColumns);
  }
  static down(config2, model, lineNumber, column, leftoverVisibleColumns, count, allowMoveOnLastLine) {
    return this.vertical(
      config2,
      model,
      lineNumber,
      column,
      leftoverVisibleColumns,
      lineNumber + count,
      allowMoveOnLastLine,
      4
      /* PositionAffinity.RightOfInjectedText */
    );
  }
  static moveDown(config2, model, cursor, inSelectionMode, linesCount) {
    let lineNumber, column;
    if (cursor.hasSelection() && !inSelectionMode) {
      lineNumber = cursor.selection.endLineNumber;
      column = cursor.selection.endColumn;
    } else {
      lineNumber = cursor.position.lineNumber;
      column = cursor.position.column;
    }
    let i = 0;
    let r;
    do {
      r = MoveOperations.down(config2, model, lineNumber + i, column, cursor.leftoverVisibleColumns, linesCount, true);
      const np = model.normalizePosition(
        new Position$2(r.lineNumber, r.column),
        2
        /* PositionAffinity.None */
      );
      if (np.lineNumber > lineNumber) {
        break;
      }
    } while (i++ < 10 && lineNumber + i < model.getLineCount());
    return cursor.move(inSelectionMode, r.lineNumber, r.column, r.leftoverVisibleColumns);
  }
  static translateDown(config2, model, cursor) {
    const selection = cursor.selection;
    const selectionStart = MoveOperations.down(config2, model, selection.selectionStartLineNumber, selection.selectionStartColumn, cursor.selectionStartLeftoverVisibleColumns, 1, false);
    const position = MoveOperations.down(config2, model, selection.positionLineNumber, selection.positionColumn, cursor.leftoverVisibleColumns, 1, false);
    return new SingleCursorState(new Range$2(selectionStart.lineNumber, selectionStart.column, selectionStart.lineNumber, selectionStart.column), 0, selectionStart.leftoverVisibleColumns, new Position$2(position.lineNumber, position.column), position.leftoverVisibleColumns);
  }
  static up(config2, model, lineNumber, column, leftoverVisibleColumns, count, allowMoveOnFirstLine) {
    return this.vertical(
      config2,
      model,
      lineNumber,
      column,
      leftoverVisibleColumns,
      lineNumber - count,
      allowMoveOnFirstLine,
      3
      /* PositionAffinity.LeftOfInjectedText */
    );
  }
  static moveUp(config2, model, cursor, inSelectionMode, linesCount) {
    let lineNumber, column;
    if (cursor.hasSelection() && !inSelectionMode) {
      lineNumber = cursor.selection.startLineNumber;
      column = cursor.selection.startColumn;
    } else {
      lineNumber = cursor.position.lineNumber;
      column = cursor.position.column;
    }
    const r = MoveOperations.up(config2, model, lineNumber, column, cursor.leftoverVisibleColumns, linesCount, true);
    return cursor.move(inSelectionMode, r.lineNumber, r.column, r.leftoverVisibleColumns);
  }
  static translateUp(config2, model, cursor) {
    const selection = cursor.selection;
    const selectionStart = MoveOperations.up(config2, model, selection.selectionStartLineNumber, selection.selectionStartColumn, cursor.selectionStartLeftoverVisibleColumns, 1, false);
    const position = MoveOperations.up(config2, model, selection.positionLineNumber, selection.positionColumn, cursor.leftoverVisibleColumns, 1, false);
    return new SingleCursorState(new Range$2(selectionStart.lineNumber, selectionStart.column, selectionStart.lineNumber, selectionStart.column), 0, selectionStart.leftoverVisibleColumns, new Position$2(position.lineNumber, position.column), position.leftoverVisibleColumns);
  }
  static _isBlankLine(model, lineNumber) {
    if (model.getLineFirstNonWhitespaceColumn(lineNumber) === 0) {
      return true;
    }
    return false;
  }
  static moveToPrevBlankLine(config2, model, cursor, inSelectionMode) {
    let lineNumber = cursor.position.lineNumber;
    while (lineNumber > 1 && this._isBlankLine(model, lineNumber)) {
      lineNumber--;
    }
    while (lineNumber > 1 && !this._isBlankLine(model, lineNumber)) {
      lineNumber--;
    }
    return cursor.move(inSelectionMode, lineNumber, model.getLineMinColumn(lineNumber), 0);
  }
  static moveToNextBlankLine(config2, model, cursor, inSelectionMode) {
    const lineCount = model.getLineCount();
    let lineNumber = cursor.position.lineNumber;
    while (lineNumber < lineCount && this._isBlankLine(model, lineNumber)) {
      lineNumber++;
    }
    while (lineNumber < lineCount && !this._isBlankLine(model, lineNumber)) {
      lineNumber++;
    }
    return cursor.move(inSelectionMode, lineNumber, model.getLineMinColumn(lineNumber), 0);
  }
  static moveToBeginningOfLine(config2, model, cursor, inSelectionMode) {
    const lineNumber = cursor.position.lineNumber;
    const minColumn = model.getLineMinColumn(lineNumber);
    const firstNonBlankColumn = model.getLineFirstNonWhitespaceColumn(lineNumber) || minColumn;
    let column;
    const relevantColumnNumber = cursor.position.column;
    if (relevantColumnNumber === firstNonBlankColumn) {
      column = minColumn;
    } else {
      column = firstNonBlankColumn;
    }
    return cursor.move(inSelectionMode, lineNumber, column, 0);
  }
  static moveToEndOfLine(config2, model, cursor, inSelectionMode, sticky) {
    const lineNumber = cursor.position.lineNumber;
    const maxColumn = model.getLineMaxColumn(lineNumber);
    return cursor.move(inSelectionMode, lineNumber, maxColumn, sticky ? 1073741824 - maxColumn : 0);
  }
  static moveToBeginningOfBuffer(config2, model, cursor, inSelectionMode) {
    return cursor.move(inSelectionMode, 1, 1, 0);
  }
  static moveToEndOfBuffer(config2, model, cursor, inSelectionMode) {
    const lastLineNumber = model.getLineCount();
    const lastColumn = model.getLineMaxColumn(lastLineNumber);
    return cursor.move(inSelectionMode, lastLineNumber, lastColumn, 0);
  }
}
class DeleteOperations {
  static deleteRight(prevEditOperationType, config2, model, selections2) {
    const commands = [];
    let shouldPushStackElementBefore = prevEditOperationType !== 3;
    for (let i = 0, len = selections2.length; i < len; i++) {
      const selection = selections2[i];
      let deleteSelection = selection;
      if (deleteSelection.isEmpty()) {
        const position = selection.getPosition();
        const rightOfPosition = MoveOperations.right(config2, model, position);
        deleteSelection = new Range$2(rightOfPosition.lineNumber, rightOfPosition.column, position.lineNumber, position.column);
      }
      if (deleteSelection.isEmpty()) {
        commands[i] = null;
        continue;
      }
      if (deleteSelection.startLineNumber !== deleteSelection.endLineNumber) {
        shouldPushStackElementBefore = true;
      }
      commands[i] = new ReplaceCommand(deleteSelection, "");
    }
    return [shouldPushStackElementBefore, commands];
  }
  static isAutoClosingPairDelete(autoClosingDelete, autoClosingBrackets, autoClosingQuotes, autoClosingPairsOpen, model, selections2, autoClosedCharacters) {
    if (autoClosingBrackets === "never" && autoClosingQuotes === "never") {
      return false;
    }
    if (autoClosingDelete === "never") {
      return false;
    }
    for (let i = 0, len = selections2.length; i < len; i++) {
      const selection = selections2[i];
      const position = selection.getPosition();
      if (!selection.isEmpty()) {
        return false;
      }
      const lineText = model.getLineContent(position.lineNumber);
      if (position.column < 2 || position.column >= lineText.length + 1) {
        return false;
      }
      const character = lineText.charAt(position.column - 2);
      const autoClosingPairCandidates = autoClosingPairsOpen.get(character);
      if (!autoClosingPairCandidates) {
        return false;
      }
      if (isQuote(character)) {
        if (autoClosingQuotes === "never") {
          return false;
        }
      } else {
        if (autoClosingBrackets === "never") {
          return false;
        }
      }
      const afterCharacter = lineText.charAt(position.column - 1);
      let foundAutoClosingPair = false;
      for (const autoClosingPairCandidate of autoClosingPairCandidates) {
        if (autoClosingPairCandidate.open === character && autoClosingPairCandidate.close === afterCharacter) {
          foundAutoClosingPair = true;
        }
      }
      if (!foundAutoClosingPair) {
        return false;
      }
      if (autoClosingDelete === "auto") {
        let found = false;
        for (let j = 0, lenJ = autoClosedCharacters.length; j < lenJ; j++) {
          const autoClosedCharacter = autoClosedCharacters[j];
          if (position.lineNumber === autoClosedCharacter.startLineNumber && position.column === autoClosedCharacter.startColumn) {
            found = true;
            break;
          }
        }
        if (!found) {
          return false;
        }
      }
    }
    return true;
  }
  static _runAutoClosingPairDelete(config2, model, selections2) {
    const commands = [];
    for (let i = 0, len = selections2.length; i < len; i++) {
      const position = selections2[i].getPosition();
      const deleteSelection = new Range$2(position.lineNumber, position.column - 1, position.lineNumber, position.column + 1);
      commands[i] = new ReplaceCommand(deleteSelection, "");
    }
    return [true, commands];
  }
  static deleteLeft(prevEditOperationType, config2, model, selections2, autoClosedCharacters) {
    if (this.isAutoClosingPairDelete(config2.autoClosingDelete, config2.autoClosingBrackets, config2.autoClosingQuotes, config2.autoClosingPairs.autoClosingPairsOpenByEnd, model, selections2, autoClosedCharacters)) {
      return this._runAutoClosingPairDelete(config2, model, selections2);
    }
    const commands = [];
    let shouldPushStackElementBefore = prevEditOperationType !== 2;
    for (let i = 0, len = selections2.length; i < len; i++) {
      const deleteRange = DeleteOperations.getDeleteRange(selections2[i], model, config2);
      if (deleteRange.isEmpty()) {
        commands[i] = null;
        continue;
      }
      if (deleteRange.startLineNumber !== deleteRange.endLineNumber) {
        shouldPushStackElementBefore = true;
      }
      commands[i] = new ReplaceCommand(deleteRange, "");
    }
    return [shouldPushStackElementBefore, commands];
  }
  static getDeleteRange(selection, model, config2) {
    if (!selection.isEmpty()) {
      return selection;
    }
    const position = selection.getPosition();
    if (config2.useTabStops && position.column > 1) {
      const lineContent = model.getLineContent(position.lineNumber);
      const firstNonWhitespaceIndex$1 = firstNonWhitespaceIndex(lineContent);
      const lastIndentationColumn = firstNonWhitespaceIndex$1 === -1 ? (
        /* entire string is whitespace */
        lineContent.length + 1
      ) : firstNonWhitespaceIndex$1 + 1;
      if (position.column <= lastIndentationColumn) {
        const fromVisibleColumn = config2.visibleColumnFromColumn(model, position);
        const toVisibleColumn = CursorColumns.prevIndentTabStop(fromVisibleColumn, config2.indentSize);
        const toColumn = config2.columnFromVisibleColumn(model, position.lineNumber, toVisibleColumn);
        return new Range$2(position.lineNumber, toColumn, position.lineNumber, position.column);
      }
    }
    return Range$2.fromPositions(DeleteOperations.getPositionAfterDeleteLeft(position, model), position);
  }
  static getPositionAfterDeleteLeft(position, model) {
    if (position.column > 1) {
      const idx = getLeftDeleteOffset(position.column - 1, model.getLineContent(position.lineNumber));
      return position.with(void 0, idx + 1);
    } else if (position.lineNumber > 1) {
      const newLine = position.lineNumber - 1;
      return new Position$2(newLine, model.getLineMaxColumn(newLine));
    } else {
      return position;
    }
  }
  static cut(config2, model, selections2) {
    const commands = [];
    let lastCutRange = null;
    selections2.sort((a, b) => Position$2.compare(a.getStartPosition(), b.getEndPosition()));
    for (let i = 0, len = selections2.length; i < len; i++) {
      const selection = selections2[i];
      if (selection.isEmpty()) {
        if (config2.emptySelectionClipboard) {
          const position = selection.getPosition();
          let startLineNumber, startColumn, endLineNumber, endColumn;
          if (position.lineNumber < model.getLineCount()) {
            startLineNumber = position.lineNumber;
            startColumn = 1;
            endLineNumber = position.lineNumber + 1;
            endColumn = 1;
          } else if (position.lineNumber > 1 && (lastCutRange === null || lastCutRange === void 0 ? void 0 : lastCutRange.endLineNumber) !== position.lineNumber) {
            startLineNumber = position.lineNumber - 1;
            startColumn = model.getLineMaxColumn(position.lineNumber - 1);
            endLineNumber = position.lineNumber;
            endColumn = model.getLineMaxColumn(position.lineNumber);
          } else {
            startLineNumber = position.lineNumber;
            startColumn = 1;
            endLineNumber = position.lineNumber;
            endColumn = model.getLineMaxColumn(position.lineNumber);
          }
          const deleteSelection = new Range$2(startLineNumber, startColumn, endLineNumber, endColumn);
          lastCutRange = deleteSelection;
          if (!deleteSelection.isEmpty()) {
            commands[i] = new ReplaceCommand(deleteSelection, "");
          } else {
            commands[i] = null;
          }
        } else {
          commands[i] = null;
        }
      } else {
        commands[i] = new ReplaceCommand(selection, "");
      }
    }
    return new EditOperationResult(0, commands, {
      shouldPushStackElementBefore: true,
      shouldPushStackElementAfter: true
    });
  }
}
function toUint8(v) {
  if (v < 0) {
    return 0;
  }
  if (v > 255) {
    return 255;
  }
  return v | 0;
}
function toUint32(v) {
  if (v < 0) {
    return 0;
  }
  if (v > 4294967295) {
    return 4294967295;
  }
  return v | 0;
}
class CharacterClassifier {
  constructor(_defaultValue) {
    const defaultValue = toUint8(_defaultValue);
    this._defaultValue = defaultValue;
    this._asciiMap = CharacterClassifier._createAsciiMap(defaultValue);
    this._map = /* @__PURE__ */ new Map();
  }
  static _createAsciiMap(defaultValue) {
    const asciiMap = new Uint8Array(256);
    asciiMap.fill(defaultValue);
    return asciiMap;
  }
  set(charCode, _value) {
    const value = toUint8(_value);
    if (charCode >= 0 && charCode < 256) {
      this._asciiMap[charCode] = value;
    } else {
      this._map.set(charCode, value);
    }
  }
  get(charCode) {
    if (charCode >= 0 && charCode < 256) {
      return this._asciiMap[charCode];
    } else {
      return this._map.get(charCode) || this._defaultValue;
    }
  }
  clear() {
    this._asciiMap.fill(this._defaultValue);
    this._map.clear();
  }
}
class CharacterSet {
  constructor() {
    this._actual = new CharacterClassifier(
      0
      /* Boolean.False */
    );
  }
  add(charCode) {
    this._actual.set(
      charCode,
      1
      /* Boolean.True */
    );
  }
  has(charCode) {
    return this._actual.get(charCode) === 1;
  }
  clear() {
    return this._actual.clear();
  }
}
class WordCharacterClassifier extends CharacterClassifier {
  constructor(wordSeparators2) {
    super(
      0
      /* WordCharacterClass.Regular */
    );
    for (let i = 0, len = wordSeparators2.length; i < len; i++) {
      this.set(
        wordSeparators2.charCodeAt(i),
        2
        /* WordCharacterClass.WordSeparator */
      );
    }
    this.set(
      32,
      1
      /* WordCharacterClass.Whitespace */
    );
    this.set(
      9,
      1
      /* WordCharacterClass.Whitespace */
    );
  }
}
function once$1(computeFn) {
  const cache2 = {};
  return (input2) => {
    if (!cache2.hasOwnProperty(input2)) {
      cache2[input2] = computeFn(input2);
    }
    return cache2[input2];
  };
}
const getMapForWordSeparators = once$1((input2) => new WordCharacterClassifier(input2));
class WordOperations {
  static _createWord(lineContent, wordType, nextCharClass, start, end) {
    return { start, end, wordType, nextCharClass };
  }
  static _findPreviousWordOnLine(wordSeparators2, model, position) {
    const lineContent = model.getLineContent(position.lineNumber);
    return this._doFindPreviousWordOnLine(lineContent, wordSeparators2, position);
  }
  static _doFindPreviousWordOnLine(lineContent, wordSeparators2, position) {
    let wordType = 0;
    for (let chIndex = position.column - 2; chIndex >= 0; chIndex--) {
      const chCode = lineContent.charCodeAt(chIndex);
      const chClass = wordSeparators2.get(chCode);
      if (chClass === 0) {
        if (wordType === 2) {
          return this._createWord(lineContent, wordType, chClass, chIndex + 1, this._findEndOfWord(lineContent, wordSeparators2, wordType, chIndex + 1));
        }
        wordType = 1;
      } else if (chClass === 2) {
        if (wordType === 1) {
          return this._createWord(lineContent, wordType, chClass, chIndex + 1, this._findEndOfWord(lineContent, wordSeparators2, wordType, chIndex + 1));
        }
        wordType = 2;
      } else if (chClass === 1) {
        if (wordType !== 0) {
          return this._createWord(lineContent, wordType, chClass, chIndex + 1, this._findEndOfWord(lineContent, wordSeparators2, wordType, chIndex + 1));
        }
      }
    }
    if (wordType !== 0) {
      return this._createWord(lineContent, wordType, 1, 0, this._findEndOfWord(lineContent, wordSeparators2, wordType, 0));
    }
    return null;
  }
  static _findEndOfWord(lineContent, wordSeparators2, wordType, startIndex) {
    const len = lineContent.length;
    for (let chIndex = startIndex; chIndex < len; chIndex++) {
      const chCode = lineContent.charCodeAt(chIndex);
      const chClass = wordSeparators2.get(chCode);
      if (chClass === 1) {
        return chIndex;
      }
      if (wordType === 1 && chClass === 2) {
        return chIndex;
      }
      if (wordType === 2 && chClass === 0) {
        return chIndex;
      }
    }
    return len;
  }
  static _findNextWordOnLine(wordSeparators2, model, position) {
    const lineContent = model.getLineContent(position.lineNumber);
    return this._doFindNextWordOnLine(lineContent, wordSeparators2, position);
  }
  static _doFindNextWordOnLine(lineContent, wordSeparators2, position) {
    let wordType = 0;
    const len = lineContent.length;
    for (let chIndex = position.column - 1; chIndex < len; chIndex++) {
      const chCode = lineContent.charCodeAt(chIndex);
      const chClass = wordSeparators2.get(chCode);
      if (chClass === 0) {
        if (wordType === 2) {
          return this._createWord(lineContent, wordType, chClass, this._findStartOfWord(lineContent, wordSeparators2, wordType, chIndex - 1), chIndex);
        }
        wordType = 1;
      } else if (chClass === 2) {
        if (wordType === 1) {
          return this._createWord(lineContent, wordType, chClass, this._findStartOfWord(lineContent, wordSeparators2, wordType, chIndex - 1), chIndex);
        }
        wordType = 2;
      } else if (chClass === 1) {
        if (wordType !== 0) {
          return this._createWord(lineContent, wordType, chClass, this._findStartOfWord(lineContent, wordSeparators2, wordType, chIndex - 1), chIndex);
        }
      }
    }
    if (wordType !== 0) {
      return this._createWord(lineContent, wordType, 1, this._findStartOfWord(lineContent, wordSeparators2, wordType, len - 1), len);
    }
    return null;
  }
  static _findStartOfWord(lineContent, wordSeparators2, wordType, startIndex) {
    for (let chIndex = startIndex; chIndex >= 0; chIndex--) {
      const chCode = lineContent.charCodeAt(chIndex);
      const chClass = wordSeparators2.get(chCode);
      if (chClass === 1) {
        return chIndex + 1;
      }
      if (wordType === 1 && chClass === 2) {
        return chIndex + 1;
      }
      if (wordType === 2 && chClass === 0) {
        return chIndex + 1;
      }
    }
    return 0;
  }
  static moveWordLeft(wordSeparators2, model, position, wordNavigationType) {
    let lineNumber = position.lineNumber;
    let column = position.column;
    if (column === 1) {
      if (lineNumber > 1) {
        lineNumber = lineNumber - 1;
        column = model.getLineMaxColumn(lineNumber);
      }
    }
    let prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators2, model, new Position$2(lineNumber, column));
    if (wordNavigationType === 0) {
      return new Position$2(lineNumber, prevWordOnLine ? prevWordOnLine.start + 1 : 1);
    }
    if (wordNavigationType === 1) {
      if (prevWordOnLine && prevWordOnLine.wordType === 2 && prevWordOnLine.end - prevWordOnLine.start === 1 && prevWordOnLine.nextCharClass === 0) {
        prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators2, model, new Position$2(lineNumber, prevWordOnLine.start + 1));
      }
      return new Position$2(lineNumber, prevWordOnLine ? prevWordOnLine.start + 1 : 1);
    }
    if (wordNavigationType === 3) {
      while (prevWordOnLine && prevWordOnLine.wordType === 2) {
        prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators2, model, new Position$2(lineNumber, prevWordOnLine.start + 1));
      }
      return new Position$2(lineNumber, prevWordOnLine ? prevWordOnLine.start + 1 : 1);
    }
    if (prevWordOnLine && column <= prevWordOnLine.end + 1) {
      prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators2, model, new Position$2(lineNumber, prevWordOnLine.start + 1));
    }
    return new Position$2(lineNumber, prevWordOnLine ? prevWordOnLine.end + 1 : 1);
  }
  static _moveWordPartLeft(model, position) {
    const lineNumber = position.lineNumber;
    const maxColumn = model.getLineMaxColumn(lineNumber);
    if (position.column === 1) {
      return lineNumber > 1 ? new Position$2(lineNumber - 1, model.getLineMaxColumn(lineNumber - 1)) : position;
    }
    const lineContent = model.getLineContent(lineNumber);
    for (let column = position.column - 1; column > 1; column--) {
      const left = lineContent.charCodeAt(column - 2);
      const right = lineContent.charCodeAt(column - 1);
      if (left === 95 && right !== 95) {
        return new Position$2(lineNumber, column);
      }
      if (left === 45 && right !== 45) {
        return new Position$2(lineNumber, column);
      }
      if ((isLowerAsciiLetter(left) || isAsciiDigit(left)) && isUpperAsciiLetter(right)) {
        return new Position$2(lineNumber, column);
      }
      if (isUpperAsciiLetter(left) && isUpperAsciiLetter(right)) {
        if (column + 1 < maxColumn) {
          const rightRight = lineContent.charCodeAt(column);
          if (isLowerAsciiLetter(rightRight) || isAsciiDigit(rightRight)) {
            return new Position$2(lineNumber, column);
          }
        }
      }
    }
    return new Position$2(lineNumber, 1);
  }
  static moveWordRight(wordSeparators2, model, position, wordNavigationType) {
    let lineNumber = position.lineNumber;
    let column = position.column;
    let movedDown = false;
    if (column === model.getLineMaxColumn(lineNumber)) {
      if (lineNumber < model.getLineCount()) {
        movedDown = true;
        lineNumber = lineNumber + 1;
        column = 1;
      }
    }
    let nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators2, model, new Position$2(lineNumber, column));
    if (wordNavigationType === 2) {
      if (nextWordOnLine && nextWordOnLine.wordType === 2) {
        if (nextWordOnLine.end - nextWordOnLine.start === 1 && nextWordOnLine.nextCharClass === 0) {
          nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators2, model, new Position$2(lineNumber, nextWordOnLine.end + 1));
        }
      }
      if (nextWordOnLine) {
        column = nextWordOnLine.end + 1;
      } else {
        column = model.getLineMaxColumn(lineNumber);
      }
    } else if (wordNavigationType === 3) {
      if (movedDown) {
        column = 0;
      }
      while (nextWordOnLine && (nextWordOnLine.wordType === 2 || nextWordOnLine.start + 1 <= column)) {
        nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators2, model, new Position$2(lineNumber, nextWordOnLine.end + 1));
      }
      if (nextWordOnLine) {
        column = nextWordOnLine.start + 1;
      } else {
        column = model.getLineMaxColumn(lineNumber);
      }
    } else {
      if (nextWordOnLine && !movedDown && column >= nextWordOnLine.start + 1) {
        nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators2, model, new Position$2(lineNumber, nextWordOnLine.end + 1));
      }
      if (nextWordOnLine) {
        column = nextWordOnLine.start + 1;
      } else {
        column = model.getLineMaxColumn(lineNumber);
      }
    }
    return new Position$2(lineNumber, column);
  }
  static _moveWordPartRight(model, position) {
    const lineNumber = position.lineNumber;
    const maxColumn = model.getLineMaxColumn(lineNumber);
    if (position.column === maxColumn) {
      return lineNumber < model.getLineCount() ? new Position$2(lineNumber + 1, 1) : position;
    }
    const lineContent = model.getLineContent(lineNumber);
    for (let column = position.column + 1; column < maxColumn; column++) {
      const left = lineContent.charCodeAt(column - 2);
      const right = lineContent.charCodeAt(column - 1);
      if (left !== 95 && right === 95) {
        return new Position$2(lineNumber, column);
      }
      if (left !== 45 && right === 45) {
        return new Position$2(lineNumber, column);
      }
      if ((isLowerAsciiLetter(left) || isAsciiDigit(left)) && isUpperAsciiLetter(right)) {
        return new Position$2(lineNumber, column);
      }
      if (isUpperAsciiLetter(left) && isUpperAsciiLetter(right)) {
        if (column + 1 < maxColumn) {
          const rightRight = lineContent.charCodeAt(column);
          if (isLowerAsciiLetter(rightRight) || isAsciiDigit(rightRight)) {
            return new Position$2(lineNumber, column);
          }
        }
      }
    }
    return new Position$2(lineNumber, maxColumn);
  }
  static _deleteWordLeftWhitespace(model, position) {
    const lineContent = model.getLineContent(position.lineNumber);
    const startIndex = position.column - 2;
    const lastNonWhitespace = lastNonWhitespaceIndex(lineContent, startIndex);
    if (lastNonWhitespace + 1 < startIndex) {
      return new Range$2(position.lineNumber, lastNonWhitespace + 2, position.lineNumber, position.column);
    }
    return null;
  }
  static deleteWordLeft(ctx, wordNavigationType) {
    const wordSeparators2 = ctx.wordSeparators;
    const model = ctx.model;
    const selection = ctx.selection;
    const whitespaceHeuristics = ctx.whitespaceHeuristics;
    if (!selection.isEmpty()) {
      return selection;
    }
    if (DeleteOperations.isAutoClosingPairDelete(ctx.autoClosingDelete, ctx.autoClosingBrackets, ctx.autoClosingQuotes, ctx.autoClosingPairs.autoClosingPairsOpenByEnd, ctx.model, [ctx.selection], ctx.autoClosedCharacters)) {
      const position2 = ctx.selection.getPosition();
      return new Range$2(position2.lineNumber, position2.column - 1, position2.lineNumber, position2.column + 1);
    }
    const position = new Position$2(selection.positionLineNumber, selection.positionColumn);
    let lineNumber = position.lineNumber;
    let column = position.column;
    if (lineNumber === 1 && column === 1) {
      return null;
    }
    if (whitespaceHeuristics) {
      const r = this._deleteWordLeftWhitespace(model, position);
      if (r) {
        return r;
      }
    }
    let prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators2, model, position);
    if (wordNavigationType === 0) {
      if (prevWordOnLine) {
        column = prevWordOnLine.start + 1;
      } else {
        if (column > 1) {
          column = 1;
        } else {
          lineNumber--;
          column = model.getLineMaxColumn(lineNumber);
        }
      }
    } else {
      if (prevWordOnLine && column <= prevWordOnLine.end + 1) {
        prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators2, model, new Position$2(lineNumber, prevWordOnLine.start + 1));
      }
      if (prevWordOnLine) {
        column = prevWordOnLine.end + 1;
      } else {
        if (column > 1) {
          column = 1;
        } else {
          lineNumber--;
          column = model.getLineMaxColumn(lineNumber);
        }
      }
    }
    return new Range$2(lineNumber, column, position.lineNumber, position.column);
  }
  static deleteInsideWord(wordSeparators2, model, selection) {
    if (!selection.isEmpty()) {
      return selection;
    }
    const position = new Position$2(selection.positionLineNumber, selection.positionColumn);
    const r = this._deleteInsideWordWhitespace(model, position);
    if (r) {
      return r;
    }
    return this._deleteInsideWordDetermineDeleteRange(wordSeparators2, model, position);
  }
  static _charAtIsWhitespace(str2, index) {
    const charCode = str2.charCodeAt(index);
    return charCode === 32 || charCode === 9;
  }
  static _deleteInsideWordWhitespace(model, position) {
    const lineContent = model.getLineContent(position.lineNumber);
    const lineContentLength = lineContent.length;
    if (lineContentLength === 0) {
      return null;
    }
    let leftIndex = Math.max(position.column - 2, 0);
    if (!this._charAtIsWhitespace(lineContent, leftIndex)) {
      return null;
    }
    let rightIndex = Math.min(position.column - 1, lineContentLength - 1);
    if (!this._charAtIsWhitespace(lineContent, rightIndex)) {
      return null;
    }
    while (leftIndex > 0 && this._charAtIsWhitespace(lineContent, leftIndex - 1)) {
      leftIndex--;
    }
    while (rightIndex + 1 < lineContentLength && this._charAtIsWhitespace(lineContent, rightIndex + 1)) {
      rightIndex++;
    }
    return new Range$2(position.lineNumber, leftIndex + 1, position.lineNumber, rightIndex + 2);
  }
  static _deleteInsideWordDetermineDeleteRange(wordSeparators2, model, position) {
    const lineContent = model.getLineContent(position.lineNumber);
    const lineLength = lineContent.length;
    if (lineLength === 0) {
      if (position.lineNumber > 1) {
        return new Range$2(position.lineNumber - 1, model.getLineMaxColumn(position.lineNumber - 1), position.lineNumber, 1);
      } else {
        if (position.lineNumber < model.getLineCount()) {
          return new Range$2(position.lineNumber, 1, position.lineNumber + 1, 1);
        } else {
          return new Range$2(position.lineNumber, 1, position.lineNumber, 1);
        }
      }
    }
    const touchesWord = (word2) => {
      return word2.start + 1 <= position.column && position.column <= word2.end + 1;
    };
    const createRangeWithPosition = (startColumn, endColumn) => {
      startColumn = Math.min(startColumn, position.column);
      endColumn = Math.max(endColumn, position.column);
      return new Range$2(position.lineNumber, startColumn, position.lineNumber, endColumn);
    };
    const deleteWordAndAdjacentWhitespace = (word2) => {
      let startColumn = word2.start + 1;
      let endColumn = word2.end + 1;
      let expandedToTheRight = false;
      while (endColumn - 1 < lineLength && this._charAtIsWhitespace(lineContent, endColumn - 1)) {
        expandedToTheRight = true;
        endColumn++;
      }
      if (!expandedToTheRight) {
        while (startColumn > 1 && this._charAtIsWhitespace(lineContent, startColumn - 2)) {
          startColumn--;
        }
      }
      return createRangeWithPosition(startColumn, endColumn);
    };
    const prevWordOnLine = WordOperations._findPreviousWordOnLine(wordSeparators2, model, position);
    if (prevWordOnLine && touchesWord(prevWordOnLine)) {
      return deleteWordAndAdjacentWhitespace(prevWordOnLine);
    }
    const nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators2, model, position);
    if (nextWordOnLine && touchesWord(nextWordOnLine)) {
      return deleteWordAndAdjacentWhitespace(nextWordOnLine);
    }
    if (prevWordOnLine && nextWordOnLine) {
      return createRangeWithPosition(prevWordOnLine.end + 1, nextWordOnLine.start + 1);
    }
    if (prevWordOnLine) {
      return createRangeWithPosition(prevWordOnLine.start + 1, prevWordOnLine.end + 1);
    }
    if (nextWordOnLine) {
      return createRangeWithPosition(nextWordOnLine.start + 1, nextWordOnLine.end + 1);
    }
    return createRangeWithPosition(1, lineLength + 1);
  }
  static _deleteWordPartLeft(model, selection) {
    if (!selection.isEmpty()) {
      return selection;
    }
    const pos = selection.getPosition();
    const toPosition = WordOperations._moveWordPartLeft(model, pos);
    return new Range$2(pos.lineNumber, pos.column, toPosition.lineNumber, toPosition.column);
  }
  static _findFirstNonWhitespaceChar(str2, startIndex) {
    const len = str2.length;
    for (let chIndex = startIndex; chIndex < len; chIndex++) {
      const ch = str2.charAt(chIndex);
      if (ch !== " " && ch !== "	") {
        return chIndex;
      }
    }
    return len;
  }
  static _deleteWordRightWhitespace(model, position) {
    const lineContent = model.getLineContent(position.lineNumber);
    const startIndex = position.column - 1;
    const firstNonWhitespace = this._findFirstNonWhitespaceChar(lineContent, startIndex);
    if (startIndex + 1 < firstNonWhitespace) {
      return new Range$2(position.lineNumber, position.column, position.lineNumber, firstNonWhitespace + 1);
    }
    return null;
  }
  static deleteWordRight(ctx, wordNavigationType) {
    const wordSeparators2 = ctx.wordSeparators;
    const model = ctx.model;
    const selection = ctx.selection;
    const whitespaceHeuristics = ctx.whitespaceHeuristics;
    if (!selection.isEmpty()) {
      return selection;
    }
    const position = new Position$2(selection.positionLineNumber, selection.positionColumn);
    let lineNumber = position.lineNumber;
    let column = position.column;
    const lineCount = model.getLineCount();
    const maxColumn = model.getLineMaxColumn(lineNumber);
    if (lineNumber === lineCount && column === maxColumn) {
      return null;
    }
    if (whitespaceHeuristics) {
      const r = this._deleteWordRightWhitespace(model, position);
      if (r) {
        return r;
      }
    }
    let nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators2, model, position);
    if (wordNavigationType === 2) {
      if (nextWordOnLine) {
        column = nextWordOnLine.end + 1;
      } else {
        if (column < maxColumn || lineNumber === lineCount) {
          column = maxColumn;
        } else {
          lineNumber++;
          nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators2, model, new Position$2(lineNumber, 1));
          if (nextWordOnLine) {
            column = nextWordOnLine.start + 1;
          } else {
            column = model.getLineMaxColumn(lineNumber);
          }
        }
      }
    } else {
      if (nextWordOnLine && column >= nextWordOnLine.start + 1) {
        nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators2, model, new Position$2(lineNumber, nextWordOnLine.end + 1));
      }
      if (nextWordOnLine) {
        column = nextWordOnLine.start + 1;
      } else {
        if (column < maxColumn || lineNumber === lineCount) {
          column = maxColumn;
        } else {
          lineNumber++;
          nextWordOnLine = WordOperations._findNextWordOnLine(wordSeparators2, model, new Position$2(lineNumber, 1));
          if (nextWordOnLine) {
            column = nextWordOnLine.start + 1;
          } else {
            column = model.getLineMaxColumn(lineNumber);
          }
        }
      }
    }
    return new Range$2(lineNumber, column, position.lineNumber, position.column);
  }
  static _deleteWordPartRight(model, selection) {
    if (!selection.isEmpty()) {
      return selection;
    }
    const pos = selection.getPosition();
    const toPosition = WordOperations._moveWordPartRight(model, pos);
    return new Range$2(pos.lineNumber, pos.column, toPosition.lineNumber, toPosition.column);
  }
  static _createWordAtPosition(model, lineNumber, word2) {
    const range2 = new Range$2(lineNumber, word2.start + 1, lineNumber, word2.end + 1);
    return {
      word: model.getValueInRange(range2),
      startColumn: range2.startColumn,
      endColumn: range2.endColumn
    };
  }
  static getWordAtPosition(model, _wordSeparators, position) {
    const wordSeparators2 = getMapForWordSeparators(_wordSeparators);
    const prevWord = WordOperations._findPreviousWordOnLine(wordSeparators2, model, position);
    if (prevWord && prevWord.wordType === 1 && prevWord.start <= position.column - 1 && position.column - 1 <= prevWord.end) {
      return WordOperations._createWordAtPosition(model, position.lineNumber, prevWord);
    }
    const nextWord2 = WordOperations._findNextWordOnLine(wordSeparators2, model, position);
    if (nextWord2 && nextWord2.wordType === 1 && nextWord2.start <= position.column - 1 && position.column - 1 <= nextWord2.end) {
      return WordOperations._createWordAtPosition(model, position.lineNumber, nextWord2);
    }
    return null;
  }
  static word(config2, model, cursor, inSelectionMode, position) {
    const wordSeparators2 = getMapForWordSeparators(config2.wordSeparators);
    const prevWord = WordOperations._findPreviousWordOnLine(wordSeparators2, model, position);
    const nextWord2 = WordOperations._findNextWordOnLine(wordSeparators2, model, position);
    if (!inSelectionMode) {
      let startColumn2;
      let endColumn2;
      if (prevWord && prevWord.wordType === 1 && prevWord.start <= position.column - 1 && position.column - 1 <= prevWord.end) {
        startColumn2 = prevWord.start + 1;
        endColumn2 = prevWord.end + 1;
      } else if (nextWord2 && nextWord2.wordType === 1 && nextWord2.start <= position.column - 1 && position.column - 1 <= nextWord2.end) {
        startColumn2 = nextWord2.start + 1;
        endColumn2 = nextWord2.end + 1;
      } else {
        if (prevWord) {
          startColumn2 = prevWord.end + 1;
        } else {
          startColumn2 = 1;
        }
        if (nextWord2) {
          endColumn2 = nextWord2.start + 1;
        } else {
          endColumn2 = model.getLineMaxColumn(position.lineNumber);
        }
      }
      return new SingleCursorState(new Range$2(position.lineNumber, startColumn2, position.lineNumber, endColumn2), 1, 0, new Position$2(position.lineNumber, endColumn2), 0);
    }
    let startColumn;
    let endColumn;
    if (prevWord && prevWord.wordType === 1 && prevWord.start < position.column - 1 && position.column - 1 < prevWord.end) {
      startColumn = prevWord.start + 1;
      endColumn = prevWord.end + 1;
    } else if (nextWord2 && nextWord2.wordType === 1 && nextWord2.start < position.column - 1 && position.column - 1 < nextWord2.end) {
      startColumn = nextWord2.start + 1;
      endColumn = nextWord2.end + 1;
    } else {
      startColumn = position.column;
      endColumn = position.column;
    }
    const lineNumber = position.lineNumber;
    let column;
    if (cursor.selectionStart.containsPosition(position)) {
      column = cursor.selectionStart.endColumn;
    } else if (position.isBeforeOrEqual(cursor.selectionStart.getStartPosition())) {
      column = startColumn;
      const possiblePosition = new Position$2(lineNumber, column);
      if (cursor.selectionStart.containsPosition(possiblePosition)) {
        column = cursor.selectionStart.endColumn;
      }
    } else {
      column = endColumn;
      const possiblePosition = new Position$2(lineNumber, column);
      if (cursor.selectionStart.containsPosition(possiblePosition)) {
        column = cursor.selectionStart.startColumn;
      }
    }
    return cursor.move(true, lineNumber, column, 0);
  }
}
class WordPartOperations extends WordOperations {
  static deleteWordPartLeft(ctx) {
    const candidates = enforceDefined([
      WordOperations.deleteWordLeft(
        ctx,
        0
        /* WordNavigationType.WordStart */
      ),
      WordOperations.deleteWordLeft(
        ctx,
        2
        /* WordNavigationType.WordEnd */
      ),
      WordOperations._deleteWordPartLeft(ctx.model, ctx.selection)
    ]);
    candidates.sort(Range$2.compareRangesUsingEnds);
    return candidates[2];
  }
  static deleteWordPartRight(ctx) {
    const candidates = enforceDefined([
      WordOperations.deleteWordRight(
        ctx,
        0
        /* WordNavigationType.WordStart */
      ),
      WordOperations.deleteWordRight(
        ctx,
        2
        /* WordNavigationType.WordEnd */
      ),
      WordOperations._deleteWordPartRight(ctx.model, ctx.selection)
    ]);
    candidates.sort(Range$2.compareRangesUsingStarts);
    return candidates[0];
  }
  static moveWordPartLeft(wordSeparators2, model, position) {
    const candidates = enforceDefined([
      WordOperations.moveWordLeft(
        wordSeparators2,
        model,
        position,
        0
        /* WordNavigationType.WordStart */
      ),
      WordOperations.moveWordLeft(
        wordSeparators2,
        model,
        position,
        2
        /* WordNavigationType.WordEnd */
      ),
      WordOperations._moveWordPartLeft(model, position)
    ]);
    candidates.sort(Position$2.compare);
    return candidates[2];
  }
  static moveWordPartRight(wordSeparators2, model, position) {
    const candidates = enforceDefined([
      WordOperations.moveWordRight(
        wordSeparators2,
        model,
        position,
        0
        /* WordNavigationType.WordStart */
      ),
      WordOperations.moveWordRight(
        wordSeparators2,
        model,
        position,
        2
        /* WordNavigationType.WordEnd */
      ),
      WordOperations._moveWordPartRight(model, position)
    ]);
    candidates.sort(Position$2.compare);
    return candidates[0];
  }
}
function enforceDefined(arr) {
  return arr.filter((el) => Boolean(el));
}
class CursorMoveCommands {
  static addCursorDown(viewModel, cursors, useLogicalLine) {
    const result2 = [];
    let resultLen = 0;
    for (let i = 0, len = cursors.length; i < len; i++) {
      const cursor = cursors[i];
      result2[resultLen++] = new CursorState$1(cursor.modelState, cursor.viewState);
      if (useLogicalLine) {
        result2[resultLen++] = CursorState$1.fromModelState(MoveOperations.translateDown(viewModel.cursorConfig, viewModel.model, cursor.modelState));
      } else {
        result2[resultLen++] = CursorState$1.fromViewState(MoveOperations.translateDown(viewModel.cursorConfig, viewModel, cursor.viewState));
      }
    }
    return result2;
  }
  static addCursorUp(viewModel, cursors, useLogicalLine) {
    const result2 = [];
    let resultLen = 0;
    for (let i = 0, len = cursors.length; i < len; i++) {
      const cursor = cursors[i];
      result2[resultLen++] = new CursorState$1(cursor.modelState, cursor.viewState);
      if (useLogicalLine) {
        result2[resultLen++] = CursorState$1.fromModelState(MoveOperations.translateUp(viewModel.cursorConfig, viewModel.model, cursor.modelState));
      } else {
        result2[resultLen++] = CursorState$1.fromViewState(MoveOperations.translateUp(viewModel.cursorConfig, viewModel, cursor.viewState));
      }
    }
    return result2;
  }
  static moveToBeginningOfLine(viewModel, cursors, inSelectionMode) {
    const result2 = [];
    for (let i = 0, len = cursors.length; i < len; i++) {
      const cursor = cursors[i];
      result2[i] = this._moveToLineStart(viewModel, cursor, inSelectionMode);
    }
    return result2;
  }
  static _moveToLineStart(viewModel, cursor, inSelectionMode) {
    const currentViewStateColumn = cursor.viewState.position.column;
    const currentModelStateColumn = cursor.modelState.position.column;
    const isFirstLineOfWrappedLine = currentViewStateColumn === currentModelStateColumn;
    const currentViewStatelineNumber = cursor.viewState.position.lineNumber;
    const firstNonBlankColumn = viewModel.getLineFirstNonWhitespaceColumn(currentViewStatelineNumber);
    const isBeginningOfViewLine = currentViewStateColumn === firstNonBlankColumn;
    if (!isFirstLineOfWrappedLine && !isBeginningOfViewLine) {
      return this._moveToLineStartByView(viewModel, cursor, inSelectionMode);
    } else {
      return this._moveToLineStartByModel(viewModel, cursor, inSelectionMode);
    }
  }
  static _moveToLineStartByView(viewModel, cursor, inSelectionMode) {
    return CursorState$1.fromViewState(MoveOperations.moveToBeginningOfLine(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode));
  }
  static _moveToLineStartByModel(viewModel, cursor, inSelectionMode) {
    return CursorState$1.fromModelState(MoveOperations.moveToBeginningOfLine(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode));
  }
  static moveToEndOfLine(viewModel, cursors, inSelectionMode, sticky) {
    const result2 = [];
    for (let i = 0, len = cursors.length; i < len; i++) {
      const cursor = cursors[i];
      result2[i] = this._moveToLineEnd(viewModel, cursor, inSelectionMode, sticky);
    }
    return result2;
  }
  static _moveToLineEnd(viewModel, cursor, inSelectionMode, sticky) {
    const viewStatePosition = cursor.viewState.position;
    const viewModelMaxColumn = viewModel.getLineMaxColumn(viewStatePosition.lineNumber);
    const isEndOfViewLine = viewStatePosition.column === viewModelMaxColumn;
    const modelStatePosition = cursor.modelState.position;
    const modelMaxColumn = viewModel.model.getLineMaxColumn(modelStatePosition.lineNumber);
    const isEndLineOfWrappedLine = viewModelMaxColumn - viewStatePosition.column === modelMaxColumn - modelStatePosition.column;
    if (isEndOfViewLine || isEndLineOfWrappedLine) {
      return this._moveToLineEndByModel(viewModel, cursor, inSelectionMode, sticky);
    } else {
      return this._moveToLineEndByView(viewModel, cursor, inSelectionMode, sticky);
    }
  }
  static _moveToLineEndByView(viewModel, cursor, inSelectionMode, sticky) {
    return CursorState$1.fromViewState(MoveOperations.moveToEndOfLine(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, sticky));
  }
  static _moveToLineEndByModel(viewModel, cursor, inSelectionMode, sticky) {
    return CursorState$1.fromModelState(MoveOperations.moveToEndOfLine(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode, sticky));
  }
  static expandLineSelection(viewModel, cursors) {
    const result2 = [];
    for (let i = 0, len = cursors.length; i < len; i++) {
      const cursor = cursors[i];
      const startLineNumber = cursor.modelState.selection.startLineNumber;
      const lineCount = viewModel.model.getLineCount();
      let endLineNumber = cursor.modelState.selection.endLineNumber;
      let endColumn;
      if (endLineNumber === lineCount) {
        endColumn = viewModel.model.getLineMaxColumn(lineCount);
      } else {
        endLineNumber++;
        endColumn = 1;
      }
      result2[i] = CursorState$1.fromModelState(new SingleCursorState(new Range$2(startLineNumber, 1, startLineNumber, 1), 0, 0, new Position$2(endLineNumber, endColumn), 0));
    }
    return result2;
  }
  static moveToBeginningOfBuffer(viewModel, cursors, inSelectionMode) {
    const result2 = [];
    for (let i = 0, len = cursors.length; i < len; i++) {
      const cursor = cursors[i];
      result2[i] = CursorState$1.fromModelState(MoveOperations.moveToBeginningOfBuffer(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode));
    }
    return result2;
  }
  static moveToEndOfBuffer(viewModel, cursors, inSelectionMode) {
    const result2 = [];
    for (let i = 0, len = cursors.length; i < len; i++) {
      const cursor = cursors[i];
      result2[i] = CursorState$1.fromModelState(MoveOperations.moveToEndOfBuffer(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode));
    }
    return result2;
  }
  static selectAll(viewModel, cursor) {
    const lineCount = viewModel.model.getLineCount();
    const maxColumn = viewModel.model.getLineMaxColumn(lineCount);
    return CursorState$1.fromModelState(new SingleCursorState(new Range$2(1, 1, 1, 1), 0, 0, new Position$2(lineCount, maxColumn), 0));
  }
  static line(viewModel, cursor, inSelectionMode, _position, _viewPosition) {
    const position = viewModel.model.validatePosition(_position);
    const viewPosition = _viewPosition ? viewModel.coordinatesConverter.validateViewPosition(new Position$2(_viewPosition.lineNumber, _viewPosition.column), position) : viewModel.coordinatesConverter.convertModelPositionToViewPosition(position);
    if (!inSelectionMode) {
      const lineCount = viewModel.model.getLineCount();
      let selectToLineNumber = position.lineNumber + 1;
      let selectToColumn = 1;
      if (selectToLineNumber > lineCount) {
        selectToLineNumber = lineCount;
        selectToColumn = viewModel.model.getLineMaxColumn(selectToLineNumber);
      }
      return CursorState$1.fromModelState(new SingleCursorState(new Range$2(position.lineNumber, 1, selectToLineNumber, selectToColumn), 2, 0, new Position$2(selectToLineNumber, selectToColumn), 0));
    }
    const enteringLineNumber = cursor.modelState.selectionStart.getStartPosition().lineNumber;
    if (position.lineNumber < enteringLineNumber) {
      return CursorState$1.fromViewState(cursor.viewState.move(true, viewPosition.lineNumber, 1, 0));
    } else if (position.lineNumber > enteringLineNumber) {
      const lineCount = viewModel.getLineCount();
      let selectToViewLineNumber = viewPosition.lineNumber + 1;
      let selectToViewColumn = 1;
      if (selectToViewLineNumber > lineCount) {
        selectToViewLineNumber = lineCount;
        selectToViewColumn = viewModel.getLineMaxColumn(selectToViewLineNumber);
      }
      return CursorState$1.fromViewState(cursor.viewState.move(true, selectToViewLineNumber, selectToViewColumn, 0));
    } else {
      const endPositionOfSelectionStart = cursor.modelState.selectionStart.getEndPosition();
      return CursorState$1.fromModelState(cursor.modelState.move(true, endPositionOfSelectionStart.lineNumber, endPositionOfSelectionStart.column, 0));
    }
  }
  static word(viewModel, cursor, inSelectionMode, _position) {
    const position = viewModel.model.validatePosition(_position);
    return CursorState$1.fromModelState(WordOperations.word(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode, position));
  }
  static cancelSelection(viewModel, cursor) {
    if (!cursor.modelState.hasSelection()) {
      return new CursorState$1(cursor.modelState, cursor.viewState);
    }
    const lineNumber = cursor.viewState.position.lineNumber;
    const column = cursor.viewState.position.column;
    return CursorState$1.fromViewState(new SingleCursorState(new Range$2(lineNumber, column, lineNumber, column), 0, 0, new Position$2(lineNumber, column), 0));
  }
  static moveTo(viewModel, cursor, inSelectionMode, _position, _viewPosition) {
    if (inSelectionMode) {
      if (cursor.modelState.selectionStartKind === 1) {
        return this.word(viewModel, cursor, inSelectionMode, _position);
      }
      if (cursor.modelState.selectionStartKind === 2) {
        return this.line(viewModel, cursor, inSelectionMode, _position, _viewPosition);
      }
    }
    const position = viewModel.model.validatePosition(_position);
    const viewPosition = _viewPosition ? viewModel.coordinatesConverter.validateViewPosition(new Position$2(_viewPosition.lineNumber, _viewPosition.column), position) : viewModel.coordinatesConverter.convertModelPositionToViewPosition(position);
    return CursorState$1.fromViewState(cursor.viewState.move(inSelectionMode, viewPosition.lineNumber, viewPosition.column, 0));
  }
  static simpleMove(viewModel, cursors, direction, inSelectionMode, value, unit) {
    switch (direction) {
      case 0: {
        if (unit === 4) {
          return this._moveHalfLineLeft(viewModel, cursors, inSelectionMode);
        } else {
          return this._moveLeft(viewModel, cursors, inSelectionMode, value);
        }
      }
      case 1: {
        if (unit === 4) {
          return this._moveHalfLineRight(viewModel, cursors, inSelectionMode);
        } else {
          return this._moveRight(viewModel, cursors, inSelectionMode, value);
        }
      }
      case 2: {
        if (unit === 2) {
          return this._moveUpByViewLines(viewModel, cursors, inSelectionMode, value);
        } else {
          return this._moveUpByModelLines(viewModel, cursors, inSelectionMode, value);
        }
      }
      case 3: {
        if (unit === 2) {
          return this._moveDownByViewLines(viewModel, cursors, inSelectionMode, value);
        } else {
          return this._moveDownByModelLines(viewModel, cursors, inSelectionMode, value);
        }
      }
      case 4: {
        if (unit === 2) {
          return cursors.map((cursor) => CursorState$1.fromViewState(MoveOperations.moveToPrevBlankLine(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode)));
        } else {
          return cursors.map((cursor) => CursorState$1.fromModelState(MoveOperations.moveToPrevBlankLine(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode)));
        }
      }
      case 5: {
        if (unit === 2) {
          return cursors.map((cursor) => CursorState$1.fromViewState(MoveOperations.moveToNextBlankLine(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode)));
        } else {
          return cursors.map((cursor) => CursorState$1.fromModelState(MoveOperations.moveToNextBlankLine(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode)));
        }
      }
      case 6: {
        return this._moveToViewMinColumn(viewModel, cursors, inSelectionMode);
      }
      case 7: {
        return this._moveToViewFirstNonWhitespaceColumn(viewModel, cursors, inSelectionMode);
      }
      case 8: {
        return this._moveToViewCenterColumn(viewModel, cursors, inSelectionMode);
      }
      case 9: {
        return this._moveToViewMaxColumn(viewModel, cursors, inSelectionMode);
      }
      case 10: {
        return this._moveToViewLastNonWhitespaceColumn(viewModel, cursors, inSelectionMode);
      }
      default:
        return null;
    }
  }
  static viewportMove(viewModel, cursors, direction, inSelectionMode, value) {
    const visibleViewRange = viewModel.getCompletelyVisibleViewRange();
    const visibleModelRange = viewModel.coordinatesConverter.convertViewRangeToModelRange(visibleViewRange);
    switch (direction) {
      case 11: {
        const modelLineNumber = this._firstLineNumberInRange(viewModel.model, visibleModelRange, value);
        const modelColumn = viewModel.model.getLineFirstNonWhitespaceColumn(modelLineNumber);
        return [this._moveToModelPosition(viewModel, cursors[0], inSelectionMode, modelLineNumber, modelColumn)];
      }
      case 13: {
        const modelLineNumber = this._lastLineNumberInRange(viewModel.model, visibleModelRange, value);
        const modelColumn = viewModel.model.getLineFirstNonWhitespaceColumn(modelLineNumber);
        return [this._moveToModelPosition(viewModel, cursors[0], inSelectionMode, modelLineNumber, modelColumn)];
      }
      case 12: {
        const modelLineNumber = Math.round((visibleModelRange.startLineNumber + visibleModelRange.endLineNumber) / 2);
        const modelColumn = viewModel.model.getLineFirstNonWhitespaceColumn(modelLineNumber);
        return [this._moveToModelPosition(viewModel, cursors[0], inSelectionMode, modelLineNumber, modelColumn)];
      }
      case 14: {
        const result2 = [];
        for (let i = 0, len = cursors.length; i < len; i++) {
          const cursor = cursors[i];
          result2[i] = this.findPositionInViewportIfOutside(viewModel, cursor, visibleViewRange, inSelectionMode);
        }
        return result2;
      }
      default:
        return null;
    }
  }
  static findPositionInViewportIfOutside(viewModel, cursor, visibleViewRange, inSelectionMode) {
    const viewLineNumber = cursor.viewState.position.lineNumber;
    if (visibleViewRange.startLineNumber <= viewLineNumber && viewLineNumber <= visibleViewRange.endLineNumber - 1) {
      return new CursorState$1(cursor.modelState, cursor.viewState);
    } else {
      let newViewLineNumber;
      if (viewLineNumber > visibleViewRange.endLineNumber - 1) {
        newViewLineNumber = visibleViewRange.endLineNumber - 1;
      } else if (viewLineNumber < visibleViewRange.startLineNumber) {
        newViewLineNumber = visibleViewRange.startLineNumber;
      } else {
        newViewLineNumber = viewLineNumber;
      }
      const position = MoveOperations.vertical(viewModel.cursorConfig, viewModel, viewLineNumber, cursor.viewState.position.column, cursor.viewState.leftoverVisibleColumns, newViewLineNumber, false);
      return CursorState$1.fromViewState(cursor.viewState.move(inSelectionMode, position.lineNumber, position.column, position.leftoverVisibleColumns));
    }
  }
  /**
   * Find the nth line start included in the range (from the start).
   */
  static _firstLineNumberInRange(model, range2, count) {
    let startLineNumber = range2.startLineNumber;
    if (range2.startColumn !== model.getLineMinColumn(startLineNumber)) {
      startLineNumber++;
    }
    return Math.min(range2.endLineNumber, startLineNumber + count - 1);
  }
  /**
   * Find the nth line start included in the range (from the end).
   */
  static _lastLineNumberInRange(model, range2, count) {
    let startLineNumber = range2.startLineNumber;
    if (range2.startColumn !== model.getLineMinColumn(startLineNumber)) {
      startLineNumber++;
    }
    return Math.max(startLineNumber, range2.endLineNumber - count + 1);
  }
  static _moveLeft(viewModel, cursors, inSelectionMode, noOfColumns) {
    return cursors.map((cursor) => CursorState$1.fromViewState(MoveOperations.moveLeft(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, noOfColumns)));
  }
  static _moveHalfLineLeft(viewModel, cursors, inSelectionMode) {
    const result2 = [];
    for (let i = 0, len = cursors.length; i < len; i++) {
      const cursor = cursors[i];
      const viewLineNumber = cursor.viewState.position.lineNumber;
      const halfLine = Math.round(viewModel.getLineContent(viewLineNumber).length / 2);
      result2[i] = CursorState$1.fromViewState(MoveOperations.moveLeft(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, halfLine));
    }
    return result2;
  }
  static _moveRight(viewModel, cursors, inSelectionMode, noOfColumns) {
    return cursors.map((cursor) => CursorState$1.fromViewState(MoveOperations.moveRight(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, noOfColumns)));
  }
  static _moveHalfLineRight(viewModel, cursors, inSelectionMode) {
    const result2 = [];
    for (let i = 0, len = cursors.length; i < len; i++) {
      const cursor = cursors[i];
      const viewLineNumber = cursor.viewState.position.lineNumber;
      const halfLine = Math.round(viewModel.getLineContent(viewLineNumber).length / 2);
      result2[i] = CursorState$1.fromViewState(MoveOperations.moveRight(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, halfLine));
    }
    return result2;
  }
  static _moveDownByViewLines(viewModel, cursors, inSelectionMode, linesCount) {
    const result2 = [];
    for (let i = 0, len = cursors.length; i < len; i++) {
      const cursor = cursors[i];
      result2[i] = CursorState$1.fromViewState(MoveOperations.moveDown(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, linesCount));
    }
    return result2;
  }
  static _moveDownByModelLines(viewModel, cursors, inSelectionMode, linesCount) {
    const result2 = [];
    for (let i = 0, len = cursors.length; i < len; i++) {
      const cursor = cursors[i];
      result2[i] = CursorState$1.fromModelState(MoveOperations.moveDown(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode, linesCount));
    }
    return result2;
  }
  static _moveUpByViewLines(viewModel, cursors, inSelectionMode, linesCount) {
    const result2 = [];
    for (let i = 0, len = cursors.length; i < len; i++) {
      const cursor = cursors[i];
      result2[i] = CursorState$1.fromViewState(MoveOperations.moveUp(viewModel.cursorConfig, viewModel, cursor.viewState, inSelectionMode, linesCount));
    }
    return result2;
  }
  static _moveUpByModelLines(viewModel, cursors, inSelectionMode, linesCount) {
    const result2 = [];
    for (let i = 0, len = cursors.length; i < len; i++) {
      const cursor = cursors[i];
      result2[i] = CursorState$1.fromModelState(MoveOperations.moveUp(viewModel.cursorConfig, viewModel.model, cursor.modelState, inSelectionMode, linesCount));
    }
    return result2;
  }
  static _moveToViewPosition(viewModel, cursor, inSelectionMode, toViewLineNumber, toViewColumn) {
    return CursorState$1.fromViewState(cursor.viewState.move(inSelectionMode, toViewLineNumber, toViewColumn, 0));
  }
  static _moveToModelPosition(viewModel, cursor, inSelectionMode, toModelLineNumber, toModelColumn) {
    return CursorState$1.fromModelState(cursor.modelState.move(inSelectionMode, toModelLineNumber, toModelColumn, 0));
  }
  static _moveToViewMinColumn(viewModel, cursors, inSelectionMode) {
    const result2 = [];
    for (let i = 0, len = cursors.length; i < len; i++) {
      const cursor = cursors[i];
      const viewLineNumber = cursor.viewState.position.lineNumber;
      const viewColumn = viewModel.getLineMinColumn(viewLineNumber);
      result2[i] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn);
    }
    return result2;
  }
  static _moveToViewFirstNonWhitespaceColumn(viewModel, cursors, inSelectionMode) {
    const result2 = [];
    for (let i = 0, len = cursors.length; i < len; i++) {
      const cursor = cursors[i];
      const viewLineNumber = cursor.viewState.position.lineNumber;
      const viewColumn = viewModel.getLineFirstNonWhitespaceColumn(viewLineNumber);
      result2[i] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn);
    }
    return result2;
  }
  static _moveToViewCenterColumn(viewModel, cursors, inSelectionMode) {
    const result2 = [];
    for (let i = 0, len = cursors.length; i < len; i++) {
      const cursor = cursors[i];
      const viewLineNumber = cursor.viewState.position.lineNumber;
      const viewColumn = Math.round((viewModel.getLineMaxColumn(viewLineNumber) + viewModel.getLineMinColumn(viewLineNumber)) / 2);
      result2[i] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn);
    }
    return result2;
  }
  static _moveToViewMaxColumn(viewModel, cursors, inSelectionMode) {
    const result2 = [];
    for (let i = 0, len = cursors.length; i < len; i++) {
      const cursor = cursors[i];
      const viewLineNumber = cursor.viewState.position.lineNumber;
      const viewColumn = viewModel.getLineMaxColumn(viewLineNumber);
      result2[i] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn);
    }
    return result2;
  }
  static _moveToViewLastNonWhitespaceColumn(viewModel, cursors, inSelectionMode) {
    const result2 = [];
    for (let i = 0, len = cursors.length; i < len; i++) {
      const cursor = cursors[i];
      const viewLineNumber = cursor.viewState.position.lineNumber;
      const viewColumn = viewModel.getLineLastNonWhitespaceColumn(viewLineNumber);
      result2[i] = this._moveToViewPosition(viewModel, cursor, inSelectionMode, viewLineNumber, viewColumn);
    }
    return result2;
  }
}
var CursorMove;
(function(CursorMove2) {
  const isCursorMoveArgs = function(arg) {
    if (!isObject$4(arg)) {
      return false;
    }
    const cursorMoveArg = arg;
    if (!isString$4(cursorMoveArg.to)) {
      return false;
    }
    if (!isUndefined$1(cursorMoveArg.select) && !isBoolean$1(cursorMoveArg.select)) {
      return false;
    }
    if (!isUndefined$1(cursorMoveArg.by) && !isString$4(cursorMoveArg.by)) {
      return false;
    }
    if (!isUndefined$1(cursorMoveArg.value) && !isNumber$3(cursorMoveArg.value)) {
      return false;
    }
    return true;
  };
  CursorMove2.description = {
    description: "Move cursor to a logical position in the view",
    args: [
      {
        name: "Cursor move argument object",
        description: `Property-value pairs that can be passed through this argument:
					* 'to': A mandatory logical position value providing where to move the cursor.
						\`\`\`
						'left', 'right', 'up', 'down', 'prevBlankLine', 'nextBlankLine',
						'wrappedLineStart', 'wrappedLineEnd', 'wrappedLineColumnCenter'
						'wrappedLineFirstNonWhitespaceCharacter', 'wrappedLineLastNonWhitespaceCharacter'
						'viewPortTop', 'viewPortCenter', 'viewPortBottom', 'viewPortIfOutside'
						\`\`\`
					* 'by': Unit to move. Default is computed based on 'to' value.
						\`\`\`
						'line', 'wrappedLine', 'character', 'halfLine'
						\`\`\`
					* 'value': Number of units to move. Default is '1'.
					* 'select': If 'true' makes the selection. Default is 'false'.
				`,
        constraint: isCursorMoveArgs,
        schema: {
          "type": "object",
          "required": ["to"],
          "properties": {
            "to": {
              "type": "string",
              "enum": ["left", "right", "up", "down", "prevBlankLine", "nextBlankLine", "wrappedLineStart", "wrappedLineEnd", "wrappedLineColumnCenter", "wrappedLineFirstNonWhitespaceCharacter", "wrappedLineLastNonWhitespaceCharacter", "viewPortTop", "viewPortCenter", "viewPortBottom", "viewPortIfOutside"]
            },
            "by": {
              "type": "string",
              "enum": ["line", "wrappedLine", "character", "halfLine"]
            },
            "value": {
              "type": "number",
              "default": 1
            },
            "select": {
              "type": "boolean",
              "default": false
            }
          }
        }
      }
    ]
  };
  CursorMove2.RawDirection = {
    Left: "left",
    Right: "right",
    Up: "up",
    Down: "down",
    PrevBlankLine: "prevBlankLine",
    NextBlankLine: "nextBlankLine",
    WrappedLineStart: "wrappedLineStart",
    WrappedLineFirstNonWhitespaceCharacter: "wrappedLineFirstNonWhitespaceCharacter",
    WrappedLineColumnCenter: "wrappedLineColumnCenter",
    WrappedLineEnd: "wrappedLineEnd",
    WrappedLineLastNonWhitespaceCharacter: "wrappedLineLastNonWhitespaceCharacter",
    ViewPortTop: "viewPortTop",
    ViewPortCenter: "viewPortCenter",
    ViewPortBottom: "viewPortBottom",
    ViewPortIfOutside: "viewPortIfOutside"
  };
  CursorMove2.RawUnit = {
    Line: "line",
    WrappedLine: "wrappedLine",
    Character: "character",
    HalfLine: "halfLine"
  };
  function parse2(args) {
    if (!args.to) {
      return null;
    }
    let direction;
    switch (args.to) {
      case CursorMove2.RawDirection.Left:
        direction = 0;
        break;
      case CursorMove2.RawDirection.Right:
        direction = 1;
        break;
      case CursorMove2.RawDirection.Up:
        direction = 2;
        break;
      case CursorMove2.RawDirection.Down:
        direction = 3;
        break;
      case CursorMove2.RawDirection.PrevBlankLine:
        direction = 4;
        break;
      case CursorMove2.RawDirection.NextBlankLine:
        direction = 5;
        break;
      case CursorMove2.RawDirection.WrappedLineStart:
        direction = 6;
        break;
      case CursorMove2.RawDirection.WrappedLineFirstNonWhitespaceCharacter:
        direction = 7;
        break;
      case CursorMove2.RawDirection.WrappedLineColumnCenter:
        direction = 8;
        break;
      case CursorMove2.RawDirection.WrappedLineEnd:
        direction = 9;
        break;
      case CursorMove2.RawDirection.WrappedLineLastNonWhitespaceCharacter:
        direction = 10;
        break;
      case CursorMove2.RawDirection.ViewPortTop:
        direction = 11;
        break;
      case CursorMove2.RawDirection.ViewPortBottom:
        direction = 13;
        break;
      case CursorMove2.RawDirection.ViewPortCenter:
        direction = 12;
        break;
      case CursorMove2.RawDirection.ViewPortIfOutside:
        direction = 14;
        break;
      default:
        return null;
    }
    let unit = 0;
    switch (args.by) {
      case CursorMove2.RawUnit.Line:
        unit = 1;
        break;
      case CursorMove2.RawUnit.WrappedLine:
        unit = 2;
        break;
      case CursorMove2.RawUnit.Character:
        unit = 3;
        break;
      case CursorMove2.RawUnit.HalfLine:
        unit = 4;
        break;
    }
    return {
      direction,
      unit,
      select: !!args.select,
      value: args.value || 1
    };
  }
  CursorMove2.parse = parse2;
})(CursorMove || (CursorMove = {}));
var IndentAction$1;
(function(IndentAction2) {
  IndentAction2[IndentAction2["None"] = 0] = "None";
  IndentAction2[IndentAction2["Indent"] = 1] = "Indent";
  IndentAction2[IndentAction2["IndentOutdent"] = 2] = "IndentOutdent";
  IndentAction2[IndentAction2["Outdent"] = 3] = "Outdent";
})(IndentAction$1 || (IndentAction$1 = {}));
class StandardAutoClosingPairConditional {
  constructor(source) {
    this._neutralCharacter = null;
    this._neutralCharacterSearched = false;
    this.open = source.open;
    this.close = source.close;
    this._inString = true;
    this._inComment = true;
    this._inRegEx = true;
    if (Array.isArray(source.notIn)) {
      for (let i = 0, len = source.notIn.length; i < len; i++) {
        const notIn = source.notIn[i];
        switch (notIn) {
          case "string":
            this._inString = false;
            break;
          case "comment":
            this._inComment = false;
            break;
          case "regex":
            this._inRegEx = false;
            break;
        }
      }
    }
  }
  isOK(standardToken) {
    switch (standardToken) {
      case 0:
        return true;
      case 1:
        return this._inComment;
      case 2:
        return this._inString;
      case 3:
        return this._inRegEx;
    }
  }
  shouldAutoClose(context, column) {
    if (context.getTokenCount() === 0) {
      return true;
    }
    const tokenIndex = context.findTokenIndexAtOffset(column - 2);
    const standardTokenType = context.getStandardTokenType(tokenIndex);
    return this.isOK(standardTokenType);
  }
  _findNeutralCharacterInRange(fromCharCode, toCharCode) {
    for (let charCode = fromCharCode; charCode <= toCharCode; charCode++) {
      const character = String.fromCharCode(charCode);
      if (!this.open.includes(character) && !this.close.includes(character)) {
        return character;
      }
    }
    return null;
  }
  /**
   * Find a character in the range [0-9a-zA-Z] that does not appear in the open or close
   */
  findNeutralCharacter() {
    if (!this._neutralCharacterSearched) {
      this._neutralCharacterSearched = true;
      if (!this._neutralCharacter) {
        this._neutralCharacter = this._findNeutralCharacterInRange(
          48,
          57
          /* CharCode.Digit9 */
        );
      }
      if (!this._neutralCharacter) {
        this._neutralCharacter = this._findNeutralCharacterInRange(
          97,
          122
          /* CharCode.z */
        );
      }
      if (!this._neutralCharacter) {
        this._neutralCharacter = this._findNeutralCharacterInRange(
          65,
          90
          /* CharCode.Z */
        );
      }
    }
    return this._neutralCharacter;
  }
}
class AutoClosingPairs {
  constructor(autoClosingPairs) {
    this.autoClosingPairsOpenByStart = /* @__PURE__ */ new Map();
    this.autoClosingPairsOpenByEnd = /* @__PURE__ */ new Map();
    this.autoClosingPairsCloseByStart = /* @__PURE__ */ new Map();
    this.autoClosingPairsCloseByEnd = /* @__PURE__ */ new Map();
    this.autoClosingPairsCloseSingleChar = /* @__PURE__ */ new Map();
    for (const pair of autoClosingPairs) {
      appendEntry(this.autoClosingPairsOpenByStart, pair.open.charAt(0), pair);
      appendEntry(this.autoClosingPairsOpenByEnd, pair.open.charAt(pair.open.length - 1), pair);
      appendEntry(this.autoClosingPairsCloseByStart, pair.close.charAt(0), pair);
      appendEntry(this.autoClosingPairsCloseByEnd, pair.close.charAt(pair.close.length - 1), pair);
      if (pair.close.length === 1 && pair.open.length === 1) {
        appendEntry(this.autoClosingPairsCloseSingleChar, pair.close, pair);
      }
    }
  }
}
function appendEntry(target, key, value) {
  if (target.has(key)) {
    target.get(key).push(value);
  } else {
    target.set(key, [value]);
  }
}
const USUAL_WORD_SEPARATORS = "`~!@#$%^&*()-=+[{]}\\|;:'\",.<>/?";
function createWordRegExp(allowInWords = "") {
  let source = "(-?\\d*\\.\\d\\w*)|([^";
  for (const sep2 of USUAL_WORD_SEPARATORS) {
    if (allowInWords.indexOf(sep2) >= 0) {
      continue;
    }
    source += "\\" + sep2;
  }
  source += "\\s]+)";
  return new RegExp(source, "g");
}
const DEFAULT_WORD_REGEXP = createWordRegExp();
function ensureValidWordDefinition(wordDefinition) {
  let result2 = DEFAULT_WORD_REGEXP;
  if (wordDefinition && wordDefinition instanceof RegExp) {
    if (!wordDefinition.global) {
      let flags = "g";
      if (wordDefinition.ignoreCase) {
        flags += "i";
      }
      if (wordDefinition.multiline) {
        flags += "m";
      }
      if (wordDefinition.unicode) {
        flags += "u";
      }
      result2 = new RegExp(wordDefinition.source, flags);
    } else {
      result2 = wordDefinition;
    }
  }
  result2.lastIndex = 0;
  return result2;
}
const _defaultConfig = new LinkedList();
_defaultConfig.unshift({
  maxLen: 1e3,
  windowSize: 15,
  timeBudget: 150
});
function getWordAtText(column, wordDefinition, text2, textOffset, config2) {
  if (!config2) {
    config2 = Iterable.first(_defaultConfig);
  }
  if (text2.length > config2.maxLen) {
    let start = column - config2.maxLen / 2;
    if (start < 0) {
      start = 0;
    } else {
      textOffset += start;
    }
    text2 = text2.substring(start, column + config2.maxLen / 2);
    return getWordAtText(column, wordDefinition, text2, textOffset, config2);
  }
  const t1 = Date.now();
  const pos = column - 1 - textOffset;
  let prevRegexIndex = -1;
  let match2 = null;
  for (let i = 1; ; i++) {
    if (Date.now() - t1 >= config2.timeBudget) {
      break;
    }
    const regexIndex = pos - config2.windowSize * i;
    wordDefinition.lastIndex = Math.max(0, regexIndex);
    const thisMatch = _findRegexMatchEnclosingPosition(wordDefinition, text2, pos, prevRegexIndex);
    if (!thisMatch && match2) {
      break;
    }
    match2 = thisMatch;
    if (regexIndex <= 0) {
      break;
    }
    prevRegexIndex = regexIndex;
  }
  if (match2) {
    const result2 = {
      word: match2[0],
      startColumn: textOffset + 1 + match2.index,
      endColumn: textOffset + 1 + match2.index + match2[0].length
    };
    wordDefinition.lastIndex = 0;
    return result2;
  }
  return null;
}
function _findRegexMatchEnclosingPosition(wordDefinition, text2, pos, stopPos) {
  let match2;
  while (match2 = wordDefinition.exec(text2)) {
    const matchIndex = match2.index || 0;
    if (matchIndex <= pos && wordDefinition.lastIndex >= pos) {
      return match2;
    } else if (stopPos > 0 && matchIndex > stopPos) {
      return null;
    }
  }
  return null;
}
class CharacterPairSupport {
  constructor(config2) {
    if (config2.autoClosingPairs) {
      this._autoClosingPairs = config2.autoClosingPairs.map((el) => new StandardAutoClosingPairConditional(el));
    } else if (config2.brackets) {
      this._autoClosingPairs = config2.brackets.map((b) => new StandardAutoClosingPairConditional({ open: b[0], close: b[1] }));
    } else {
      this._autoClosingPairs = [];
    }
    if (config2.__electricCharacterSupport && config2.__electricCharacterSupport.docComment) {
      const docComment = config2.__electricCharacterSupport.docComment;
      this._autoClosingPairs.push(new StandardAutoClosingPairConditional({ open: docComment.open, close: docComment.close || "" }));
    }
    this._autoCloseBeforeForQuotes = typeof config2.autoCloseBefore === "string" ? config2.autoCloseBefore : CharacterPairSupport.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED_QUOTES;
    this._autoCloseBeforeForBrackets = typeof config2.autoCloseBefore === "string" ? config2.autoCloseBefore : CharacterPairSupport.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED_BRACKETS;
    this._surroundingPairs = config2.surroundingPairs || this._autoClosingPairs;
  }
  getAutoClosingPairs() {
    return this._autoClosingPairs;
  }
  getAutoCloseBeforeSet(forQuotes) {
    return forQuotes ? this._autoCloseBeforeForQuotes : this._autoCloseBeforeForBrackets;
  }
  getSurroundingPairs() {
    return this._surroundingPairs;
  }
}
CharacterPairSupport.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED_QUOTES = ";:.,=}])> \n	";
CharacterPairSupport.DEFAULT_AUTOCLOSE_BEFORE_LANGUAGE_DEFINED_BRACKETS = "'\"`;:.,=}])> \n	";
function tail(array2, n2 = 0) {
  return array2[array2.length - (1 + n2)];
}
function tail2(arr) {
  if (arr.length === 0) {
    throw new Error("Invalid tail call");
  }
  return [arr.slice(0, arr.length - 1), arr[arr.length - 1]];
}
function equals$3(one, other, itemEquals = (a, b) => a === b) {
  if (one === other) {
    return true;
  }
  if (!one || !other) {
    return false;
  }
  if (one.length !== other.length) {
    return false;
  }
  for (let i = 0, len = one.length; i < len; i++) {
    if (!itemEquals(one[i], other[i])) {
      return false;
    }
  }
  return true;
}
function removeFastWithoutKeepingOrder(array2, index) {
  const last2 = array2.length - 1;
  if (index < last2) {
    array2[index] = array2[last2];
  }
  array2.pop();
}
function binarySearch$4(array2, key, comparator2) {
  return binarySearch2(array2.length, (i) => comparator2(array2[i], key));
}
function binarySearch2(length2, compareToKey) {
  let low = 0, high = length2 - 1;
  while (low <= high) {
    const mid = (low + high) / 2 | 0;
    const comp = compareToKey(mid);
    if (comp < 0) {
      low = mid + 1;
    } else if (comp > 0) {
      high = mid - 1;
    } else {
      return mid;
    }
  }
  return -(low + 1);
}
function findFirstInSorted$1(array2, p2) {
  let low = 0, high = array2.length;
  if (high === 0) {
    return 0;
  }
  while (low < high) {
    const mid = Math.floor((low + high) / 2);
    if (p2(array2[mid])) {
      high = mid;
    } else {
      low = mid + 1;
    }
  }
  return low;
}
function quickSelect(nth, data, compare4) {
  nth = nth | 0;
  if (nth >= data.length) {
    throw new TypeError("invalid index");
  }
  const pivotValue = data[Math.floor(data.length * Math.random())];
  const lower = [];
  const higher = [];
  const pivots = [];
  for (const value of data) {
    const val = compare4(value, pivotValue);
    if (val < 0) {
      lower.push(value);
    } else if (val > 0) {
      higher.push(value);
    } else {
      pivots.push(value);
    }
  }
  if (nth < lower.length) {
    return quickSelect(nth, lower, compare4);
  } else if (nth < lower.length + pivots.length) {
    return pivots[0];
  } else {
    return quickSelect(nth - (lower.length + pivots.length), higher, compare4);
  }
}
function groupBy(data, compare4) {
  const result2 = [];
  let currentGroup = void 0;
  for (const element of data.slice(0).sort(compare4)) {
    if (!currentGroup || compare4(currentGroup[0], element) !== 0) {
      currentGroup = [element];
      result2.push(currentGroup);
    } else {
      currentGroup.push(element);
    }
  }
  return result2;
}
function coalesce(array2) {
  return array2.filter((e) => !!e);
}
function coalesceInPlace(array2) {
  let to = 0;
  for (let i = 0; i < array2.length; i++) {
    if (!!array2[i]) {
      array2[to] = array2[i];
      to += 1;
    }
  }
  array2.length = to;
}
function isFalsyOrEmpty(obj) {
  return !Array.isArray(obj) || obj.length === 0;
}
function isNonEmptyArray(obj) {
  return Array.isArray(obj) && obj.length > 0;
}
function distinct(array2, keyFn = (value) => value) {
  const seen2 = /* @__PURE__ */ new Set();
  return array2.filter((element) => {
    const key = keyFn(element);
    if (seen2.has(key)) {
      return false;
    }
    seen2.add(key);
    return true;
  });
}
function findLast(arr, predicate) {
  const idx = lastIndex(arr, predicate);
  if (idx === -1) {
    return void 0;
  }
  return arr[idx];
}
function lastIndex(array2, fn) {
  for (let i = array2.length - 1; i >= 0; i--) {
    const element = array2[i];
    if (fn(element)) {
      return i;
    }
  }
  return -1;
}
function firstOrDefault(array2, notFoundValue) {
  return array2.length > 0 ? array2[0] : notFoundValue;
}
function range$1(arg, to) {
  let from2 = typeof to === "number" ? arg : 0;
  if (typeof to === "number") {
    from2 = arg;
  } else {
    from2 = 0;
    to = arg;
  }
  const result2 = [];
  if (from2 <= to) {
    for (let i = from2; i < to; i++) {
      result2.push(i);
    }
  } else {
    for (let i = from2; i > to; i--) {
      result2.push(i);
    }
  }
  return result2;
}
function arrayInsert(target, insertIndex, insertArr) {
  const before = target.slice(0, insertIndex);
  const after = target.slice(insertIndex);
  return before.concat(insertArr, after);
}
function pushToStart(arr, value) {
  const index = arr.indexOf(value);
  if (index > -1) {
    arr.splice(index, 1);
    arr.unshift(value);
  }
}
function pushToEnd(arr, value) {
  const index = arr.indexOf(value);
  if (index > -1) {
    arr.splice(index, 1);
    arr.push(value);
  }
}
function pushMany(arr, items) {
  for (const item of items) {
    arr.push(item);
  }
}
function asArray(x) {
  return Array.isArray(x) ? x : [x];
}
function mapFind(array2, mapFn) {
  for (const value of array2) {
    const mapped = mapFn(value);
    if (mapped !== void 0) {
      return mapped;
    }
  }
  return void 0;
}
function insertInto(array2, start, newItems) {
  const startIdx = getActualStartIndex(array2, start);
  const originalLength = array2.length;
  const newItemsLength = newItems.length;
  array2.length = originalLength + newItemsLength;
  for (let i = originalLength - 1; i >= startIdx; i--) {
    array2[i + newItemsLength] = array2[i];
  }
  for (let i = 0; i < newItemsLength; i++) {
    array2[i + startIdx] = newItems[i];
  }
}
function splice$1(array2, start, deleteCount, newItems) {
  const index = getActualStartIndex(array2, start);
  const result2 = array2.splice(index, deleteCount);
  insertInto(array2, index, newItems);
  return result2;
}
function getActualStartIndex(array2, start) {
  return start < 0 ? Math.max(start + array2.length, 0) : Math.min(start, array2.length);
}
var CompareResult;
(function(CompareResult2) {
  function isLessThan(result2) {
    return result2 < 0;
  }
  CompareResult2.isLessThan = isLessThan;
  function isGreaterThan(result2) {
    return result2 > 0;
  }
  CompareResult2.isGreaterThan = isGreaterThan;
  function isNeitherLessOrGreaterThan(result2) {
    return result2 === 0;
  }
  CompareResult2.isNeitherLessOrGreaterThan = isNeitherLessOrGreaterThan;
  CompareResult2.greaterThan = 1;
  CompareResult2.lessThan = -1;
  CompareResult2.neitherLessOrGreaterThan = 0;
})(CompareResult || (CompareResult = {}));
function compareBy(selector3, comparator2) {
  return (a, b) => comparator2(selector3(a), selector3(b));
}
const numberComparator = (a, b) => a - b;
function findMaxBy(items, comparator2) {
  if (items.length === 0) {
    return void 0;
  }
  let max = items[0];
  for (let i = 1; i < items.length; i++) {
    const item = items[i];
    if (comparator2(item, max) > 0) {
      max = item;
    }
  }
  return max;
}
function findLastMaxBy(items, comparator2) {
  if (items.length === 0) {
    return void 0;
  }
  let max = items[0];
  for (let i = 1; i < items.length; i++) {
    const item = items[i];
    if (comparator2(item, max) >= 0) {
      max = item;
    }
  }
  return max;
}
function findMinBy(items, comparator2) {
  return findMaxBy(items, (a, b) => -comparator2(a, b));
}
class ArrayQueue {
  /**
   * Constructs a queue that is backed by the given array. Runtime is O(1).
  */
  constructor(items) {
    this.items = items;
    this.firstIdx = 0;
    this.lastIdx = this.items.length - 1;
  }
  get length() {
    return this.lastIdx - this.firstIdx + 1;
  }
  /**
   * Consumes elements from the beginning of the queue as long as the predicate returns true.
   * If no elements were consumed, `null` is returned. Has a runtime of O(result.length).
  */
  takeWhile(predicate) {
    let startIdx = this.firstIdx;
    while (startIdx < this.items.length && predicate(this.items[startIdx])) {
      startIdx++;
    }
    const result2 = startIdx === this.firstIdx ? null : this.items.slice(this.firstIdx, startIdx);
    this.firstIdx = startIdx;
    return result2;
  }
  /**
   * Consumes elements from the end of the queue as long as the predicate returns true.
   * If no elements were consumed, `null` is returned.
   * The result has the same order as the underlying array!
  */
  takeFromEndWhile(predicate) {
    let endIdx = this.lastIdx;
    while (endIdx >= 0 && predicate(this.items[endIdx])) {
      endIdx--;
    }
    const result2 = endIdx === this.lastIdx ? null : this.items.slice(endIdx + 1, this.lastIdx + 1);
    this.lastIdx = endIdx;
    return result2;
  }
  peek() {
    if (this.length === 0) {
      return void 0;
    }
    return this.items[this.firstIdx];
  }
  dequeue() {
    const result2 = this.items[this.firstIdx];
    this.firstIdx++;
    return result2;
  }
  takeCount(count) {
    const result2 = this.items.slice(this.firstIdx, this.firstIdx + count);
    this.firstIdx += count;
    return result2;
  }
}
class CallbackIterable {
  constructor(iterate) {
    this.iterate = iterate;
  }
  toArray() {
    const result2 = [];
    this.iterate((item) => {
      result2.push(item);
      return true;
    });
    return result2;
  }
  filter(predicate) {
    return new CallbackIterable((cb) => this.iterate((item) => predicate(item) ? cb(item) : true));
  }
  map(mapFn) {
    return new CallbackIterable((cb) => this.iterate((item) => cb(mapFn(item))));
  }
  findLast(predicate) {
    let result2;
    this.iterate((item) => {
      if (predicate(item)) {
        result2 = item;
      }
      return true;
    });
    return result2;
  }
  findLastMaxBy(comparator2) {
    let result2;
    let first2 = true;
    this.iterate((item) => {
      if (first2 || CompareResult.isGreaterThan(comparator2(item, result2))) {
        first2 = false;
        result2 = item;
      }
      return true;
    });
    return result2;
  }
}
CallbackIterable.empty = new CallbackIterable((_callback) => {
});
const hasBuffer = typeof Buffer !== "undefined";
let textDecoder;
class VSBuffer {
  /**
   * When running in a nodejs context, if `actual` is not a nodejs Buffer, the backing store for
   * the returned `VSBuffer` instance might use a nodejs Buffer allocated from node's Buffer pool,
   * which is not transferrable.
   */
  static wrap(actual) {
    if (hasBuffer && !Buffer.isBuffer(actual)) {
      actual = Buffer.from(actual.buffer, actual.byteOffset, actual.byteLength);
    }
    return new VSBuffer(actual);
  }
  constructor(buffer) {
    this.buffer = buffer;
    this.byteLength = this.buffer.byteLength;
  }
  toString() {
    if (hasBuffer) {
      return this.buffer.toString();
    } else {
      if (!textDecoder) {
        textDecoder = new TextDecoder();
      }
      return textDecoder.decode(this.buffer);
    }
  }
}
function readUInt16LE(source, offset) {
  return source[offset + 0] << 0 >>> 0 | source[offset + 1] << 8 >>> 0;
}
function writeUInt16LE(destination, value, offset) {
  destination[offset + 0] = value & 255;
  value = value >>> 8;
  destination[offset + 1] = value & 255;
}
function readUInt32BE(source, offset) {
  return source[offset] * Math.pow(2, 24) + source[offset + 1] * Math.pow(2, 16) + source[offset + 2] * Math.pow(2, 8) + source[offset + 3];
}
function writeUInt32BE(destination, value, offset) {
  destination[offset + 3] = value;
  value = value >>> 8;
  destination[offset + 2] = value;
  value = value >>> 8;
  destination[offset + 1] = value;
  value = value >>> 8;
  destination[offset] = value;
}
function readUInt8(source, offset) {
  return source[offset];
}
function writeUInt8(destination, value, offset) {
  destination[offset] = value;
}
let _utf16LE_TextDecoder;
function getUTF16LE_TextDecoder() {
  if (!_utf16LE_TextDecoder) {
    _utf16LE_TextDecoder = new TextDecoder("UTF-16LE");
  }
  return _utf16LE_TextDecoder;
}
let _utf16BE_TextDecoder;
function getUTF16BE_TextDecoder() {
  if (!_utf16BE_TextDecoder) {
    _utf16BE_TextDecoder = new TextDecoder("UTF-16BE");
  }
  return _utf16BE_TextDecoder;
}
let _platformTextDecoder;
function getPlatformTextDecoder() {
  if (!_platformTextDecoder) {
    _platformTextDecoder = isLittleEndian() ? getUTF16LE_TextDecoder() : getUTF16BE_TextDecoder();
  }
  return _platformTextDecoder;
}
function decodeUTF16LE(source, offset, len) {
  const view = new Uint16Array(source.buffer, offset, len);
  if (len > 0 && (view[0] === 65279 || view[0] === 65534)) {
    return compatDecodeUTF16LE(source, offset, len);
  }
  return getUTF16LE_TextDecoder().decode(view);
}
function compatDecodeUTF16LE(source, offset, len) {
  const result2 = [];
  let resultLen = 0;
  for (let i = 0; i < len; i++) {
    const charCode = readUInt16LE(source, offset);
    offset += 2;
    result2[resultLen++] = String.fromCharCode(charCode);
  }
  return result2.join("");
}
class StringBuilder {
  constructor(capacity) {
    this._capacity = capacity | 0;
    this._buffer = new Uint16Array(this._capacity);
    this._completedStrings = null;
    this._bufferLength = 0;
  }
  reset() {
    this._completedStrings = null;
    this._bufferLength = 0;
  }
  build() {
    if (this._completedStrings !== null) {
      this._flushBuffer();
      return this._completedStrings.join("");
    }
    return this._buildBuffer();
  }
  _buildBuffer() {
    if (this._bufferLength === 0) {
      return "";
    }
    const view = new Uint16Array(this._buffer.buffer, 0, this._bufferLength);
    return getPlatformTextDecoder().decode(view);
  }
  _flushBuffer() {
    const bufferString = this._buildBuffer();
    this._bufferLength = 0;
    if (this._completedStrings === null) {
      this._completedStrings = [bufferString];
    } else {
      this._completedStrings[this._completedStrings.length] = bufferString;
    }
  }
  /**
   * Append a char code (<2^16)
   */
  appendCharCode(charCode) {
    const remainingSpace = this._capacity - this._bufferLength;
    if (remainingSpace <= 1) {
      if (remainingSpace === 0 || isHighSurrogate(charCode)) {
        this._flushBuffer();
      }
    }
    this._buffer[this._bufferLength++] = charCode;
  }
  /**
   * Append an ASCII char code (<2^8)
   */
  appendASCIICharCode(charCode) {
    if (this._bufferLength === this._capacity) {
      this._flushBuffer();
    }
    this._buffer[this._bufferLength++] = charCode;
  }
  appendString(str2) {
    const strLen = str2.length;
    if (this._bufferLength + strLen >= this._capacity) {
      this._flushBuffer();
      this._completedStrings[this._completedStrings.length] = str2;
      return;
    }
    for (let i = 0; i < strLen; i++) {
      this._buffer[this._bufferLength++] = str2.charCodeAt(i);
    }
  }
}
class RichEditBracket {
  constructor(languageId, index, open, close, forwardRegex, reversedRegex) {
    this._richEditBracketBrand = void 0;
    this.languageId = languageId;
    this.index = index;
    this.open = open;
    this.close = close;
    this.forwardRegex = forwardRegex;
    this.reversedRegex = reversedRegex;
    this._openSet = RichEditBracket._toSet(this.open);
    this._closeSet = RichEditBracket._toSet(this.close);
  }
  /**
   * Check if the provided `text` is an open bracket in this group.
   */
  isOpen(text2) {
    return this._openSet.has(text2);
  }
  /**
   * Check if the provided `text` is a close bracket in this group.
   */
  isClose(text2) {
    return this._closeSet.has(text2);
  }
  static _toSet(arr) {
    const result2 = /* @__PURE__ */ new Set();
    for (const element of arr) {
      result2.add(element);
    }
    return result2;
  }
}
function groupFuzzyBrackets(brackets) {
  const N = brackets.length;
  brackets = brackets.map((b) => [b[0].toLowerCase(), b[1].toLowerCase()]);
  const group2 = [];
  for (let i = 0; i < N; i++) {
    group2[i] = i;
  }
  const areOverlapping = (a, b) => {
    const [aOpen, aClose] = a;
    const [bOpen, bClose] = b;
    return aOpen === bOpen || aOpen === bClose || aClose === bOpen || aClose === bClose;
  };
  const mergeGroups = (g1, g2) => {
    const newG = Math.min(g1, g2);
    const oldG = Math.max(g1, g2);
    for (let i = 0; i < N; i++) {
      if (group2[i] === oldG) {
        group2[i] = newG;
      }
    }
  };
  for (let i = 0; i < N; i++) {
    const a = brackets[i];
    for (let j = i + 1; j < N; j++) {
      const b = brackets[j];
      if (areOverlapping(a, b)) {
        mergeGroups(group2[i], group2[j]);
      }
    }
  }
  const result2 = [];
  for (let g = 0; g < N; g++) {
    const currentOpen = [];
    const currentClose = [];
    for (let i = 0; i < N; i++) {
      if (group2[i] === g) {
        const [open, close] = brackets[i];
        currentOpen.push(open);
        currentClose.push(close);
      }
    }
    if (currentOpen.length > 0) {
      result2.push({
        open: currentOpen,
        close: currentClose
      });
    }
  }
  return result2;
}
class RichEditBrackets {
  constructor(languageId, _brackets) {
    this._richEditBracketsBrand = void 0;
    const brackets = groupFuzzyBrackets(_brackets);
    this.brackets = brackets.map((b, index) => {
      return new RichEditBracket(languageId, index, b.open, b.close, getRegexForBracketPair(b.open, b.close, brackets, index), getReversedRegexForBracketPair(b.open, b.close, brackets, index));
    });
    this.forwardRegex = getRegexForBrackets(this.brackets);
    this.reversedRegex = getReversedRegexForBrackets(this.brackets);
    this.textIsBracket = {};
    this.textIsOpenBracket = {};
    this.maxBracketLength = 0;
    for (const bracket of this.brackets) {
      for (const open of bracket.open) {
        this.textIsBracket[open] = bracket;
        this.textIsOpenBracket[open] = true;
        this.maxBracketLength = Math.max(this.maxBracketLength, open.length);
      }
      for (const close of bracket.close) {
        this.textIsBracket[close] = bracket;
        this.textIsOpenBracket[close] = false;
        this.maxBracketLength = Math.max(this.maxBracketLength, close.length);
      }
    }
  }
}
function collectSuperstrings(str2, brackets, currentIndex, dest) {
  for (let i = 0, len = brackets.length; i < len; i++) {
    if (i === currentIndex) {
      continue;
    }
    const bracket = brackets[i];
    for (const open of bracket.open) {
      if (open.indexOf(str2) >= 0) {
        dest.push(open);
      }
    }
    for (const close of bracket.close) {
      if (close.indexOf(str2) >= 0) {
        dest.push(close);
      }
    }
  }
}
function lengthcmp(a, b) {
  return a.length - b.length;
}
function unique(arr) {
  if (arr.length <= 1) {
    return arr;
  }
  const result2 = [];
  const seen2 = /* @__PURE__ */ new Set();
  for (const element of arr) {
    if (seen2.has(element)) {
      continue;
    }
    result2.push(element);
    seen2.add(element);
  }
  return result2;
}
function getRegexForBracketPair(open, close, brackets, currentIndex) {
  let pieces = [];
  pieces = pieces.concat(open);
  pieces = pieces.concat(close);
  for (let i = 0, len = pieces.length; i < len; i++) {
    collectSuperstrings(pieces[i], brackets, currentIndex, pieces);
  }
  pieces = unique(pieces);
  pieces.sort(lengthcmp);
  pieces.reverse();
  return createBracketOrRegExp(pieces);
}
function getReversedRegexForBracketPair(open, close, brackets, currentIndex) {
  let pieces = [];
  pieces = pieces.concat(open);
  pieces = pieces.concat(close);
  for (let i = 0, len = pieces.length; i < len; i++) {
    collectSuperstrings(pieces[i], brackets, currentIndex, pieces);
  }
  pieces = unique(pieces);
  pieces.sort(lengthcmp);
  pieces.reverse();
  return createBracketOrRegExp(pieces.map(toReversedString));
}
function getRegexForBrackets(brackets) {
  let pieces = [];
  for (const bracket of brackets) {
    for (const open of bracket.open) {
      pieces.push(open);
    }
    for (const close of bracket.close) {
      pieces.push(close);
    }
  }
  pieces = unique(pieces);
  return createBracketOrRegExp(pieces);
}
function getReversedRegexForBrackets(brackets) {
  let pieces = [];
  for (const bracket of brackets) {
    for (const open of bracket.open) {
      pieces.push(open);
    }
    for (const close of bracket.close) {
      pieces.push(close);
    }
  }
  pieces = unique(pieces);
  return createBracketOrRegExp(pieces.map(toReversedString));
}
function prepareBracketForRegExp$1(str2) {
  const insertWordBoundaries = /^[\w ]+$/.test(str2);
  str2 = escapeRegExpCharacters(str2);
  return insertWordBoundaries ? `\\b${str2}\\b` : str2;
}
function createBracketOrRegExp(pieces) {
  const regexStr = `(${pieces.map(prepareBracketForRegExp$1).join(")|(")})`;
  return createRegExp(regexStr, true);
}
const toReversedString = function() {
  function reverse(str2) {
    const arr = new Uint16Array(str2.length);
    let offset = 0;
    for (let i = str2.length - 1; i >= 0; i--) {
      arr[offset++] = str2.charCodeAt(i);
    }
    return getPlatformTextDecoder().decode(arr);
  }
  let lastInput = null;
  let lastOutput = null;
  return function toReversedString2(str2) {
    if (lastInput !== str2) {
      lastInput = str2;
      lastOutput = reverse(lastInput);
    }
    return lastOutput;
  };
}();
class BracketsUtils {
  static _findPrevBracketInText(reversedBracketRegex, lineNumber, reversedText, offset) {
    const m = reversedText.match(reversedBracketRegex);
    if (!m) {
      return null;
    }
    const matchOffset = reversedText.length - (m.index || 0);
    const matchLength = m[0].length;
    const absoluteMatchOffset = offset + matchOffset;
    return new Range$2(lineNumber, absoluteMatchOffset - matchLength + 1, lineNumber, absoluteMatchOffset + 1);
  }
  static findPrevBracketInRange(reversedBracketRegex, lineNumber, lineText, startOffset, endOffset) {
    const reversedLineText = toReversedString(lineText);
    const reversedSubstr = reversedLineText.substring(lineText.length - endOffset, lineText.length - startOffset);
    return this._findPrevBracketInText(reversedBracketRegex, lineNumber, reversedSubstr, startOffset);
  }
  static findNextBracketInText(bracketRegex, lineNumber, text2, offset) {
    const m = text2.match(bracketRegex);
    if (!m) {
      return null;
    }
    const matchOffset = m.index || 0;
    const matchLength = m[0].length;
    if (matchLength === 0) {
      return null;
    }
    const absoluteMatchOffset = offset + matchOffset;
    return new Range$2(lineNumber, absoluteMatchOffset + 1, lineNumber, absoluteMatchOffset + 1 + matchLength);
  }
  static findNextBracketInRange(bracketRegex, lineNumber, lineText, startOffset, endOffset) {
    const substr2 = lineText.substring(startOffset, endOffset);
    return this.findNextBracketInText(bracketRegex, lineNumber, substr2, startOffset);
  }
}
class BracketElectricCharacterSupport {
  constructor(richEditBrackets) {
    this._richEditBrackets = richEditBrackets;
  }
  getElectricCharacters() {
    const result2 = [];
    if (this._richEditBrackets) {
      for (const bracket of this._richEditBrackets.brackets) {
        for (const close of bracket.close) {
          const lastChar = close.charAt(close.length - 1);
          result2.push(lastChar);
        }
      }
    }
    return distinct(result2);
  }
  onElectricCharacter(character, context, column) {
    if (!this._richEditBrackets || this._richEditBrackets.brackets.length === 0) {
      return null;
    }
    const tokenIndex = context.findTokenIndexAtOffset(column - 1);
    if (ignoreBracketsInToken(context.getStandardTokenType(tokenIndex))) {
      return null;
    }
    const reversedBracketRegex = this._richEditBrackets.reversedRegex;
    const text2 = context.getLineContent().substring(0, column - 1) + character;
    const r = BracketsUtils.findPrevBracketInRange(reversedBracketRegex, 1, text2, 0, text2.length);
    if (!r) {
      return null;
    }
    const bracketText = text2.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase();
    const isOpen = this._richEditBrackets.textIsOpenBracket[bracketText];
    if (isOpen) {
      return null;
    }
    const textBeforeBracket = context.getActualLineContentBefore(r.startColumn - 1);
    if (!/^\s*$/.test(textBeforeBracket)) {
      return null;
    }
    return {
      matchOpenBracket: bracketText
    };
  }
}
function resetGlobalRegex(reg) {
  if (reg.global) {
    reg.lastIndex = 0;
  }
  return true;
}
class IndentRulesSupport {
  constructor(indentationRules) {
    this._indentationRules = indentationRules;
  }
  shouldIncrease(text2) {
    if (this._indentationRules) {
      if (this._indentationRules.increaseIndentPattern && resetGlobalRegex(this._indentationRules.increaseIndentPattern) && this._indentationRules.increaseIndentPattern.test(text2)) {
        return true;
      }
    }
    return false;
  }
  shouldDecrease(text2) {
    if (this._indentationRules && this._indentationRules.decreaseIndentPattern && resetGlobalRegex(this._indentationRules.decreaseIndentPattern) && this._indentationRules.decreaseIndentPattern.test(text2)) {
      return true;
    }
    return false;
  }
  shouldIndentNextLine(text2) {
    if (this._indentationRules && this._indentationRules.indentNextLinePattern && resetGlobalRegex(this._indentationRules.indentNextLinePattern) && this._indentationRules.indentNextLinePattern.test(text2)) {
      return true;
    }
    return false;
  }
  shouldIgnore(text2) {
    if (this._indentationRules && this._indentationRules.unIndentedLinePattern && resetGlobalRegex(this._indentationRules.unIndentedLinePattern) && this._indentationRules.unIndentedLinePattern.test(text2)) {
      return true;
    }
    return false;
  }
  getIndentMetadata(text2) {
    let ret = 0;
    if (this.shouldIncrease(text2)) {
      ret += 1;
    }
    if (this.shouldDecrease(text2)) {
      ret += 2;
    }
    if (this.shouldIndentNextLine(text2)) {
      ret += 4;
    }
    if (this.shouldIgnore(text2)) {
      ret += 8;
    }
    return ret;
  }
}
class OnEnterSupport {
  constructor(opts) {
    opts = opts || {};
    opts.brackets = opts.brackets || [
      ["(", ")"],
      ["{", "}"],
      ["[", "]"]
    ];
    this._brackets = [];
    opts.brackets.forEach((bracket) => {
      const openRegExp = OnEnterSupport._createOpenBracketRegExp(bracket[0]);
      const closeRegExp = OnEnterSupport._createCloseBracketRegExp(bracket[1]);
      if (openRegExp && closeRegExp) {
        this._brackets.push({
          open: bracket[0],
          openRegExp,
          close: bracket[1],
          closeRegExp
        });
      }
    });
    this._regExpRules = opts.onEnterRules || [];
  }
  onEnter(autoIndent, previousLineText, beforeEnterText, afterEnterText) {
    if (autoIndent >= 3) {
      for (let i = 0, len = this._regExpRules.length; i < len; i++) {
        const rule2 = this._regExpRules[i];
        const regResult = [{
          reg: rule2.beforeText,
          text: beforeEnterText
        }, {
          reg: rule2.afterText,
          text: afterEnterText
        }, {
          reg: rule2.previousLineText,
          text: previousLineText
        }].every((obj) => {
          if (!obj.reg) {
            return true;
          }
          obj.reg.lastIndex = 0;
          return obj.reg.test(obj.text);
        });
        if (regResult) {
          return rule2.action;
        }
      }
    }
    if (autoIndent >= 2) {
      if (beforeEnterText.length > 0 && afterEnterText.length > 0) {
        for (let i = 0, len = this._brackets.length; i < len; i++) {
          const bracket = this._brackets[i];
          if (bracket.openRegExp.test(beforeEnterText) && bracket.closeRegExp.test(afterEnterText)) {
            return { indentAction: IndentAction$1.IndentOutdent };
          }
        }
      }
    }
    if (autoIndent >= 2) {
      if (beforeEnterText.length > 0) {
        for (let i = 0, len = this._brackets.length; i < len; i++) {
          const bracket = this._brackets[i];
          if (bracket.openRegExp.test(beforeEnterText)) {
            return { indentAction: IndentAction$1.Indent };
          }
        }
      }
    }
    return null;
  }
  static _createOpenBracketRegExp(bracket) {
    let str2 = escapeRegExpCharacters(bracket);
    if (!/\B/.test(str2.charAt(0))) {
      str2 = "\\b" + str2;
    }
    str2 += "\\s*$";
    return OnEnterSupport._safeRegExp(str2);
  }
  static _createCloseBracketRegExp(bracket) {
    let str2 = escapeRegExpCharacters(bracket);
    if (!/\B/.test(str2.charAt(str2.length - 1))) {
      str2 = str2 + "\\b";
    }
    str2 = "^\\s*" + str2;
    return OnEnterSupport._safeRegExp(str2);
  }
  static _safeRegExp(def2) {
    try {
      return new RegExp(def2);
    } catch (err) {
      onUnexpectedError(err);
      return null;
    }
  }
}
const IConfigurationService = createDecorator("configurationService");
function toValuesTree(properties, conflictReporter) {
  const root3 = /* @__PURE__ */ Object.create(null);
  for (const key in properties) {
    addToValueTree(root3, key, properties[key], conflictReporter);
  }
  return root3;
}
function addToValueTree(settingsTreeRoot, key, value, conflictReporter) {
  const segments = key.split(".");
  const last2 = segments.pop();
  let curr = settingsTreeRoot;
  for (let i = 0; i < segments.length; i++) {
    const s = segments[i];
    let obj = curr[s];
    switch (typeof obj) {
      case "undefined":
        obj = curr[s] = /* @__PURE__ */ Object.create(null);
        break;
      case "object":
        break;
      default:
        conflictReporter(`Ignoring ${key} as ${segments.slice(0, i + 1).join(".")} is ${JSON.stringify(obj)}`);
        return;
    }
    curr = obj;
  }
  if (typeof curr === "object" && curr !== null) {
    try {
      curr[last2] = value;
    } catch (e) {
      conflictReporter(`Ignoring ${key} as ${segments.join(".")} is ${JSON.stringify(curr)}`);
    }
  } else {
    conflictReporter(`Ignoring ${key} as ${segments.join(".")} is ${JSON.stringify(curr)}`);
  }
}
function removeFromValueTree(valueTree, key) {
  const segments = key.split(".");
  doRemoveFromValueTree(valueTree, segments);
}
function doRemoveFromValueTree(valueTree, segments) {
  const first2 = segments.shift();
  if (segments.length === 0) {
    delete valueTree[first2];
    return;
  }
  if (Object.keys(valueTree).indexOf(first2) !== -1) {
    const value = valueTree[first2];
    if (typeof value === "object" && !Array.isArray(value)) {
      doRemoveFromValueTree(value, segments);
      if (Object.keys(value).length === 0) {
        delete valueTree[first2];
      }
    }
  }
}
function getConfigurationValue(config2, settingPath, defaultValue) {
  function accessSetting(config3, path3) {
    let current = config3;
    for (const component of path3) {
      if (typeof current !== "object" || current === null) {
        return void 0;
      }
      current = current[component];
    }
    return current;
  }
  const path2 = settingPath.split(".");
  const result2 = accessSetting(config2, path2);
  return typeof result2 === "undefined" ? defaultValue : result2;
}
function getLanguageTagSettingPlainKey(settingKey) {
  return settingKey.replace(/[\[\]]/g, "");
}
const ILanguageService = createDecorator("languageService");
class SyncDescriptor {
  constructor(ctor, staticArguments = [], supportsDelayedInstantiation = false) {
    this.ctor = ctor;
    this.staticArguments = staticArguments;
    this.supportsDelayedInstantiation = supportsDelayedInstantiation;
  }
}
const _registry = [];
function registerSingleton(id3, ctorOrDescriptor, supportsDelayedInstantiation) {
  if (!(ctorOrDescriptor instanceof SyncDescriptor)) {
    ctorOrDescriptor = new SyncDescriptor(ctorOrDescriptor, [], Boolean(supportsDelayedInstantiation));
  }
  _registry.push([id3, ctorOrDescriptor]);
}
function getSingletonServiceDescriptors() {
  return _registry;
}
const Mimes = Object.freeze({
  text: "text/plain",
  binary: "application/octet-stream",
  unknown: "application/unknown",
  markdown: "text/markdown",
  latex: "text/latex",
  uriList: "text/uri-list"
});
const Extensions$7 = {
  JSONContribution: "base.contributions.json"
};
function normalizeId(id3) {
  if (id3.length > 0 && id3.charAt(id3.length - 1) === "#") {
    return id3.substring(0, id3.length - 1);
  }
  return id3;
}
class JSONContributionRegistry {
  constructor() {
    this._onDidChangeSchema = new Emitter$1();
    this.schemasById = {};
  }
  registerSchema(uri, unresolvedSchemaContent) {
    this.schemasById[normalizeId(uri)] = unresolvedSchemaContent;
    this._onDidChangeSchema.fire(uri);
  }
  notifySchemaChanged(uri) {
    this._onDidChangeSchema.fire(uri);
  }
}
const jsonContributionRegistry = new JSONContributionRegistry();
Registry.add(Extensions$7.JSONContribution, jsonContributionRegistry);
const Extensions$6 = {
  Configuration: "base.contributions.configuration"
};
const resourceLanguageSettingsSchemaId = "vscode://schemas/settings/resourceLanguage";
const contributionRegistry = Registry.as(Extensions$7.JSONContribution);
class ConfigurationRegistry {
  constructor() {
    this.overrideIdentifiers = /* @__PURE__ */ new Set();
    this._onDidSchemaChange = new Emitter$1();
    this._onDidUpdateConfiguration = new Emitter$1();
    this.configurationDefaultsOverrides = /* @__PURE__ */ new Map();
    this.defaultLanguageConfigurationOverridesNode = {
      id: "defaultOverrides",
      title: localize("defaultLanguageConfigurationOverrides.title", "Default Language Configuration Overrides"),
      properties: {}
    };
    this.configurationContributors = [this.defaultLanguageConfigurationOverridesNode];
    this.resourceLanguageSettingsSchema = {
      properties: {},
      patternProperties: {},
      additionalProperties: true,
      allowTrailingCommas: true,
      allowComments: true
    };
    this.configurationProperties = {};
    this.policyConfigurations = /* @__PURE__ */ new Map();
    this.excludedConfigurationProperties = {};
    contributionRegistry.registerSchema(resourceLanguageSettingsSchemaId, this.resourceLanguageSettingsSchema);
    this.registerOverridePropertyPatternKey();
  }
  registerConfiguration(configuration, validate = true) {
    this.registerConfigurations([configuration], validate);
  }
  registerConfigurations(configurations, validate = true) {
    const properties = /* @__PURE__ */ new Set();
    this.doRegisterConfigurations(configurations, validate, properties);
    contributionRegistry.registerSchema(resourceLanguageSettingsSchemaId, this.resourceLanguageSettingsSchema);
    this._onDidSchemaChange.fire();
    this._onDidUpdateConfiguration.fire({ properties });
  }
  registerDefaultConfigurations(configurationDefaults) {
    const properties = /* @__PURE__ */ new Set();
    this.doRegisterDefaultConfigurations(configurationDefaults, properties);
    this._onDidSchemaChange.fire();
    this._onDidUpdateConfiguration.fire({ properties, defaultsOverrides: true });
  }
  doRegisterDefaultConfigurations(configurationDefaults, bucket) {
    var _a2;
    const overrideIdentifiers = [];
    for (const { overrides, source } of configurationDefaults) {
      for (const key in overrides) {
        bucket.add(key);
        if (OVERRIDE_PROPERTY_REGEX.test(key)) {
          const configurationDefaultOverride = this.configurationDefaultsOverrides.get(key);
          const valuesSources = (_a2 = configurationDefaultOverride === null || configurationDefaultOverride === void 0 ? void 0 : configurationDefaultOverride.valuesSources) !== null && _a2 !== void 0 ? _a2 : /* @__PURE__ */ new Map();
          if (source) {
            for (const configuration of Object.keys(overrides[key])) {
              valuesSources.set(configuration, source);
            }
          }
          const defaultValue = Object.assign(Object.assign({}, (configurationDefaultOverride === null || configurationDefaultOverride === void 0 ? void 0 : configurationDefaultOverride.value) || {}), overrides[key]);
          this.configurationDefaultsOverrides.set(key, { source, value: defaultValue, valuesSources });
          const plainKey = getLanguageTagSettingPlainKey(key);
          const property = {
            type: "object",
            default: defaultValue,
            description: localize("defaultLanguageConfiguration.description", "Configure settings to be overridden for the {0} language.", plainKey),
            $ref: resourceLanguageSettingsSchemaId,
            defaultDefaultValue: defaultValue,
            source: isString$4(source) ? void 0 : source,
            defaultValueSource: source
          };
          overrideIdentifiers.push(...overrideIdentifiersFromKey(key));
          this.configurationProperties[key] = property;
          this.defaultLanguageConfigurationOverridesNode.properties[key] = property;
        } else {
          this.configurationDefaultsOverrides.set(key, { value: overrides[key], source });
          const property = this.configurationProperties[key];
          if (property) {
            this.updatePropertyDefaultValue(key, property);
            this.updateSchema(key, property);
          }
        }
      }
    }
    this.doRegisterOverrideIdentifiers(overrideIdentifiers);
  }
  registerOverrideIdentifiers(overrideIdentifiers) {
    this.doRegisterOverrideIdentifiers(overrideIdentifiers);
    this._onDidSchemaChange.fire();
  }
  doRegisterOverrideIdentifiers(overrideIdentifiers) {
    for (const overrideIdentifier of overrideIdentifiers) {
      this.overrideIdentifiers.add(overrideIdentifier);
    }
    this.updateOverridePropertyPatternKey();
  }
  doRegisterConfigurations(configurations, validate, bucket) {
    configurations.forEach((configuration) => {
      this.validateAndRegisterProperties(configuration, validate, configuration.extensionInfo, configuration.restrictedProperties, void 0, bucket);
      this.configurationContributors.push(configuration);
      this.registerJSONConfiguration(configuration);
    });
  }
  validateAndRegisterProperties(configuration, validate = true, extensionInfo, restrictedProperties, scope = 3, bucket) {
    var _a2;
    scope = isUndefinedOrNull(configuration.scope) ? scope : configuration.scope;
    const properties = configuration.properties;
    if (properties) {
      for (const key in properties) {
        const property = properties[key];
        if (validate && validateProperty(key, property)) {
          delete properties[key];
          continue;
        }
        property.source = extensionInfo;
        property.defaultDefaultValue = properties[key].default;
        this.updatePropertyDefaultValue(key, property);
        if (OVERRIDE_PROPERTY_REGEX.test(key)) {
          property.scope = void 0;
        } else {
          property.scope = isUndefinedOrNull(property.scope) ? scope : property.scope;
          property.restricted = isUndefinedOrNull(property.restricted) ? !!(restrictedProperties === null || restrictedProperties === void 0 ? void 0 : restrictedProperties.includes(key)) : property.restricted;
        }
        if (properties[key].hasOwnProperty("included") && !properties[key].included) {
          this.excludedConfigurationProperties[key] = properties[key];
          delete properties[key];
          continue;
        } else {
          this.configurationProperties[key] = properties[key];
          if ((_a2 = properties[key].policy) === null || _a2 === void 0 ? void 0 : _a2.name) {
            this.policyConfigurations.set(properties[key].policy.name, key);
          }
        }
        if (!properties[key].deprecationMessage && properties[key].markdownDeprecationMessage) {
          properties[key].deprecationMessage = properties[key].markdownDeprecationMessage;
        }
        bucket.add(key);
      }
    }
    const subNodes = configuration.allOf;
    if (subNodes) {
      for (const node2 of subNodes) {
        this.validateAndRegisterProperties(node2, validate, extensionInfo, restrictedProperties, scope, bucket);
      }
    }
  }
  getConfigurationProperties() {
    return this.configurationProperties;
  }
  getPolicyConfigurations() {
    return this.policyConfigurations;
  }
  registerJSONConfiguration(configuration) {
    const register2 = (configuration2) => {
      const properties = configuration2.properties;
      if (properties) {
        for (const key in properties) {
          this.updateSchema(key, properties[key]);
        }
      }
      const subNodes = configuration2.allOf;
      subNodes === null || subNodes === void 0 ? void 0 : subNodes.forEach(register2);
    };
    register2(configuration);
  }
  updateSchema(key, property) {
    switch (property.scope) {
      case 1:
        break;
      case 2:
        break;
      case 6:
        break;
      case 3:
        break;
      case 4:
        break;
      case 5:
        this.resourceLanguageSettingsSchema.properties[key] = property;
        break;
    }
  }
  updateOverridePropertyPatternKey() {
    for (const overrideIdentifier of this.overrideIdentifiers.values()) {
      const overrideIdentifierProperty = `[${overrideIdentifier}]`;
      const resourceLanguagePropertiesSchema = {
        type: "object",
        description: localize("overrideSettings.defaultDescription", "Configure editor settings to be overridden for a language."),
        errorMessage: localize("overrideSettings.errorMessage", "This setting does not support per-language configuration."),
        $ref: resourceLanguageSettingsSchemaId
      };
      this.updatePropertyDefaultValue(overrideIdentifierProperty, resourceLanguagePropertiesSchema);
    }
  }
  registerOverridePropertyPatternKey() {
    ({
      type: "object",
      description: localize("overrideSettings.defaultDescription", "Configure editor settings to be overridden for a language."),
      errorMessage: localize("overrideSettings.errorMessage", "This setting does not support per-language configuration."),
      $ref: resourceLanguageSettingsSchemaId
    });
    this._onDidSchemaChange.fire();
  }
  updatePropertyDefaultValue(key, property) {
    const configurationdefaultOverride = this.configurationDefaultsOverrides.get(key);
    let defaultValue = configurationdefaultOverride === null || configurationdefaultOverride === void 0 ? void 0 : configurationdefaultOverride.value;
    let defaultSource = configurationdefaultOverride === null || configurationdefaultOverride === void 0 ? void 0 : configurationdefaultOverride.source;
    if (isUndefined$1(defaultValue)) {
      defaultValue = property.defaultDefaultValue;
      defaultSource = void 0;
    }
    if (isUndefined$1(defaultValue)) {
      defaultValue = getDefaultValue(property.type);
    }
    property.default = defaultValue;
    property.defaultValueSource = defaultSource;
  }
}
const OVERRIDE_IDENTIFIER_PATTERN = `\\[([^\\]]+)\\]`;
const OVERRIDE_IDENTIFIER_REGEX = new RegExp(OVERRIDE_IDENTIFIER_PATTERN, "g");
const OVERRIDE_PROPERTY_PATTERN = `^(${OVERRIDE_IDENTIFIER_PATTERN})+$`;
const OVERRIDE_PROPERTY_REGEX = new RegExp(OVERRIDE_PROPERTY_PATTERN);
function overrideIdentifiersFromKey(key) {
  const identifiers = [];
  if (OVERRIDE_PROPERTY_REGEX.test(key)) {
    let matches = OVERRIDE_IDENTIFIER_REGEX.exec(key);
    while (matches === null || matches === void 0 ? void 0 : matches.length) {
      const identifier = matches[1].trim();
      if (identifier) {
        identifiers.push(identifier);
      }
      matches = OVERRIDE_IDENTIFIER_REGEX.exec(key);
    }
  }
  return distinct(identifiers);
}
function getDefaultValue(type) {
  const t = Array.isArray(type) ? type[0] : type;
  switch (t) {
    case "boolean":
      return false;
    case "integer":
    case "number":
      return 0;
    case "string":
      return "";
    case "array":
      return [];
    case "object":
      return {};
    default:
      return null;
  }
}
const configurationRegistry$2 = new ConfigurationRegistry();
Registry.add(Extensions$6.Configuration, configurationRegistry$2);
function validateProperty(property, schema) {
  var _a2, _b2, _c2, _d2;
  if (!property.trim()) {
    return localize("config.property.empty", "Cannot register an empty property");
  }
  if (OVERRIDE_PROPERTY_REGEX.test(property)) {
    return localize("config.property.languageDefault", "Cannot register '{0}'. This matches property pattern '\\\\[.*\\\\]$' for describing language specific editor settings. Use 'configurationDefaults' contribution.", property);
  }
  if (configurationRegistry$2.getConfigurationProperties()[property] !== void 0) {
    return localize("config.property.duplicate", "Cannot register '{0}'. This property is already registered.", property);
  }
  if (((_a2 = schema.policy) === null || _a2 === void 0 ? void 0 : _a2.name) && configurationRegistry$2.getPolicyConfigurations().get((_b2 = schema.policy) === null || _b2 === void 0 ? void 0 : _b2.name) !== void 0) {
    return localize("config.policy.duplicate", "Cannot register '{0}'. The associated policy {1} is already registered with {2}.", property, (_c2 = schema.policy) === null || _c2 === void 0 ? void 0 : _c2.name, configurationRegistry$2.getPolicyConfigurations().get((_d2 = schema.policy) === null || _d2 === void 0 ? void 0 : _d2.name));
  }
  return null;
}
const Extensions$5 = {
  ModesRegistry: "editor.modesRegistry"
};
class EditorModesRegistry {
  constructor() {
    this._onDidChangeLanguages = new Emitter$1();
    this.onDidChangeLanguages = this._onDidChangeLanguages.event;
    this._languages = [];
  }
  registerLanguage(def2) {
    this._languages.push(def2);
    this._onDidChangeLanguages.fire(void 0);
    return {
      dispose: () => {
        for (let i = 0, len = this._languages.length; i < len; i++) {
          if (this._languages[i] === def2) {
            this._languages.splice(i, 1);
            return;
          }
        }
      }
    };
  }
  getLanguages() {
    return this._languages;
  }
}
const ModesRegistry = new EditorModesRegistry();
Registry.add(Extensions$5.ModesRegistry, ModesRegistry);
const PLAINTEXT_LANGUAGE_ID = "plaintext";
const PLAINTEXT_EXTENSION = ".txt";
ModesRegistry.registerLanguage({
  id: PLAINTEXT_LANGUAGE_ID,
  extensions: [PLAINTEXT_EXTENSION],
  aliases: [localize("plainText.alias", "Plain Text"), "text"],
  mimetypes: [Mimes.text]
});
Registry.as(Extensions$6.Configuration).registerDefaultConfigurations([{
  overrides: {
    "[plaintext]": {
      "editor.unicodeHighlight.ambiguousCharacters": false,
      "editor.unicodeHighlight.invisibleCharacters": false
    }
  }
}]);
class LanguageBracketsConfiguration {
  constructor(languageId, config2) {
    this.languageId = languageId;
    const bracketPairs = config2.brackets ? filterValidBrackets(config2.brackets) : [];
    const openingBracketInfos = new CachedFunction((bracket) => {
      const closing = /* @__PURE__ */ new Set();
      return {
        info: new OpeningBracketKind(this, bracket, closing),
        closing
      };
    });
    const closingBracketInfos = new CachedFunction((bracket) => {
      const opening = /* @__PURE__ */ new Set();
      const openingColorized = /* @__PURE__ */ new Set();
      return {
        info: new ClosingBracketKind(this, bracket, opening, openingColorized),
        opening,
        openingColorized
      };
    });
    for (const [open, close] of bracketPairs) {
      const opening = openingBracketInfos.get(open);
      const closing = closingBracketInfos.get(close);
      opening.closing.add(closing.info);
      closing.opening.add(opening.info);
    }
    const colorizedBracketPairs = config2.colorizedBracketPairs ? filterValidBrackets(config2.colorizedBracketPairs) : bracketPairs.filter((p2) => !(p2[0] === "<" && p2[1] === ">"));
    for (const [open, close] of colorizedBracketPairs) {
      const opening = openingBracketInfos.get(open);
      const closing = closingBracketInfos.get(close);
      opening.closing.add(closing.info);
      closing.openingColorized.add(opening.info);
      closing.opening.add(opening.info);
    }
    this._openingBrackets = new Map([...openingBracketInfos.cachedValues].map(([k, v]) => [k, v.info]));
    this._closingBrackets = new Map([...closingBracketInfos.cachedValues].map(([k, v]) => [k, v.info]));
  }
  /**
   * No two brackets have the same bracket text.
  */
  get openingBrackets() {
    return [...this._openingBrackets.values()];
  }
  /**
   * No two brackets have the same bracket text.
  */
  get closingBrackets() {
    return [...this._closingBrackets.values()];
  }
  getOpeningBracketInfo(bracketText) {
    return this._openingBrackets.get(bracketText);
  }
  getClosingBracketInfo(bracketText) {
    return this._closingBrackets.get(bracketText);
  }
  getBracketInfo(bracketText) {
    return this.getOpeningBracketInfo(bracketText) || this.getClosingBracketInfo(bracketText);
  }
}
function filterValidBrackets(bracketPairs) {
  return bracketPairs.filter(([open, close]) => open !== "" && close !== "");
}
class BracketKindBase {
  constructor(config2, bracketText) {
    this.config = config2;
    this.bracketText = bracketText;
  }
  get languageId() {
    return this.config.languageId;
  }
}
class OpeningBracketKind extends BracketKindBase {
  constructor(config2, bracketText, openedBrackets) {
    super(config2, bracketText);
    this.openedBrackets = openedBrackets;
    this.isOpeningBracket = true;
  }
}
class ClosingBracketKind extends BracketKindBase {
  constructor(config2, bracketText, openingBrackets, openingColorizedBrackets) {
    super(config2, bracketText);
    this.openingBrackets = openingBrackets;
    this.openingColorizedBrackets = openingColorizedBrackets;
    this.isOpeningBracket = false;
  }
  /**
   * Checks if this bracket closes the given other bracket.
   * If the bracket infos come from different configurations, this method will return false.
  */
  closes(other) {
    if (other["config"] !== this.config) {
      return false;
    }
    return this.openingBrackets.has(other);
  }
  closesColorized(other) {
    if (other["config"] !== this.config) {
      return false;
    }
    return this.openingColorizedBrackets.has(other);
  }
  getOpeningBrackets() {
    return [...this.openingBrackets];
  }
}
var __decorate$2a = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$23 = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
class LanguageConfigurationServiceChangeEvent {
  constructor(languageId) {
    this.languageId = languageId;
  }
  affects(languageId) {
    return !this.languageId ? true : this.languageId === languageId;
  }
}
const ILanguageConfigurationService = createDecorator("languageConfigurationService");
let LanguageConfigurationService = class LanguageConfigurationService2 extends Disposable {
  constructor(configurationService, languageService) {
    super();
    this.configurationService = configurationService;
    this.languageService = languageService;
    this._registry = this._register(new LanguageConfigurationRegistry());
    this.onDidChangeEmitter = this._register(new Emitter$1());
    this.onDidChange = this.onDidChangeEmitter.event;
    this.configurations = /* @__PURE__ */ new Map();
    const languageConfigKeys = new Set(Object.values(customizedLanguageConfigKeys));
    this._register(this.configurationService.onDidChangeConfiguration((e) => {
      const globalConfigChanged = e.change.keys.some((k) => languageConfigKeys.has(k));
      const localConfigChanged = e.change.overrides.filter(([overrideLangName, keys]) => keys.some((k) => languageConfigKeys.has(k))).map(([overrideLangName]) => overrideLangName);
      if (globalConfigChanged) {
        this.configurations.clear();
        this.onDidChangeEmitter.fire(new LanguageConfigurationServiceChangeEvent(void 0));
      } else {
        for (const languageId of localConfigChanged) {
          if (this.languageService.isRegisteredLanguageId(languageId)) {
            this.configurations.delete(languageId);
            this.onDidChangeEmitter.fire(new LanguageConfigurationServiceChangeEvent(languageId));
          }
        }
      }
    }));
    this._register(this._registry.onDidChange((e) => {
      this.configurations.delete(e.languageId);
      this.onDidChangeEmitter.fire(new LanguageConfigurationServiceChangeEvent(e.languageId));
    }));
  }
  register(languageId, configuration, priority) {
    return this._registry.register(languageId, configuration, priority);
  }
  getLanguageConfiguration(languageId) {
    let result2 = this.configurations.get(languageId);
    if (!result2) {
      result2 = computeConfig(languageId, this._registry, this.configurationService, this.languageService);
      this.configurations.set(languageId, result2);
    }
    return result2;
  }
};
LanguageConfigurationService = __decorate$2a([
  __param$23(0, IConfigurationService),
  __param$23(1, ILanguageService)
], LanguageConfigurationService);
function computeConfig(languageId, registry, configurationService, languageService) {
  let languageConfig = registry.getLanguageConfiguration(languageId);
  if (!languageConfig) {
    if (!languageService.isRegisteredLanguageId(languageId)) {
      return new ResolvedLanguageConfiguration(languageId, {});
    }
    languageConfig = new ResolvedLanguageConfiguration(languageId, {});
  }
  const customizedConfig = getCustomizedLanguageConfig(languageConfig.languageId, configurationService);
  const data = combineLanguageConfigurations([languageConfig.underlyingConfig, customizedConfig]);
  const config2 = new ResolvedLanguageConfiguration(languageConfig.languageId, data);
  return config2;
}
const customizedLanguageConfigKeys = {
  brackets: "editor.language.brackets",
  colorizedBracketPairs: "editor.language.colorizedBracketPairs"
};
function getCustomizedLanguageConfig(languageId, configurationService) {
  const brackets = configurationService.getValue(customizedLanguageConfigKeys.brackets, {
    overrideIdentifier: languageId
  });
  const colorizedBracketPairs = configurationService.getValue(customizedLanguageConfigKeys.colorizedBracketPairs, {
    overrideIdentifier: languageId
  });
  return {
    brackets: validateBracketPairs(brackets),
    colorizedBracketPairs: validateBracketPairs(colorizedBracketPairs)
  };
}
function validateBracketPairs(data) {
  if (!Array.isArray(data)) {
    return void 0;
  }
  return data.map((pair) => {
    if (!Array.isArray(pair) || pair.length !== 2) {
      return void 0;
    }
    return [pair[0], pair[1]];
  }).filter((p2) => !!p2);
}
function getIndentationAtPosition(model, lineNumber, column) {
  const lineText = model.getLineContent(lineNumber);
  let indentation = getLeadingWhitespace(lineText);
  if (indentation.length > column - 1) {
    indentation = indentation.substring(0, column - 1);
  }
  return indentation;
}
function getScopedLineTokens(model, lineNumber, columnNumber) {
  model.tokenization.forceTokenization(lineNumber);
  const lineTokens = model.tokenization.getLineTokens(lineNumber);
  const column = typeof columnNumber === "undefined" ? model.getLineMaxColumn(lineNumber) - 1 : columnNumber - 1;
  return createScopedLineTokens(lineTokens, column);
}
class ComposedLanguageConfiguration {
  constructor(languageId) {
    this.languageId = languageId;
    this._resolved = null;
    this._entries = [];
    this._order = 0;
    this._resolved = null;
  }
  register(configuration, priority) {
    const entry = new LanguageConfigurationContribution(configuration, priority, ++this._order);
    this._entries.push(entry);
    this._resolved = null;
    return toDisposable(() => {
      for (let i = 0; i < this._entries.length; i++) {
        if (this._entries[i] === entry) {
          this._entries.splice(i, 1);
          this._resolved = null;
          break;
        }
      }
    });
  }
  getResolvedConfiguration() {
    if (!this._resolved) {
      const config2 = this._resolve();
      if (config2) {
        this._resolved = new ResolvedLanguageConfiguration(this.languageId, config2);
      }
    }
    return this._resolved;
  }
  _resolve() {
    if (this._entries.length === 0) {
      return null;
    }
    this._entries.sort(LanguageConfigurationContribution.cmp);
    return combineLanguageConfigurations(this._entries.map((e) => e.configuration));
  }
}
function combineLanguageConfigurations(configs) {
  let result2 = {
    comments: void 0,
    brackets: void 0,
    wordPattern: void 0,
    indentationRules: void 0,
    onEnterRules: void 0,
    autoClosingPairs: void 0,
    surroundingPairs: void 0,
    autoCloseBefore: void 0,
    folding: void 0,
    colorizedBracketPairs: void 0,
    __electricCharacterSupport: void 0
  };
  for (const entry of configs) {
    result2 = {
      comments: entry.comments || result2.comments,
      brackets: entry.brackets || result2.brackets,
      wordPattern: entry.wordPattern || result2.wordPattern,
      indentationRules: entry.indentationRules || result2.indentationRules,
      onEnterRules: entry.onEnterRules || result2.onEnterRules,
      autoClosingPairs: entry.autoClosingPairs || result2.autoClosingPairs,
      surroundingPairs: entry.surroundingPairs || result2.surroundingPairs,
      autoCloseBefore: entry.autoCloseBefore || result2.autoCloseBefore,
      folding: entry.folding || result2.folding,
      colorizedBracketPairs: entry.colorizedBracketPairs || result2.colorizedBracketPairs,
      __electricCharacterSupport: entry.__electricCharacterSupport || result2.__electricCharacterSupport
    };
  }
  return result2;
}
class LanguageConfigurationContribution {
  constructor(configuration, priority, order) {
    this.configuration = configuration;
    this.priority = priority;
    this.order = order;
  }
  static cmp(a, b) {
    if (a.priority === b.priority) {
      return a.order - b.order;
    }
    return a.priority - b.priority;
  }
}
class LanguageConfigurationChangeEvent {
  constructor(languageId) {
    this.languageId = languageId;
  }
}
class LanguageConfigurationRegistry extends Disposable {
  constructor() {
    super();
    this._entries = /* @__PURE__ */ new Map();
    this._onDidChange = this._register(new Emitter$1());
    this.onDidChange = this._onDidChange.event;
    this._register(this.register(PLAINTEXT_LANGUAGE_ID, {
      brackets: [
        ["(", ")"],
        ["[", "]"],
        ["{", "}"]
      ],
      surroundingPairs: [
        { open: "{", close: "}" },
        { open: "[", close: "]" },
        { open: "(", close: ")" },
        { open: "<", close: ">" },
        { open: '"', close: '"' },
        { open: "'", close: "'" },
        { open: "`", close: "`" }
      ],
      colorizedBracketPairs: [],
      folding: {
        offSide: true
      }
    }, 0));
  }
  /**
   * @param priority Use a higher number for higher priority
   */
  register(languageId, configuration, priority = 0) {
    let entries = this._entries.get(languageId);
    if (!entries) {
      entries = new ComposedLanguageConfiguration(languageId);
      this._entries.set(languageId, entries);
    }
    const disposable = entries.register(configuration, priority);
    this._onDidChange.fire(new LanguageConfigurationChangeEvent(languageId));
    return toDisposable(() => {
      disposable.dispose();
      this._onDidChange.fire(new LanguageConfigurationChangeEvent(languageId));
    });
  }
  getLanguageConfiguration(languageId) {
    const entries = this._entries.get(languageId);
    return (entries === null || entries === void 0 ? void 0 : entries.getResolvedConfiguration()) || null;
  }
}
class ResolvedLanguageConfiguration {
  constructor(languageId, underlyingConfig) {
    this.languageId = languageId;
    this.underlyingConfig = underlyingConfig;
    this._brackets = null;
    this._electricCharacter = null;
    this._onEnterSupport = this.underlyingConfig.brackets || this.underlyingConfig.indentationRules || this.underlyingConfig.onEnterRules ? new OnEnterSupport(this.underlyingConfig) : null;
    this.comments = ResolvedLanguageConfiguration._handleComments(this.underlyingConfig);
    this.characterPair = new CharacterPairSupport(this.underlyingConfig);
    this.wordDefinition = this.underlyingConfig.wordPattern || DEFAULT_WORD_REGEXP;
    this.indentationRules = this.underlyingConfig.indentationRules;
    if (this.underlyingConfig.indentationRules) {
      this.indentRulesSupport = new IndentRulesSupport(this.underlyingConfig.indentationRules);
    } else {
      this.indentRulesSupport = null;
    }
    this.foldingRules = this.underlyingConfig.folding || {};
    this.bracketsNew = new LanguageBracketsConfiguration(languageId, this.underlyingConfig);
  }
  getWordDefinition() {
    return ensureValidWordDefinition(this.wordDefinition);
  }
  get brackets() {
    if (!this._brackets && this.underlyingConfig.brackets) {
      this._brackets = new RichEditBrackets(this.languageId, this.underlyingConfig.brackets);
    }
    return this._brackets;
  }
  get electricCharacter() {
    if (!this._electricCharacter) {
      this._electricCharacter = new BracketElectricCharacterSupport(this.brackets);
    }
    return this._electricCharacter;
  }
  onEnter(autoIndent, previousLineText, beforeEnterText, afterEnterText) {
    if (!this._onEnterSupport) {
      return null;
    }
    return this._onEnterSupport.onEnter(autoIndent, previousLineText, beforeEnterText, afterEnterText);
  }
  getAutoClosingPairs() {
    return new AutoClosingPairs(this.characterPair.getAutoClosingPairs());
  }
  getAutoCloseBeforeSet(forQuotes) {
    return this.characterPair.getAutoCloseBeforeSet(forQuotes);
  }
  getSurroundingPairs() {
    return this.characterPair.getSurroundingPairs();
  }
  static _handleComments(conf) {
    const commentRule = conf.comments;
    if (!commentRule) {
      return null;
    }
    const comments = {};
    if (commentRule.lineComment) {
      comments.lineCommentToken = commentRule.lineComment;
    }
    if (commentRule.blockComment) {
      const [blockStart, blockEnd] = commentRule.blockComment;
      comments.blockCommentStartToken = blockStart;
      comments.blockCommentEndToken = blockEnd;
    }
    return comments;
  }
}
registerSingleton(
  ILanguageConfigurationService,
  LanguageConfigurationService,
  1
  /* InstantiationType.Delayed */
);
function getEnterAction(autoIndent, model, range2, languageConfigurationService) {
  const scopedLineTokens = getScopedLineTokens(model, range2.startLineNumber, range2.startColumn);
  const richEditSupport = languageConfigurationService.getLanguageConfiguration(scopedLineTokens.languageId);
  if (!richEditSupport) {
    return null;
  }
  const scopedLineText = scopedLineTokens.getLineContent();
  const beforeEnterText = scopedLineText.substr(0, range2.startColumn - 1 - scopedLineTokens.firstCharOffset);
  let afterEnterText;
  if (range2.isEmpty()) {
    afterEnterText = scopedLineText.substr(range2.startColumn - 1 - scopedLineTokens.firstCharOffset);
  } else {
    const endScopedLineTokens = getScopedLineTokens(model, range2.endLineNumber, range2.endColumn);
    afterEnterText = endScopedLineTokens.getLineContent().substr(range2.endColumn - 1 - scopedLineTokens.firstCharOffset);
  }
  let previousLineText = "";
  if (range2.startLineNumber > 1 && scopedLineTokens.firstCharOffset === 0) {
    const oneLineAboveScopedLineTokens = getScopedLineTokens(model, range2.startLineNumber - 1);
    if (oneLineAboveScopedLineTokens.languageId === scopedLineTokens.languageId) {
      previousLineText = oneLineAboveScopedLineTokens.getLineContent();
    }
  }
  const enterResult = richEditSupport.onEnter(autoIndent, previousLineText, beforeEnterText, afterEnterText);
  if (!enterResult) {
    return null;
  }
  const indentAction = enterResult.indentAction;
  let appendText = enterResult.appendText;
  const removeText = enterResult.removeText || 0;
  if (!appendText) {
    if (indentAction === IndentAction$1.Indent || indentAction === IndentAction$1.IndentOutdent) {
      appendText = "	";
    } else {
      appendText = "";
    }
  } else if (indentAction === IndentAction$1.Indent) {
    appendText = "	" + appendText;
  }
  let indentation = getIndentationAtPosition(model, range2.startLineNumber, range2.startColumn);
  if (removeText) {
    indentation = indentation.substring(0, indentation.length - removeText);
  }
  return {
    indentAction,
    appendText,
    removeText,
    indentation
  };
}
var __decorate$29 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$22 = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
const repeatCache = /* @__PURE__ */ Object.create(null);
function cachedStringRepeat(str2, count) {
  if (count <= 0) {
    return "";
  }
  if (!repeatCache[str2]) {
    repeatCache[str2] = ["", str2];
  }
  const cache2 = repeatCache[str2];
  for (let i = cache2.length; i <= count; i++) {
    cache2[i] = cache2[i - 1] + str2;
  }
  return cache2[count];
}
let ShiftCommand = class ShiftCommand2 {
  static unshiftIndent(line, column, tabSize, indentSize, insertSpaces) {
    const contentStartVisibleColumn = CursorColumns.visibleColumnFromColumn(line, column, tabSize);
    if (insertSpaces) {
      const indent = cachedStringRepeat(" ", indentSize);
      const desiredTabStop = CursorColumns.prevIndentTabStop(contentStartVisibleColumn, indentSize);
      const indentCount = desiredTabStop / indentSize;
      return cachedStringRepeat(indent, indentCount);
    } else {
      const indent = "	";
      const desiredTabStop = CursorColumns.prevRenderTabStop(contentStartVisibleColumn, tabSize);
      const indentCount = desiredTabStop / tabSize;
      return cachedStringRepeat(indent, indentCount);
    }
  }
  static shiftIndent(line, column, tabSize, indentSize, insertSpaces) {
    const contentStartVisibleColumn = CursorColumns.visibleColumnFromColumn(line, column, tabSize);
    if (insertSpaces) {
      const indent = cachedStringRepeat(" ", indentSize);
      const desiredTabStop = CursorColumns.nextIndentTabStop(contentStartVisibleColumn, indentSize);
      const indentCount = desiredTabStop / indentSize;
      return cachedStringRepeat(indent, indentCount);
    } else {
      const indent = "	";
      const desiredTabStop = CursorColumns.nextRenderTabStop(contentStartVisibleColumn, tabSize);
      const indentCount = desiredTabStop / tabSize;
      return cachedStringRepeat(indent, indentCount);
    }
  }
  constructor(range2, opts, _languageConfigurationService) {
    this._languageConfigurationService = _languageConfigurationService;
    this._opts = opts;
    this._selection = range2;
    this._selectionId = null;
    this._useLastEditRangeForCursorEndPosition = false;
    this._selectionStartColumnStaysPut = false;
  }
  _addEditOperation(builder, range2, text2) {
    if (this._useLastEditRangeForCursorEndPosition) {
      builder.addTrackedEditOperation(range2, text2);
    } else {
      builder.addEditOperation(range2, text2);
    }
  }
  getEditOperations(model, builder) {
    const startLine = this._selection.startLineNumber;
    let endLine = this._selection.endLineNumber;
    if (this._selection.endColumn === 1 && startLine !== endLine) {
      endLine = endLine - 1;
    }
    const { tabSize, indentSize, insertSpaces } = this._opts;
    const shouldIndentEmptyLines = startLine === endLine;
    if (this._opts.useTabStops) {
      if (this._selection.isEmpty()) {
        if (/^\s*$/.test(model.getLineContent(startLine))) {
          this._useLastEditRangeForCursorEndPosition = true;
        }
      }
      let previousLineExtraSpaces = 0, extraSpaces = 0;
      for (let lineNumber = startLine; lineNumber <= endLine; lineNumber++, previousLineExtraSpaces = extraSpaces) {
        extraSpaces = 0;
        const lineText = model.getLineContent(lineNumber);
        let indentationEndIndex = firstNonWhitespaceIndex(lineText);
        if (this._opts.isUnshift && (lineText.length === 0 || indentationEndIndex === 0)) {
          continue;
        }
        if (!shouldIndentEmptyLines && !this._opts.isUnshift && lineText.length === 0) {
          continue;
        }
        if (indentationEndIndex === -1) {
          indentationEndIndex = lineText.length;
        }
        if (lineNumber > 1) {
          const contentStartVisibleColumn = CursorColumns.visibleColumnFromColumn(lineText, indentationEndIndex + 1, tabSize);
          if (contentStartVisibleColumn % indentSize !== 0) {
            if (model.tokenization.isCheapToTokenize(lineNumber - 1)) {
              const enterAction = getEnterAction(this._opts.autoIndent, model, new Range$2(lineNumber - 1, model.getLineMaxColumn(lineNumber - 1), lineNumber - 1, model.getLineMaxColumn(lineNumber - 1)), this._languageConfigurationService);
              if (enterAction) {
                extraSpaces = previousLineExtraSpaces;
                if (enterAction.appendText) {
                  for (let j = 0, lenJ = enterAction.appendText.length; j < lenJ && extraSpaces < indentSize; j++) {
                    if (enterAction.appendText.charCodeAt(j) === 32) {
                      extraSpaces++;
                    } else {
                      break;
                    }
                  }
                }
                if (enterAction.removeText) {
                  extraSpaces = Math.max(0, extraSpaces - enterAction.removeText);
                }
                for (let j = 0; j < extraSpaces; j++) {
                  if (indentationEndIndex === 0 || lineText.charCodeAt(indentationEndIndex - 1) !== 32) {
                    break;
                  }
                  indentationEndIndex--;
                }
              }
            }
          }
        }
        if (this._opts.isUnshift && indentationEndIndex === 0) {
          continue;
        }
        let desiredIndent;
        if (this._opts.isUnshift) {
          desiredIndent = ShiftCommand2.unshiftIndent(lineText, indentationEndIndex + 1, tabSize, indentSize, insertSpaces);
        } else {
          desiredIndent = ShiftCommand2.shiftIndent(lineText, indentationEndIndex + 1, tabSize, indentSize, insertSpaces);
        }
        this._addEditOperation(builder, new Range$2(lineNumber, 1, lineNumber, indentationEndIndex + 1), desiredIndent);
        if (lineNumber === startLine && !this._selection.isEmpty()) {
          this._selectionStartColumnStaysPut = this._selection.startColumn <= indentationEndIndex + 1;
        }
      }
    } else {
      if (!this._opts.isUnshift && this._selection.isEmpty() && model.getLineLength(startLine) === 0) {
        this._useLastEditRangeForCursorEndPosition = true;
      }
      const oneIndent = insertSpaces ? cachedStringRepeat(" ", indentSize) : "	";
      for (let lineNumber = startLine; lineNumber <= endLine; lineNumber++) {
        const lineText = model.getLineContent(lineNumber);
        let indentationEndIndex = firstNonWhitespaceIndex(lineText);
        if (this._opts.isUnshift && (lineText.length === 0 || indentationEndIndex === 0)) {
          continue;
        }
        if (!shouldIndentEmptyLines && !this._opts.isUnshift && lineText.length === 0) {
          continue;
        }
        if (indentationEndIndex === -1) {
          indentationEndIndex = lineText.length;
        }
        if (this._opts.isUnshift && indentationEndIndex === 0) {
          continue;
        }
        if (this._opts.isUnshift) {
          indentationEndIndex = Math.min(indentationEndIndex, indentSize);
          for (let i = 0; i < indentationEndIndex; i++) {
            const chr = lineText.charCodeAt(i);
            if (chr === 9) {
              indentationEndIndex = i + 1;
              break;
            }
          }
          this._addEditOperation(builder, new Range$2(lineNumber, 1, lineNumber, indentationEndIndex + 1), "");
        } else {
          this._addEditOperation(builder, new Range$2(lineNumber, 1, lineNumber, 1), oneIndent);
          if (lineNumber === startLine && !this._selection.isEmpty()) {
            this._selectionStartColumnStaysPut = this._selection.startColumn === 1;
          }
        }
      }
    }
    this._selectionId = builder.trackSelection(this._selection);
  }
  computeCursorState(model, helper) {
    if (this._useLastEditRangeForCursorEndPosition) {
      const lastOp = helper.getInverseEditOperations()[0];
      return new Selection$1(lastOp.range.endLineNumber, lastOp.range.endColumn, lastOp.range.endLineNumber, lastOp.range.endColumn);
    }
    const result2 = helper.getTrackedSelection(this._selectionId);
    if (this._selectionStartColumnStaysPut) {
      const initialStartColumn = this._selection.startColumn;
      const resultStartColumn = result2.startColumn;
      if (resultStartColumn <= initialStartColumn) {
        return result2;
      }
      if (result2.getDirection() === 0) {
        return new Selection$1(result2.startLineNumber, initialStartColumn, result2.endLineNumber, result2.endColumn);
      }
      return new Selection$1(result2.endLineNumber, result2.endColumn, result2.startLineNumber, initialStartColumn);
    }
    return result2;
  }
};
ShiftCommand = __decorate$29([
  __param$22(2, ILanguageConfigurationService)
], ShiftCommand);
class SurroundSelectionCommand {
  constructor(range2, charBeforeSelection, charAfterSelection) {
    this._range = range2;
    this._charBeforeSelection = charBeforeSelection;
    this._charAfterSelection = charAfterSelection;
  }
  getEditOperations(model, builder) {
    builder.addTrackedEditOperation(new Range$2(this._range.startLineNumber, this._range.startColumn, this._range.startLineNumber, this._range.startColumn), this._charBeforeSelection);
    builder.addTrackedEditOperation(new Range$2(this._range.endLineNumber, this._range.endColumn, this._range.endLineNumber, this._range.endColumn), this._charAfterSelection);
  }
  computeCursorState(model, helper) {
    const inverseEditOperations = helper.getInverseEditOperations();
    const firstOperationRange = inverseEditOperations[0].range;
    const secondOperationRange = inverseEditOperations[1].range;
    return new Selection$1(firstOperationRange.endLineNumber, firstOperationRange.endColumn, secondOperationRange.endLineNumber, secondOperationRange.endColumn - this._charAfterSelection.length);
  }
}
class CompositionSurroundSelectionCommand {
  constructor(_position, _text, _charAfter) {
    this._position = _position;
    this._text = _text;
    this._charAfter = _charAfter;
  }
  getEditOperations(model, builder) {
    builder.addTrackedEditOperation(new Range$2(this._position.lineNumber, this._position.column, this._position.lineNumber, this._position.column), this._text + this._charAfter);
  }
  computeCursorState(model, helper) {
    const inverseEditOperations = helper.getInverseEditOperations();
    const opRange = inverseEditOperations[0].range;
    return new Selection$1(opRange.endLineNumber, opRange.startColumn, opRange.endLineNumber, opRange.endColumn - this._charAfter.length);
  }
}
function getPrecedingValidLine(model, lineNumber, indentRulesSupport) {
  const languageId = model.tokenization.getLanguageIdAtPosition(lineNumber, 0);
  if (lineNumber > 1) {
    let lastLineNumber;
    let resultLineNumber = -1;
    for (lastLineNumber = lineNumber - 1; lastLineNumber >= 1; lastLineNumber--) {
      if (model.tokenization.getLanguageIdAtPosition(lastLineNumber, 0) !== languageId) {
        return resultLineNumber;
      }
      const text2 = model.getLineContent(lastLineNumber);
      if (indentRulesSupport.shouldIgnore(text2) || /^\s+$/.test(text2) || text2 === "") {
        resultLineNumber = lastLineNumber;
        continue;
      }
      return lastLineNumber;
    }
  }
  return -1;
}
function getInheritIndentForLine(autoIndent, model, lineNumber, honorIntentialIndent = true, languageConfigurationService) {
  if (autoIndent < 4) {
    return null;
  }
  const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(model.tokenization.getLanguageId()).indentRulesSupport;
  if (!indentRulesSupport) {
    return null;
  }
  if (lineNumber <= 1) {
    return {
      indentation: "",
      action: null
    };
  }
  for (let priorLineNumber = lineNumber - 1; priorLineNumber > 0; priorLineNumber--) {
    if (model.getLineContent(priorLineNumber) !== "") {
      break;
    }
    if (priorLineNumber === 1) {
      return {
        indentation: "",
        action: null
      };
    }
  }
  const precedingUnIgnoredLine = getPrecedingValidLine(model, lineNumber, indentRulesSupport);
  if (precedingUnIgnoredLine < 0) {
    return null;
  } else if (precedingUnIgnoredLine < 1) {
    return {
      indentation: "",
      action: null
    };
  }
  const precedingUnIgnoredLineContent = model.getLineContent(precedingUnIgnoredLine);
  if (indentRulesSupport.shouldIncrease(precedingUnIgnoredLineContent) || indentRulesSupport.shouldIndentNextLine(precedingUnIgnoredLineContent)) {
    return {
      indentation: getLeadingWhitespace(precedingUnIgnoredLineContent),
      action: IndentAction$1.Indent,
      line: precedingUnIgnoredLine
    };
  } else if (indentRulesSupport.shouldDecrease(precedingUnIgnoredLineContent)) {
    return {
      indentation: getLeadingWhitespace(precedingUnIgnoredLineContent),
      action: null,
      line: precedingUnIgnoredLine
    };
  } else {
    if (precedingUnIgnoredLine === 1) {
      return {
        indentation: getLeadingWhitespace(model.getLineContent(precedingUnIgnoredLine)),
        action: null,
        line: precedingUnIgnoredLine
      };
    }
    const previousLine = precedingUnIgnoredLine - 1;
    const previousLineIndentMetadata = indentRulesSupport.getIndentMetadata(model.getLineContent(previousLine));
    if (!(previousLineIndentMetadata & (1 | 2)) && previousLineIndentMetadata & 4) {
      let stopLine = 0;
      for (let i = previousLine - 1; i > 0; i--) {
        if (indentRulesSupport.shouldIndentNextLine(model.getLineContent(i))) {
          continue;
        }
        stopLine = i;
        break;
      }
      return {
        indentation: getLeadingWhitespace(model.getLineContent(stopLine + 1)),
        action: null,
        line: stopLine + 1
      };
    }
    if (honorIntentialIndent) {
      return {
        indentation: getLeadingWhitespace(model.getLineContent(precedingUnIgnoredLine)),
        action: null,
        line: precedingUnIgnoredLine
      };
    } else {
      for (let i = precedingUnIgnoredLine; i > 0; i--) {
        const lineContent = model.getLineContent(i);
        if (indentRulesSupport.shouldIncrease(lineContent)) {
          return {
            indentation: getLeadingWhitespace(lineContent),
            action: IndentAction$1.Indent,
            line: i
          };
        } else if (indentRulesSupport.shouldIndentNextLine(lineContent)) {
          let stopLine = 0;
          for (let j = i - 1; j > 0; j--) {
            if (indentRulesSupport.shouldIndentNextLine(model.getLineContent(i))) {
              continue;
            }
            stopLine = j;
            break;
          }
          return {
            indentation: getLeadingWhitespace(model.getLineContent(stopLine + 1)),
            action: null,
            line: stopLine + 1
          };
        } else if (indentRulesSupport.shouldDecrease(lineContent)) {
          return {
            indentation: getLeadingWhitespace(lineContent),
            action: null,
            line: i
          };
        }
      }
      return {
        indentation: getLeadingWhitespace(model.getLineContent(1)),
        action: null,
        line: 1
      };
    }
  }
}
function getGoodIndentForLine(autoIndent, virtualModel, languageId, lineNumber, indentConverter, languageConfigurationService) {
  if (autoIndent < 4) {
    return null;
  }
  const richEditSupport = languageConfigurationService.getLanguageConfiguration(languageId);
  if (!richEditSupport) {
    return null;
  }
  const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(languageId).indentRulesSupport;
  if (!indentRulesSupport) {
    return null;
  }
  const indent = getInheritIndentForLine(autoIndent, virtualModel, lineNumber, void 0, languageConfigurationService);
  const lineContent = virtualModel.getLineContent(lineNumber);
  if (indent) {
    const inheritLine = indent.line;
    if (inheritLine !== void 0) {
      let shouldApplyEnterRules = true;
      for (let inBetweenLine = inheritLine; inBetweenLine < lineNumber - 1; inBetweenLine++) {
        if (!/^\s*$/.test(virtualModel.getLineContent(inBetweenLine))) {
          shouldApplyEnterRules = false;
          break;
        }
      }
      if (shouldApplyEnterRules) {
        const enterResult = richEditSupport.onEnter(autoIndent, "", virtualModel.getLineContent(inheritLine), "");
        if (enterResult) {
          let indentation = getLeadingWhitespace(virtualModel.getLineContent(inheritLine));
          if (enterResult.removeText) {
            indentation = indentation.substring(0, indentation.length - enterResult.removeText);
          }
          if (enterResult.indentAction === IndentAction$1.Indent || enterResult.indentAction === IndentAction$1.IndentOutdent) {
            indentation = indentConverter.shiftIndent(indentation);
          } else if (enterResult.indentAction === IndentAction$1.Outdent) {
            indentation = indentConverter.unshiftIndent(indentation);
          }
          if (indentRulesSupport.shouldDecrease(lineContent)) {
            indentation = indentConverter.unshiftIndent(indentation);
          }
          if (enterResult.appendText) {
            indentation += enterResult.appendText;
          }
          return getLeadingWhitespace(indentation);
        }
      }
    }
    if (indentRulesSupport.shouldDecrease(lineContent)) {
      if (indent.action === IndentAction$1.Indent) {
        return indent.indentation;
      } else {
        return indentConverter.unshiftIndent(indent.indentation);
      }
    } else {
      if (indent.action === IndentAction$1.Indent) {
        return indentConverter.shiftIndent(indent.indentation);
      } else {
        return indent.indentation;
      }
    }
  }
  return null;
}
function getIndentForEnter(autoIndent, model, range2, indentConverter, languageConfigurationService) {
  if (autoIndent < 4) {
    return null;
  }
  model.tokenization.forceTokenization(range2.startLineNumber);
  const lineTokens = model.tokenization.getLineTokens(range2.startLineNumber);
  const scopedLineTokens = createScopedLineTokens(lineTokens, range2.startColumn - 1);
  const scopedLineText = scopedLineTokens.getLineContent();
  let embeddedLanguage = false;
  let beforeEnterText;
  if (scopedLineTokens.firstCharOffset > 0 && lineTokens.getLanguageId(0) !== scopedLineTokens.languageId) {
    embeddedLanguage = true;
    beforeEnterText = scopedLineText.substr(0, range2.startColumn - 1 - scopedLineTokens.firstCharOffset);
  } else {
    beforeEnterText = lineTokens.getLineContent().substring(0, range2.startColumn - 1);
  }
  let afterEnterText;
  if (range2.isEmpty()) {
    afterEnterText = scopedLineText.substr(range2.startColumn - 1 - scopedLineTokens.firstCharOffset);
  } else {
    const endScopedLineTokens = getScopedLineTokens(model, range2.endLineNumber, range2.endColumn);
    afterEnterText = endScopedLineTokens.getLineContent().substr(range2.endColumn - 1 - scopedLineTokens.firstCharOffset);
  }
  const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(scopedLineTokens.languageId).indentRulesSupport;
  if (!indentRulesSupport) {
    return null;
  }
  const beforeEnterResult = beforeEnterText;
  const beforeEnterIndent = getLeadingWhitespace(beforeEnterText);
  const virtualModel = {
    tokenization: {
      getLineTokens: (lineNumber) => {
        return model.tokenization.getLineTokens(lineNumber);
      },
      getLanguageId: () => {
        return model.getLanguageId();
      },
      getLanguageIdAtPosition: (lineNumber, column) => {
        return model.getLanguageIdAtPosition(lineNumber, column);
      }
    },
    getLineContent: (lineNumber) => {
      if (lineNumber === range2.startLineNumber) {
        return beforeEnterResult;
      } else {
        return model.getLineContent(lineNumber);
      }
    }
  };
  const currentLineIndent = getLeadingWhitespace(lineTokens.getLineContent());
  const afterEnterAction = getInheritIndentForLine(autoIndent, virtualModel, range2.startLineNumber + 1, void 0, languageConfigurationService);
  if (!afterEnterAction) {
    const beforeEnter = embeddedLanguage ? currentLineIndent : beforeEnterIndent;
    return {
      beforeEnter,
      afterEnter: beforeEnter
    };
  }
  let afterEnterIndent = embeddedLanguage ? currentLineIndent : afterEnterAction.indentation;
  if (afterEnterAction.action === IndentAction$1.Indent) {
    afterEnterIndent = indentConverter.shiftIndent(afterEnterIndent);
  }
  if (indentRulesSupport.shouldDecrease(afterEnterText)) {
    afterEnterIndent = indentConverter.unshiftIndent(afterEnterIndent);
  }
  return {
    beforeEnter: embeddedLanguage ? currentLineIndent : beforeEnterIndent,
    afterEnter: afterEnterIndent
  };
}
function getIndentActionForType(autoIndent, model, range2, ch, indentConverter, languageConfigurationService) {
  if (autoIndent < 4) {
    return null;
  }
  const scopedLineTokens = getScopedLineTokens(model, range2.startLineNumber, range2.startColumn);
  if (scopedLineTokens.firstCharOffset) {
    return null;
  }
  const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(scopedLineTokens.languageId).indentRulesSupport;
  if (!indentRulesSupport) {
    return null;
  }
  const scopedLineText = scopedLineTokens.getLineContent();
  const beforeTypeText = scopedLineText.substr(0, range2.startColumn - 1 - scopedLineTokens.firstCharOffset);
  let afterTypeText;
  if (range2.isEmpty()) {
    afterTypeText = scopedLineText.substr(range2.startColumn - 1 - scopedLineTokens.firstCharOffset);
  } else {
    const endScopedLineTokens = getScopedLineTokens(model, range2.endLineNumber, range2.endColumn);
    afterTypeText = endScopedLineTokens.getLineContent().substr(range2.endColumn - 1 - scopedLineTokens.firstCharOffset);
  }
  if (!indentRulesSupport.shouldDecrease(beforeTypeText + afterTypeText) && indentRulesSupport.shouldDecrease(beforeTypeText + ch + afterTypeText)) {
    const r = getInheritIndentForLine(autoIndent, model, range2.startLineNumber, false, languageConfigurationService);
    if (!r) {
      return null;
    }
    let indentation = r.indentation;
    if (r.action !== IndentAction$1.Indent) {
      indentation = indentConverter.unshiftIndent(indentation);
    }
    return indentation;
  }
  return null;
}
function getIndentMetadata(model, lineNumber, languageConfigurationService) {
  const indentRulesSupport = languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).indentRulesSupport;
  if (!indentRulesSupport) {
    return null;
  }
  if (lineNumber < 1 || lineNumber > model.getLineCount()) {
    return null;
  }
  return indentRulesSupport.getIndentMetadata(model.getLineContent(lineNumber));
}
class TypeOperations {
  static indent(config2, model, selections2) {
    if (model === null || selections2 === null) {
      return [];
    }
    const commands = [];
    for (let i = 0, len = selections2.length; i < len; i++) {
      commands[i] = new ShiftCommand(selections2[i], {
        isUnshift: false,
        tabSize: config2.tabSize,
        indentSize: config2.indentSize,
        insertSpaces: config2.insertSpaces,
        useTabStops: config2.useTabStops,
        autoIndent: config2.autoIndent
      }, config2.languageConfigurationService);
    }
    return commands;
  }
  static outdent(config2, model, selections2) {
    const commands = [];
    for (let i = 0, len = selections2.length; i < len; i++) {
      commands[i] = new ShiftCommand(selections2[i], {
        isUnshift: true,
        tabSize: config2.tabSize,
        indentSize: config2.indentSize,
        insertSpaces: config2.insertSpaces,
        useTabStops: config2.useTabStops,
        autoIndent: config2.autoIndent
      }, config2.languageConfigurationService);
    }
    return commands;
  }
  static shiftIndent(config2, indentation, count) {
    count = count || 1;
    return ShiftCommand.shiftIndent(indentation, indentation.length + count, config2.tabSize, config2.indentSize, config2.insertSpaces);
  }
  static unshiftIndent(config2, indentation, count) {
    count = count || 1;
    return ShiftCommand.unshiftIndent(indentation, indentation.length + count, config2.tabSize, config2.indentSize, config2.insertSpaces);
  }
  static _distributedPaste(config2, model, selections2, text2) {
    const commands = [];
    for (let i = 0, len = selections2.length; i < len; i++) {
      commands[i] = new ReplaceCommand(selections2[i], text2[i]);
    }
    return new EditOperationResult(0, commands, {
      shouldPushStackElementBefore: true,
      shouldPushStackElementAfter: true
    });
  }
  static _simplePaste(config2, model, selections2, text2, pasteOnNewLine) {
    const commands = [];
    for (let i = 0, len = selections2.length; i < len; i++) {
      const selection = selections2[i];
      const position = selection.getPosition();
      if (pasteOnNewLine && !selection.isEmpty()) {
        pasteOnNewLine = false;
      }
      if (pasteOnNewLine && text2.indexOf("\n") !== text2.length - 1) {
        pasteOnNewLine = false;
      }
      if (pasteOnNewLine) {
        const typeSelection = new Range$2(position.lineNumber, 1, position.lineNumber, 1);
        commands[i] = new ReplaceCommandThatPreservesSelection(typeSelection, text2, selection, true);
      } else {
        commands[i] = new ReplaceCommand(selection, text2);
      }
    }
    return new EditOperationResult(0, commands, {
      shouldPushStackElementBefore: true,
      shouldPushStackElementAfter: true
    });
  }
  static _distributePasteToCursors(config2, selections2, text2, pasteOnNewLine, multicursorText) {
    if (pasteOnNewLine) {
      return null;
    }
    if (selections2.length === 1) {
      return null;
    }
    if (multicursorText && multicursorText.length === selections2.length) {
      return multicursorText;
    }
    if (config2.multiCursorPaste === "spread") {
      if (text2.charCodeAt(text2.length - 1) === 10) {
        text2 = text2.substr(0, text2.length - 1);
      }
      if (text2.charCodeAt(text2.length - 1) === 13) {
        text2 = text2.substr(0, text2.length - 1);
      }
      const lines = splitLines(text2);
      if (lines.length === selections2.length) {
        return lines;
      }
    }
    return null;
  }
  static paste(config2, model, selections2, text2, pasteOnNewLine, multicursorText) {
    const distributedPaste = this._distributePasteToCursors(config2, selections2, text2, pasteOnNewLine, multicursorText);
    if (distributedPaste) {
      selections2 = selections2.sort(Range$2.compareRangesUsingStarts);
      return this._distributedPaste(config2, model, selections2, distributedPaste);
    } else {
      return this._simplePaste(config2, model, selections2, text2, pasteOnNewLine);
    }
  }
  static _goodIndentForLine(config2, model, lineNumber) {
    let action = null;
    let indentation = "";
    const expectedIndentAction = getInheritIndentForLine(config2.autoIndent, model, lineNumber, false, config2.languageConfigurationService);
    if (expectedIndentAction) {
      action = expectedIndentAction.action;
      indentation = expectedIndentAction.indentation;
    } else if (lineNumber > 1) {
      let lastLineNumber;
      for (lastLineNumber = lineNumber - 1; lastLineNumber >= 1; lastLineNumber--) {
        const lineText = model.getLineContent(lastLineNumber);
        const nonWhitespaceIdx = lastNonWhitespaceIndex(lineText);
        if (nonWhitespaceIdx >= 0) {
          break;
        }
      }
      if (lastLineNumber < 1) {
        return null;
      }
      const maxColumn = model.getLineMaxColumn(lastLineNumber);
      const expectedEnterAction = getEnterAction(config2.autoIndent, model, new Range$2(lastLineNumber, maxColumn, lastLineNumber, maxColumn), config2.languageConfigurationService);
      if (expectedEnterAction) {
        indentation = expectedEnterAction.indentation + expectedEnterAction.appendText;
      }
    }
    if (action) {
      if (action === IndentAction$1.Indent) {
        indentation = TypeOperations.shiftIndent(config2, indentation);
      }
      if (action === IndentAction$1.Outdent) {
        indentation = TypeOperations.unshiftIndent(config2, indentation);
      }
      indentation = config2.normalizeIndentation(indentation);
    }
    if (!indentation) {
      return null;
    }
    return indentation;
  }
  static _replaceJumpToNextIndent(config2, model, selection, insertsAutoWhitespace) {
    let typeText = "";
    const position = selection.getStartPosition();
    if (config2.insertSpaces) {
      const visibleColumnFromColumn = config2.visibleColumnFromColumn(model, position);
      const indentSize = config2.indentSize;
      const spacesCnt = indentSize - visibleColumnFromColumn % indentSize;
      for (let i = 0; i < spacesCnt; i++) {
        typeText += " ";
      }
    } else {
      typeText = "	";
    }
    return new ReplaceCommand(selection, typeText, insertsAutoWhitespace);
  }
  static tab(config2, model, selections2) {
    const commands = [];
    for (let i = 0, len = selections2.length; i < len; i++) {
      const selection = selections2[i];
      if (selection.isEmpty()) {
        const lineText = model.getLineContent(selection.startLineNumber);
        if (/^\s*$/.test(lineText) && model.tokenization.isCheapToTokenize(selection.startLineNumber)) {
          let goodIndent = this._goodIndentForLine(config2, model, selection.startLineNumber);
          goodIndent = goodIndent || "	";
          const possibleTypeText = config2.normalizeIndentation(goodIndent);
          if (!lineText.startsWith(possibleTypeText)) {
            commands[i] = new ReplaceCommand(new Range$2(selection.startLineNumber, 1, selection.startLineNumber, lineText.length + 1), possibleTypeText, true);
            continue;
          }
        }
        commands[i] = this._replaceJumpToNextIndent(config2, model, selection, true);
      } else {
        if (selection.startLineNumber === selection.endLineNumber) {
          const lineMaxColumn = model.getLineMaxColumn(selection.startLineNumber);
          if (selection.startColumn !== 1 || selection.endColumn !== lineMaxColumn) {
            commands[i] = this._replaceJumpToNextIndent(config2, model, selection, false);
            continue;
          }
        }
        commands[i] = new ShiftCommand(selection, {
          isUnshift: false,
          tabSize: config2.tabSize,
          indentSize: config2.indentSize,
          insertSpaces: config2.insertSpaces,
          useTabStops: config2.useTabStops,
          autoIndent: config2.autoIndent
        }, config2.languageConfigurationService);
      }
    }
    return commands;
  }
  static compositionType(prevEditOperationType, config2, model, selections2, text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta) {
    const commands = selections2.map((selection) => this._compositionType(model, selection, text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta));
    return new EditOperationResult(4, commands, {
      shouldPushStackElementBefore: shouldPushStackElementBetween(
        prevEditOperationType,
        4
        /* EditOperationType.TypingOther */
      ),
      shouldPushStackElementAfter: false
    });
  }
  static _compositionType(model, selection, text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta) {
    if (!selection.isEmpty()) {
      return null;
    }
    const pos = selection.getPosition();
    const startColumn = Math.max(1, pos.column - replacePrevCharCnt);
    const endColumn = Math.min(model.getLineMaxColumn(pos.lineNumber), pos.column + replaceNextCharCnt);
    const range2 = new Range$2(pos.lineNumber, startColumn, pos.lineNumber, endColumn);
    const oldText = model.getValueInRange(range2);
    if (oldText === text2 && positionDelta === 0) {
      return null;
    }
    return new ReplaceCommandWithOffsetCursorState(range2, text2, 0, positionDelta);
  }
  static _typeCommand(range2, text2, keepPosition) {
    if (keepPosition) {
      return new ReplaceCommandWithoutChangingPosition(range2, text2, true);
    } else {
      return new ReplaceCommand(range2, text2, true);
    }
  }
  static _enter(config2, model, keepPosition, range2) {
    if (config2.autoIndent === 0) {
      return TypeOperations._typeCommand(range2, "\n", keepPosition);
    }
    if (!model.tokenization.isCheapToTokenize(range2.getStartPosition().lineNumber) || config2.autoIndent === 1) {
      const lineText2 = model.getLineContent(range2.startLineNumber);
      const indentation2 = getLeadingWhitespace(lineText2).substring(0, range2.startColumn - 1);
      return TypeOperations._typeCommand(range2, "\n" + config2.normalizeIndentation(indentation2), keepPosition);
    }
    const r = getEnterAction(config2.autoIndent, model, range2, config2.languageConfigurationService);
    if (r) {
      if (r.indentAction === IndentAction$1.None) {
        return TypeOperations._typeCommand(range2, "\n" + config2.normalizeIndentation(r.indentation + r.appendText), keepPosition);
      } else if (r.indentAction === IndentAction$1.Indent) {
        return TypeOperations._typeCommand(range2, "\n" + config2.normalizeIndentation(r.indentation + r.appendText), keepPosition);
      } else if (r.indentAction === IndentAction$1.IndentOutdent) {
        const normalIndent = config2.normalizeIndentation(r.indentation);
        const increasedIndent = config2.normalizeIndentation(r.indentation + r.appendText);
        const typeText = "\n" + increasedIndent + "\n" + normalIndent;
        if (keepPosition) {
          return new ReplaceCommandWithoutChangingPosition(range2, typeText, true);
        } else {
          return new ReplaceCommandWithOffsetCursorState(range2, typeText, -1, increasedIndent.length - normalIndent.length, true);
        }
      } else if (r.indentAction === IndentAction$1.Outdent) {
        const actualIndentation = TypeOperations.unshiftIndent(config2, r.indentation);
        return TypeOperations._typeCommand(range2, "\n" + config2.normalizeIndentation(actualIndentation + r.appendText), keepPosition);
      }
    }
    const lineText = model.getLineContent(range2.startLineNumber);
    const indentation = getLeadingWhitespace(lineText).substring(0, range2.startColumn - 1);
    if (config2.autoIndent >= 4) {
      const ir = getIndentForEnter(config2.autoIndent, model, range2, {
        unshiftIndent: (indent) => {
          return TypeOperations.unshiftIndent(config2, indent);
        },
        shiftIndent: (indent) => {
          return TypeOperations.shiftIndent(config2, indent);
        },
        normalizeIndentation: (indent) => {
          return config2.normalizeIndentation(indent);
        }
      }, config2.languageConfigurationService);
      if (ir) {
        let oldEndViewColumn = config2.visibleColumnFromColumn(model, range2.getEndPosition());
        const oldEndColumn = range2.endColumn;
        const newLineContent = model.getLineContent(range2.endLineNumber);
        const firstNonWhitespace = firstNonWhitespaceIndex(newLineContent);
        if (firstNonWhitespace >= 0) {
          range2 = range2.setEndPosition(range2.endLineNumber, Math.max(range2.endColumn, firstNonWhitespace + 1));
        } else {
          range2 = range2.setEndPosition(range2.endLineNumber, model.getLineMaxColumn(range2.endLineNumber));
        }
        if (keepPosition) {
          return new ReplaceCommandWithoutChangingPosition(range2, "\n" + config2.normalizeIndentation(ir.afterEnter), true);
        } else {
          let offset = 0;
          if (oldEndColumn <= firstNonWhitespace + 1) {
            if (!config2.insertSpaces) {
              oldEndViewColumn = Math.ceil(oldEndViewColumn / config2.indentSize);
            }
            offset = Math.min(oldEndViewColumn + 1 - config2.normalizeIndentation(ir.afterEnter).length - 1, 0);
          }
          return new ReplaceCommandWithOffsetCursorState(range2, "\n" + config2.normalizeIndentation(ir.afterEnter), 0, offset, true);
        }
      }
    }
    return TypeOperations._typeCommand(range2, "\n" + config2.normalizeIndentation(indentation), keepPosition);
  }
  static _isAutoIndentType(config2, model, selections2) {
    if (config2.autoIndent < 4) {
      return false;
    }
    for (let i = 0, len = selections2.length; i < len; i++) {
      if (!model.tokenization.isCheapToTokenize(selections2[i].getEndPosition().lineNumber)) {
        return false;
      }
    }
    return true;
  }
  static _runAutoIndentType(config2, model, range2, ch) {
    const currentIndentation = getIndentationAtPosition(model, range2.startLineNumber, range2.startColumn);
    const actualIndentation = getIndentActionForType(config2.autoIndent, model, range2, ch, {
      shiftIndent: (indentation) => {
        return TypeOperations.shiftIndent(config2, indentation);
      },
      unshiftIndent: (indentation) => {
        return TypeOperations.unshiftIndent(config2, indentation);
      }
    }, config2.languageConfigurationService);
    if (actualIndentation === null) {
      return null;
    }
    if (actualIndentation !== config2.normalizeIndentation(currentIndentation)) {
      const firstNonWhitespace = model.getLineFirstNonWhitespaceColumn(range2.startLineNumber);
      if (firstNonWhitespace === 0) {
        return TypeOperations._typeCommand(new Range$2(range2.startLineNumber, 1, range2.endLineNumber, range2.endColumn), config2.normalizeIndentation(actualIndentation) + ch, false);
      } else {
        return TypeOperations._typeCommand(new Range$2(range2.startLineNumber, 1, range2.endLineNumber, range2.endColumn), config2.normalizeIndentation(actualIndentation) + model.getLineContent(range2.startLineNumber).substring(firstNonWhitespace - 1, range2.startColumn - 1) + ch, false);
      }
    }
    return null;
  }
  static _isAutoClosingOvertype(config2, model, selections2, autoClosedCharacters, ch) {
    if (config2.autoClosingOvertype === "never") {
      return false;
    }
    if (!config2.autoClosingPairs.autoClosingPairsCloseSingleChar.has(ch)) {
      return false;
    }
    for (let i = 0, len = selections2.length; i < len; i++) {
      const selection = selections2[i];
      if (!selection.isEmpty()) {
        return false;
      }
      const position = selection.getPosition();
      const lineText = model.getLineContent(position.lineNumber);
      const afterCharacter = lineText.charAt(position.column - 1);
      if (afterCharacter !== ch) {
        return false;
      }
      const chIsQuote = isQuote(ch);
      const beforeCharacter = position.column > 2 ? lineText.charCodeAt(position.column - 2) : 0;
      if (beforeCharacter === 92 && chIsQuote) {
        return false;
      }
      if (config2.autoClosingOvertype === "auto") {
        let found = false;
        for (let j = 0, lenJ = autoClosedCharacters.length; j < lenJ; j++) {
          const autoClosedCharacter = autoClosedCharacters[j];
          if (position.lineNumber === autoClosedCharacter.startLineNumber && position.column === autoClosedCharacter.startColumn) {
            found = true;
            break;
          }
        }
        if (!found) {
          return false;
        }
      }
    }
    return true;
  }
  static _runAutoClosingOvertype(prevEditOperationType, config2, model, selections2, ch) {
    const commands = [];
    for (let i = 0, len = selections2.length; i < len; i++) {
      const selection = selections2[i];
      const position = selection.getPosition();
      const typeSelection = new Range$2(position.lineNumber, position.column, position.lineNumber, position.column + 1);
      commands[i] = new ReplaceCommand(typeSelection, ch);
    }
    return new EditOperationResult(4, commands, {
      shouldPushStackElementBefore: shouldPushStackElementBetween(
        prevEditOperationType,
        4
        /* EditOperationType.TypingOther */
      ),
      shouldPushStackElementAfter: false
    });
  }
  static _isBeforeClosingBrace(config2, lineAfter) {
    const nextChar = lineAfter.charAt(0);
    const potentialStartingBraces = config2.autoClosingPairs.autoClosingPairsOpenByStart.get(nextChar) || [];
    const potentialClosingBraces = config2.autoClosingPairs.autoClosingPairsCloseByStart.get(nextChar) || [];
    const isBeforeStartingBrace = potentialStartingBraces.some((x) => lineAfter.startsWith(x.open));
    const isBeforeClosingBrace = potentialClosingBraces.some((x) => lineAfter.startsWith(x.close));
    return !isBeforeStartingBrace && isBeforeClosingBrace;
  }
  /**
   * Determine if typing `ch` at all `positions` in the `model` results in an
   * auto closing open sequence being typed.
   *
   * Auto closing open sequences can consist of multiple characters, which
   * can lead to ambiguities. In such a case, the longest auto-closing open
   * sequence is returned.
   */
  static _findAutoClosingPairOpen(config2, model, positions, ch) {
    const candidates = config2.autoClosingPairs.autoClosingPairsOpenByEnd.get(ch);
    if (!candidates) {
      return null;
    }
    let result2 = null;
    for (const candidate of candidates) {
      if (result2 === null || candidate.open.length > result2.open.length) {
        let candidateIsMatch = true;
        for (const position of positions) {
          const relevantText = model.getValueInRange(new Range$2(position.lineNumber, position.column - candidate.open.length + 1, position.lineNumber, position.column));
          if (relevantText + ch !== candidate.open) {
            candidateIsMatch = false;
            break;
          }
        }
        if (candidateIsMatch) {
          result2 = candidate;
        }
      }
    }
    return result2;
  }
  /**
   * Find another auto-closing pair that is contained by the one passed in.
   *
   * e.g. when having [(,)] and [(*,*)] as auto-closing pairs
   * this method will find [(,)] as a containment pair for [(*,*)]
   */
  static _findContainedAutoClosingPair(config2, pair) {
    if (pair.open.length <= 1) {
      return null;
    }
    const lastChar = pair.close.charAt(pair.close.length - 1);
    const candidates = config2.autoClosingPairs.autoClosingPairsCloseByEnd.get(lastChar) || [];
    let result2 = null;
    for (const candidate of candidates) {
      if (candidate.open !== pair.open && pair.open.includes(candidate.open) && pair.close.endsWith(candidate.close)) {
        if (!result2 || candidate.open.length > result2.open.length) {
          result2 = candidate;
        }
      }
    }
    return result2;
  }
  static _getAutoClosingPairClose(config2, model, selections2, ch, chIsAlreadyTyped) {
    const chIsQuote = isQuote(ch);
    const autoCloseConfig = chIsQuote ? config2.autoClosingQuotes : config2.autoClosingBrackets;
    const shouldAutoCloseBefore = chIsQuote ? config2.shouldAutoCloseBefore.quote : config2.shouldAutoCloseBefore.bracket;
    if (autoCloseConfig === "never") {
      return null;
    }
    for (const selection of selections2) {
      if (!selection.isEmpty()) {
        return null;
      }
    }
    const positions = selections2.map((s) => {
      const position = s.getPosition();
      if (chIsAlreadyTyped) {
        return { lineNumber: position.lineNumber, beforeColumn: position.column - ch.length, afterColumn: position.column };
      } else {
        return { lineNumber: position.lineNumber, beforeColumn: position.column, afterColumn: position.column };
      }
    });
    const pair = this._findAutoClosingPairOpen(config2, model, positions.map((p2) => new Position$2(p2.lineNumber, p2.beforeColumn)), ch);
    if (!pair) {
      return null;
    }
    const containedPair = this._findContainedAutoClosingPair(config2, pair);
    const containedPairClose = containedPair ? containedPair.close : "";
    let isContainedPairPresent = true;
    for (const position of positions) {
      const { lineNumber, beforeColumn, afterColumn } = position;
      const lineText = model.getLineContent(lineNumber);
      const lineBefore = lineText.substring(0, beforeColumn - 1);
      const lineAfter = lineText.substring(afterColumn - 1);
      if (!lineAfter.startsWith(containedPairClose)) {
        isContainedPairPresent = false;
      }
      if (lineAfter.length > 0) {
        const characterAfter = lineAfter.charAt(0);
        const isBeforeCloseBrace = TypeOperations._isBeforeClosingBrace(config2, lineAfter);
        if (!isBeforeCloseBrace && !shouldAutoCloseBefore(characterAfter)) {
          return null;
        }
      }
      if (pair.open.length === 1 && (ch === "'" || ch === '"') && autoCloseConfig !== "always") {
        const wordSeparators2 = getMapForWordSeparators(config2.wordSeparators);
        if (lineBefore.length > 0) {
          const characterBefore = lineBefore.charCodeAt(lineBefore.length - 1);
          if (wordSeparators2.get(characterBefore) === 0) {
            return null;
          }
        }
      }
      if (!model.tokenization.isCheapToTokenize(lineNumber)) {
        return null;
      }
      model.tokenization.forceTokenization(lineNumber);
      const lineTokens = model.tokenization.getLineTokens(lineNumber);
      const scopedLineTokens = createScopedLineTokens(lineTokens, beforeColumn - 1);
      if (!pair.shouldAutoClose(scopedLineTokens, beforeColumn - scopedLineTokens.firstCharOffset)) {
        return null;
      }
      const neutralCharacter = pair.findNeutralCharacter();
      if (neutralCharacter) {
        const tokenType = model.tokenization.getTokenTypeIfInsertingCharacter(lineNumber, beforeColumn, neutralCharacter);
        if (!pair.isOK(tokenType)) {
          return null;
        }
      }
    }
    if (isContainedPairPresent) {
      return pair.close.substring(0, pair.close.length - containedPairClose.length);
    } else {
      return pair.close;
    }
  }
  static _runAutoClosingOpenCharType(prevEditOperationType, config2, model, selections2, ch, chIsAlreadyTyped, autoClosingPairClose) {
    const commands = [];
    for (let i = 0, len = selections2.length; i < len; i++) {
      const selection = selections2[i];
      commands[i] = new TypeWithAutoClosingCommand(selection, ch, !chIsAlreadyTyped, autoClosingPairClose);
    }
    return new EditOperationResult(4, commands, {
      shouldPushStackElementBefore: true,
      shouldPushStackElementAfter: false
    });
  }
  static _shouldSurroundChar(config2, ch) {
    if (isQuote(ch)) {
      return config2.autoSurround === "quotes" || config2.autoSurround === "languageDefined";
    } else {
      return config2.autoSurround === "brackets" || config2.autoSurround === "languageDefined";
    }
  }
  static _isSurroundSelectionType(config2, model, selections2, ch) {
    if (!TypeOperations._shouldSurroundChar(config2, ch) || !config2.surroundingPairs.hasOwnProperty(ch)) {
      return false;
    }
    const isTypingAQuoteCharacter = isQuote(ch);
    for (const selection of selections2) {
      if (selection.isEmpty()) {
        return false;
      }
      let selectionContainsOnlyWhitespace = true;
      for (let lineNumber = selection.startLineNumber; lineNumber <= selection.endLineNumber; lineNumber++) {
        const lineText = model.getLineContent(lineNumber);
        const startIndex = lineNumber === selection.startLineNumber ? selection.startColumn - 1 : 0;
        const endIndex = lineNumber === selection.endLineNumber ? selection.endColumn - 1 : lineText.length;
        const selectedText = lineText.substring(startIndex, endIndex);
        if (/[^ \t]/.test(selectedText)) {
          selectionContainsOnlyWhitespace = false;
          break;
        }
      }
      if (selectionContainsOnlyWhitespace) {
        return false;
      }
      if (isTypingAQuoteCharacter && selection.startLineNumber === selection.endLineNumber && selection.startColumn + 1 === selection.endColumn) {
        const selectionText = model.getValueInRange(selection);
        if (isQuote(selectionText)) {
          return false;
        }
      }
    }
    return true;
  }
  static _runSurroundSelectionType(prevEditOperationType, config2, model, selections2, ch) {
    const commands = [];
    for (let i = 0, len = selections2.length; i < len; i++) {
      const selection = selections2[i];
      const closeCharacter = config2.surroundingPairs[ch];
      commands[i] = new SurroundSelectionCommand(selection, ch, closeCharacter);
    }
    return new EditOperationResult(0, commands, {
      shouldPushStackElementBefore: true,
      shouldPushStackElementAfter: true
    });
  }
  static _isTypeInterceptorElectricChar(config2, model, selections2) {
    if (selections2.length === 1 && model.tokenization.isCheapToTokenize(selections2[0].getEndPosition().lineNumber)) {
      return true;
    }
    return false;
  }
  static _typeInterceptorElectricChar(prevEditOperationType, config2, model, selection, ch) {
    if (!config2.electricChars.hasOwnProperty(ch) || !selection.isEmpty()) {
      return null;
    }
    const position = selection.getPosition();
    model.tokenization.forceTokenization(position.lineNumber);
    const lineTokens = model.tokenization.getLineTokens(position.lineNumber);
    let electricAction;
    try {
      electricAction = config2.onElectricCharacter(ch, lineTokens, position.column);
    } catch (e) {
      onUnexpectedError(e);
      return null;
    }
    if (!electricAction) {
      return null;
    }
    if (electricAction.matchOpenBracket) {
      const endColumn = (lineTokens.getLineContent() + ch).lastIndexOf(electricAction.matchOpenBracket) + 1;
      const match2 = model.bracketPairs.findMatchingBracketUp(
        electricAction.matchOpenBracket,
        {
          lineNumber: position.lineNumber,
          column: endColumn
        },
        500
        /* give at most 500ms to compute */
      );
      if (match2) {
        if (match2.startLineNumber === position.lineNumber) {
          return null;
        }
        const matchLine = model.getLineContent(match2.startLineNumber);
        const matchLineIndentation = getLeadingWhitespace(matchLine);
        const newIndentation = config2.normalizeIndentation(matchLineIndentation);
        const lineText = model.getLineContent(position.lineNumber);
        const lineFirstNonBlankColumn = model.getLineFirstNonWhitespaceColumn(position.lineNumber) || position.column;
        const prefix2 = lineText.substring(lineFirstNonBlankColumn - 1, position.column - 1);
        const typeText = newIndentation + prefix2 + ch;
        const typeSelection = new Range$2(position.lineNumber, 1, position.lineNumber, position.column);
        const command = new ReplaceCommand(typeSelection, typeText);
        return new EditOperationResult(getTypingOperation(typeText, prevEditOperationType), [command], {
          shouldPushStackElementBefore: false,
          shouldPushStackElementAfter: true
        });
      }
    }
    return null;
  }
  /**
   * This is very similar with typing, but the character is already in the text buffer!
   */
  static compositionEndWithInterceptors(prevEditOperationType, config2, model, compositions, selections2, autoClosedCharacters) {
    if (!compositions) {
      return null;
    }
    let insertedText = null;
    for (const composition of compositions) {
      if (insertedText === null) {
        insertedText = composition.insertedText;
      } else if (insertedText !== composition.insertedText) {
        return null;
      }
    }
    if (!insertedText || insertedText.length !== 1) {
      return null;
    }
    const ch = insertedText;
    let hasDeletion = false;
    for (const composition of compositions) {
      if (composition.deletedText.length !== 0) {
        hasDeletion = true;
        break;
      }
    }
    if (hasDeletion) {
      if (!TypeOperations._shouldSurroundChar(config2, ch) || !config2.surroundingPairs.hasOwnProperty(ch)) {
        return null;
      }
      const isTypingAQuoteCharacter = isQuote(ch);
      for (const composition of compositions) {
        if (composition.deletedSelectionStart !== 0 || composition.deletedSelectionEnd !== composition.deletedText.length) {
          return null;
        }
        if (/^[ \t]+$/.test(composition.deletedText)) {
          return null;
        }
        if (isTypingAQuoteCharacter && isQuote(composition.deletedText)) {
          return null;
        }
      }
      const positions = [];
      for (const selection of selections2) {
        if (!selection.isEmpty()) {
          return null;
        }
        positions.push(selection.getPosition());
      }
      if (positions.length !== compositions.length) {
        return null;
      }
      const commands = [];
      for (let i = 0, len = positions.length; i < len; i++) {
        commands.push(new CompositionSurroundSelectionCommand(positions[i], compositions[i].deletedText, config2.surroundingPairs[ch]));
      }
      return new EditOperationResult(4, commands, {
        shouldPushStackElementBefore: true,
        shouldPushStackElementAfter: false
      });
    }
    if (this._isAutoClosingOvertype(config2, model, selections2, autoClosedCharacters, ch)) {
      const commands = selections2.map((s) => new ReplaceCommand(new Range$2(s.positionLineNumber, s.positionColumn, s.positionLineNumber, s.positionColumn + 1), "", false));
      return new EditOperationResult(4, commands, {
        shouldPushStackElementBefore: true,
        shouldPushStackElementAfter: false
      });
    }
    const autoClosingPairClose = this._getAutoClosingPairClose(config2, model, selections2, ch, true);
    if (autoClosingPairClose !== null) {
      return this._runAutoClosingOpenCharType(prevEditOperationType, config2, model, selections2, ch, true, autoClosingPairClose);
    }
    return null;
  }
  static typeWithInterceptors(isDoingComposition, prevEditOperationType, config2, model, selections2, autoClosedCharacters, ch) {
    if (!isDoingComposition && ch === "\n") {
      const commands2 = [];
      for (let i = 0, len = selections2.length; i < len; i++) {
        commands2[i] = TypeOperations._enter(config2, model, false, selections2[i]);
      }
      return new EditOperationResult(4, commands2, {
        shouldPushStackElementBefore: true,
        shouldPushStackElementAfter: false
      });
    }
    if (!isDoingComposition && this._isAutoIndentType(config2, model, selections2)) {
      const commands2 = [];
      let autoIndentFails = false;
      for (let i = 0, len = selections2.length; i < len; i++) {
        commands2[i] = this._runAutoIndentType(config2, model, selections2[i], ch);
        if (!commands2[i]) {
          autoIndentFails = true;
          break;
        }
      }
      if (!autoIndentFails) {
        return new EditOperationResult(4, commands2, {
          shouldPushStackElementBefore: true,
          shouldPushStackElementAfter: false
        });
      }
    }
    if (this._isAutoClosingOvertype(config2, model, selections2, autoClosedCharacters, ch)) {
      return this._runAutoClosingOvertype(prevEditOperationType, config2, model, selections2, ch);
    }
    if (!isDoingComposition) {
      const autoClosingPairClose = this._getAutoClosingPairClose(config2, model, selections2, ch, false);
      if (autoClosingPairClose) {
        return this._runAutoClosingOpenCharType(prevEditOperationType, config2, model, selections2, ch, false, autoClosingPairClose);
      }
    }
    if (!isDoingComposition && this._isSurroundSelectionType(config2, model, selections2, ch)) {
      return this._runSurroundSelectionType(prevEditOperationType, config2, model, selections2, ch);
    }
    if (!isDoingComposition && this._isTypeInterceptorElectricChar(config2, model, selections2)) {
      const r = this._typeInterceptorElectricChar(prevEditOperationType, config2, model, selections2[0], ch);
      if (r) {
        return r;
      }
    }
    const commands = [];
    for (let i = 0, len = selections2.length; i < len; i++) {
      commands[i] = new ReplaceCommand(selections2[i], ch);
    }
    const opType = getTypingOperation(ch, prevEditOperationType);
    return new EditOperationResult(opType, commands, {
      shouldPushStackElementBefore: shouldPushStackElementBetween(prevEditOperationType, opType),
      shouldPushStackElementAfter: false
    });
  }
  static typeWithoutInterceptors(prevEditOperationType, config2, model, selections2, str2) {
    const commands = [];
    for (let i = 0, len = selections2.length; i < len; i++) {
      commands[i] = new ReplaceCommand(selections2[i], str2);
    }
    const opType = getTypingOperation(str2, prevEditOperationType);
    return new EditOperationResult(opType, commands, {
      shouldPushStackElementBefore: shouldPushStackElementBetween(prevEditOperationType, opType),
      shouldPushStackElementAfter: false
    });
  }
  static lineInsertBefore(config2, model, selections2) {
    if (model === null || selections2 === null) {
      return [];
    }
    const commands = [];
    for (let i = 0, len = selections2.length; i < len; i++) {
      let lineNumber = selections2[i].positionLineNumber;
      if (lineNumber === 1) {
        commands[i] = new ReplaceCommandWithoutChangingPosition(new Range$2(1, 1, 1, 1), "\n");
      } else {
        lineNumber--;
        const column = model.getLineMaxColumn(lineNumber);
        commands[i] = this._enter(config2, model, false, new Range$2(lineNumber, column, lineNumber, column));
      }
    }
    return commands;
  }
  static lineInsertAfter(config2, model, selections2) {
    if (model === null || selections2 === null) {
      return [];
    }
    const commands = [];
    for (let i = 0, len = selections2.length; i < len; i++) {
      const lineNumber = selections2[i].positionLineNumber;
      const column = model.getLineMaxColumn(lineNumber);
      commands[i] = this._enter(config2, model, false, new Range$2(lineNumber, column, lineNumber, column));
    }
    return commands;
  }
  static lineBreakInsert(config2, model, selections2) {
    const commands = [];
    for (let i = 0, len = selections2.length; i < len; i++) {
      commands[i] = this._enter(config2, model, true, selections2[i]);
    }
    return commands;
  }
}
class TypeWithAutoClosingCommand extends ReplaceCommandWithOffsetCursorState {
  constructor(selection, openCharacter, insertOpenCharacter, closeCharacter) {
    super(selection, (insertOpenCharacter ? openCharacter : "") + closeCharacter, 0, -closeCharacter.length);
    this._openCharacter = openCharacter;
    this._closeCharacter = closeCharacter;
    this.closeCharacterRange = null;
    this.enclosingRange = null;
  }
  computeCursorState(model, helper) {
    const inverseEditOperations = helper.getInverseEditOperations();
    const range2 = inverseEditOperations[0].range;
    this.closeCharacterRange = new Range$2(range2.startLineNumber, range2.endColumn - this._closeCharacter.length, range2.endLineNumber, range2.endColumn);
    this.enclosingRange = new Range$2(range2.startLineNumber, range2.endColumn - this._openCharacter.length - this._closeCharacter.length, range2.endLineNumber, range2.endColumn);
    return super.computeCursorState(model, helper);
  }
}
class CompositionOutcome {
  constructor(deletedText, deletedSelectionStart, deletedSelectionEnd, insertedText, insertedSelectionStart, insertedSelectionEnd) {
    this.deletedText = deletedText;
    this.deletedSelectionStart = deletedSelectionStart;
    this.deletedSelectionEnd = deletedSelectionEnd;
    this.insertedText = insertedText;
    this.insertedSelectionStart = insertedSelectionStart;
    this.insertedSelectionEnd = insertedSelectionEnd;
  }
}
function getTypingOperation(typedText, previousTypingOperation) {
  if (typedText === " ") {
    return previousTypingOperation === 5 || previousTypingOperation === 6 ? 6 : 5;
  }
  return 4;
}
function shouldPushStackElementBetween(previousTypingOperation, typingOperation) {
  if (isTypingOperation(previousTypingOperation) && !isTypingOperation(typingOperation)) {
    return true;
  }
  if (previousTypingOperation === 5) {
    return false;
  }
  return normalizeOperationType(previousTypingOperation) !== normalizeOperationType(typingOperation);
}
function normalizeOperationType(type) {
  return type === 6 || type === 5 ? "space" : type;
}
function isTypingOperation(type) {
  return type === 4 || type === 5 || type === 6;
}
var EditorContextKeys;
(function(EditorContextKeys2) {
  EditorContextKeys2.editorSimpleInput = new RawContextKey("editorSimpleInput", false, true);
  EditorContextKeys2.editorTextFocus = new RawContextKey("editorTextFocus", false, localize("editorTextFocus", "Whether the editor text has focus (cursor is blinking)"));
  EditorContextKeys2.focus = new RawContextKey("editorFocus", false, localize("editorFocus", "Whether the editor or an editor widget has focus (e.g. focus is in the find widget)"));
  EditorContextKeys2.textInputFocus = new RawContextKey("textInputFocus", false, localize("textInputFocus", "Whether an editor or a rich text input has focus (cursor is blinking)"));
  EditorContextKeys2.readOnly = new RawContextKey("editorReadonly", false, localize("editorReadonly", "Whether the editor is read-only"));
  EditorContextKeys2.inDiffEditor = new RawContextKey("inDiffEditor", false, localize("inDiffEditor", "Whether the context is a diff editor"));
  EditorContextKeys2.isEmbeddedDiffEditor = new RawContextKey("isEmbeddedDiffEditor", false, localize("isEmbeddedDiffEditor", "Whether the context is an embedded diff editor"));
  EditorContextKeys2.accessibleDiffViewerVisible = new RawContextKey("accessibleDiffViewerVisible", false, localize("accessibleDiffViewerVisible", "Whether the accessible diff viewer is visible"));
  EditorContextKeys2.columnSelection = new RawContextKey("editorColumnSelection", false, localize("editorColumnSelection", "Whether `editor.columnSelection` is enabled"));
  EditorContextKeys2.writable = EditorContextKeys2.readOnly.toNegated();
  EditorContextKeys2.hasNonEmptySelection = new RawContextKey("editorHasSelection", false, localize("editorHasSelection", "Whether the editor has text selected"));
  EditorContextKeys2.hasOnlyEmptySelection = EditorContextKeys2.hasNonEmptySelection.toNegated();
  EditorContextKeys2.hasMultipleSelections = new RawContextKey("editorHasMultipleSelections", false, localize("editorHasMultipleSelections", "Whether the editor has multiple selections"));
  EditorContextKeys2.hasSingleSelection = EditorContextKeys2.hasMultipleSelections.toNegated();
  EditorContextKeys2.tabMovesFocus = new RawContextKey("editorTabMovesFocus", false, localize("editorTabMovesFocus", "Whether `Tab` will move focus out of the editor"));
  EditorContextKeys2.tabDoesNotMoveFocus = EditorContextKeys2.tabMovesFocus.toNegated();
  EditorContextKeys2.isInWalkThroughSnippet = new RawContextKey("isInEmbeddedEditor", false, true);
  EditorContextKeys2.canUndo = new RawContextKey("canUndo", false, true);
  EditorContextKeys2.canRedo = new RawContextKey("canRedo", false, true);
  EditorContextKeys2.hoverVisible = new RawContextKey("editorHoverVisible", false, localize("editorHoverVisible", "Whether the editor hover is visible"));
  EditorContextKeys2.hoverFocused = new RawContextKey("editorHoverFocused", false, localize("editorHoverFocused", "Whether the editor hover is focused"));
  EditorContextKeys2.stickyScrollFocused = new RawContextKey("stickyScrollFocused", false, localize("stickyScrollFocused", "Whether the sticky scroll is focused"));
  EditorContextKeys2.stickyScrollVisible = new RawContextKey("stickyScrollVisible", false, localize("stickyScrollVisible", "Whether the sticky scroll is visible"));
  EditorContextKeys2.standaloneColorPickerVisible = new RawContextKey("standaloneColorPickerVisible", false, localize("standaloneColorPickerVisible", "Whether the standalone color picker is visible"));
  EditorContextKeys2.standaloneColorPickerFocused = new RawContextKey("standaloneColorPickerFocused", false, localize("standaloneColorPickerFocused", "Whether the standalone color picker is focused"));
  EditorContextKeys2.inCompositeEditor = new RawContextKey("inCompositeEditor", void 0, localize("inCompositeEditor", "Whether the editor is part of a larger editor (e.g. notebooks)"));
  EditorContextKeys2.notInCompositeEditor = EditorContextKeys2.inCompositeEditor.toNegated();
  EditorContextKeys2.languageId = new RawContextKey("editorLangId", "", localize("editorLangId", "The language identifier of the editor"));
  EditorContextKeys2.hasCompletionItemProvider = new RawContextKey("editorHasCompletionItemProvider", false, localize("editorHasCompletionItemProvider", "Whether the editor has a completion item provider"));
  EditorContextKeys2.hasCodeActionsProvider = new RawContextKey("editorHasCodeActionsProvider", false, localize("editorHasCodeActionsProvider", "Whether the editor has a code actions provider"));
  EditorContextKeys2.hasCodeLensProvider = new RawContextKey("editorHasCodeLensProvider", false, localize("editorHasCodeLensProvider", "Whether the editor has a code lens provider"));
  EditorContextKeys2.hasDefinitionProvider = new RawContextKey("editorHasDefinitionProvider", false, localize("editorHasDefinitionProvider", "Whether the editor has a definition provider"));
  EditorContextKeys2.hasDeclarationProvider = new RawContextKey("editorHasDeclarationProvider", false, localize("editorHasDeclarationProvider", "Whether the editor has a declaration provider"));
  EditorContextKeys2.hasImplementationProvider = new RawContextKey("editorHasImplementationProvider", false, localize("editorHasImplementationProvider", "Whether the editor has an implementation provider"));
  EditorContextKeys2.hasTypeDefinitionProvider = new RawContextKey("editorHasTypeDefinitionProvider", false, localize("editorHasTypeDefinitionProvider", "Whether the editor has a type definition provider"));
  EditorContextKeys2.hasHoverProvider = new RawContextKey("editorHasHoverProvider", false, localize("editorHasHoverProvider", "Whether the editor has a hover provider"));
  EditorContextKeys2.hasDocumentHighlightProvider = new RawContextKey("editorHasDocumentHighlightProvider", false, localize("editorHasDocumentHighlightProvider", "Whether the editor has a document highlight provider"));
  EditorContextKeys2.hasDocumentSymbolProvider = new RawContextKey("editorHasDocumentSymbolProvider", false, localize("editorHasDocumentSymbolProvider", "Whether the editor has a document symbol provider"));
  EditorContextKeys2.hasReferenceProvider = new RawContextKey("editorHasReferenceProvider", false, localize("editorHasReferenceProvider", "Whether the editor has a reference provider"));
  EditorContextKeys2.hasRenameProvider = new RawContextKey("editorHasRenameProvider", false, localize("editorHasRenameProvider", "Whether the editor has a rename provider"));
  EditorContextKeys2.hasSignatureHelpProvider = new RawContextKey("editorHasSignatureHelpProvider", false, localize("editorHasSignatureHelpProvider", "Whether the editor has a signature help provider"));
  EditorContextKeys2.hasInlayHintsProvider = new RawContextKey("editorHasInlayHintsProvider", false, localize("editorHasInlayHintsProvider", "Whether the editor has an inline hints provider"));
  EditorContextKeys2.hasDocumentFormattingProvider = new RawContextKey("editorHasDocumentFormattingProvider", false, localize("editorHasDocumentFormattingProvider", "Whether the editor has a document formatting provider"));
  EditorContextKeys2.hasDocumentSelectionFormattingProvider = new RawContextKey("editorHasDocumentSelectionFormattingProvider", false, localize("editorHasDocumentSelectionFormattingProvider", "Whether the editor has a document selection formatting provider"));
  EditorContextKeys2.hasMultipleDocumentFormattingProvider = new RawContextKey("editorHasMultipleDocumentFormattingProvider", false, localize("editorHasMultipleDocumentFormattingProvider", "Whether the editor has multiple document formatting providers"));
  EditorContextKeys2.hasMultipleDocumentSelectionFormattingProvider = new RawContextKey("editorHasMultipleDocumentSelectionFormattingProvider", false, localize("editorHasMultipleDocumentSelectionFormattingProvider", "Whether the editor has multiple document selection formatting providers"));
})(EditorContextKeys || (EditorContextKeys = {}));
const CORE_WEIGHT = 0;
class CoreEditorCommand extends EditorCommand {
  runEditorCommand(accessor, editor2, args) {
    const viewModel = editor2._getViewModel();
    if (!viewModel) {
      return;
    }
    this.runCoreEditorCommand(viewModel, args || {});
  }
}
var EditorScroll_;
(function(EditorScroll_2) {
  const isEditorScrollArgs = function(arg) {
    if (!isObject$4(arg)) {
      return false;
    }
    const scrollArg = arg;
    if (!isString$4(scrollArg.to)) {
      return false;
    }
    if (!isUndefined$1(scrollArg.by) && !isString$4(scrollArg.by)) {
      return false;
    }
    if (!isUndefined$1(scrollArg.value) && !isNumber$3(scrollArg.value)) {
      return false;
    }
    if (!isUndefined$1(scrollArg.revealCursor) && !isBoolean$1(scrollArg.revealCursor)) {
      return false;
    }
    return true;
  };
  EditorScroll_2.description = {
    description: "Scroll editor in the given direction",
    args: [
      {
        name: "Editor scroll argument object",
        description: `Property-value pairs that can be passed through this argument:
					* 'to': A mandatory direction value.
						\`\`\`
						'up', 'down'
						\`\`\`
					* 'by': Unit to move. Default is computed based on 'to' value.
						\`\`\`
						'line', 'wrappedLine', 'page', 'halfPage', 'editor'
						\`\`\`
					* 'value': Number of units to move. Default is '1'.
					* 'revealCursor': If 'true' reveals the cursor if it is outside view port.
				`,
        constraint: isEditorScrollArgs,
        schema: {
          "type": "object",
          "required": ["to"],
          "properties": {
            "to": {
              "type": "string",
              "enum": ["up", "down"]
            },
            "by": {
              "type": "string",
              "enum": ["line", "wrappedLine", "page", "halfPage", "editor"]
            },
            "value": {
              "type": "number",
              "default": 1
            },
            "revealCursor": {
              "type": "boolean"
            }
          }
        }
      }
    ]
  };
  EditorScroll_2.RawDirection = {
    Up: "up",
    Right: "right",
    Down: "down",
    Left: "left"
  };
  EditorScroll_2.RawUnit = {
    Line: "line",
    WrappedLine: "wrappedLine",
    Page: "page",
    HalfPage: "halfPage",
    Editor: "editor",
    Column: "column"
  };
  function parse2(args) {
    let direction;
    switch (args.to) {
      case EditorScroll_2.RawDirection.Up:
        direction = 1;
        break;
      case EditorScroll_2.RawDirection.Right:
        direction = 2;
        break;
      case EditorScroll_2.RawDirection.Down:
        direction = 3;
        break;
      case EditorScroll_2.RawDirection.Left:
        direction = 4;
        break;
      default:
        return null;
    }
    let unit;
    switch (args.by) {
      case EditorScroll_2.RawUnit.Line:
        unit = 1;
        break;
      case EditorScroll_2.RawUnit.WrappedLine:
        unit = 2;
        break;
      case EditorScroll_2.RawUnit.Page:
        unit = 3;
        break;
      case EditorScroll_2.RawUnit.HalfPage:
        unit = 4;
        break;
      case EditorScroll_2.RawUnit.Editor:
        unit = 5;
        break;
      case EditorScroll_2.RawUnit.Column:
        unit = 6;
        break;
      default:
        unit = 2;
    }
    const value = Math.floor(args.value || 1);
    const revealCursor = !!args.revealCursor;
    return {
      direction,
      unit,
      value,
      revealCursor,
      select: !!args.select
    };
  }
  EditorScroll_2.parse = parse2;
})(EditorScroll_ || (EditorScroll_ = {}));
var RevealLine_;
(function(RevealLine_2) {
  const isRevealLineArgs = function(arg) {
    if (!isObject$4(arg)) {
      return false;
    }
    const reveaLineArg = arg;
    if (!isNumber$3(reveaLineArg.lineNumber) && !isString$4(reveaLineArg.lineNumber)) {
      return false;
    }
    if (!isUndefined$1(reveaLineArg.at) && !isString$4(reveaLineArg.at)) {
      return false;
    }
    return true;
  };
  RevealLine_2.description = {
    description: "Reveal the given line at the given logical position",
    args: [
      {
        name: "Reveal line argument object",
        description: `Property-value pairs that can be passed through this argument:
					* 'lineNumber': A mandatory line number value.
					* 'at': Logical position at which line has to be revealed.
						\`\`\`
						'top', 'center', 'bottom'
						\`\`\`
				`,
        constraint: isRevealLineArgs,
        schema: {
          "type": "object",
          "required": ["lineNumber"],
          "properties": {
            "lineNumber": {
              "type": ["number", "string"]
            },
            "at": {
              "type": "string",
              "enum": ["top", "center", "bottom"]
            }
          }
        }
      }
    ]
  };
  RevealLine_2.RawAtArgument = {
    Top: "top",
    Center: "center",
    Bottom: "bottom"
  };
})(RevealLine_ || (RevealLine_ = {}));
class EditorOrNativeTextInputCommand {
  constructor(target) {
    target.addImplementation(1e4, "code-editor", (accessor, args) => {
      const focusedEditor = accessor.get(ICodeEditorService).getFocusedCodeEditor();
      if (focusedEditor && focusedEditor.hasTextFocus()) {
        return this._runEditorCommand(accessor, focusedEditor, args);
      }
      return false;
    });
    target.addImplementation(1e3, "generic-dom-input-textarea", (accessor, args) => {
      const activeElement = document.activeElement;
      if (activeElement && ["input", "textarea"].indexOf(activeElement.tagName.toLowerCase()) >= 0) {
        this.runDOMCommand();
        return true;
      }
      return false;
    });
    target.addImplementation(0, "generic-dom", (accessor, args) => {
      const activeEditor = accessor.get(ICodeEditorService).getActiveCodeEditor();
      if (activeEditor) {
        activeEditor.focus();
        return this._runEditorCommand(accessor, activeEditor, args);
      }
      return false;
    });
  }
  _runEditorCommand(accessor, editor2, args) {
    const result2 = this.runEditorCommand(accessor, editor2, args);
    if (result2) {
      return result2;
    }
    return true;
  }
}
var CoreNavigationCommands;
(function(CoreNavigationCommands2) {
  class BaseMoveToCommand extends CoreEditorCommand {
    constructor(opts) {
      super(opts);
      this._inSelectionMode = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args) {
      if (!args.position) {
        return;
      }
      viewModel.model.pushStackElement();
      const cursorStateChanged = viewModel.setCursorStates(args.source, 3, [
        CursorMoveCommands.moveTo(viewModel, viewModel.getPrimaryCursorState(), this._inSelectionMode, args.position, args.viewPosition)
      ]);
      if (cursorStateChanged && args.revealType !== 2) {
        viewModel.revealPrimaryCursor(args.source, true, true);
      }
    }
  }
  CoreNavigationCommands2.MoveTo = registerEditorCommand(new BaseMoveToCommand({
    id: "_moveTo",
    inSelectionMode: false,
    precondition: void 0
  }));
  CoreNavigationCommands2.MoveToSelect = registerEditorCommand(new BaseMoveToCommand({
    id: "_moveToSelect",
    inSelectionMode: true,
    precondition: void 0
  }));
  class ColumnSelectCommand extends CoreEditorCommand {
    runCoreEditorCommand(viewModel, args) {
      viewModel.model.pushStackElement();
      const result2 = this._getColumnSelectResult(viewModel, viewModel.getPrimaryCursorState(), viewModel.getCursorColumnSelectData(), args);
      if (result2 === null) {
        return;
      }
      viewModel.setCursorStates(args.source, 3, result2.viewStates.map((viewState) => CursorState$1.fromViewState(viewState)));
      viewModel.setCursorColumnSelectData({
        isReal: true,
        fromViewLineNumber: result2.fromLineNumber,
        fromViewVisualColumn: result2.fromVisualColumn,
        toViewLineNumber: result2.toLineNumber,
        toViewVisualColumn: result2.toVisualColumn
      });
      if (result2.reversed) {
        viewModel.revealTopMostCursor(args.source);
      } else {
        viewModel.revealBottomMostCursor(args.source);
      }
    }
  }
  CoreNavigationCommands2.ColumnSelect = registerEditorCommand(new class extends ColumnSelectCommand {
    constructor() {
      super({
        id: "columnSelect",
        precondition: void 0
      });
    }
    _getColumnSelectResult(viewModel, primary, prevColumnSelectData, args) {
      if (typeof args.position === "undefined" || typeof args.viewPosition === "undefined" || typeof args.mouseColumn === "undefined") {
        return null;
      }
      const validatedPosition = viewModel.model.validatePosition(args.position);
      const validatedViewPosition = viewModel.coordinatesConverter.validateViewPosition(new Position$2(args.viewPosition.lineNumber, args.viewPosition.column), validatedPosition);
      const fromViewLineNumber = args.doColumnSelect ? prevColumnSelectData.fromViewLineNumber : validatedViewPosition.lineNumber;
      const fromViewVisualColumn = args.doColumnSelect ? prevColumnSelectData.fromViewVisualColumn : args.mouseColumn - 1;
      return ColumnSelection.columnSelect(viewModel.cursorConfig, viewModel, fromViewLineNumber, fromViewVisualColumn, validatedViewPosition.lineNumber, args.mouseColumn - 1);
    }
  }());
  CoreNavigationCommands2.CursorColumnSelectLeft = registerEditorCommand(new class extends ColumnSelectCommand {
    constructor() {
      super({
        id: "cursorColumnSelectLeft",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 2048 | 1024 | 512 | 15,
          linux: { primary: 0 }
        }
      });
    }
    _getColumnSelectResult(viewModel, primary, prevColumnSelectData, args) {
      return ColumnSelection.columnSelectLeft(viewModel.cursorConfig, viewModel, prevColumnSelectData);
    }
  }());
  CoreNavigationCommands2.CursorColumnSelectRight = registerEditorCommand(new class extends ColumnSelectCommand {
    constructor() {
      super({
        id: "cursorColumnSelectRight",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 2048 | 1024 | 512 | 17,
          linux: { primary: 0 }
        }
      });
    }
    _getColumnSelectResult(viewModel, primary, prevColumnSelectData, args) {
      return ColumnSelection.columnSelectRight(viewModel.cursorConfig, viewModel, prevColumnSelectData);
    }
  }());
  class ColumnSelectUpCommand extends ColumnSelectCommand {
    constructor(opts) {
      super(opts);
      this._isPaged = opts.isPaged;
    }
    _getColumnSelectResult(viewModel, primary, prevColumnSelectData, args) {
      return ColumnSelection.columnSelectUp(viewModel.cursorConfig, viewModel, prevColumnSelectData, this._isPaged);
    }
  }
  CoreNavigationCommands2.CursorColumnSelectUp = registerEditorCommand(new ColumnSelectUpCommand({
    isPaged: false,
    id: "cursorColumnSelectUp",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2048 | 1024 | 512 | 16,
      linux: { primary: 0 }
    }
  }));
  CoreNavigationCommands2.CursorColumnSelectPageUp = registerEditorCommand(new ColumnSelectUpCommand({
    isPaged: true,
    id: "cursorColumnSelectPageUp",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2048 | 1024 | 512 | 11,
      linux: { primary: 0 }
    }
  }));
  class ColumnSelectDownCommand extends ColumnSelectCommand {
    constructor(opts) {
      super(opts);
      this._isPaged = opts.isPaged;
    }
    _getColumnSelectResult(viewModel, primary, prevColumnSelectData, args) {
      return ColumnSelection.columnSelectDown(viewModel.cursorConfig, viewModel, prevColumnSelectData, this._isPaged);
    }
  }
  CoreNavigationCommands2.CursorColumnSelectDown = registerEditorCommand(new ColumnSelectDownCommand({
    isPaged: false,
    id: "cursorColumnSelectDown",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2048 | 1024 | 512 | 18,
      linux: { primary: 0 }
    }
  }));
  CoreNavigationCommands2.CursorColumnSelectPageDown = registerEditorCommand(new ColumnSelectDownCommand({
    isPaged: true,
    id: "cursorColumnSelectPageDown",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2048 | 1024 | 512 | 12,
      linux: { primary: 0 }
    }
  }));
  class CursorMoveImpl extends CoreEditorCommand {
    constructor() {
      super({
        id: "cursorMove",
        precondition: void 0,
        description: CursorMove.description
      });
    }
    runCoreEditorCommand(viewModel, args) {
      const parsed = CursorMove.parse(args);
      if (!parsed) {
        return;
      }
      this._runCursorMove(viewModel, args.source, parsed);
    }
    _runCursorMove(viewModel, source, args) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(source, 3, CursorMoveImpl._move(viewModel, viewModel.getCursorStates(), args));
      viewModel.revealPrimaryCursor(source, true);
    }
    static _move(viewModel, cursors, args) {
      const inSelectionMode = args.select;
      const value = args.value;
      switch (args.direction) {
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
        case 8:
        case 9:
        case 10:
          return CursorMoveCommands.simpleMove(viewModel, cursors, args.direction, inSelectionMode, value, args.unit);
        case 11:
        case 13:
        case 12:
        case 14:
          return CursorMoveCommands.viewportMove(viewModel, cursors, args.direction, inSelectionMode, value);
        default:
          return null;
      }
    }
  }
  CoreNavigationCommands2.CursorMoveImpl = CursorMoveImpl;
  CoreNavigationCommands2.CursorMove = registerEditorCommand(new CursorMoveImpl());
  class CursorMoveBasedCommand extends CoreEditorCommand {
    constructor(opts) {
      super(opts);
      this._staticArgs = opts.args;
    }
    runCoreEditorCommand(viewModel, dynamicArgs) {
      let args = this._staticArgs;
      if (this._staticArgs.value === -1) {
        args = {
          direction: this._staticArgs.direction,
          unit: this._staticArgs.unit,
          select: this._staticArgs.select,
          value: dynamicArgs.pageSize || viewModel.cursorConfig.pageSize
        };
      }
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(dynamicArgs.source, 3, CursorMoveCommands.simpleMove(viewModel, viewModel.getCursorStates(), args.direction, args.select, args.value, args.unit));
      viewModel.revealPrimaryCursor(dynamicArgs.source, true);
    }
  }
  CoreNavigationCommands2.CursorLeft = registerEditorCommand(new CursorMoveBasedCommand({
    args: {
      direction: 0,
      unit: 0,
      select: false,
      value: 1
    },
    id: "cursorLeft",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 15,
      mac: { primary: 15, secondary: [
        256 | 32
        /* KeyCode.KeyB */
      ] }
    }
  }));
  CoreNavigationCommands2.CursorLeftSelect = registerEditorCommand(new CursorMoveBasedCommand({
    args: {
      direction: 0,
      unit: 0,
      select: true,
      value: 1
    },
    id: "cursorLeftSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 1024 | 15
      /* KeyCode.LeftArrow */
    }
  }));
  CoreNavigationCommands2.CursorRight = registerEditorCommand(new CursorMoveBasedCommand({
    args: {
      direction: 1,
      unit: 0,
      select: false,
      value: 1
    },
    id: "cursorRight",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 17,
      mac: { primary: 17, secondary: [
        256 | 36
        /* KeyCode.KeyF */
      ] }
    }
  }));
  CoreNavigationCommands2.CursorRightSelect = registerEditorCommand(new CursorMoveBasedCommand({
    args: {
      direction: 1,
      unit: 0,
      select: true,
      value: 1
    },
    id: "cursorRightSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 1024 | 17
      /* KeyCode.RightArrow */
    }
  }));
  CoreNavigationCommands2.CursorUp = registerEditorCommand(new CursorMoveBasedCommand({
    args: {
      direction: 2,
      unit: 2,
      select: false,
      value: 1
    },
    id: "cursorUp",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 16,
      mac: { primary: 16, secondary: [
        256 | 46
        /* KeyCode.KeyP */
      ] }
    }
  }));
  CoreNavigationCommands2.CursorUpSelect = registerEditorCommand(new CursorMoveBasedCommand({
    args: {
      direction: 2,
      unit: 2,
      select: true,
      value: 1
    },
    id: "cursorUpSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 1024 | 16,
      secondary: [
        2048 | 1024 | 16
        /* KeyCode.UpArrow */
      ],
      mac: {
        primary: 1024 | 16
        /* KeyCode.UpArrow */
      },
      linux: {
        primary: 1024 | 16
        /* KeyCode.UpArrow */
      }
    }
  }));
  CoreNavigationCommands2.CursorPageUp = registerEditorCommand(new CursorMoveBasedCommand({
    args: {
      direction: 2,
      unit: 2,
      select: false,
      value: -1
      /* Constants.PAGE_SIZE_MARKER */
    },
    id: "cursorPageUp",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 11
      /* KeyCode.PageUp */
    }
  }));
  CoreNavigationCommands2.CursorPageUpSelect = registerEditorCommand(new CursorMoveBasedCommand({
    args: {
      direction: 2,
      unit: 2,
      select: true,
      value: -1
      /* Constants.PAGE_SIZE_MARKER */
    },
    id: "cursorPageUpSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 1024 | 11
      /* KeyCode.PageUp */
    }
  }));
  CoreNavigationCommands2.CursorDown = registerEditorCommand(new CursorMoveBasedCommand({
    args: {
      direction: 3,
      unit: 2,
      select: false,
      value: 1
    },
    id: "cursorDown",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 18,
      mac: { primary: 18, secondary: [
        256 | 44
        /* KeyCode.KeyN */
      ] }
    }
  }));
  CoreNavigationCommands2.CursorDownSelect = registerEditorCommand(new CursorMoveBasedCommand({
    args: {
      direction: 3,
      unit: 2,
      select: true,
      value: 1
    },
    id: "cursorDownSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 1024 | 18,
      secondary: [
        2048 | 1024 | 18
        /* KeyCode.DownArrow */
      ],
      mac: {
        primary: 1024 | 18
        /* KeyCode.DownArrow */
      },
      linux: {
        primary: 1024 | 18
        /* KeyCode.DownArrow */
      }
    }
  }));
  CoreNavigationCommands2.CursorPageDown = registerEditorCommand(new CursorMoveBasedCommand({
    args: {
      direction: 3,
      unit: 2,
      select: false,
      value: -1
      /* Constants.PAGE_SIZE_MARKER */
    },
    id: "cursorPageDown",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 12
      /* KeyCode.PageDown */
    }
  }));
  CoreNavigationCommands2.CursorPageDownSelect = registerEditorCommand(new CursorMoveBasedCommand({
    args: {
      direction: 3,
      unit: 2,
      select: true,
      value: -1
      /* Constants.PAGE_SIZE_MARKER */
    },
    id: "cursorPageDownSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 1024 | 12
      /* KeyCode.PageDown */
    }
  }));
  CoreNavigationCommands2.CreateCursor = registerEditorCommand(new class extends CoreEditorCommand {
    constructor() {
      super({
        id: "createCursor",
        precondition: void 0
      });
    }
    runCoreEditorCommand(viewModel, args) {
      if (!args.position) {
        return;
      }
      let newState;
      if (args.wholeLine) {
        newState = CursorMoveCommands.line(viewModel, viewModel.getPrimaryCursorState(), false, args.position, args.viewPosition);
      } else {
        newState = CursorMoveCommands.moveTo(viewModel, viewModel.getPrimaryCursorState(), false, args.position, args.viewPosition);
      }
      const states = viewModel.getCursorStates();
      if (states.length > 1) {
        const newModelPosition = newState.modelState ? newState.modelState.position : null;
        const newViewPosition = newState.viewState ? newState.viewState.position : null;
        for (let i = 0, len = states.length; i < len; i++) {
          const state = states[i];
          if (newModelPosition && !state.modelState.selection.containsPosition(newModelPosition)) {
            continue;
          }
          if (newViewPosition && !state.viewState.selection.containsPosition(newViewPosition)) {
            continue;
          }
          states.splice(i, 1);
          viewModel.model.pushStackElement();
          viewModel.setCursorStates(args.source, 3, states);
          return;
        }
      }
      states.push(newState);
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, states);
    }
  }());
  CoreNavigationCommands2.LastCursorMoveToSelect = registerEditorCommand(new class extends CoreEditorCommand {
    constructor() {
      super({
        id: "_lastCursorMoveToSelect",
        precondition: void 0
      });
    }
    runCoreEditorCommand(viewModel, args) {
      if (!args.position) {
        return;
      }
      const lastAddedCursorIndex = viewModel.getLastAddedCursorIndex();
      const states = viewModel.getCursorStates();
      const newStates = states.slice(0);
      newStates[lastAddedCursorIndex] = CursorMoveCommands.moveTo(viewModel, states[lastAddedCursorIndex], true, args.position, args.viewPosition);
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, newStates);
    }
  }());
  class HomeCommand extends CoreEditorCommand {
    constructor(opts) {
      super(opts);
      this._inSelectionMode = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, CursorMoveCommands.moveToBeginningOfLine(viewModel, viewModel.getCursorStates(), this._inSelectionMode));
      viewModel.revealPrimaryCursor(args.source, true);
    }
  }
  CoreNavigationCommands2.CursorHome = registerEditorCommand(new HomeCommand({
    inSelectionMode: false,
    id: "cursorHome",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 14,
      mac: { primary: 14, secondary: [
        2048 | 15
        /* KeyCode.LeftArrow */
      ] }
    }
  }));
  CoreNavigationCommands2.CursorHomeSelect = registerEditorCommand(new HomeCommand({
    inSelectionMode: true,
    id: "cursorHomeSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 1024 | 14,
      mac: { primary: 1024 | 14, secondary: [
        2048 | 1024 | 15
        /* KeyCode.LeftArrow */
      ] }
    }
  }));
  class LineStartCommand extends CoreEditorCommand {
    constructor(opts) {
      super(opts);
      this._inSelectionMode = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, this._exec(viewModel.getCursorStates()));
      viewModel.revealPrimaryCursor(args.source, true);
    }
    _exec(cursors) {
      const result2 = [];
      for (let i = 0, len = cursors.length; i < len; i++) {
        const cursor = cursors[i];
        const lineNumber = cursor.modelState.position.lineNumber;
        result2[i] = CursorState$1.fromModelState(cursor.modelState.move(this._inSelectionMode, lineNumber, 1, 0));
      }
      return result2;
    }
  }
  CoreNavigationCommands2.CursorLineStart = registerEditorCommand(new LineStartCommand({
    inSelectionMode: false,
    id: "cursorLineStart",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 0,
      mac: {
        primary: 256 | 31
        /* KeyCode.KeyA */
      }
    }
  }));
  CoreNavigationCommands2.CursorLineStartSelect = registerEditorCommand(new LineStartCommand({
    inSelectionMode: true,
    id: "cursorLineStartSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 0,
      mac: {
        primary: 256 | 1024 | 31
        /* KeyCode.KeyA */
      }
    }
  }));
  class EndCommand extends CoreEditorCommand {
    constructor(opts) {
      super(opts);
      this._inSelectionMode = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, CursorMoveCommands.moveToEndOfLine(viewModel, viewModel.getCursorStates(), this._inSelectionMode, args.sticky || false));
      viewModel.revealPrimaryCursor(args.source, true);
    }
  }
  CoreNavigationCommands2.CursorEnd = registerEditorCommand(new EndCommand({
    inSelectionMode: false,
    id: "cursorEnd",
    precondition: void 0,
    kbOpts: {
      args: { sticky: false },
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 13,
      mac: { primary: 13, secondary: [
        2048 | 17
        /* KeyCode.RightArrow */
      ] }
    },
    description: {
      description: `Go to End`,
      args: [{
        name: "args",
        schema: {
          type: "object",
          properties: {
            "sticky": {
              description: localize("stickydesc", "Stick to the end even when going to longer lines"),
              type: "boolean",
              default: false
            }
          }
        }
      }]
    }
  }));
  CoreNavigationCommands2.CursorEndSelect = registerEditorCommand(new EndCommand({
    inSelectionMode: true,
    id: "cursorEndSelect",
    precondition: void 0,
    kbOpts: {
      args: { sticky: false },
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 1024 | 13,
      mac: { primary: 1024 | 13, secondary: [
        2048 | 1024 | 17
        /* KeyCode.RightArrow */
      ] }
    },
    description: {
      description: `Select to End`,
      args: [{
        name: "args",
        schema: {
          type: "object",
          properties: {
            "sticky": {
              description: localize("stickydesc", "Stick to the end even when going to longer lines"),
              type: "boolean",
              default: false
            }
          }
        }
      }]
    }
  }));
  class LineEndCommand extends CoreEditorCommand {
    constructor(opts) {
      super(opts);
      this._inSelectionMode = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, this._exec(viewModel, viewModel.getCursorStates()));
      viewModel.revealPrimaryCursor(args.source, true);
    }
    _exec(viewModel, cursors) {
      const result2 = [];
      for (let i = 0, len = cursors.length; i < len; i++) {
        const cursor = cursors[i];
        const lineNumber = cursor.modelState.position.lineNumber;
        const maxColumn = viewModel.model.getLineMaxColumn(lineNumber);
        result2[i] = CursorState$1.fromModelState(cursor.modelState.move(this._inSelectionMode, lineNumber, maxColumn, 0));
      }
      return result2;
    }
  }
  CoreNavigationCommands2.CursorLineEnd = registerEditorCommand(new LineEndCommand({
    inSelectionMode: false,
    id: "cursorLineEnd",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 0,
      mac: {
        primary: 256 | 35
        /* KeyCode.KeyE */
      }
    }
  }));
  CoreNavigationCommands2.CursorLineEndSelect = registerEditorCommand(new LineEndCommand({
    inSelectionMode: true,
    id: "cursorLineEndSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 0,
      mac: {
        primary: 256 | 1024 | 35
        /* KeyCode.KeyE */
      }
    }
  }));
  class TopCommand extends CoreEditorCommand {
    constructor(opts) {
      super(opts);
      this._inSelectionMode = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, CursorMoveCommands.moveToBeginningOfBuffer(viewModel, viewModel.getCursorStates(), this._inSelectionMode));
      viewModel.revealPrimaryCursor(args.source, true);
    }
  }
  CoreNavigationCommands2.CursorTop = registerEditorCommand(new TopCommand({
    inSelectionMode: false,
    id: "cursorTop",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2048 | 14,
      mac: {
        primary: 2048 | 16
        /* KeyCode.UpArrow */
      }
    }
  }));
  CoreNavigationCommands2.CursorTopSelect = registerEditorCommand(new TopCommand({
    inSelectionMode: true,
    id: "cursorTopSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2048 | 1024 | 14,
      mac: {
        primary: 2048 | 1024 | 16
        /* KeyCode.UpArrow */
      }
    }
  }));
  class BottomCommand extends CoreEditorCommand {
    constructor(opts) {
      super(opts);
      this._inSelectionMode = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, CursorMoveCommands.moveToEndOfBuffer(viewModel, viewModel.getCursorStates(), this._inSelectionMode));
      viewModel.revealPrimaryCursor(args.source, true);
    }
  }
  CoreNavigationCommands2.CursorBottom = registerEditorCommand(new BottomCommand({
    inSelectionMode: false,
    id: "cursorBottom",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2048 | 13,
      mac: {
        primary: 2048 | 18
        /* KeyCode.DownArrow */
      }
    }
  }));
  CoreNavigationCommands2.CursorBottomSelect = registerEditorCommand(new BottomCommand({
    inSelectionMode: true,
    id: "cursorBottomSelect",
    precondition: void 0,
    kbOpts: {
      weight: CORE_WEIGHT,
      kbExpr: EditorContextKeys.textInputFocus,
      primary: 2048 | 1024 | 13,
      mac: {
        primary: 2048 | 1024 | 18
        /* KeyCode.DownArrow */
      }
    }
  }));
  class EditorScrollImpl extends CoreEditorCommand {
    constructor() {
      super({
        id: "editorScroll",
        precondition: void 0,
        description: EditorScroll_.description
      });
    }
    determineScrollMethod(args) {
      const horizontalUnits = [
        6
        /* EditorScroll_.Unit.Column */
      ];
      const verticalUnits = [
        1,
        2,
        3,
        4,
        5,
        6
        /* EditorScroll_.Unit.Column */
      ];
      const horizontalDirections = [
        4,
        2
        /* EditorScroll_.Direction.Right */
      ];
      const verticalDirections = [
        1,
        3
        /* EditorScroll_.Direction.Down */
      ];
      if (horizontalUnits.includes(args.unit) && horizontalDirections.includes(args.direction)) {
        return this._runHorizontalEditorScroll.bind(this);
      }
      if (verticalUnits.includes(args.unit) && verticalDirections.includes(args.direction)) {
        return this._runVerticalEditorScroll.bind(this);
      }
      return null;
    }
    runCoreEditorCommand(viewModel, args) {
      const parsed = EditorScroll_.parse(args);
      if (!parsed) {
        return;
      }
      const runEditorScroll = this.determineScrollMethod(parsed);
      if (!runEditorScroll) {
        return;
      }
      runEditorScroll(viewModel, args.source, parsed);
    }
    _runVerticalEditorScroll(viewModel, source, args) {
      const desiredScrollTop = this._computeDesiredScrollTop(viewModel, args);
      if (args.revealCursor) {
        const desiredVisibleViewRange = viewModel.getCompletelyVisibleViewRangeAtScrollTop(desiredScrollTop);
        viewModel.setCursorStates(source, 3, [
          CursorMoveCommands.findPositionInViewportIfOutside(viewModel, viewModel.getPrimaryCursorState(), desiredVisibleViewRange, args.select)
        ]);
      }
      viewModel.viewLayout.setScrollPosition(
        { scrollTop: desiredScrollTop },
        0
        /* ScrollType.Smooth */
      );
    }
    _computeDesiredScrollTop(viewModel, args) {
      if (args.unit === 1) {
        const futureViewport = viewModel.viewLayout.getFutureViewport();
        const visibleViewRange = viewModel.getCompletelyVisibleViewRangeAtScrollTop(futureViewport.top);
        const visibleModelRange = viewModel.coordinatesConverter.convertViewRangeToModelRange(visibleViewRange);
        let desiredTopModelLineNumber;
        if (args.direction === 1) {
          desiredTopModelLineNumber = Math.max(1, visibleModelRange.startLineNumber - args.value);
        } else {
          desiredTopModelLineNumber = Math.min(viewModel.model.getLineCount(), visibleModelRange.startLineNumber + args.value);
        }
        const viewPosition = viewModel.coordinatesConverter.convertModelPositionToViewPosition(new Position$2(desiredTopModelLineNumber, 1));
        return viewModel.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber);
      }
      if (args.unit === 5) {
        let desiredTopModelLineNumber = 0;
        if (args.direction === 3) {
          desiredTopModelLineNumber = viewModel.model.getLineCount() - viewModel.cursorConfig.pageSize;
        }
        return viewModel.viewLayout.getVerticalOffsetForLineNumber(desiredTopModelLineNumber);
      }
      let noOfLines;
      if (args.unit === 3) {
        noOfLines = viewModel.cursorConfig.pageSize * args.value;
      } else if (args.unit === 4) {
        noOfLines = Math.round(viewModel.cursorConfig.pageSize / 2) * args.value;
      } else {
        noOfLines = args.value;
      }
      const deltaLines = (args.direction === 1 ? -1 : 1) * noOfLines;
      return viewModel.viewLayout.getCurrentScrollTop() + deltaLines * viewModel.cursorConfig.lineHeight;
    }
    _runHorizontalEditorScroll(viewModel, source, args) {
      const desiredScrollLeft = this._computeDesiredScrollLeft(viewModel, args);
      viewModel.viewLayout.setScrollPosition(
        { scrollLeft: desiredScrollLeft },
        0
        /* ScrollType.Smooth */
      );
    }
    _computeDesiredScrollLeft(viewModel, args) {
      const deltaColumns = (args.direction === 4 ? -1 : 1) * args.value;
      return viewModel.viewLayout.getCurrentScrollLeft() + deltaColumns * viewModel.cursorConfig.typicalHalfwidthCharacterWidth;
    }
  }
  CoreNavigationCommands2.EditorScrollImpl = EditorScrollImpl;
  CoreNavigationCommands2.EditorScroll = registerEditorCommand(new EditorScrollImpl());
  CoreNavigationCommands2.ScrollLineUp = registerEditorCommand(new class extends CoreEditorCommand {
    constructor() {
      super({
        id: "scrollLineUp",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 2048 | 16,
          mac: {
            primary: 256 | 11
            /* KeyCode.PageUp */
          }
        }
      });
    }
    runCoreEditorCommand(viewModel, args) {
      CoreNavigationCommands2.EditorScroll.runCoreEditorCommand(viewModel, {
        to: EditorScroll_.RawDirection.Up,
        by: EditorScroll_.RawUnit.WrappedLine,
        value: 1,
        revealCursor: false,
        select: false,
        source: args.source
      });
    }
  }());
  CoreNavigationCommands2.ScrollPageUp = registerEditorCommand(new class extends CoreEditorCommand {
    constructor() {
      super({
        id: "scrollPageUp",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 2048 | 11,
          win: {
            primary: 512 | 11
            /* KeyCode.PageUp */
          },
          linux: {
            primary: 512 | 11
            /* KeyCode.PageUp */
          }
        }
      });
    }
    runCoreEditorCommand(viewModel, args) {
      CoreNavigationCommands2.EditorScroll.runCoreEditorCommand(viewModel, {
        to: EditorScroll_.RawDirection.Up,
        by: EditorScroll_.RawUnit.Page,
        value: 1,
        revealCursor: false,
        select: false,
        source: args.source
      });
    }
  }());
  CoreNavigationCommands2.ScrollEditorTop = registerEditorCommand(new class extends CoreEditorCommand {
    constructor() {
      super({
        id: "scrollEditorTop",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus
        }
      });
    }
    runCoreEditorCommand(viewModel, args) {
      CoreNavigationCommands2.EditorScroll.runCoreEditorCommand(viewModel, {
        to: EditorScroll_.RawDirection.Up,
        by: EditorScroll_.RawUnit.Editor,
        value: 1,
        revealCursor: false,
        select: false,
        source: args.source
      });
    }
  }());
  CoreNavigationCommands2.ScrollLineDown = registerEditorCommand(new class extends CoreEditorCommand {
    constructor() {
      super({
        id: "scrollLineDown",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 2048 | 18,
          mac: {
            primary: 256 | 12
            /* KeyCode.PageDown */
          }
        }
      });
    }
    runCoreEditorCommand(viewModel, args) {
      CoreNavigationCommands2.EditorScroll.runCoreEditorCommand(viewModel, {
        to: EditorScroll_.RawDirection.Down,
        by: EditorScroll_.RawUnit.WrappedLine,
        value: 1,
        revealCursor: false,
        select: false,
        source: args.source
      });
    }
  }());
  CoreNavigationCommands2.ScrollPageDown = registerEditorCommand(new class extends CoreEditorCommand {
    constructor() {
      super({
        id: "scrollPageDown",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 2048 | 12,
          win: {
            primary: 512 | 12
            /* KeyCode.PageDown */
          },
          linux: {
            primary: 512 | 12
            /* KeyCode.PageDown */
          }
        }
      });
    }
    runCoreEditorCommand(viewModel, args) {
      CoreNavigationCommands2.EditorScroll.runCoreEditorCommand(viewModel, {
        to: EditorScroll_.RawDirection.Down,
        by: EditorScroll_.RawUnit.Page,
        value: 1,
        revealCursor: false,
        select: false,
        source: args.source
      });
    }
  }());
  CoreNavigationCommands2.ScrollEditorBottom = registerEditorCommand(new class extends CoreEditorCommand {
    constructor() {
      super({
        id: "scrollEditorBottom",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus
        }
      });
    }
    runCoreEditorCommand(viewModel, args) {
      CoreNavigationCommands2.EditorScroll.runCoreEditorCommand(viewModel, {
        to: EditorScroll_.RawDirection.Down,
        by: EditorScroll_.RawUnit.Editor,
        value: 1,
        revealCursor: false,
        select: false,
        source: args.source
      });
    }
  }());
  CoreNavigationCommands2.ScrollLeft = registerEditorCommand(new class extends CoreEditorCommand {
    constructor() {
      super({
        id: "scrollLeft",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus
        }
      });
    }
    runCoreEditorCommand(viewModel, args) {
      CoreNavigationCommands2.EditorScroll.runCoreEditorCommand(viewModel, {
        to: EditorScroll_.RawDirection.Left,
        by: EditorScroll_.RawUnit.Column,
        value: 2,
        revealCursor: false,
        select: false,
        source: args.source
      });
    }
  }());
  CoreNavigationCommands2.ScrollRight = registerEditorCommand(new class extends CoreEditorCommand {
    constructor() {
      super({
        id: "scrollRight",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus
        }
      });
    }
    runCoreEditorCommand(viewModel, args) {
      CoreNavigationCommands2.EditorScroll.runCoreEditorCommand(viewModel, {
        to: EditorScroll_.RawDirection.Right,
        by: EditorScroll_.RawUnit.Column,
        value: 2,
        revealCursor: false,
        select: false,
        source: args.source
      });
    }
  }());
  class WordCommand extends CoreEditorCommand {
    constructor(opts) {
      super(opts);
      this._inSelectionMode = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args) {
      if (!args.position) {
        return;
      }
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, [
        CursorMoveCommands.word(viewModel, viewModel.getPrimaryCursorState(), this._inSelectionMode, args.position)
      ]);
      if (args.revealType !== 2) {
        viewModel.revealPrimaryCursor(args.source, true, true);
      }
    }
  }
  CoreNavigationCommands2.WordSelect = registerEditorCommand(new WordCommand({
    inSelectionMode: false,
    id: "_wordSelect",
    precondition: void 0
  }));
  CoreNavigationCommands2.WordSelectDrag = registerEditorCommand(new WordCommand({
    inSelectionMode: true,
    id: "_wordSelectDrag",
    precondition: void 0
  }));
  CoreNavigationCommands2.LastCursorWordSelect = registerEditorCommand(new class extends CoreEditorCommand {
    constructor() {
      super({
        id: "lastCursorWordSelect",
        precondition: void 0
      });
    }
    runCoreEditorCommand(viewModel, args) {
      if (!args.position) {
        return;
      }
      const lastAddedCursorIndex = viewModel.getLastAddedCursorIndex();
      const states = viewModel.getCursorStates();
      const newStates = states.slice(0);
      const lastAddedState = states[lastAddedCursorIndex];
      newStates[lastAddedCursorIndex] = CursorMoveCommands.word(viewModel, lastAddedState, lastAddedState.modelState.hasSelection(), args.position);
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, newStates);
    }
  }());
  class LineCommand extends CoreEditorCommand {
    constructor(opts) {
      super(opts);
      this._inSelectionMode = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args) {
      if (!args.position) {
        return;
      }
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, [
        CursorMoveCommands.line(viewModel, viewModel.getPrimaryCursorState(), this._inSelectionMode, args.position, args.viewPosition)
      ]);
      if (args.revealType !== 2) {
        viewModel.revealPrimaryCursor(args.source, false, true);
      }
    }
  }
  CoreNavigationCommands2.LineSelect = registerEditorCommand(new LineCommand({
    inSelectionMode: false,
    id: "_lineSelect",
    precondition: void 0
  }));
  CoreNavigationCommands2.LineSelectDrag = registerEditorCommand(new LineCommand({
    inSelectionMode: true,
    id: "_lineSelectDrag",
    precondition: void 0
  }));
  class LastCursorLineCommand extends CoreEditorCommand {
    constructor(opts) {
      super(opts);
      this._inSelectionMode = opts.inSelectionMode;
    }
    runCoreEditorCommand(viewModel, args) {
      if (!args.position) {
        return;
      }
      const lastAddedCursorIndex = viewModel.getLastAddedCursorIndex();
      const states = viewModel.getCursorStates();
      const newStates = states.slice(0);
      newStates[lastAddedCursorIndex] = CursorMoveCommands.line(viewModel, states[lastAddedCursorIndex], this._inSelectionMode, args.position, args.viewPosition);
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, newStates);
    }
  }
  CoreNavigationCommands2.LastCursorLineSelect = registerEditorCommand(new LastCursorLineCommand({
    inSelectionMode: false,
    id: "lastCursorLineSelect",
    precondition: void 0
  }));
  CoreNavigationCommands2.LastCursorLineSelectDrag = registerEditorCommand(new LastCursorLineCommand({
    inSelectionMode: true,
    id: "lastCursorLineSelectDrag",
    precondition: void 0
  }));
  CoreNavigationCommands2.CancelSelection = registerEditorCommand(new class extends CoreEditorCommand {
    constructor() {
      super({
        id: "cancelSelection",
        precondition: EditorContextKeys.hasNonEmptySelection,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 9,
          secondary: [
            1024 | 9
            /* KeyCode.Escape */
          ]
        }
      });
    }
    runCoreEditorCommand(viewModel, args) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, [
        CursorMoveCommands.cancelSelection(viewModel, viewModel.getPrimaryCursorState())
      ]);
      viewModel.revealPrimaryCursor(args.source, true);
    }
  }());
  CoreNavigationCommands2.RemoveSecondaryCursors = registerEditorCommand(new class extends CoreEditorCommand {
    constructor() {
      super({
        id: "removeSecondaryCursors",
        precondition: EditorContextKeys.hasMultipleSelections,
        kbOpts: {
          weight: CORE_WEIGHT + 1,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 9,
          secondary: [
            1024 | 9
            /* KeyCode.Escape */
          ]
        }
      });
    }
    runCoreEditorCommand(viewModel, args) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, [
        viewModel.getPrimaryCursorState()
      ]);
      viewModel.revealPrimaryCursor(args.source, true);
      status(localize("removedCursor", "Removed secondary cursors"));
    }
  }());
  CoreNavigationCommands2.RevealLine = registerEditorCommand(new class extends CoreEditorCommand {
    constructor() {
      super({
        id: "revealLine",
        precondition: void 0,
        description: RevealLine_.description
      });
    }
    runCoreEditorCommand(viewModel, args) {
      const revealLineArg = args;
      const lineNumberArg = revealLineArg.lineNumber || 0;
      let lineNumber = typeof lineNumberArg === "number" ? lineNumberArg + 1 : parseInt(lineNumberArg) + 1;
      if (lineNumber < 1) {
        lineNumber = 1;
      }
      const lineCount = viewModel.model.getLineCount();
      if (lineNumber > lineCount) {
        lineNumber = lineCount;
      }
      const range2 = new Range$2(lineNumber, 1, lineNumber, viewModel.model.getLineMaxColumn(lineNumber));
      let revealAt = 0;
      if (revealLineArg.at) {
        switch (revealLineArg.at) {
          case RevealLine_.RawAtArgument.Top:
            revealAt = 3;
            break;
          case RevealLine_.RawAtArgument.Center:
            revealAt = 1;
            break;
          case RevealLine_.RawAtArgument.Bottom:
            revealAt = 4;
            break;
        }
      }
      const viewRange = viewModel.coordinatesConverter.convertModelRangeToViewRange(range2);
      viewModel.revealRange(
        args.source,
        false,
        viewRange,
        revealAt,
        0
        /* ScrollType.Smooth */
      );
    }
  }());
  CoreNavigationCommands2.SelectAll = new class extends EditorOrNativeTextInputCommand {
    constructor() {
      super(SelectAllCommand);
    }
    runDOMCommand() {
      if (isFirefox$1) {
        document.activeElement.focus();
        document.activeElement.select();
      }
      document.execCommand("selectAll");
    }
    runEditorCommand(accessor, editor2, args) {
      const viewModel = editor2._getViewModel();
      if (!viewModel) {
        return;
      }
      this.runCoreEditorCommand(viewModel, args);
    }
    runCoreEditorCommand(viewModel, args) {
      viewModel.model.pushStackElement();
      viewModel.setCursorStates("keyboard", 3, [
        CursorMoveCommands.selectAll(viewModel, viewModel.getPrimaryCursorState())
      ]);
    }
  }();
  CoreNavigationCommands2.SetSelection = registerEditorCommand(new class extends CoreEditorCommand {
    constructor() {
      super({
        id: "setSelection",
        precondition: void 0
      });
    }
    runCoreEditorCommand(viewModel, args) {
      if (!args.selection) {
        return;
      }
      viewModel.model.pushStackElement();
      viewModel.setCursorStates(args.source, 3, [
        CursorState$1.fromModelSelection(args.selection)
      ]);
    }
  }());
})(CoreNavigationCommands || (CoreNavigationCommands = {}));
const columnSelectionCondition = ContextKeyExpr.and(EditorContextKeys.textInputFocus, EditorContextKeys.columnSelection);
function registerColumnSelection(id3, keybinding) {
  KeybindingsRegistry.registerKeybindingRule({
    id: id3,
    primary: keybinding,
    when: columnSelectionCondition,
    weight: CORE_WEIGHT + 1
  });
}
registerColumnSelection(
  CoreNavigationCommands.CursorColumnSelectLeft.id,
  1024 | 15
  /* KeyCode.LeftArrow */
);
registerColumnSelection(
  CoreNavigationCommands.CursorColumnSelectRight.id,
  1024 | 17
  /* KeyCode.RightArrow */
);
registerColumnSelection(
  CoreNavigationCommands.CursorColumnSelectUp.id,
  1024 | 16
  /* KeyCode.UpArrow */
);
registerColumnSelection(
  CoreNavigationCommands.CursorColumnSelectPageUp.id,
  1024 | 11
  /* KeyCode.PageUp */
);
registerColumnSelection(
  CoreNavigationCommands.CursorColumnSelectDown.id,
  1024 | 18
  /* KeyCode.DownArrow */
);
registerColumnSelection(
  CoreNavigationCommands.CursorColumnSelectPageDown.id,
  1024 | 12
  /* KeyCode.PageDown */
);
function registerCommand$2(command) {
  command.register();
  return command;
}
var CoreEditingCommands;
(function(CoreEditingCommands2) {
  class CoreEditingCommand extends EditorCommand {
    runEditorCommand(accessor, editor2, args) {
      const viewModel = editor2._getViewModel();
      if (!viewModel) {
        return;
      }
      this.runCoreEditingCommand(editor2, viewModel, args || {});
    }
  }
  CoreEditingCommands2.CoreEditingCommand = CoreEditingCommand;
  CoreEditingCommands2.LineBreakInsert = registerEditorCommand(new class extends CoreEditingCommand {
    constructor() {
      super({
        id: "lineBreakInsert",
        precondition: EditorContextKeys.writable,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 0,
          mac: {
            primary: 256 | 45
            /* KeyCode.KeyO */
          }
        }
      });
    }
    runCoreEditingCommand(editor2, viewModel, args) {
      editor2.pushUndoStop();
      editor2.executeCommands(this.id, TypeOperations.lineBreakInsert(viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map((s) => s.modelState.selection)));
    }
  }());
  CoreEditingCommands2.Outdent = registerEditorCommand(new class extends CoreEditingCommand {
    constructor() {
      super({
        id: "outdent",
        precondition: EditorContextKeys.writable,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: ContextKeyExpr.and(EditorContextKeys.editorTextFocus, EditorContextKeys.tabDoesNotMoveFocus),
          primary: 1024 | 2
          /* KeyCode.Tab */
        }
      });
    }
    runCoreEditingCommand(editor2, viewModel, args) {
      editor2.pushUndoStop();
      editor2.executeCommands(this.id, TypeOperations.outdent(viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map((s) => s.modelState.selection)));
      editor2.pushUndoStop();
    }
  }());
  CoreEditingCommands2.Tab = registerEditorCommand(new class extends CoreEditingCommand {
    constructor() {
      super({
        id: "tab",
        precondition: EditorContextKeys.writable,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: ContextKeyExpr.and(EditorContextKeys.editorTextFocus, EditorContextKeys.tabDoesNotMoveFocus),
          primary: 2
          /* KeyCode.Tab */
        }
      });
    }
    runCoreEditingCommand(editor2, viewModel, args) {
      editor2.pushUndoStop();
      editor2.executeCommands(this.id, TypeOperations.tab(viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map((s) => s.modelState.selection)));
      editor2.pushUndoStop();
    }
  }());
  CoreEditingCommands2.DeleteLeft = registerEditorCommand(new class extends CoreEditingCommand {
    constructor() {
      super({
        id: "deleteLeft",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 1,
          secondary: [
            1024 | 1
            /* KeyCode.Backspace */
          ],
          mac: { primary: 1, secondary: [
            1024 | 1,
            256 | 38,
            256 | 1
            /* KeyCode.Backspace */
          ] }
        }
      });
    }
    runCoreEditingCommand(editor2, viewModel, args) {
      const [shouldPushStackElementBefore, commands] = DeleteOperations.deleteLeft(viewModel.getPrevEditOperationType(), viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map((s) => s.modelState.selection), viewModel.getCursorAutoClosedCharacters());
      if (shouldPushStackElementBefore) {
        editor2.pushUndoStop();
      }
      editor2.executeCommands(this.id, commands);
      viewModel.setPrevEditOperationType(
        2
        /* EditOperationType.DeletingLeft */
      );
    }
  }());
  CoreEditingCommands2.DeleteRight = registerEditorCommand(new class extends CoreEditingCommand {
    constructor() {
      super({
        id: "deleteRight",
        precondition: void 0,
        kbOpts: {
          weight: CORE_WEIGHT,
          kbExpr: EditorContextKeys.textInputFocus,
          primary: 20,
          mac: { primary: 20, secondary: [
            256 | 34,
            256 | 20
            /* KeyCode.Delete */
          ] }
        }
      });
    }
    runCoreEditingCommand(editor2, viewModel, args) {
      const [shouldPushStackElementBefore, commands] = DeleteOperations.deleteRight(viewModel.getPrevEditOperationType(), viewModel.cursorConfig, viewModel.model, viewModel.getCursorStates().map((s) => s.modelState.selection));
      if (shouldPushStackElementBefore) {
        editor2.pushUndoStop();
      }
      editor2.executeCommands(this.id, commands);
      viewModel.setPrevEditOperationType(
        3
        /* EditOperationType.DeletingRight */
      );
    }
  }());
  CoreEditingCommands2.Undo = new class extends EditorOrNativeTextInputCommand {
    constructor() {
      super(UndoCommand);
    }
    runDOMCommand() {
      document.execCommand("undo");
    }
    runEditorCommand(accessor, editor2, args) {
      if (!editor2.hasModel() || editor2.getOption(
        89
        /* EditorOption.readOnly */
      ) === true) {
        return;
      }
      return editor2.getModel().undo();
    }
  }();
  CoreEditingCommands2.Redo = new class extends EditorOrNativeTextInputCommand {
    constructor() {
      super(RedoCommand);
    }
    runDOMCommand() {
      document.execCommand("redo");
    }
    runEditorCommand(accessor, editor2, args) {
      if (!editor2.hasModel() || editor2.getOption(
        89
        /* EditorOption.readOnly */
      ) === true) {
        return;
      }
      return editor2.getModel().redo();
    }
  }();
})(CoreEditingCommands || (CoreEditingCommands = {}));
class EditorHandlerCommand extends Command$1 {
  constructor(id3, handlerId, description) {
    super({
      id: id3,
      precondition: void 0,
      description
    });
    this._handlerId = handlerId;
  }
  runCommand(accessor, args) {
    const editor2 = accessor.get(ICodeEditorService).getFocusedCodeEditor();
    if (!editor2) {
      return;
    }
    editor2.trigger("keyboard", this._handlerId, args);
  }
}
function registerOverwritableCommand(handlerId, description) {
  registerCommand$2(new EditorHandlerCommand("default:" + handlerId, handlerId));
  registerCommand$2(new EditorHandlerCommand(handlerId, handlerId, description));
}
registerOverwritableCommand("type", {
  description: `Type`,
  args: [{
    name: "args",
    schema: {
      "type": "object",
      "required": ["text"],
      "properties": {
        "text": {
          "type": "string"
        }
      }
    }
  }]
});
registerOverwritableCommand(
  "replacePreviousChar"
  /* Handler.ReplacePreviousChar */
);
registerOverwritableCommand(
  "compositionType"
  /* Handler.CompositionType */
);
registerOverwritableCommand(
  "compositionStart"
  /* Handler.CompositionStart */
);
registerOverwritableCommand(
  "compositionEnd"
  /* Handler.CompositionEnd */
);
registerOverwritableCommand(
  "paste"
  /* Handler.Paste */
);
registerOverwritableCommand(
  "cut"
  /* Handler.Cut */
);
const IMarkerDecorationsService = createDecorator("markerDecorationsService");
var __decorate$28 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$21 = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let MarkerDecorationsContribution = class MarkerDecorationsContribution2 {
  constructor(_editor, _markerDecorationsService) {
  }
  dispose() {
  }
};
MarkerDecorationsContribution.ID = "editor.contrib.markerDecorations";
MarkerDecorationsContribution = __decorate$28([
  __param$21(1, IMarkerDecorationsService)
], MarkerDecorationsContribution);
registerEditorContribution(
  MarkerDecorationsContribution.ID,
  MarkerDecorationsContribution,
  0
  /* EditorContributionInstantiation.Eager */
);
const editor$1 = "";
function deepClone(obj) {
  if (!obj || typeof obj !== "object") {
    return obj;
  }
  if (obj instanceof RegExp) {
    return obj;
  }
  const result2 = Array.isArray(obj) ? [] : {};
  Object.entries(obj).forEach(([key, value]) => {
    result2[key] = value && typeof value === "object" ? deepClone(value) : value;
  });
  return result2;
}
function deepFreeze(obj) {
  if (!obj || typeof obj !== "object") {
    return obj;
  }
  const stack = [obj];
  while (stack.length > 0) {
    const obj2 = stack.shift();
    Object.freeze(obj2);
    for (const key in obj2) {
      if (_hasOwnProperty.call(obj2, key)) {
        const prop = obj2[key];
        if (typeof prop === "object" && !Object.isFrozen(prop) && !isTypedArray(prop)) {
          stack.push(prop);
        }
      }
    }
  }
  return obj;
}
const _hasOwnProperty = Object.prototype.hasOwnProperty;
function cloneAndChange(obj, changer) {
  return _cloneAndChange(obj, changer, /* @__PURE__ */ new Set());
}
function _cloneAndChange(obj, changer, seen2) {
  if (isUndefinedOrNull(obj)) {
    return obj;
  }
  const changed = changer(obj);
  if (typeof changed !== "undefined") {
    return changed;
  }
  if (Array.isArray(obj)) {
    const r1 = [];
    for (const e of obj) {
      r1.push(_cloneAndChange(e, changer, seen2));
    }
    return r1;
  }
  if (isObject$4(obj)) {
    if (seen2.has(obj)) {
      throw new Error("Cannot clone recursive data-structure");
    }
    seen2.add(obj);
    const r2 = {};
    for (const i2 in obj) {
      if (_hasOwnProperty.call(obj, i2)) {
        r2[i2] = _cloneAndChange(obj[i2], changer, seen2);
      }
    }
    seen2.delete(obj);
    return r2;
  }
  return obj;
}
function mixin(destination, source, overwrite = true) {
  if (!isObject$4(destination)) {
    return source;
  }
  if (isObject$4(source)) {
    Object.keys(source).forEach((key) => {
      if (key in destination) {
        if (overwrite) {
          if (isObject$4(destination[key]) && isObject$4(source[key])) {
            mixin(destination[key], source[key], overwrite);
          } else {
            destination[key] = source[key];
          }
        }
      } else {
        destination[key] = source[key];
      }
    });
  }
  return destination;
}
function equals$2(one, other) {
  if (one === other) {
    return true;
  }
  if (one === null || one === void 0 || other === null || other === void 0) {
    return false;
  }
  if (typeof one !== typeof other) {
    return false;
  }
  if (typeof one !== "object") {
    return false;
  }
  if (Array.isArray(one) !== Array.isArray(other)) {
    return false;
  }
  let i;
  let key;
  if (Array.isArray(one)) {
    if (one.length !== other.length) {
      return false;
    }
    for (i = 0; i < one.length; i++) {
      if (!equals$2(one[i], other[i])) {
        return false;
      }
    }
  } else {
    const oneKeys = [];
    for (key in one) {
      oneKeys.push(key);
    }
    oneKeys.sort();
    const otherKeys = [];
    for (key in other) {
      otherKeys.push(key);
    }
    otherKeys.sort();
    if (!equals$2(oneKeys, otherKeys)) {
      return false;
    }
    for (i = 0; i < oneKeys.length; i++) {
      if (!equals$2(one[oneKeys[i]], other[oneKeys[i]])) {
        return false;
      }
    }
  }
  return true;
}
function getAllPropertyNames(obj) {
  let res = [];
  while (Object.prototype !== obj) {
    res = res.concat(Object.getOwnPropertyNames(obj));
    obj = Object.getPrototypeOf(obj);
  }
  return res;
}
function getAllMethodNames(obj) {
  const methods = [];
  for (const prop of getAllPropertyNames(obj)) {
    if (typeof obj[prop] === "function") {
      methods.push(prop);
    }
  }
  return methods;
}
function createProxyObject$1(methodNames, invoke) {
  const createProxyMethod = (method) => {
    return function() {
      const args = Array.prototype.slice.call(arguments, 0);
      return invoke(method, args);
    };
  };
  const result2 = {};
  for (const methodName of methodNames) {
    result2[methodName] = createProxyMethod(methodName);
  }
  return result2;
}
class ElementSizeObserver extends Disposable {
  constructor(referenceDomElement, dimension) {
    super();
    this._onDidChange = this._register(new Emitter$1());
    this.onDidChange = this._onDidChange.event;
    this._referenceDomElement = referenceDomElement;
    this._width = -1;
    this._height = -1;
    this._resizeObserver = null;
    this.measureReferenceDomElement(false, dimension);
  }
  dispose() {
    this.stopObserving();
    super.dispose();
  }
  getWidth() {
    return this._width;
  }
  getHeight() {
    return this._height;
  }
  startObserving() {
    if (!this._resizeObserver && this._referenceDomElement) {
      this._resizeObserver = new ResizeObserver((entries) => {
        if (entries && entries[0] && entries[0].contentRect) {
          this.observe({ width: entries[0].contentRect.width, height: entries[0].contentRect.height });
        } else {
          this.observe();
        }
      });
      this._resizeObserver.observe(this._referenceDomElement);
    }
  }
  stopObserving() {
    if (this._resizeObserver) {
      this._resizeObserver.disconnect();
      this._resizeObserver = null;
    }
  }
  observe(dimension) {
    this.measureReferenceDomElement(true, dimension);
  }
  measureReferenceDomElement(emitEvent, dimension) {
    let observedWidth = 0;
    let observedHeight = 0;
    if (dimension) {
      observedWidth = dimension.width;
      observedHeight = dimension.height;
    } else if (this._referenceDomElement) {
      observedWidth = this._referenceDomElement.clientWidth;
      observedHeight = this._referenceDomElement.clientHeight;
    }
    observedWidth = Math.max(5, observedWidth);
    observedHeight = Math.max(5, observedHeight);
    if (this._width !== observedWidth || this._height !== observedHeight) {
      this._width = observedWidth;
      this._height = observedHeight;
      if (emitEvent) {
        this._onDidChange.fire();
      }
    }
  }
}
class FastDomNode {
  constructor(domNode) {
    this.domNode = domNode;
    this._maxWidth = "";
    this._width = "";
    this._height = "";
    this._top = "";
    this._left = "";
    this._bottom = "";
    this._right = "";
    this._paddingLeft = "";
    this._fontFamily = "";
    this._fontWeight = "";
    this._fontSize = "";
    this._fontStyle = "";
    this._fontFeatureSettings = "";
    this._fontVariationSettings = "";
    this._textDecoration = "";
    this._lineHeight = "";
    this._letterSpacing = "";
    this._className = "";
    this._display = "";
    this._position = "";
    this._visibility = "";
    this._color = "";
    this._backgroundColor = "";
    this._layerHint = false;
    this._contain = "none";
    this._boxShadow = "";
  }
  setMaxWidth(_maxWidth) {
    const maxWidth = numberAsPixels(_maxWidth);
    if (this._maxWidth === maxWidth) {
      return;
    }
    this._maxWidth = maxWidth;
    this.domNode.style.maxWidth = this._maxWidth;
  }
  setWidth(_width) {
    const width = numberAsPixels(_width);
    if (this._width === width) {
      return;
    }
    this._width = width;
    this.domNode.style.width = this._width;
  }
  setHeight(_height) {
    const height = numberAsPixels(_height);
    if (this._height === height) {
      return;
    }
    this._height = height;
    this.domNode.style.height = this._height;
  }
  setTop(_top) {
    const top = numberAsPixels(_top);
    if (this._top === top) {
      return;
    }
    this._top = top;
    this.domNode.style.top = this._top;
  }
  setLeft(_left) {
    const left = numberAsPixels(_left);
    if (this._left === left) {
      return;
    }
    this._left = left;
    this.domNode.style.left = this._left;
  }
  setBottom(_bottom) {
    const bottom = numberAsPixels(_bottom);
    if (this._bottom === bottom) {
      return;
    }
    this._bottom = bottom;
    this.domNode.style.bottom = this._bottom;
  }
  setRight(_right) {
    const right = numberAsPixels(_right);
    if (this._right === right) {
      return;
    }
    this._right = right;
    this.domNode.style.right = this._right;
  }
  setPaddingLeft(_paddingLeft) {
    const paddingLeft = numberAsPixels(_paddingLeft);
    if (this._paddingLeft === paddingLeft) {
      return;
    }
    this._paddingLeft = paddingLeft;
    this.domNode.style.paddingLeft = this._paddingLeft;
  }
  setFontFamily(fontFamily) {
    if (this._fontFamily === fontFamily) {
      return;
    }
    this._fontFamily = fontFamily;
    this.domNode.style.fontFamily = this._fontFamily;
  }
  setFontWeight(fontWeight) {
    if (this._fontWeight === fontWeight) {
      return;
    }
    this._fontWeight = fontWeight;
    this.domNode.style.fontWeight = this._fontWeight;
  }
  setFontSize(_fontSize) {
    const fontSize = numberAsPixels(_fontSize);
    if (this._fontSize === fontSize) {
      return;
    }
    this._fontSize = fontSize;
    this.domNode.style.fontSize = this._fontSize;
  }
  setFontStyle(fontStyle) {
    if (this._fontStyle === fontStyle) {
      return;
    }
    this._fontStyle = fontStyle;
    this.domNode.style.fontStyle = this._fontStyle;
  }
  setFontFeatureSettings(fontFeatureSettings) {
    if (this._fontFeatureSettings === fontFeatureSettings) {
      return;
    }
    this._fontFeatureSettings = fontFeatureSettings;
    this.domNode.style.fontFeatureSettings = this._fontFeatureSettings;
  }
  setFontVariationSettings(fontVariationSettings) {
    if (this._fontVariationSettings === fontVariationSettings) {
      return;
    }
    this._fontVariationSettings = fontVariationSettings;
    this.domNode.style.fontVariationSettings = this._fontVariationSettings;
  }
  setTextDecoration(textDecoration) {
    if (this._textDecoration === textDecoration) {
      return;
    }
    this._textDecoration = textDecoration;
    this.domNode.style.textDecoration = this._textDecoration;
  }
  setLineHeight(_lineHeight) {
    const lineHeight = numberAsPixels(_lineHeight);
    if (this._lineHeight === lineHeight) {
      return;
    }
    this._lineHeight = lineHeight;
    this.domNode.style.lineHeight = this._lineHeight;
  }
  setLetterSpacing(_letterSpacing) {
    const letterSpacing = numberAsPixels(_letterSpacing);
    if (this._letterSpacing === letterSpacing) {
      return;
    }
    this._letterSpacing = letterSpacing;
    this.domNode.style.letterSpacing = this._letterSpacing;
  }
  setClassName(className3) {
    if (this._className === className3) {
      return;
    }
    this._className = className3;
    this.domNode.className = this._className;
  }
  toggleClassName(className3, shouldHaveIt) {
    this.domNode.classList.toggle(className3, shouldHaveIt);
    this._className = this.domNode.className;
  }
  setDisplay(display) {
    if (this._display === display) {
      return;
    }
    this._display = display;
    this.domNode.style.display = this._display;
  }
  setPosition(position) {
    if (this._position === position) {
      return;
    }
    this._position = position;
    this.domNode.style.position = this._position;
  }
  setVisibility(visibility) {
    if (this._visibility === visibility) {
      return;
    }
    this._visibility = visibility;
    this.domNode.style.visibility = this._visibility;
  }
  setColor(color) {
    if (this._color === color) {
      return;
    }
    this._color = color;
    this.domNode.style.color = this._color;
  }
  setBackgroundColor(backgroundColor) {
    if (this._backgroundColor === backgroundColor) {
      return;
    }
    this._backgroundColor = backgroundColor;
    this.domNode.style.backgroundColor = this._backgroundColor;
  }
  setLayerHinting(layerHint) {
    if (this._layerHint === layerHint) {
      return;
    }
    this._layerHint = layerHint;
    this.domNode.style.transform = this._layerHint ? "translate3d(0px, 0px, 0px)" : "";
  }
  setBoxShadow(boxShadow) {
    if (this._boxShadow === boxShadow) {
      return;
    }
    this._boxShadow = boxShadow;
    this.domNode.style.boxShadow = boxShadow;
  }
  setContain(contain) {
    if (this._contain === contain) {
      return;
    }
    this._contain = contain;
    this.domNode.style.contain = this._contain;
  }
  setAttribute(name, value) {
    this.domNode.setAttribute(name, value);
  }
  removeAttribute(name) {
    this.domNode.removeAttribute(name);
  }
  appendChild(child) {
    this.domNode.appendChild(child.domNode);
  }
  removeChild(child) {
    this.domNode.removeChild(child.domNode);
  }
}
function numberAsPixels(value) {
  return typeof value === "number" ? `${value}px` : value;
}
function createFastDomNode(domNode) {
  return new FastDomNode(domNode);
}
function applyFontInfo(domNode, fontInfo) {
  if (domNode instanceof FastDomNode) {
    domNode.setFontFamily(fontInfo.getMassagedFontFamily());
    domNode.setFontWeight(fontInfo.fontWeight);
    domNode.setFontSize(fontInfo.fontSize);
    domNode.setFontFeatureSettings(fontInfo.fontFeatureSettings);
    domNode.setFontVariationSettings(fontInfo.fontVariationSettings);
    domNode.setLineHeight(fontInfo.lineHeight);
    domNode.setLetterSpacing(fontInfo.letterSpacing);
  } else {
    domNode.style.fontFamily = fontInfo.getMassagedFontFamily();
    domNode.style.fontWeight = fontInfo.fontWeight;
    domNode.style.fontSize = fontInfo.fontSize + "px";
    domNode.style.fontFeatureSettings = fontInfo.fontFeatureSettings;
    domNode.style.fontVariationSettings = fontInfo.fontVariationSettings;
    domNode.style.lineHeight = fontInfo.lineHeight + "px";
    domNode.style.letterSpacing = fontInfo.letterSpacing + "px";
  }
}
class CharWidthRequest {
  constructor(chr, type) {
    this.chr = chr;
    this.type = type;
    this.width = 0;
  }
  fulfill(width) {
    this.width = width;
  }
}
class DomCharWidthReader {
  constructor(bareFontInfo, requests) {
    this._bareFontInfo = bareFontInfo;
    this._requests = requests;
    this._container = null;
    this._testElements = null;
  }
  read() {
    this._createDomElements();
    document.body.appendChild(this._container);
    this._readFromDomElements();
    document.body.removeChild(this._container);
    this._container = null;
    this._testElements = null;
  }
  _createDomElements() {
    const container2 = document.createElement("div");
    container2.style.position = "absolute";
    container2.style.top = "-50000px";
    container2.style.width = "50000px";
    const regularDomNode = document.createElement("div");
    applyFontInfo(regularDomNode, this._bareFontInfo);
    container2.appendChild(regularDomNode);
    const boldDomNode = document.createElement("div");
    applyFontInfo(boldDomNode, this._bareFontInfo);
    boldDomNode.style.fontWeight = "bold";
    container2.appendChild(boldDomNode);
    const italicDomNode = document.createElement("div");
    applyFontInfo(italicDomNode, this._bareFontInfo);
    italicDomNode.style.fontStyle = "italic";
    container2.appendChild(italicDomNode);
    const testElements = [];
    for (const request of this._requests) {
      let parent;
      if (request.type === 0) {
        parent = regularDomNode;
      }
      if (request.type === 2) {
        parent = boldDomNode;
      }
      if (request.type === 1) {
        parent = italicDomNode;
      }
      parent.appendChild(document.createElement("br"));
      const testElement = document.createElement("span");
      DomCharWidthReader._render(testElement, request);
      parent.appendChild(testElement);
      testElements.push(testElement);
    }
    this._container = container2;
    this._testElements = testElements;
  }
  static _render(testElement, request) {
    if (request.chr === " ") {
      let htmlString = " ";
      for (let i = 0; i < 8; i++) {
        htmlString += htmlString;
      }
      testElement.innerText = htmlString;
    } else {
      let testString = request.chr;
      for (let i = 0; i < 8; i++) {
        testString += testString;
      }
      testElement.textContent = testString;
    }
  }
  _readFromDomElements() {
    for (let i = 0, len = this._requests.length; i < len; i++) {
      const request = this._requests[i];
      const testElement = this._testElements[i];
      request.fulfill(testElement.offsetWidth / 256);
    }
  }
}
function readCharWidths(bareFontInfo, requests) {
  const reader = new DomCharWidthReader(bareFontInfo, requests);
  reader.read();
}
const EDITOR_MODEL_DEFAULTS = {
  tabSize: 4,
  indentSize: 4,
  insertSpaces: true,
  detectIndentation: true,
  trimAutoWhitespace: true,
  largeFileOptimizations: true,
  bracketPairColorizationOptions: {
    enabled: true,
    independentColorPoolPerBracketType: false
  }
};
const MINIMAP_GUTTER_WIDTH = 8;
class ConfigurationChangedEvent {
  /**
   * @internal
   */
  constructor(values) {
    this._values = values;
  }
  hasChanged(id3) {
    return this._values[id3];
  }
}
class ComputeOptionsMemory {
  constructor() {
    this.stableMinimapLayoutInput = null;
    this.stableFitMaxMinimapScale = 0;
    this.stableFitRemainingWidth = 0;
  }
}
class BaseEditorOption {
  constructor(id3, name, defaultValue, schema) {
    this.id = id3;
    this.name = name;
    this.defaultValue = defaultValue;
    this.schema = schema;
  }
  applyUpdate(value, update) {
    return applyUpdate(value, update);
  }
  compute(env2, options, value) {
    return value;
  }
}
class ApplyUpdateResult {
  constructor(newValue, didChange) {
    this.newValue = newValue;
    this.didChange = didChange;
  }
}
function applyUpdate(value, update) {
  if (typeof value !== "object" || typeof update !== "object" || !value || !update) {
    return new ApplyUpdateResult(update, value !== update);
  }
  if (Array.isArray(value) || Array.isArray(update)) {
    const arrayEquals = Array.isArray(value) && Array.isArray(update) && equals$3(value, update);
    return new ApplyUpdateResult(update, !arrayEquals);
  }
  let didChange = false;
  for (const key in update) {
    if (update.hasOwnProperty(key)) {
      const result2 = applyUpdate(value[key], update[key]);
      if (result2.didChange) {
        value[key] = result2.newValue;
        didChange = true;
      }
    }
  }
  return new ApplyUpdateResult(value, didChange);
}
class ComputedEditorOption {
  constructor(id3) {
    this.schema = void 0;
    this.id = id3;
    this.name = "_never_";
    this.defaultValue = void 0;
  }
  applyUpdate(value, update) {
    return applyUpdate(value, update);
  }
  validate(input2) {
    return this.defaultValue;
  }
}
class SimpleEditorOption {
  constructor(id3, name, defaultValue, schema) {
    this.id = id3;
    this.name = name;
    this.defaultValue = defaultValue;
    this.schema = schema;
  }
  applyUpdate(value, update) {
    return applyUpdate(value, update);
  }
  validate(input2) {
    if (typeof input2 === "undefined") {
      return this.defaultValue;
    }
    return input2;
  }
  compute(env2, options, value) {
    return value;
  }
}
function boolean(value, defaultValue) {
  if (typeof value === "undefined") {
    return defaultValue;
  }
  if (value === "false") {
    return false;
  }
  return Boolean(value);
}
class EditorBooleanOption extends SimpleEditorOption {
  constructor(id3, name, defaultValue, schema = void 0) {
    if (typeof schema !== "undefined") {
      schema.type = "boolean";
      schema.default = defaultValue;
    }
    super(id3, name, defaultValue, schema);
  }
  validate(input2) {
    return boolean(input2, this.defaultValue);
  }
}
function clampedInt(value, defaultValue, minimum, maximum) {
  if (typeof value === "undefined") {
    return defaultValue;
  }
  let r = parseInt(value, 10);
  if (isNaN(r)) {
    return defaultValue;
  }
  r = Math.max(minimum, r);
  r = Math.min(maximum, r);
  return r | 0;
}
class EditorIntOption extends SimpleEditorOption {
  static clampedInt(value, defaultValue, minimum, maximum) {
    return clampedInt(value, defaultValue, minimum, maximum);
  }
  constructor(id3, name, defaultValue, minimum, maximum, schema = void 0) {
    if (typeof schema !== "undefined") {
      schema.type = "integer";
      schema.default = defaultValue;
      schema.minimum = minimum;
      schema.maximum = maximum;
    }
    super(id3, name, defaultValue, schema);
    this.minimum = minimum;
    this.maximum = maximum;
  }
  validate(input2) {
    return EditorIntOption.clampedInt(input2, this.defaultValue, this.minimum, this.maximum);
  }
}
function clampedFloat(value, defaultValue, minimum, maximum) {
  if (typeof value === "undefined") {
    return defaultValue;
  }
  const r = EditorFloatOption.float(value, defaultValue);
  return EditorFloatOption.clamp(r, minimum, maximum);
}
class EditorFloatOption extends SimpleEditorOption {
  static clamp(n2, min, max) {
    if (n2 < min) {
      return min;
    }
    if (n2 > max) {
      return max;
    }
    return n2;
  }
  static float(value, defaultValue) {
    if (typeof value === "number") {
      return value;
    }
    if (typeof value === "undefined") {
      return defaultValue;
    }
    const r = parseFloat(value);
    return isNaN(r) ? defaultValue : r;
  }
  constructor(id3, name, defaultValue, validationFn, schema) {
    if (typeof schema !== "undefined") {
      schema.type = "number";
      schema.default = defaultValue;
    }
    super(id3, name, defaultValue, schema);
    this.validationFn = validationFn;
  }
  validate(input2) {
    return this.validationFn(EditorFloatOption.float(input2, this.defaultValue));
  }
}
class EditorStringOption extends SimpleEditorOption {
  static string(value, defaultValue) {
    if (typeof value !== "string") {
      return defaultValue;
    }
    return value;
  }
  constructor(id3, name, defaultValue, schema = void 0) {
    if (typeof schema !== "undefined") {
      schema.type = "string";
      schema.default = defaultValue;
    }
    super(id3, name, defaultValue, schema);
  }
  validate(input2) {
    return EditorStringOption.string(input2, this.defaultValue);
  }
}
function stringSet(value, defaultValue, allowedValues, renamedValues) {
  if (typeof value !== "string") {
    return defaultValue;
  }
  if (renamedValues && value in renamedValues) {
    return renamedValues[value];
  }
  if (allowedValues.indexOf(value) === -1) {
    return defaultValue;
  }
  return value;
}
class EditorStringEnumOption extends SimpleEditorOption {
  constructor(id3, name, defaultValue, allowedValues, schema = void 0) {
    if (typeof schema !== "undefined") {
      schema.type = "string";
      schema.enum = allowedValues;
      schema.default = defaultValue;
    }
    super(id3, name, defaultValue, schema);
    this._allowedValues = allowedValues;
  }
  validate(input2) {
    return stringSet(input2, this.defaultValue, this._allowedValues);
  }
}
class EditorEnumOption extends BaseEditorOption {
  constructor(id3, name, defaultValue, defaultStringValue, allowedValues, convert, schema = void 0) {
    if (typeof schema !== "undefined") {
      schema.type = "string";
      schema.enum = allowedValues;
      schema.default = defaultStringValue;
    }
    super(id3, name, defaultValue, schema);
    this._allowedValues = allowedValues;
    this._convert = convert;
  }
  validate(input2) {
    if (typeof input2 !== "string") {
      return this.defaultValue;
    }
    if (this._allowedValues.indexOf(input2) === -1) {
      return this.defaultValue;
    }
    return this._convert(input2);
  }
}
function _autoIndentFromString(autoIndent) {
  switch (autoIndent) {
    case "none":
      return 0;
    case "keep":
      return 1;
    case "brackets":
      return 2;
    case "advanced":
      return 3;
    case "full":
      return 4;
  }
}
class EditorAccessibilitySupport extends BaseEditorOption {
  constructor() {
    super(2, "accessibilitySupport", 0, {
      type: "string",
      enum: ["auto", "on", "off"],
      enumDescriptions: [
        localize("accessibilitySupport.auto", "Use platform APIs to detect when a Screen Reader is attached"),
        localize("accessibilitySupport.on", "Optimize for usage with a Screen Reader"),
        localize("accessibilitySupport.off", "Assume a screen reader is not attached")
      ],
      default: "auto",
      tags: ["accessibility"],
      description: localize("accessibilitySupport", "Controls if the UI should run in a mode where it is optimized for screen readers.")
    });
  }
  validate(input2) {
    switch (input2) {
      case "auto":
        return 0;
      case "off":
        return 1;
      case "on":
        return 2;
    }
    return this.defaultValue;
  }
  compute(env2, options, value) {
    if (value === 0) {
      return env2.accessibilitySupport;
    }
    return value;
  }
}
class EditorComments extends BaseEditorOption {
  constructor() {
    const defaults = {
      insertSpace: true,
      ignoreEmptyLines: true
    };
    super(22, "comments", defaults, {
      "editor.comments.insertSpace": {
        type: "boolean",
        default: defaults.insertSpace,
        description: localize("comments.insertSpace", "Controls whether a space character is inserted when commenting.")
      },
      "editor.comments.ignoreEmptyLines": {
        type: "boolean",
        default: defaults.ignoreEmptyLines,
        description: localize("comments.ignoreEmptyLines", "Controls if empty lines should be ignored with toggle, add or remove actions for line comments.")
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input2 = _input;
    return {
      insertSpace: boolean(input2.insertSpace, this.defaultValue.insertSpace),
      ignoreEmptyLines: boolean(input2.ignoreEmptyLines, this.defaultValue.ignoreEmptyLines)
    };
  }
}
function _cursorBlinkingStyleFromString(cursorBlinkingStyle) {
  switch (cursorBlinkingStyle) {
    case "blink":
      return 1;
    case "smooth":
      return 2;
    case "phase":
      return 3;
    case "expand":
      return 4;
    case "solid":
      return 5;
  }
}
var TextEditorCursorStyle$1;
(function(TextEditorCursorStyle2) {
  TextEditorCursorStyle2[TextEditorCursorStyle2["Line"] = 1] = "Line";
  TextEditorCursorStyle2[TextEditorCursorStyle2["Block"] = 2] = "Block";
  TextEditorCursorStyle2[TextEditorCursorStyle2["Underline"] = 3] = "Underline";
  TextEditorCursorStyle2[TextEditorCursorStyle2["LineThin"] = 4] = "LineThin";
  TextEditorCursorStyle2[TextEditorCursorStyle2["BlockOutline"] = 5] = "BlockOutline";
  TextEditorCursorStyle2[TextEditorCursorStyle2["UnderlineThin"] = 6] = "UnderlineThin";
})(TextEditorCursorStyle$1 || (TextEditorCursorStyle$1 = {}));
function _cursorStyleFromString(cursorStyle) {
  switch (cursorStyle) {
    case "line":
      return TextEditorCursorStyle$1.Line;
    case "block":
      return TextEditorCursorStyle$1.Block;
    case "underline":
      return TextEditorCursorStyle$1.Underline;
    case "line-thin":
      return TextEditorCursorStyle$1.LineThin;
    case "block-outline":
      return TextEditorCursorStyle$1.BlockOutline;
    case "underline-thin":
      return TextEditorCursorStyle$1.UnderlineThin;
  }
}
class EditorClassName extends ComputedEditorOption {
  constructor() {
    super(
      139
      /* EditorOption.editorClassName */
    );
  }
  compute(env2, options, _) {
    const classNames = ["monaco-editor"];
    if (options.get(
      38
      /* EditorOption.extraEditorClassName */
    )) {
      classNames.push(options.get(
        38
        /* EditorOption.extraEditorClassName */
      ));
    }
    if (env2.extraEditorClassName) {
      classNames.push(env2.extraEditorClassName);
    }
    if (options.get(
      72
      /* EditorOption.mouseStyle */
    ) === "default") {
      classNames.push("mouse-default");
    } else if (options.get(
      72
      /* EditorOption.mouseStyle */
    ) === "copy") {
      classNames.push("mouse-copy");
    }
    if (options.get(
      109
      /* EditorOption.showUnused */
    )) {
      classNames.push("showUnused");
    }
    if (options.get(
      137
      /* EditorOption.showDeprecated */
    )) {
      classNames.push("showDeprecated");
    }
    return classNames.join(" ");
  }
}
class EditorEmptySelectionClipboard extends EditorBooleanOption {
  constructor() {
    super(36, "emptySelectionClipboard", true, { description: localize("emptySelectionClipboard", "Controls whether copying without a selection copies the current line.") });
  }
  compute(env2, options, value) {
    return value && env2.emptySelectionClipboard;
  }
}
class EditorFind extends BaseEditorOption {
  constructor() {
    const defaults = {
      cursorMoveOnType: true,
      seedSearchStringFromSelection: "always",
      autoFindInSelection: "never",
      globalFindClipboard: false,
      addExtraSpaceOnTop: true,
      loop: true
    };
    super(40, "find", defaults, {
      "editor.find.cursorMoveOnType": {
        type: "boolean",
        default: defaults.cursorMoveOnType,
        description: localize("find.cursorMoveOnType", "Controls whether the cursor should jump to find matches while typing.")
      },
      "editor.find.seedSearchStringFromSelection": {
        type: "string",
        enum: ["never", "always", "selection"],
        default: defaults.seedSearchStringFromSelection,
        enumDescriptions: [
          localize("editor.find.seedSearchStringFromSelection.never", "Never seed search string from the editor selection."),
          localize("editor.find.seedSearchStringFromSelection.always", "Always seed search string from the editor selection, including word at cursor position."),
          localize("editor.find.seedSearchStringFromSelection.selection", "Only seed search string from the editor selection.")
        ],
        description: localize("find.seedSearchStringFromSelection", "Controls whether the search string in the Find Widget is seeded from the editor selection.")
      },
      "editor.find.autoFindInSelection": {
        type: "string",
        enum: ["never", "always", "multiline"],
        default: defaults.autoFindInSelection,
        enumDescriptions: [
          localize("editor.find.autoFindInSelection.never", "Never turn on Find in Selection automatically (default)."),
          localize("editor.find.autoFindInSelection.always", "Always turn on Find in Selection automatically."),
          localize("editor.find.autoFindInSelection.multiline", "Turn on Find in Selection automatically when multiple lines of content are selected.")
        ],
        description: localize("find.autoFindInSelection", "Controls the condition for turning on Find in Selection automatically.")
      },
      "editor.find.globalFindClipboard": {
        type: "boolean",
        default: defaults.globalFindClipboard,
        description: localize("find.globalFindClipboard", "Controls whether the Find Widget should read or modify the shared find clipboard on macOS."),
        included: isMacintosh
      },
      "editor.find.addExtraSpaceOnTop": {
        type: "boolean",
        default: defaults.addExtraSpaceOnTop,
        description: localize("find.addExtraSpaceOnTop", "Controls whether the Find Widget should add extra lines on top of the editor. When true, you can scroll beyond the first line when the Find Widget is visible.")
      },
      "editor.find.loop": {
        type: "boolean",
        default: defaults.loop,
        description: localize("find.loop", "Controls whether the search automatically restarts from the beginning (or the end) when no further matches can be found.")
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input2 = _input;
    return {
      cursorMoveOnType: boolean(input2.cursorMoveOnType, this.defaultValue.cursorMoveOnType),
      seedSearchStringFromSelection: typeof _input.seedSearchStringFromSelection === "boolean" ? _input.seedSearchStringFromSelection ? "always" : "never" : stringSet(input2.seedSearchStringFromSelection, this.defaultValue.seedSearchStringFromSelection, ["never", "always", "selection"]),
      autoFindInSelection: typeof _input.autoFindInSelection === "boolean" ? _input.autoFindInSelection ? "always" : "never" : stringSet(input2.autoFindInSelection, this.defaultValue.autoFindInSelection, ["never", "always", "multiline"]),
      globalFindClipboard: boolean(input2.globalFindClipboard, this.defaultValue.globalFindClipboard),
      addExtraSpaceOnTop: boolean(input2.addExtraSpaceOnTop, this.defaultValue.addExtraSpaceOnTop),
      loop: boolean(input2.loop, this.defaultValue.loop)
    };
  }
}
class EditorFontLigatures extends BaseEditorOption {
  constructor() {
    super(50, "fontLigatures", EditorFontLigatures.OFF, {
      anyOf: [
        {
          type: "boolean",
          description: localize("fontLigatures", "Enables/Disables font ligatures ('calt' and 'liga' font features). Change this to a string for fine-grained control of the 'font-feature-settings' CSS property.")
        },
        {
          type: "string",
          description: localize("fontFeatureSettings", "Explicit 'font-feature-settings' CSS property. A boolean can be passed instead if one only needs to turn on/off ligatures.")
        }
      ],
      description: localize("fontLigaturesGeneral", "Configures font ligatures or font features. Can be either a boolean to enable/disable ligatures or a string for the value of the CSS 'font-feature-settings' property."),
      default: false
    });
  }
  validate(input2) {
    if (typeof input2 === "undefined") {
      return this.defaultValue;
    }
    if (typeof input2 === "string") {
      if (input2 === "false") {
        return EditorFontLigatures.OFF;
      }
      if (input2 === "true") {
        return EditorFontLigatures.ON;
      }
      return input2;
    }
    if (Boolean(input2)) {
      return EditorFontLigatures.ON;
    }
    return EditorFontLigatures.OFF;
  }
}
EditorFontLigatures.OFF = '"liga" off, "calt" off';
EditorFontLigatures.ON = '"liga" on, "calt" on';
class EditorFontVariations extends BaseEditorOption {
  constructor() {
    super(53, "fontVariations", EditorFontVariations.OFF, {
      anyOf: [
        {
          type: "boolean",
          description: localize("fontVariations", "Enables/Disables the translation from font-weight to font-variation-settings. Change this to a string for fine-grained control of the 'font-variation-settings' CSS property.")
        },
        {
          type: "string",
          description: localize("fontVariationSettings", "Explicit 'font-variation-settings' CSS property. A boolean can be passed instead if one only needs to translate font-weight to font-variation-settings.")
        }
      ],
      description: localize("fontVariationsGeneral", "Configures font variations. Can be either a boolean to enable/disable the translation from font-weight to font-variation-settings or a string for the value of the CSS 'font-variation-settings' property."),
      default: false
    });
  }
  validate(input2) {
    if (typeof input2 === "undefined") {
      return this.defaultValue;
    }
    if (typeof input2 === "string") {
      if (input2 === "false") {
        return EditorFontVariations.OFF;
      }
      if (input2 === "true") {
        return EditorFontVariations.TRANSLATE;
      }
      return input2;
    }
    if (Boolean(input2)) {
      return EditorFontVariations.TRANSLATE;
    }
    return EditorFontVariations.OFF;
  }
  compute(env2, options, value) {
    return env2.fontInfo.fontVariationSettings;
  }
}
EditorFontVariations.OFF = "normal";
EditorFontVariations.TRANSLATE = "translate";
class EditorFontInfo extends ComputedEditorOption {
  constructor() {
    super(
      49
      /* EditorOption.fontInfo */
    );
  }
  compute(env2, options, _) {
    return env2.fontInfo;
  }
}
class EditorFontSize extends SimpleEditorOption {
  constructor() {
    super(51, "fontSize", EDITOR_FONT_DEFAULTS.fontSize, {
      type: "number",
      minimum: 6,
      maximum: 100,
      default: EDITOR_FONT_DEFAULTS.fontSize,
      description: localize("fontSize", "Controls the font size in pixels.")
    });
  }
  validate(input2) {
    const r = EditorFloatOption.float(input2, this.defaultValue);
    if (r === 0) {
      return EDITOR_FONT_DEFAULTS.fontSize;
    }
    return EditorFloatOption.clamp(r, 6, 100);
  }
  compute(env2, options, value) {
    return env2.fontInfo.fontSize;
  }
}
class EditorFontWeight extends BaseEditorOption {
  constructor() {
    super(52, "fontWeight", EDITOR_FONT_DEFAULTS.fontWeight, {
      anyOf: [
        {
          type: "number",
          minimum: EditorFontWeight.MINIMUM_VALUE,
          maximum: EditorFontWeight.MAXIMUM_VALUE,
          errorMessage: localize("fontWeightErrorMessage", 'Only "normal" and "bold" keywords or numbers between 1 and 1000 are allowed.')
        },
        {
          type: "string",
          pattern: "^(normal|bold|1000|[1-9][0-9]{0,2})$"
        },
        {
          enum: EditorFontWeight.SUGGESTION_VALUES
        }
      ],
      default: EDITOR_FONT_DEFAULTS.fontWeight,
      description: localize("fontWeight", 'Controls the font weight. Accepts "normal" and "bold" keywords or numbers between 1 and 1000.')
    });
  }
  validate(input2) {
    if (input2 === "normal" || input2 === "bold") {
      return input2;
    }
    return String(EditorIntOption.clampedInt(input2, EDITOR_FONT_DEFAULTS.fontWeight, EditorFontWeight.MINIMUM_VALUE, EditorFontWeight.MAXIMUM_VALUE));
  }
}
EditorFontWeight.SUGGESTION_VALUES = ["normal", "bold", "100", "200", "300", "400", "500", "600", "700", "800", "900"];
EditorFontWeight.MINIMUM_VALUE = 1;
EditorFontWeight.MAXIMUM_VALUE = 1e3;
class EditorGoToLocation extends BaseEditorOption {
  constructor() {
    const defaults = {
      multiple: "peek",
      multipleDefinitions: "peek",
      multipleTypeDefinitions: "peek",
      multipleDeclarations: "peek",
      multipleImplementations: "peek",
      multipleReferences: "peek",
      alternativeDefinitionCommand: "editor.action.goToReferences",
      alternativeTypeDefinitionCommand: "editor.action.goToReferences",
      alternativeDeclarationCommand: "editor.action.goToReferences",
      alternativeImplementationCommand: "",
      alternativeReferenceCommand: ""
    };
    const jsonSubset = {
      type: "string",
      enum: ["peek", "gotoAndPeek", "goto"],
      default: defaults.multiple,
      enumDescriptions: [
        localize("editor.gotoLocation.multiple.peek", "Show Peek view of the results (default)"),
        localize("editor.gotoLocation.multiple.gotoAndPeek", "Go to the primary result and show a Peek view"),
        localize("editor.gotoLocation.multiple.goto", "Go to the primary result and enable Peek-less navigation to others")
      ]
    };
    const alternativeCommandOptions = ["", "editor.action.referenceSearch.trigger", "editor.action.goToReferences", "editor.action.peekImplementation", "editor.action.goToImplementation", "editor.action.peekTypeDefinition", "editor.action.goToTypeDefinition", "editor.action.peekDeclaration", "editor.action.revealDeclaration", "editor.action.peekDefinition", "editor.action.revealDefinitionAside", "editor.action.revealDefinition"];
    super(57, "gotoLocation", defaults, {
      "editor.gotoLocation.multiple": {
        deprecationMessage: localize("editor.gotoLocation.multiple.deprecated", "This setting is deprecated, please use separate settings like 'editor.editor.gotoLocation.multipleDefinitions' or 'editor.editor.gotoLocation.multipleImplementations' instead.")
      },
      "editor.gotoLocation.multipleDefinitions": Object.assign({ description: localize("editor.editor.gotoLocation.multipleDefinitions", "Controls the behavior the 'Go to Definition'-command when multiple target locations exist.") }, jsonSubset),
      "editor.gotoLocation.multipleTypeDefinitions": Object.assign({ description: localize("editor.editor.gotoLocation.multipleTypeDefinitions", "Controls the behavior the 'Go to Type Definition'-command when multiple target locations exist.") }, jsonSubset),
      "editor.gotoLocation.multipleDeclarations": Object.assign({ description: localize("editor.editor.gotoLocation.multipleDeclarations", "Controls the behavior the 'Go to Declaration'-command when multiple target locations exist.") }, jsonSubset),
      "editor.gotoLocation.multipleImplementations": Object.assign({ description: localize("editor.editor.gotoLocation.multipleImplemenattions", "Controls the behavior the 'Go to Implementations'-command when multiple target locations exist.") }, jsonSubset),
      "editor.gotoLocation.multipleReferences": Object.assign({ description: localize("editor.editor.gotoLocation.multipleReferences", "Controls the behavior the 'Go to References'-command when multiple target locations exist.") }, jsonSubset),
      "editor.gotoLocation.alternativeDefinitionCommand": {
        type: "string",
        default: defaults.alternativeDefinitionCommand,
        enum: alternativeCommandOptions,
        description: localize("alternativeDefinitionCommand", "Alternative command id that is being executed when the result of 'Go to Definition' is the current location.")
      },
      "editor.gotoLocation.alternativeTypeDefinitionCommand": {
        type: "string",
        default: defaults.alternativeTypeDefinitionCommand,
        enum: alternativeCommandOptions,
        description: localize("alternativeTypeDefinitionCommand", "Alternative command id that is being executed when the result of 'Go to Type Definition' is the current location.")
      },
      "editor.gotoLocation.alternativeDeclarationCommand": {
        type: "string",
        default: defaults.alternativeDeclarationCommand,
        enum: alternativeCommandOptions,
        description: localize("alternativeDeclarationCommand", "Alternative command id that is being executed when the result of 'Go to Declaration' is the current location.")
      },
      "editor.gotoLocation.alternativeImplementationCommand": {
        type: "string",
        default: defaults.alternativeImplementationCommand,
        enum: alternativeCommandOptions,
        description: localize("alternativeImplementationCommand", "Alternative command id that is being executed when the result of 'Go to Implementation' is the current location.")
      },
      "editor.gotoLocation.alternativeReferenceCommand": {
        type: "string",
        default: defaults.alternativeReferenceCommand,
        enum: alternativeCommandOptions,
        description: localize("alternativeReferenceCommand", "Alternative command id that is being executed when the result of 'Go to Reference' is the current location.")
      }
    });
  }
  validate(_input) {
    var _a2, _b2, _c2, _d2, _e2;
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input2 = _input;
    return {
      multiple: stringSet(input2.multiple, this.defaultValue.multiple, ["peek", "gotoAndPeek", "goto"]),
      multipleDefinitions: (_a2 = input2.multipleDefinitions) !== null && _a2 !== void 0 ? _a2 : stringSet(input2.multipleDefinitions, "peek", ["peek", "gotoAndPeek", "goto"]),
      multipleTypeDefinitions: (_b2 = input2.multipleTypeDefinitions) !== null && _b2 !== void 0 ? _b2 : stringSet(input2.multipleTypeDefinitions, "peek", ["peek", "gotoAndPeek", "goto"]),
      multipleDeclarations: (_c2 = input2.multipleDeclarations) !== null && _c2 !== void 0 ? _c2 : stringSet(input2.multipleDeclarations, "peek", ["peek", "gotoAndPeek", "goto"]),
      multipleImplementations: (_d2 = input2.multipleImplementations) !== null && _d2 !== void 0 ? _d2 : stringSet(input2.multipleImplementations, "peek", ["peek", "gotoAndPeek", "goto"]),
      multipleReferences: (_e2 = input2.multipleReferences) !== null && _e2 !== void 0 ? _e2 : stringSet(input2.multipleReferences, "peek", ["peek", "gotoAndPeek", "goto"]),
      alternativeDefinitionCommand: EditorStringOption.string(input2.alternativeDefinitionCommand, this.defaultValue.alternativeDefinitionCommand),
      alternativeTypeDefinitionCommand: EditorStringOption.string(input2.alternativeTypeDefinitionCommand, this.defaultValue.alternativeTypeDefinitionCommand),
      alternativeDeclarationCommand: EditorStringOption.string(input2.alternativeDeclarationCommand, this.defaultValue.alternativeDeclarationCommand),
      alternativeImplementationCommand: EditorStringOption.string(input2.alternativeImplementationCommand, this.defaultValue.alternativeImplementationCommand),
      alternativeReferenceCommand: EditorStringOption.string(input2.alternativeReferenceCommand, this.defaultValue.alternativeReferenceCommand)
    };
  }
}
class EditorHover extends BaseEditorOption {
  constructor() {
    const defaults = {
      enabled: true,
      delay: 300,
      sticky: true,
      above: true
    };
    super(59, "hover", defaults, {
      "editor.hover.enabled": {
        type: "boolean",
        default: defaults.enabled,
        description: localize("hover.enabled", "Controls whether the hover is shown.")
      },
      "editor.hover.delay": {
        type: "number",
        default: defaults.delay,
        minimum: 0,
        maximum: 1e4,
        description: localize("hover.delay", "Controls the delay in milliseconds after which the hover is shown.")
      },
      "editor.hover.sticky": {
        type: "boolean",
        default: defaults.sticky,
        description: localize("hover.sticky", "Controls whether the hover should remain visible when mouse is moved over it.")
      },
      "editor.hover.above": {
        type: "boolean",
        default: defaults.above,
        description: localize("hover.above", "Prefer showing hovers above the line, if there's space.")
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input2 = _input;
    return {
      enabled: boolean(input2.enabled, this.defaultValue.enabled),
      delay: EditorIntOption.clampedInt(input2.delay, this.defaultValue.delay, 0, 1e4),
      sticky: boolean(input2.sticky, this.defaultValue.sticky),
      above: boolean(input2.above, this.defaultValue.above)
    };
  }
}
class EditorLayoutInfoComputer extends ComputedEditorOption {
  constructor() {
    super(
      142
      /* EditorOption.layoutInfo */
    );
  }
  compute(env2, options, _) {
    return EditorLayoutInfoComputer.computeLayout(options, {
      memory: env2.memory,
      outerWidth: env2.outerWidth,
      outerHeight: env2.outerHeight,
      isDominatedByLongLines: env2.isDominatedByLongLines,
      lineHeight: env2.fontInfo.lineHeight,
      viewLineCount: env2.viewLineCount,
      lineNumbersDigitCount: env2.lineNumbersDigitCount,
      typicalHalfwidthCharacterWidth: env2.fontInfo.typicalHalfwidthCharacterWidth,
      maxDigitWidth: env2.fontInfo.maxDigitWidth,
      pixelRatio: env2.pixelRatio,
      glyphMarginDecorationLaneCount: env2.glyphMarginDecorationLaneCount
    });
  }
  static computeContainedMinimapLineCount(input2) {
    const typicalViewportLineCount = input2.height / input2.lineHeight;
    const extraLinesBeforeFirstLine = Math.floor(input2.paddingTop / input2.lineHeight);
    let extraLinesBeyondLastLine = Math.floor(input2.paddingBottom / input2.lineHeight);
    if (input2.scrollBeyondLastLine) {
      extraLinesBeyondLastLine = Math.max(extraLinesBeyondLastLine, typicalViewportLineCount - 1);
    }
    const desiredRatio = (extraLinesBeforeFirstLine + input2.viewLineCount + extraLinesBeyondLastLine) / (input2.pixelRatio * input2.height);
    const minimapLineCount = Math.floor(input2.viewLineCount / desiredRatio);
    return { typicalViewportLineCount, extraLinesBeforeFirstLine, extraLinesBeyondLastLine, desiredRatio, minimapLineCount };
  }
  static _computeMinimapLayout(input2, memory) {
    const outerWidth = input2.outerWidth;
    const outerHeight = input2.outerHeight;
    const pixelRatio = input2.pixelRatio;
    if (!input2.minimap.enabled) {
      return {
        renderMinimap: 0,
        minimapLeft: 0,
        minimapWidth: 0,
        minimapHeightIsEditorHeight: false,
        minimapIsSampling: false,
        minimapScale: 1,
        minimapLineHeight: 1,
        minimapCanvasInnerWidth: 0,
        minimapCanvasInnerHeight: Math.floor(pixelRatio * outerHeight),
        minimapCanvasOuterWidth: 0,
        minimapCanvasOuterHeight: outerHeight
      };
    }
    const stableMinimapLayoutInput = memory.stableMinimapLayoutInput;
    const couldUseMemory = stableMinimapLayoutInput && input2.outerHeight === stableMinimapLayoutInput.outerHeight && input2.lineHeight === stableMinimapLayoutInput.lineHeight && input2.typicalHalfwidthCharacterWidth === stableMinimapLayoutInput.typicalHalfwidthCharacterWidth && input2.pixelRatio === stableMinimapLayoutInput.pixelRatio && input2.scrollBeyondLastLine === stableMinimapLayoutInput.scrollBeyondLastLine && input2.paddingTop === stableMinimapLayoutInput.paddingTop && input2.paddingBottom === stableMinimapLayoutInput.paddingBottom && input2.minimap.enabled === stableMinimapLayoutInput.minimap.enabled && input2.minimap.side === stableMinimapLayoutInput.minimap.side && input2.minimap.size === stableMinimapLayoutInput.minimap.size && input2.minimap.showSlider === stableMinimapLayoutInput.minimap.showSlider && input2.minimap.renderCharacters === stableMinimapLayoutInput.minimap.renderCharacters && input2.minimap.maxColumn === stableMinimapLayoutInput.minimap.maxColumn && input2.minimap.scale === stableMinimapLayoutInput.minimap.scale && input2.verticalScrollbarWidth === stableMinimapLayoutInput.verticalScrollbarWidth && input2.isViewportWrapping === stableMinimapLayoutInput.isViewportWrapping;
    const lineHeight = input2.lineHeight;
    const typicalHalfwidthCharacterWidth = input2.typicalHalfwidthCharacterWidth;
    const scrollBeyondLastLine = input2.scrollBeyondLastLine;
    const minimapRenderCharacters = input2.minimap.renderCharacters;
    let minimapScale = pixelRatio >= 2 ? Math.round(input2.minimap.scale * 2) : input2.minimap.scale;
    const minimapMaxColumn = input2.minimap.maxColumn;
    const minimapSize = input2.minimap.size;
    const minimapSide = input2.minimap.side;
    const verticalScrollbarWidth = input2.verticalScrollbarWidth;
    const viewLineCount = input2.viewLineCount;
    const remainingWidth = input2.remainingWidth;
    const isViewportWrapping = input2.isViewportWrapping;
    const baseCharHeight = minimapRenderCharacters ? 2 : 3;
    let minimapCanvasInnerHeight = Math.floor(pixelRatio * outerHeight);
    const minimapCanvasOuterHeight = minimapCanvasInnerHeight / pixelRatio;
    let minimapHeightIsEditorHeight = false;
    let minimapIsSampling = false;
    let minimapLineHeight = baseCharHeight * minimapScale;
    let minimapCharWidth = minimapScale / pixelRatio;
    let minimapWidthMultiplier = 1;
    if (minimapSize === "fill" || minimapSize === "fit") {
      const { typicalViewportLineCount, extraLinesBeforeFirstLine, extraLinesBeyondLastLine, desiredRatio, minimapLineCount } = EditorLayoutInfoComputer.computeContainedMinimapLineCount({
        viewLineCount,
        scrollBeyondLastLine,
        paddingTop: input2.paddingTop,
        paddingBottom: input2.paddingBottom,
        height: outerHeight,
        lineHeight,
        pixelRatio
      });
      const ratio = viewLineCount / minimapLineCount;
      if (ratio > 1) {
        minimapHeightIsEditorHeight = true;
        minimapIsSampling = true;
        minimapScale = 1;
        minimapLineHeight = 1;
        minimapCharWidth = minimapScale / pixelRatio;
      } else {
        let fitBecomesFill = false;
        let maxMinimapScale = minimapScale + 1;
        if (minimapSize === "fit") {
          const effectiveMinimapHeight = Math.ceil((extraLinesBeforeFirstLine + viewLineCount + extraLinesBeyondLastLine) * minimapLineHeight);
          if (isViewportWrapping && couldUseMemory && remainingWidth <= memory.stableFitRemainingWidth) {
            fitBecomesFill = true;
            maxMinimapScale = memory.stableFitMaxMinimapScale;
          } else {
            fitBecomesFill = effectiveMinimapHeight > minimapCanvasInnerHeight;
          }
        }
        if (minimapSize === "fill" || fitBecomesFill) {
          minimapHeightIsEditorHeight = true;
          const configuredMinimapScale = minimapScale;
          minimapLineHeight = Math.min(lineHeight * pixelRatio, Math.max(1, Math.floor(1 / desiredRatio)));
          if (isViewportWrapping && couldUseMemory && remainingWidth <= memory.stableFitRemainingWidth) {
            maxMinimapScale = memory.stableFitMaxMinimapScale;
          }
          minimapScale = Math.min(maxMinimapScale, Math.max(1, Math.floor(minimapLineHeight / baseCharHeight)));
          if (minimapScale > configuredMinimapScale) {
            minimapWidthMultiplier = Math.min(2, minimapScale / configuredMinimapScale);
          }
          minimapCharWidth = minimapScale / pixelRatio / minimapWidthMultiplier;
          minimapCanvasInnerHeight = Math.ceil(Math.max(typicalViewportLineCount, extraLinesBeforeFirstLine + viewLineCount + extraLinesBeyondLastLine) * minimapLineHeight);
          if (isViewportWrapping) {
            memory.stableMinimapLayoutInput = input2;
            memory.stableFitRemainingWidth = remainingWidth;
            memory.stableFitMaxMinimapScale = minimapScale;
          } else {
            memory.stableMinimapLayoutInput = null;
            memory.stableFitRemainingWidth = 0;
          }
        }
      }
    }
    const minimapMaxWidth = Math.floor(minimapMaxColumn * minimapCharWidth);
    const minimapWidth = Math.min(minimapMaxWidth, Math.max(0, Math.floor((remainingWidth - verticalScrollbarWidth - 2) * minimapCharWidth / (typicalHalfwidthCharacterWidth + minimapCharWidth))) + MINIMAP_GUTTER_WIDTH);
    let minimapCanvasInnerWidth = Math.floor(pixelRatio * minimapWidth);
    const minimapCanvasOuterWidth = minimapCanvasInnerWidth / pixelRatio;
    minimapCanvasInnerWidth = Math.floor(minimapCanvasInnerWidth * minimapWidthMultiplier);
    const renderMinimap = minimapRenderCharacters ? 1 : 2;
    const minimapLeft = minimapSide === "left" ? 0 : outerWidth - minimapWidth - verticalScrollbarWidth;
    return {
      renderMinimap,
      minimapLeft,
      minimapWidth,
      minimapHeightIsEditorHeight,
      minimapIsSampling,
      minimapScale,
      minimapLineHeight,
      minimapCanvasInnerWidth,
      minimapCanvasInnerHeight,
      minimapCanvasOuterWidth,
      minimapCanvasOuterHeight
    };
  }
  static computeLayout(options, env2) {
    const outerWidth = env2.outerWidth | 0;
    const outerHeight = env2.outerHeight | 0;
    const lineHeight = env2.lineHeight | 0;
    const lineNumbersDigitCount = env2.lineNumbersDigitCount | 0;
    const typicalHalfwidthCharacterWidth = env2.typicalHalfwidthCharacterWidth;
    const maxDigitWidth = env2.maxDigitWidth;
    const pixelRatio = env2.pixelRatio;
    const viewLineCount = env2.viewLineCount;
    const wordWrapOverride2 = options.get(
      134
      /* EditorOption.wordWrapOverride2 */
    );
    const wordWrapOverride1 = wordWrapOverride2 === "inherit" ? options.get(
      133
      /* EditorOption.wordWrapOverride1 */
    ) : wordWrapOverride2;
    const wordWrap = wordWrapOverride1 === "inherit" ? options.get(
      129
      /* EditorOption.wordWrap */
    ) : wordWrapOverride1;
    const wordWrapColumn = options.get(
      132
      /* EditorOption.wordWrapColumn */
    );
    const isDominatedByLongLines = env2.isDominatedByLongLines;
    const showGlyphMargin = options.get(
      56
      /* EditorOption.glyphMargin */
    );
    const showLineNumbers = options.get(
      66
      /* EditorOption.lineNumbers */
    ).renderType !== 0;
    const lineNumbersMinChars = options.get(
      67
      /* EditorOption.lineNumbersMinChars */
    );
    const scrollBeyondLastLine = options.get(
      103
      /* EditorOption.scrollBeyondLastLine */
    );
    const padding = options.get(
      82
      /* EditorOption.padding */
    );
    const minimap2 = options.get(
      71
      /* EditorOption.minimap */
    );
    const scrollbar = options.get(
      101
      /* EditorOption.scrollbar */
    );
    const verticalScrollbarWidth = scrollbar.verticalScrollbarSize;
    const verticalScrollbarHasArrows = scrollbar.verticalHasArrows;
    const scrollbarArrowSize = scrollbar.arrowSize;
    const horizontalScrollbarHeight = scrollbar.horizontalScrollbarSize;
    const folding2 = options.get(
      42
      /* EditorOption.folding */
    );
    const showFoldingDecoration = options.get(
      108
      /* EditorOption.showFoldingControls */
    ) !== "never";
    let lineDecorationsWidth = options.get(
      64
      /* EditorOption.lineDecorationsWidth */
    );
    if (folding2 && showFoldingDecoration) {
      lineDecorationsWidth += 16;
    }
    let lineNumbersWidth = 0;
    if (showLineNumbers) {
      const digitCount2 = Math.max(lineNumbersDigitCount, lineNumbersMinChars);
      lineNumbersWidth = Math.round(digitCount2 * maxDigitWidth);
    }
    let glyphMarginWidth = 0;
    if (showGlyphMargin) {
      glyphMarginWidth = lineHeight * env2.glyphMarginDecorationLaneCount;
    }
    let glyphMarginLeft = 0;
    let lineNumbersLeft = glyphMarginLeft + glyphMarginWidth;
    let decorationsLeft = lineNumbersLeft + lineNumbersWidth;
    let contentLeft = decorationsLeft + lineDecorationsWidth;
    const remainingWidth = outerWidth - glyphMarginWidth - lineNumbersWidth - lineDecorationsWidth;
    let isWordWrapMinified = false;
    let isViewportWrapping = false;
    let wrappingColumn = -1;
    if (wordWrapOverride1 === "inherit" && isDominatedByLongLines) {
      isWordWrapMinified = true;
      isViewportWrapping = true;
    } else if (wordWrap === "on" || wordWrap === "bounded") {
      isViewportWrapping = true;
    } else if (wordWrap === "wordWrapColumn") {
      wrappingColumn = wordWrapColumn;
    }
    const minimapLayout = EditorLayoutInfoComputer._computeMinimapLayout({
      outerWidth,
      outerHeight,
      lineHeight,
      typicalHalfwidthCharacterWidth,
      pixelRatio,
      scrollBeyondLastLine,
      paddingTop: padding.top,
      paddingBottom: padding.bottom,
      minimap: minimap2,
      verticalScrollbarWidth,
      viewLineCount,
      remainingWidth,
      isViewportWrapping
    }, env2.memory || new ComputeOptionsMemory());
    if (minimapLayout.renderMinimap !== 0 && minimapLayout.minimapLeft === 0) {
      glyphMarginLeft += minimapLayout.minimapWidth;
      lineNumbersLeft += minimapLayout.minimapWidth;
      decorationsLeft += minimapLayout.minimapWidth;
      contentLeft += minimapLayout.minimapWidth;
    }
    const contentWidth = remainingWidth - minimapLayout.minimapWidth;
    const viewportColumn = Math.max(1, Math.floor((contentWidth - verticalScrollbarWidth - 2) / typicalHalfwidthCharacterWidth));
    const verticalArrowSize = verticalScrollbarHasArrows ? scrollbarArrowSize : 0;
    if (isViewportWrapping) {
      wrappingColumn = Math.max(1, viewportColumn);
      if (wordWrap === "bounded") {
        wrappingColumn = Math.min(wrappingColumn, wordWrapColumn);
      }
    }
    return {
      width: outerWidth,
      height: outerHeight,
      glyphMarginLeft,
      glyphMarginWidth,
      glyphMarginDecorationLaneCount: env2.glyphMarginDecorationLaneCount,
      lineNumbersLeft,
      lineNumbersWidth,
      decorationsLeft,
      decorationsWidth: lineDecorationsWidth,
      contentLeft,
      contentWidth,
      minimap: minimapLayout,
      viewportColumn,
      isWordWrapMinified,
      isViewportWrapping,
      wrappingColumn,
      verticalScrollbarWidth,
      horizontalScrollbarHeight,
      overviewRuler: {
        top: verticalArrowSize,
        width: verticalScrollbarWidth,
        height: outerHeight - 2 * verticalArrowSize,
        right: 0
      }
    };
  }
}
class WrappingStrategy extends BaseEditorOption {
  constructor() {
    super(136, "wrappingStrategy", "simple", {
      "editor.wrappingStrategy": {
        enumDescriptions: [
          localize("wrappingStrategy.simple", "Assumes that all characters are of the same width. This is a fast algorithm that works correctly for monospace fonts and certain scripts (like Latin characters) where glyphs are of equal width."),
          localize("wrappingStrategy.advanced", "Delegates wrapping points computation to the browser. This is a slow algorithm, that might cause freezes for large files, but it works correctly in all cases.")
        ],
        type: "string",
        enum: ["simple", "advanced"],
        default: "simple",
        description: localize("wrappingStrategy", "Controls the algorithm that computes wrapping points. Note that when in accessibility mode, advanced will be used for the best experience.")
      }
    });
  }
  validate(input2) {
    return stringSet(input2, "simple", ["simple", "advanced"]);
  }
  compute(env2, options, value) {
    const accessibilitySupport = options.get(
      2
      /* EditorOption.accessibilitySupport */
    );
    if (accessibilitySupport === 2) {
      return "advanced";
    }
    return value;
  }
}
class EditorLightbulb extends BaseEditorOption {
  constructor() {
    const defaults = { enabled: true };
    super(63, "lightbulb", defaults, {
      "editor.lightbulb.enabled": {
        type: "boolean",
        default: defaults.enabled,
        description: localize("codeActions", "Enables the Code Action lightbulb in the editor.")
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input2 = _input;
    return {
      enabled: boolean(input2.enabled, this.defaultValue.enabled)
    };
  }
}
class EditorStickyScroll extends BaseEditorOption {
  constructor() {
    const defaults = { enabled: false, maxLineCount: 5, defaultModel: "outlineModel" };
    super(113, "stickyScroll", defaults, {
      "editor.stickyScroll.enabled": {
        type: "boolean",
        default: defaults.enabled,
        description: localize("editor.stickyScroll.enabled", "Shows the nested current scopes during the scroll at the top of the editor.")
      },
      "editor.stickyScroll.maxLineCount": {
        type: "number",
        default: defaults.maxLineCount,
        minimum: 1,
        maximum: 10,
        description: localize("editor.stickyScroll.maxLineCount", "Defines the maximum number of sticky lines to show.")
      },
      "editor.stickyScroll.defaultModel": {
        type: "string",
        enum: ["outlineModel", "foldingProviderModel", "indentationModel"],
        default: defaults.defaultModel,
        description: localize("editor.stickyScroll.defaultModel", "Defines the model to use for determining which lines to stick. If the outline model does not exist, it will fall back on the folding provider model which falls back on the indentation model. This order is respected in all three cases.")
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input2 = _input;
    return {
      enabled: boolean(input2.enabled, this.defaultValue.enabled),
      maxLineCount: EditorIntOption.clampedInt(input2.maxLineCount, this.defaultValue.maxLineCount, 1, 10),
      defaultModel: stringSet(input2.defaultModel, this.defaultValue.defaultModel, ["outlineModel", "foldingProviderModel", "indentationModel"])
    };
  }
}
class EditorInlayHints extends BaseEditorOption {
  constructor() {
    const defaults = { enabled: "on", fontSize: 0, fontFamily: "", padding: false };
    super(138, "inlayHints", defaults, {
      "editor.inlayHints.enabled": {
        type: "string",
        default: defaults.enabled,
        description: localize("inlayHints.enable", "Enables the inlay hints in the editor."),
        enum: ["on", "onUnlessPressed", "offUnlessPressed", "off"],
        markdownEnumDescriptions: [
          localize("editor.inlayHints.on", "Inlay hints are enabled"),
          localize("editor.inlayHints.onUnlessPressed", "Inlay hints are showing by default and hide when holding {0}", isMacintosh ? `Ctrl+Option` : `Ctrl+Alt`),
          localize("editor.inlayHints.offUnlessPressed", "Inlay hints are hidden by default and show when holding {0}", isMacintosh ? `Ctrl+Option` : `Ctrl+Alt`),
          localize("editor.inlayHints.off", "Inlay hints are disabled")
        ]
      },
      "editor.inlayHints.fontSize": {
        type: "number",
        default: defaults.fontSize,
        markdownDescription: localize("inlayHints.fontSize", "Controls font size of inlay hints in the editor. As default the {0} is used when the configured value is less than {1} or greater than the editor font size.", "`#editor.fontSize#`", "`5`")
      },
      "editor.inlayHints.fontFamily": {
        type: "string",
        default: defaults.fontFamily,
        markdownDescription: localize("inlayHints.fontFamily", "Controls font family of inlay hints in the editor. When set to empty, the {0} is used.", "`#editor.fontFamily#`")
      },
      "editor.inlayHints.padding": {
        type: "boolean",
        default: defaults.padding,
        description: localize("inlayHints.padding", "Enables the padding around the inlay hints in the editor.")
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input2 = _input;
    if (typeof input2.enabled === "boolean") {
      input2.enabled = input2.enabled ? "on" : "off";
    }
    return {
      enabled: stringSet(input2.enabled, this.defaultValue.enabled, ["on", "off", "offUnlessPressed", "onUnlessPressed"]),
      fontSize: EditorIntOption.clampedInt(input2.fontSize, this.defaultValue.fontSize, 0, 100),
      fontFamily: EditorStringOption.string(input2.fontFamily, this.defaultValue.fontFamily),
      padding: boolean(input2.padding, this.defaultValue.padding)
    };
  }
}
class EditorLineDecorationsWidth extends BaseEditorOption {
  constructor() {
    super(64, "lineDecorationsWidth", 10);
  }
  validate(input2) {
    if (typeof input2 === "string" && /^\d+(\.\d+)?ch$/.test(input2)) {
      const multiple = parseFloat(input2.substring(0, input2.length - 2));
      return -multiple;
    } else {
      return EditorIntOption.clampedInt(input2, this.defaultValue, 0, 1e3);
    }
  }
  compute(env2, options, value) {
    if (value < 0) {
      return EditorIntOption.clampedInt(-value * env2.fontInfo.typicalHalfwidthCharacterWidth, this.defaultValue, 0, 1e3);
    } else {
      return value;
    }
  }
}
class EditorLineHeight extends EditorFloatOption {
  constructor() {
    super(65, "lineHeight", EDITOR_FONT_DEFAULTS.lineHeight, (x) => EditorFloatOption.clamp(x, 0, 150), { markdownDescription: localize("lineHeight", "Controls the line height. \n - Use 0 to automatically compute the line height from the font size.\n - Values between 0 and 8 will be used as a multiplier with the font size.\n - Values greater than or equal to 8 will be used as effective values.") });
  }
  compute(env2, options, value) {
    return env2.fontInfo.lineHeight;
  }
}
class EditorMinimap extends BaseEditorOption {
  constructor() {
    const defaults = {
      enabled: true,
      size: "proportional",
      side: "right",
      showSlider: "mouseover",
      autohide: false,
      renderCharacters: true,
      maxColumn: 120,
      scale: 1
    };
    super(71, "minimap", defaults, {
      "editor.minimap.enabled": {
        type: "boolean",
        default: defaults.enabled,
        description: localize("minimap.enabled", "Controls whether the minimap is shown.")
      },
      "editor.minimap.autohide": {
        type: "boolean",
        default: defaults.autohide,
        description: localize("minimap.autohide", "Controls whether the minimap is hidden automatically.")
      },
      "editor.minimap.size": {
        type: "string",
        enum: ["proportional", "fill", "fit"],
        enumDescriptions: [
          localize("minimap.size.proportional", "The minimap has the same size as the editor contents (and might scroll)."),
          localize("minimap.size.fill", "The minimap will stretch or shrink as necessary to fill the height of the editor (no scrolling)."),
          localize("minimap.size.fit", "The minimap will shrink as necessary to never be larger than the editor (no scrolling).")
        ],
        default: defaults.size,
        description: localize("minimap.size", "Controls the size of the minimap.")
      },
      "editor.minimap.side": {
        type: "string",
        enum: ["left", "right"],
        default: defaults.side,
        description: localize("minimap.side", "Controls the side where to render the minimap.")
      },
      "editor.minimap.showSlider": {
        type: "string",
        enum: ["always", "mouseover"],
        default: defaults.showSlider,
        description: localize("minimap.showSlider", "Controls when the minimap slider is shown.")
      },
      "editor.minimap.scale": {
        type: "number",
        default: defaults.scale,
        minimum: 1,
        maximum: 3,
        enum: [1, 2, 3],
        description: localize("minimap.scale", "Scale of content drawn in the minimap: 1, 2 or 3.")
      },
      "editor.minimap.renderCharacters": {
        type: "boolean",
        default: defaults.renderCharacters,
        description: localize("minimap.renderCharacters", "Render the actual characters on a line as opposed to color blocks.")
      },
      "editor.minimap.maxColumn": {
        type: "number",
        default: defaults.maxColumn,
        description: localize("minimap.maxColumn", "Limit the width of the minimap to render at most a certain number of columns.")
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input2 = _input;
    return {
      enabled: boolean(input2.enabled, this.defaultValue.enabled),
      autohide: boolean(input2.autohide, this.defaultValue.autohide),
      size: stringSet(input2.size, this.defaultValue.size, ["proportional", "fill", "fit"]),
      side: stringSet(input2.side, this.defaultValue.side, ["right", "left"]),
      showSlider: stringSet(input2.showSlider, this.defaultValue.showSlider, ["always", "mouseover"]),
      renderCharacters: boolean(input2.renderCharacters, this.defaultValue.renderCharacters),
      scale: EditorIntOption.clampedInt(input2.scale, 1, 1, 3),
      maxColumn: EditorIntOption.clampedInt(input2.maxColumn, this.defaultValue.maxColumn, 1, 1e4)
    };
  }
}
function _multiCursorModifierFromString(multiCursorModifier) {
  if (multiCursorModifier === "ctrlCmd") {
    return isMacintosh ? "metaKey" : "ctrlKey";
  }
  return "altKey";
}
class EditorPadding extends BaseEditorOption {
  constructor() {
    super(82, "padding", { top: 0, bottom: 0 }, {
      "editor.padding.top": {
        type: "number",
        default: 0,
        minimum: 0,
        maximum: 1e3,
        description: localize("padding.top", "Controls the amount of space between the top edge of the editor and the first line.")
      },
      "editor.padding.bottom": {
        type: "number",
        default: 0,
        minimum: 0,
        maximum: 1e3,
        description: localize("padding.bottom", "Controls the amount of space between the bottom edge of the editor and the last line.")
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input2 = _input;
    return {
      top: EditorIntOption.clampedInt(input2.top, 0, 0, 1e3),
      bottom: EditorIntOption.clampedInt(input2.bottom, 0, 0, 1e3)
    };
  }
}
class EditorParameterHints extends BaseEditorOption {
  constructor() {
    const defaults = {
      enabled: true,
      cycle: true
    };
    super(84, "parameterHints", defaults, {
      "editor.parameterHints.enabled": {
        type: "boolean",
        default: defaults.enabled,
        description: localize("parameterHints.enabled", "Enables a pop-up that shows parameter documentation and type information as you type.")
      },
      "editor.parameterHints.cycle": {
        type: "boolean",
        default: defaults.cycle,
        description: localize("parameterHints.cycle", "Controls whether the parameter hints menu cycles or closes when reaching the end of the list.")
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input2 = _input;
    return {
      enabled: boolean(input2.enabled, this.defaultValue.enabled),
      cycle: boolean(input2.cycle, this.defaultValue.cycle)
    };
  }
}
class EditorPixelRatio extends ComputedEditorOption {
  constructor() {
    super(
      140
      /* EditorOption.pixelRatio */
    );
  }
  compute(env2, options, _) {
    return env2.pixelRatio;
  }
}
class EditorQuickSuggestions extends BaseEditorOption {
  constructor() {
    const defaults = {
      other: "on",
      comments: "off",
      strings: "off"
    };
    const types2 = [
      { type: "boolean" },
      {
        type: "string",
        enum: ["on", "inline", "off"],
        enumDescriptions: [localize("on", "Quick suggestions show inside the suggest widget"), localize("inline", "Quick suggestions show as ghost text"), localize("off", "Quick suggestions are disabled")]
      }
    ];
    super(87, "quickSuggestions", defaults, {
      type: "object",
      additionalProperties: false,
      properties: {
        strings: {
          anyOf: types2,
          default: defaults.strings,
          description: localize("quickSuggestions.strings", "Enable quick suggestions inside strings.")
        },
        comments: {
          anyOf: types2,
          default: defaults.comments,
          description: localize("quickSuggestions.comments", "Enable quick suggestions inside comments.")
        },
        other: {
          anyOf: types2,
          default: defaults.other,
          description: localize("quickSuggestions.other", "Enable quick suggestions outside of strings and comments.")
        }
      },
      default: defaults,
      markdownDescription: localize("quickSuggestions", "Controls whether suggestions should automatically show up while typing. This can be controlled for typing in comments, strings, and other code. Quick suggestion can be configured to show as ghost text or with the suggest widget. Also be aware of the '{0}'-setting which controls if suggestions are triggered by special characters.", `#editor.suggestOnTriggerCharacters#`)
    });
    this.defaultValue = defaults;
  }
  validate(input2) {
    if (typeof input2 === "boolean") {
      const value = input2 ? "on" : "off";
      return { comments: value, strings: value, other: value };
    }
    if (!input2 || typeof input2 !== "object") {
      return this.defaultValue;
    }
    const { other, comments, strings } = input2;
    const allowedValues = ["on", "inline", "off"];
    let validatedOther;
    let validatedComments;
    let validatedStrings;
    if (typeof other === "boolean") {
      validatedOther = other ? "on" : "off";
    } else {
      validatedOther = stringSet(other, this.defaultValue.other, allowedValues);
    }
    if (typeof comments === "boolean") {
      validatedComments = comments ? "on" : "off";
    } else {
      validatedComments = stringSet(comments, this.defaultValue.comments, allowedValues);
    }
    if (typeof strings === "boolean") {
      validatedStrings = strings ? "on" : "off";
    } else {
      validatedStrings = stringSet(strings, this.defaultValue.strings, allowedValues);
    }
    return {
      other: validatedOther,
      comments: validatedComments,
      strings: validatedStrings
    };
  }
}
class EditorRenderLineNumbersOption extends BaseEditorOption {
  constructor() {
    super(66, "lineNumbers", { renderType: 1, renderFn: null }, {
      type: "string",
      enum: ["off", "on", "relative", "interval"],
      enumDescriptions: [
        localize("lineNumbers.off", "Line numbers are not rendered."),
        localize("lineNumbers.on", "Line numbers are rendered as absolute number."),
        localize("lineNumbers.relative", "Line numbers are rendered as distance in lines to cursor position."),
        localize("lineNumbers.interval", "Line numbers are rendered every 10 lines.")
      ],
      default: "on",
      description: localize("lineNumbers", "Controls the display of line numbers.")
    });
  }
  validate(lineNumbers2) {
    let renderType = this.defaultValue.renderType;
    let renderFn = this.defaultValue.renderFn;
    if (typeof lineNumbers2 !== "undefined") {
      if (typeof lineNumbers2 === "function") {
        renderType = 4;
        renderFn = lineNumbers2;
      } else if (lineNumbers2 === "interval") {
        renderType = 3;
      } else if (lineNumbers2 === "relative") {
        renderType = 2;
      } else if (lineNumbers2 === "on") {
        renderType = 1;
      } else {
        renderType = 0;
      }
    }
    return {
      renderType,
      renderFn
    };
  }
}
function filterValidationDecorations(options) {
  const renderValidationDecorations = options.get(
    96
    /* EditorOption.renderValidationDecorations */
  );
  if (renderValidationDecorations === "editable") {
    return options.get(
      89
      /* EditorOption.readOnly */
    );
  }
  return renderValidationDecorations === "on" ? false : true;
}
class EditorRulers extends BaseEditorOption {
  constructor() {
    const defaults = [];
    const columnSchema = { type: "number", description: localize("rulers.size", "Number of monospace characters at which this editor ruler will render.") };
    super(100, "rulers", defaults, {
      type: "array",
      items: {
        anyOf: [
          columnSchema,
          {
            type: [
              "object"
            ],
            properties: {
              column: columnSchema,
              color: {
                type: "string",
                description: localize("rulers.color", "Color of this editor ruler."),
                format: "color-hex"
              }
            }
          }
        ]
      },
      default: defaults,
      description: localize("rulers", "Render vertical rulers after a certain number of monospace characters. Use multiple values for multiple rulers. No rulers are drawn if array is empty.")
    });
  }
  validate(input2) {
    if (Array.isArray(input2)) {
      const rulers2 = [];
      for (const _element of input2) {
        if (typeof _element === "number") {
          rulers2.push({
            column: EditorIntOption.clampedInt(_element, 0, 0, 1e4),
            color: null
          });
        } else if (_element && typeof _element === "object") {
          const element = _element;
          rulers2.push({
            column: EditorIntOption.clampedInt(element.column, 0, 0, 1e4),
            color: element.color
          });
        }
      }
      rulers2.sort((a, b) => a.column - b.column);
      return rulers2;
    }
    return this.defaultValue;
  }
}
class ReadonlyMessage extends BaseEditorOption {
  constructor() {
    const defaults = void 0;
    super(90, "readOnlyMessage", defaults);
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    return _input;
  }
}
function _scrollbarVisibilityFromString(visibility, defaultValue) {
  if (typeof visibility !== "string") {
    return defaultValue;
  }
  switch (visibility) {
    case "hidden":
      return 2;
    case "visible":
      return 3;
    default:
      return 1;
  }
}
let EditorScrollbar$1 = class EditorScrollbar extends BaseEditorOption {
  constructor() {
    const defaults = {
      vertical: 1,
      horizontal: 1,
      arrowSize: 11,
      useShadows: true,
      verticalHasArrows: false,
      horizontalHasArrows: false,
      horizontalScrollbarSize: 12,
      horizontalSliderSize: 12,
      verticalScrollbarSize: 14,
      verticalSliderSize: 14,
      handleMouseWheel: true,
      alwaysConsumeMouseWheel: true,
      scrollByPage: false
    };
    super(101, "scrollbar", defaults, {
      "editor.scrollbar.vertical": {
        type: "string",
        enum: ["auto", "visible", "hidden"],
        enumDescriptions: [
          localize("scrollbar.vertical.auto", "The vertical scrollbar will be visible only when necessary."),
          localize("scrollbar.vertical.visible", "The vertical scrollbar will always be visible."),
          localize("scrollbar.vertical.fit", "The vertical scrollbar will always be hidden.")
        ],
        default: "auto",
        description: localize("scrollbar.vertical", "Controls the visibility of the vertical scrollbar.")
      },
      "editor.scrollbar.horizontal": {
        type: "string",
        enum: ["auto", "visible", "hidden"],
        enumDescriptions: [
          localize("scrollbar.horizontal.auto", "The horizontal scrollbar will be visible only when necessary."),
          localize("scrollbar.horizontal.visible", "The horizontal scrollbar will always be visible."),
          localize("scrollbar.horizontal.fit", "The horizontal scrollbar will always be hidden.")
        ],
        default: "auto",
        description: localize("scrollbar.horizontal", "Controls the visibility of the horizontal scrollbar.")
      },
      "editor.scrollbar.verticalScrollbarSize": {
        type: "number",
        default: defaults.verticalScrollbarSize,
        description: localize("scrollbar.verticalScrollbarSize", "The width of the vertical scrollbar.")
      },
      "editor.scrollbar.horizontalScrollbarSize": {
        type: "number",
        default: defaults.horizontalScrollbarSize,
        description: localize("scrollbar.horizontalScrollbarSize", "The height of the horizontal scrollbar.")
      },
      "editor.scrollbar.scrollByPage": {
        type: "boolean",
        default: defaults.scrollByPage,
        description: localize("scrollbar.scrollByPage", "Controls whether clicks scroll by page or jump to click position.")
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input2 = _input;
    const horizontalScrollbarSize = EditorIntOption.clampedInt(input2.horizontalScrollbarSize, this.defaultValue.horizontalScrollbarSize, 0, 1e3);
    const verticalScrollbarSize = EditorIntOption.clampedInt(input2.verticalScrollbarSize, this.defaultValue.verticalScrollbarSize, 0, 1e3);
    return {
      arrowSize: EditorIntOption.clampedInt(input2.arrowSize, this.defaultValue.arrowSize, 0, 1e3),
      vertical: _scrollbarVisibilityFromString(input2.vertical, this.defaultValue.vertical),
      horizontal: _scrollbarVisibilityFromString(input2.horizontal, this.defaultValue.horizontal),
      useShadows: boolean(input2.useShadows, this.defaultValue.useShadows),
      verticalHasArrows: boolean(input2.verticalHasArrows, this.defaultValue.verticalHasArrows),
      horizontalHasArrows: boolean(input2.horizontalHasArrows, this.defaultValue.horizontalHasArrows),
      handleMouseWheel: boolean(input2.handleMouseWheel, this.defaultValue.handleMouseWheel),
      alwaysConsumeMouseWheel: boolean(input2.alwaysConsumeMouseWheel, this.defaultValue.alwaysConsumeMouseWheel),
      horizontalScrollbarSize,
      horizontalSliderSize: EditorIntOption.clampedInt(input2.horizontalSliderSize, horizontalScrollbarSize, 0, 1e3),
      verticalScrollbarSize,
      verticalSliderSize: EditorIntOption.clampedInt(input2.verticalSliderSize, verticalScrollbarSize, 0, 1e3),
      scrollByPage: boolean(input2.scrollByPage, this.defaultValue.scrollByPage)
    };
  }
};
const inUntrustedWorkspace = "inUntrustedWorkspace";
const unicodeHighlightConfigKeys = {
  allowedCharacters: "editor.unicodeHighlight.allowedCharacters",
  invisibleCharacters: "editor.unicodeHighlight.invisibleCharacters",
  nonBasicASCII: "editor.unicodeHighlight.nonBasicASCII",
  ambiguousCharacters: "editor.unicodeHighlight.ambiguousCharacters",
  includeComments: "editor.unicodeHighlight.includeComments",
  includeStrings: "editor.unicodeHighlight.includeStrings",
  allowedLocales: "editor.unicodeHighlight.allowedLocales"
};
class UnicodeHighlight extends BaseEditorOption {
  constructor() {
    const defaults = {
      nonBasicASCII: inUntrustedWorkspace,
      invisibleCharacters: true,
      ambiguousCharacters: true,
      includeComments: inUntrustedWorkspace,
      includeStrings: true,
      allowedCharacters: {},
      allowedLocales: { _os: true, _vscode: true }
    };
    super(123, "unicodeHighlight", defaults, {
      [unicodeHighlightConfigKeys.nonBasicASCII]: {
        restricted: true,
        type: ["boolean", "string"],
        enum: [true, false, inUntrustedWorkspace],
        default: defaults.nonBasicASCII,
        description: localize("unicodeHighlight.nonBasicASCII", "Controls whether all non-basic ASCII characters are highlighted. Only characters between U+0020 and U+007E, tab, line-feed and carriage-return are considered basic ASCII.")
      },
      [unicodeHighlightConfigKeys.invisibleCharacters]: {
        restricted: true,
        type: "boolean",
        default: defaults.invisibleCharacters,
        description: localize("unicodeHighlight.invisibleCharacters", "Controls whether characters that just reserve space or have no width at all are highlighted.")
      },
      [unicodeHighlightConfigKeys.ambiguousCharacters]: {
        restricted: true,
        type: "boolean",
        default: defaults.ambiguousCharacters,
        description: localize("unicodeHighlight.ambiguousCharacters", "Controls whether characters are highlighted that can be confused with basic ASCII characters, except those that are common in the current user locale.")
      },
      [unicodeHighlightConfigKeys.includeComments]: {
        restricted: true,
        type: ["boolean", "string"],
        enum: [true, false, inUntrustedWorkspace],
        default: defaults.includeComments,
        description: localize("unicodeHighlight.includeComments", "Controls whether characters in comments should also be subject to Unicode highlighting.")
      },
      [unicodeHighlightConfigKeys.includeStrings]: {
        restricted: true,
        type: ["boolean", "string"],
        enum: [true, false, inUntrustedWorkspace],
        default: defaults.includeStrings,
        description: localize("unicodeHighlight.includeStrings", "Controls whether characters in strings should also be subject to Unicode highlighting.")
      },
      [unicodeHighlightConfigKeys.allowedCharacters]: {
        restricted: true,
        type: "object",
        default: defaults.allowedCharacters,
        description: localize("unicodeHighlight.allowedCharacters", "Defines allowed characters that are not being highlighted."),
        additionalProperties: {
          type: "boolean"
        }
      },
      [unicodeHighlightConfigKeys.allowedLocales]: {
        restricted: true,
        type: "object",
        additionalProperties: {
          type: "boolean"
        },
        default: defaults.allowedLocales,
        description: localize("unicodeHighlight.allowedLocales", "Unicode characters that are common in allowed locales are not being highlighted.")
      }
    });
  }
  applyUpdate(value, update) {
    let didChange = false;
    if (update.allowedCharacters && value) {
      if (!equals$2(value.allowedCharacters, update.allowedCharacters)) {
        value = Object.assign(Object.assign({}, value), { allowedCharacters: update.allowedCharacters });
        didChange = true;
      }
    }
    if (update.allowedLocales && value) {
      if (!equals$2(value.allowedLocales, update.allowedLocales)) {
        value = Object.assign(Object.assign({}, value), { allowedLocales: update.allowedLocales });
        didChange = true;
      }
    }
    const result2 = super.applyUpdate(value, update);
    if (didChange) {
      return new ApplyUpdateResult(result2.newValue, true);
    }
    return result2;
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input2 = _input;
    return {
      nonBasicASCII: primitiveSet(input2.nonBasicASCII, inUntrustedWorkspace, [true, false, inUntrustedWorkspace]),
      invisibleCharacters: boolean(input2.invisibleCharacters, this.defaultValue.invisibleCharacters),
      ambiguousCharacters: boolean(input2.ambiguousCharacters, this.defaultValue.ambiguousCharacters),
      includeComments: primitiveSet(input2.includeComments, inUntrustedWorkspace, [true, false, inUntrustedWorkspace]),
      includeStrings: primitiveSet(input2.includeStrings, inUntrustedWorkspace, [true, false, inUntrustedWorkspace]),
      allowedCharacters: this.validateBooleanMap(_input.allowedCharacters, this.defaultValue.allowedCharacters),
      allowedLocales: this.validateBooleanMap(_input.allowedLocales, this.defaultValue.allowedLocales)
    };
  }
  validateBooleanMap(map2, defaultValue) {
    if (typeof map2 !== "object" || !map2) {
      return defaultValue;
    }
    const result2 = {};
    for (const [key, value] of Object.entries(map2)) {
      if (value === true) {
        result2[key] = true;
      }
    }
    return result2;
  }
}
class InlineEditorSuggest extends BaseEditorOption {
  constructor() {
    const defaults = {
      enabled: true,
      mode: "subwordSmart",
      showToolbar: "onHover",
      suppressSuggestions: false,
      keepOnBlur: false
    };
    super(61, "inlineSuggest", defaults, {
      "editor.inlineSuggest.enabled": {
        type: "boolean",
        default: defaults.enabled,
        description: localize("inlineSuggest.enabled", "Controls whether to automatically show inline suggestions in the editor.")
      },
      "editor.inlineSuggest.showToolbar": {
        type: "string",
        default: defaults.showToolbar,
        enum: ["always", "onHover"],
        enumDescriptions: [
          localize("inlineSuggest.showToolbar.always", "Show the inline suggestion toolbar whenever an inline suggestion is shown."),
          localize("inlineSuggest.showToolbar.onHover", "Show the inline suggestion toolbar when hovering over an inline suggestion.")
        ],
        description: localize("inlineSuggest.showToolbar", "Controls when to show the inline suggestion toolbar.")
      },
      "editor.inlineSuggest.suppressSuggestions": {
        type: "boolean",
        default: defaults.suppressSuggestions,
        description: localize("inlineSuggest.suppressSuggestions", "Controls how inline suggestions interact with the suggest widget. If enabled, the suggest widget is not shown automatically when inline suggestions are available.")
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input2 = _input;
    return {
      enabled: boolean(input2.enabled, this.defaultValue.enabled),
      mode: stringSet(input2.mode, this.defaultValue.mode, ["prefix", "subword", "subwordSmart"]),
      showToolbar: stringSet(input2.showToolbar, this.defaultValue.showToolbar, ["always", "onHover"]),
      suppressSuggestions: boolean(input2.suppressSuggestions, this.defaultValue.suppressSuggestions),
      keepOnBlur: boolean(input2.keepOnBlur, this.defaultValue.keepOnBlur)
    };
  }
}
class BracketPairColorization extends BaseEditorOption {
  constructor() {
    const defaults = {
      enabled: EDITOR_MODEL_DEFAULTS.bracketPairColorizationOptions.enabled,
      independentColorPoolPerBracketType: EDITOR_MODEL_DEFAULTS.bracketPairColorizationOptions.independentColorPoolPerBracketType
    };
    super(14, "bracketPairColorization", defaults, {
      "editor.bracketPairColorization.enabled": {
        type: "boolean",
        default: defaults.enabled,
        markdownDescription: localize("bracketPairColorization.enabled", "Controls whether bracket pair colorization is enabled or not. Use {0} to override the bracket highlight colors.", "`#workbench.colorCustomizations#`")
      },
      "editor.bracketPairColorization.independentColorPoolPerBracketType": {
        type: "boolean",
        default: defaults.independentColorPoolPerBracketType,
        description: localize("bracketPairColorization.independentColorPoolPerBracketType", "Controls whether each bracket type has its own independent color pool.")
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input2 = _input;
    return {
      enabled: boolean(input2.enabled, this.defaultValue.enabled),
      independentColorPoolPerBracketType: boolean(input2.independentColorPoolPerBracketType, this.defaultValue.independentColorPoolPerBracketType)
    };
  }
}
class GuideOptions extends BaseEditorOption {
  constructor() {
    const defaults = {
      bracketPairs: false,
      bracketPairsHorizontal: "active",
      highlightActiveBracketPair: true,
      indentation: true,
      highlightActiveIndentation: true
    };
    super(15, "guides", defaults, {
      "editor.guides.bracketPairs": {
        type: ["boolean", "string"],
        enum: [true, "active", false],
        enumDescriptions: [
          localize("editor.guides.bracketPairs.true", "Enables bracket pair guides."),
          localize("editor.guides.bracketPairs.active", "Enables bracket pair guides only for the active bracket pair."),
          localize("editor.guides.bracketPairs.false", "Disables bracket pair guides.")
        ],
        default: defaults.bracketPairs,
        description: localize("editor.guides.bracketPairs", "Controls whether bracket pair guides are enabled or not.")
      },
      "editor.guides.bracketPairsHorizontal": {
        type: ["boolean", "string"],
        enum: [true, "active", false],
        enumDescriptions: [
          localize("editor.guides.bracketPairsHorizontal.true", "Enables horizontal guides as addition to vertical bracket pair guides."),
          localize("editor.guides.bracketPairsHorizontal.active", "Enables horizontal guides only for the active bracket pair."),
          localize("editor.guides.bracketPairsHorizontal.false", "Disables horizontal bracket pair guides.")
        ],
        default: defaults.bracketPairsHorizontal,
        description: localize("editor.guides.bracketPairsHorizontal", "Controls whether horizontal bracket pair guides are enabled or not.")
      },
      "editor.guides.highlightActiveBracketPair": {
        type: "boolean",
        default: defaults.highlightActiveBracketPair,
        description: localize("editor.guides.highlightActiveBracketPair", "Controls whether the editor should highlight the active bracket pair.")
      },
      "editor.guides.indentation": {
        type: "boolean",
        default: defaults.indentation,
        description: localize("editor.guides.indentation", "Controls whether the editor should render indent guides.")
      },
      "editor.guides.highlightActiveIndentation": {
        type: ["boolean", "string"],
        enum: [true, "always", false],
        enumDescriptions: [
          localize("editor.guides.highlightActiveIndentation.true", "Highlights the active indent guide."),
          localize("editor.guides.highlightActiveIndentation.always", "Highlights the active indent guide even if bracket guides are highlighted."),
          localize("editor.guides.highlightActiveIndentation.false", "Do not highlight the active indent guide.")
        ],
        default: defaults.highlightActiveIndentation,
        description: localize("editor.guides.highlightActiveIndentation", "Controls whether the editor should highlight the active indent guide.")
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input2 = _input;
    return {
      bracketPairs: primitiveSet(input2.bracketPairs, this.defaultValue.bracketPairs, [true, false, "active"]),
      bracketPairsHorizontal: primitiveSet(input2.bracketPairsHorizontal, this.defaultValue.bracketPairsHorizontal, [true, false, "active"]),
      highlightActiveBracketPair: boolean(input2.highlightActiveBracketPair, this.defaultValue.highlightActiveBracketPair),
      indentation: boolean(input2.indentation, this.defaultValue.indentation),
      highlightActiveIndentation: primitiveSet(input2.highlightActiveIndentation, this.defaultValue.highlightActiveIndentation, [true, false, "always"])
    };
  }
}
function primitiveSet(value, defaultValue, allowedValues) {
  const idx = allowedValues.indexOf(value);
  if (idx === -1) {
    return defaultValue;
  }
  return allowedValues[idx];
}
class EditorSuggest extends BaseEditorOption {
  constructor() {
    const defaults = {
      insertMode: "insert",
      filterGraceful: true,
      snippetsPreventQuickSuggestions: false,
      localityBonus: false,
      shareSuggestSelections: false,
      selectionMode: "always",
      showIcons: true,
      showStatusBar: false,
      preview: false,
      previewMode: "subwordSmart",
      showInlineDetails: true,
      showMethods: true,
      showFunctions: true,
      showConstructors: true,
      showDeprecated: true,
      matchOnWordStartOnly: true,
      showFields: true,
      showVariables: true,
      showClasses: true,
      showStructs: true,
      showInterfaces: true,
      showModules: true,
      showProperties: true,
      showEvents: true,
      showOperators: true,
      showUnits: true,
      showValues: true,
      showConstants: true,
      showEnums: true,
      showEnumMembers: true,
      showKeywords: true,
      showWords: true,
      showColors: true,
      showFiles: true,
      showReferences: true,
      showFolders: true,
      showTypeParameters: true,
      showSnippets: true,
      showUsers: true,
      showIssues: true
    };
    super(116, "suggest", defaults, {
      "editor.suggest.insertMode": {
        type: "string",
        enum: ["insert", "replace"],
        enumDescriptions: [
          localize("suggest.insertMode.insert", "Insert suggestion without overwriting text right of the cursor."),
          localize("suggest.insertMode.replace", "Insert suggestion and overwrite text right of the cursor.")
        ],
        default: defaults.insertMode,
        description: localize("suggest.insertMode", "Controls whether words are overwritten when accepting completions. Note that this depends on extensions opting into this feature.")
      },
      "editor.suggest.filterGraceful": {
        type: "boolean",
        default: defaults.filterGraceful,
        description: localize("suggest.filterGraceful", "Controls whether filtering and sorting suggestions accounts for small typos.")
      },
      "editor.suggest.localityBonus": {
        type: "boolean",
        default: defaults.localityBonus,
        description: localize("suggest.localityBonus", "Controls whether sorting favors words that appear close to the cursor.")
      },
      "editor.suggest.shareSuggestSelections": {
        type: "boolean",
        default: defaults.shareSuggestSelections,
        markdownDescription: localize("suggest.shareSuggestSelections", "Controls whether remembered suggestion selections are shared between multiple workspaces and windows (needs `#editor.suggestSelection#`).")
      },
      "editor.suggest.selectionMode": {
        type: "string",
        enum: ["always", "never", "whenTriggerCharacter", "whenQuickSuggestion"],
        enumDescriptions: [
          localize("suggest.insertMode.always", "Always select a suggestion when automatically triggering IntelliSense."),
          localize("suggest.insertMode.never", "Never select a suggestion when automatically triggering IntelliSense."),
          localize("suggest.insertMode.whenTriggerCharacter", "Select a suggestion only when triggering IntelliSense from a trigger character."),
          localize("suggest.insertMode.whenQuickSuggestion", "Select a suggestion only when triggering IntelliSense as you type.")
        ],
        default: defaults.selectionMode,
        markdownDescription: localize("suggest.selectionMode", "Controls whether a suggestion is selected when the widget shows. Note that this only applies to automatically triggered suggestions (`#editor.quickSuggestions#` and `#editor.suggestOnTriggerCharacters#`) and that a suggestion is always selected when explicitly invoked, e.g via `Ctrl+Space`.")
      },
      "editor.suggest.snippetsPreventQuickSuggestions": {
        type: "boolean",
        default: defaults.snippetsPreventQuickSuggestions,
        description: localize("suggest.snippetsPreventQuickSuggestions", "Controls whether an active snippet prevents quick suggestions.")
      },
      "editor.suggest.showIcons": {
        type: "boolean",
        default: defaults.showIcons,
        description: localize("suggest.showIcons", "Controls whether to show or hide icons in suggestions.")
      },
      "editor.suggest.showStatusBar": {
        type: "boolean",
        default: defaults.showStatusBar,
        description: localize("suggest.showStatusBar", "Controls the visibility of the status bar at the bottom of the suggest widget.")
      },
      "editor.suggest.preview": {
        type: "boolean",
        default: defaults.preview,
        description: localize("suggest.preview", "Controls whether to preview the suggestion outcome in the editor.")
      },
      "editor.suggest.showInlineDetails": {
        type: "boolean",
        default: defaults.showInlineDetails,
        description: localize("suggest.showInlineDetails", "Controls whether suggest details show inline with the label or only in the details widget.")
      },
      "editor.suggest.maxVisibleSuggestions": {
        type: "number",
        deprecationMessage: localize("suggest.maxVisibleSuggestions.dep", "This setting is deprecated. The suggest widget can now be resized.")
      },
      "editor.suggest.filteredTypes": {
        type: "object",
        deprecationMessage: localize("deprecated", "This setting is deprecated, please use separate settings like 'editor.suggest.showKeywords' or 'editor.suggest.showSnippets' instead.")
      },
      "editor.suggest.showMethods": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showMethods", "When enabled IntelliSense shows `method`-suggestions.")
      },
      "editor.suggest.showFunctions": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showFunctions", "When enabled IntelliSense shows `function`-suggestions.")
      },
      "editor.suggest.showConstructors": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showConstructors", "When enabled IntelliSense shows `constructor`-suggestions.")
      },
      "editor.suggest.showDeprecated": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showDeprecated", "When enabled IntelliSense shows `deprecated`-suggestions.")
      },
      "editor.suggest.matchOnWordStartOnly": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.matchOnWordStartOnly", "When enabled IntelliSense filtering requires that the first character matches on a word start. For example, `c` on `Console` or `WebContext` but _not_ on `description`. When disabled IntelliSense will show more results but still sorts them by match quality.")
      },
      "editor.suggest.showFields": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showFields", "When enabled IntelliSense shows `field`-suggestions.")
      },
      "editor.suggest.showVariables": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showVariables", "When enabled IntelliSense shows `variable`-suggestions.")
      },
      "editor.suggest.showClasses": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showClasss", "When enabled IntelliSense shows `class`-suggestions.")
      },
      "editor.suggest.showStructs": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showStructs", "When enabled IntelliSense shows `struct`-suggestions.")
      },
      "editor.suggest.showInterfaces": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showInterfaces", "When enabled IntelliSense shows `interface`-suggestions.")
      },
      "editor.suggest.showModules": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showModules", "When enabled IntelliSense shows `module`-suggestions.")
      },
      "editor.suggest.showProperties": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showPropertys", "When enabled IntelliSense shows `property`-suggestions.")
      },
      "editor.suggest.showEvents": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showEvents", "When enabled IntelliSense shows `event`-suggestions.")
      },
      "editor.suggest.showOperators": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showOperators", "When enabled IntelliSense shows `operator`-suggestions.")
      },
      "editor.suggest.showUnits": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showUnits", "When enabled IntelliSense shows `unit`-suggestions.")
      },
      "editor.suggest.showValues": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showValues", "When enabled IntelliSense shows `value`-suggestions.")
      },
      "editor.suggest.showConstants": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showConstants", "When enabled IntelliSense shows `constant`-suggestions.")
      },
      "editor.suggest.showEnums": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showEnums", "When enabled IntelliSense shows `enum`-suggestions.")
      },
      "editor.suggest.showEnumMembers": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showEnumMembers", "When enabled IntelliSense shows `enumMember`-suggestions.")
      },
      "editor.suggest.showKeywords": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showKeywords", "When enabled IntelliSense shows `keyword`-suggestions.")
      },
      "editor.suggest.showWords": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showTexts", "When enabled IntelliSense shows `text`-suggestions.")
      },
      "editor.suggest.showColors": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showColors", "When enabled IntelliSense shows `color`-suggestions.")
      },
      "editor.suggest.showFiles": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showFiles", "When enabled IntelliSense shows `file`-suggestions.")
      },
      "editor.suggest.showReferences": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showReferences", "When enabled IntelliSense shows `reference`-suggestions.")
      },
      "editor.suggest.showCustomcolors": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showCustomcolors", "When enabled IntelliSense shows `customcolor`-suggestions.")
      },
      "editor.suggest.showFolders": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showFolders", "When enabled IntelliSense shows `folder`-suggestions.")
      },
      "editor.suggest.showTypeParameters": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showTypeParameters", "When enabled IntelliSense shows `typeParameter`-suggestions.")
      },
      "editor.suggest.showSnippets": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showSnippets", "When enabled IntelliSense shows `snippet`-suggestions.")
      },
      "editor.suggest.showUsers": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showUsers", "When enabled IntelliSense shows `user`-suggestions.")
      },
      "editor.suggest.showIssues": {
        type: "boolean",
        default: true,
        markdownDescription: localize("editor.suggest.showIssues", "When enabled IntelliSense shows `issues`-suggestions.")
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input2 = _input;
    return {
      insertMode: stringSet(input2.insertMode, this.defaultValue.insertMode, ["insert", "replace"]),
      filterGraceful: boolean(input2.filterGraceful, this.defaultValue.filterGraceful),
      snippetsPreventQuickSuggestions: boolean(input2.snippetsPreventQuickSuggestions, this.defaultValue.filterGraceful),
      localityBonus: boolean(input2.localityBonus, this.defaultValue.localityBonus),
      shareSuggestSelections: boolean(input2.shareSuggestSelections, this.defaultValue.shareSuggestSelections),
      selectionMode: stringSet(input2.selectionMode, this.defaultValue.selectionMode, ["always", "never", "whenQuickSuggestion", "whenTriggerCharacter"]),
      showIcons: boolean(input2.showIcons, this.defaultValue.showIcons),
      showStatusBar: boolean(input2.showStatusBar, this.defaultValue.showStatusBar),
      preview: boolean(input2.preview, this.defaultValue.preview),
      previewMode: stringSet(input2.previewMode, this.defaultValue.previewMode, ["prefix", "subword", "subwordSmart"]),
      showInlineDetails: boolean(input2.showInlineDetails, this.defaultValue.showInlineDetails),
      showMethods: boolean(input2.showMethods, this.defaultValue.showMethods),
      showFunctions: boolean(input2.showFunctions, this.defaultValue.showFunctions),
      showConstructors: boolean(input2.showConstructors, this.defaultValue.showConstructors),
      showDeprecated: boolean(input2.showDeprecated, this.defaultValue.showDeprecated),
      matchOnWordStartOnly: boolean(input2.matchOnWordStartOnly, this.defaultValue.matchOnWordStartOnly),
      showFields: boolean(input2.showFields, this.defaultValue.showFields),
      showVariables: boolean(input2.showVariables, this.defaultValue.showVariables),
      showClasses: boolean(input2.showClasses, this.defaultValue.showClasses),
      showStructs: boolean(input2.showStructs, this.defaultValue.showStructs),
      showInterfaces: boolean(input2.showInterfaces, this.defaultValue.showInterfaces),
      showModules: boolean(input2.showModules, this.defaultValue.showModules),
      showProperties: boolean(input2.showProperties, this.defaultValue.showProperties),
      showEvents: boolean(input2.showEvents, this.defaultValue.showEvents),
      showOperators: boolean(input2.showOperators, this.defaultValue.showOperators),
      showUnits: boolean(input2.showUnits, this.defaultValue.showUnits),
      showValues: boolean(input2.showValues, this.defaultValue.showValues),
      showConstants: boolean(input2.showConstants, this.defaultValue.showConstants),
      showEnums: boolean(input2.showEnums, this.defaultValue.showEnums),
      showEnumMembers: boolean(input2.showEnumMembers, this.defaultValue.showEnumMembers),
      showKeywords: boolean(input2.showKeywords, this.defaultValue.showKeywords),
      showWords: boolean(input2.showWords, this.defaultValue.showWords),
      showColors: boolean(input2.showColors, this.defaultValue.showColors),
      showFiles: boolean(input2.showFiles, this.defaultValue.showFiles),
      showReferences: boolean(input2.showReferences, this.defaultValue.showReferences),
      showFolders: boolean(input2.showFolders, this.defaultValue.showFolders),
      showTypeParameters: boolean(input2.showTypeParameters, this.defaultValue.showTypeParameters),
      showSnippets: boolean(input2.showSnippets, this.defaultValue.showSnippets),
      showUsers: boolean(input2.showUsers, this.defaultValue.showUsers),
      showIssues: boolean(input2.showIssues, this.defaultValue.showIssues)
    };
  }
}
class SmartSelect extends BaseEditorOption {
  constructor() {
    super(111, "smartSelect", {
      selectLeadingAndTrailingWhitespace: true,
      selectSubwords: true
    }, {
      "editor.smartSelect.selectLeadingAndTrailingWhitespace": {
        description: localize("selectLeadingAndTrailingWhitespace", "Whether leading and trailing whitespace should always be selected."),
        default: true,
        type: "boolean"
      },
      "editor.smartSelect.selectSubwords": {
        description: localize("selectSubwords", "Whether subwords (like 'foo' in 'fooBar' or 'foo_bar') should be selected."),
        default: true,
        type: "boolean"
      }
    });
  }
  validate(input2) {
    if (!input2 || typeof input2 !== "object") {
      return this.defaultValue;
    }
    return {
      selectLeadingAndTrailingWhitespace: boolean(input2.selectLeadingAndTrailingWhitespace, this.defaultValue.selectLeadingAndTrailingWhitespace),
      selectSubwords: boolean(input2.selectSubwords, this.defaultValue.selectSubwords)
    };
  }
}
class WrappingIndentOption extends BaseEditorOption {
  constructor() {
    super(135, "wrappingIndent", 1, {
      "editor.wrappingIndent": {
        type: "string",
        enum: ["none", "same", "indent", "deepIndent"],
        enumDescriptions: [
          localize("wrappingIndent.none", "No indentation. Wrapped lines begin at column 1."),
          localize("wrappingIndent.same", "Wrapped lines get the same indentation as the parent."),
          localize("wrappingIndent.indent", "Wrapped lines get +1 indentation toward the parent."),
          localize("wrappingIndent.deepIndent", "Wrapped lines get +2 indentation toward the parent.")
        ],
        description: localize("wrappingIndent", "Controls the indentation of wrapped lines."),
        default: "same"
      }
    });
  }
  validate(input2) {
    switch (input2) {
      case "none":
        return 0;
      case "same":
        return 1;
      case "indent":
        return 2;
      case "deepIndent":
        return 3;
    }
    return 1;
  }
  compute(env2, options, value) {
    const accessibilitySupport = options.get(
      2
      /* EditorOption.accessibilitySupport */
    );
    if (accessibilitySupport === 2) {
      return 0;
    }
    return value;
  }
}
class EditorWrappingInfoComputer extends ComputedEditorOption {
  constructor() {
    super(
      143
      /* EditorOption.wrappingInfo */
    );
  }
  compute(env2, options, _) {
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    return {
      isDominatedByLongLines: env2.isDominatedByLongLines,
      isWordWrapMinified: layoutInfo.isWordWrapMinified,
      isViewportWrapping: layoutInfo.isViewportWrapping,
      wrappingColumn: layoutInfo.wrappingColumn
    };
  }
}
class EditorDropIntoEditor extends BaseEditorOption {
  constructor() {
    const defaults = { enabled: true, showDropSelector: "afterDrop" };
    super(35, "dropIntoEditor", defaults, {
      "editor.dropIntoEditor.enabled": {
        type: "boolean",
        default: defaults.enabled,
        markdownDescription: localize("dropIntoEditor.enabled", "Controls whether you can drag and drop a file into a text editor by holding down `shift` (instead of opening the file in an editor).")
      },
      "editor.dropIntoEditor.showDropSelector": {
        type: "string",
        markdownDescription: localize("dropIntoEditor.showDropSelector", "Controls if a widget is shown when dropping files into the editor. This widget lets you control how the file is dropped."),
        enum: [
          "afterDrop",
          "never"
        ],
        enumDescriptions: [
          localize("dropIntoEditor.showDropSelector.afterDrop", "Show the drop selector widget after a file is dropped into the editor."),
          localize("dropIntoEditor.showDropSelector.never", "Never show the drop selector widget. Instead the default drop provider is always used.")
        ],
        default: "afterDrop"
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input2 = _input;
    return {
      enabled: boolean(input2.enabled, this.defaultValue.enabled),
      showDropSelector: stringSet(input2.showDropSelector, this.defaultValue.showDropSelector, ["afterDrop", "never"])
    };
  }
}
class EditorPasteAs extends BaseEditorOption {
  constructor() {
    const defaults = { enabled: true, showPasteSelector: "afterPaste" };
    super(83, "pasteAs", defaults, {
      "editor.pasteAs.enabled": {
        type: "boolean",
        default: defaults.enabled,
        markdownDescription: localize("pasteAs.enabled", "Controls whether you can paste content in different ways.")
      },
      "editor.pasteAs.showPasteSelector": {
        type: "string",
        markdownDescription: localize("pasteAs.showPasteSelector", "Controls if a widget is shown when pasting content in to the editor. This widget lets you control how the file is pasted."),
        enum: [
          "afterPaste",
          "never"
        ],
        enumDescriptions: [
          localize("pasteAs.showPasteSelector.afterPaste", "Show the paste selector widget after content is pasted into the editor."),
          localize("pasteAs.showPasteSelector.never", "Never show the paste selector widget. Instead the default pasting behavior is always used.")
        ],
        default: "afterPaste"
      }
    });
  }
  validate(_input) {
    if (!_input || typeof _input !== "object") {
      return this.defaultValue;
    }
    const input2 = _input;
    return {
      enabled: boolean(input2.enabled, this.defaultValue.enabled),
      showPasteSelector: stringSet(input2.showPasteSelector, this.defaultValue.showPasteSelector, ["afterPaste", "never"])
    };
  }
}
const DEFAULT_WINDOWS_FONT_FAMILY = "Consolas, 'Courier New', monospace";
const DEFAULT_MAC_FONT_FAMILY = "Menlo, Monaco, 'Courier New', monospace";
const DEFAULT_LINUX_FONT_FAMILY = "'Droid Sans Mono', 'monospace', monospace";
const EDITOR_FONT_DEFAULTS = {
  fontFamily: isMacintosh ? DEFAULT_MAC_FONT_FAMILY : isLinux ? DEFAULT_LINUX_FONT_FAMILY : DEFAULT_WINDOWS_FONT_FAMILY,
  fontWeight: "normal",
  fontSize: isMacintosh ? 12 : 14,
  lineHeight: 0,
  letterSpacing: 0
};
const editorOptionsRegistry = [];
function register$1(option) {
  editorOptionsRegistry[option.id] = option;
  return option;
}
const EditorOptions = {
  acceptSuggestionOnCommitCharacter: register$1(new EditorBooleanOption(0, "acceptSuggestionOnCommitCharacter", true, { markdownDescription: localize("acceptSuggestionOnCommitCharacter", "Controls whether suggestions should be accepted on commit characters. For example, in JavaScript, the semi-colon (`;`) can be a commit character that accepts a suggestion and types that character.") })),
  acceptSuggestionOnEnter: register$1(new EditorStringEnumOption(1, "acceptSuggestionOnEnter", "on", ["on", "smart", "off"], {
    markdownEnumDescriptions: [
      "",
      localize("acceptSuggestionOnEnterSmart", "Only accept a suggestion with `Enter` when it makes a textual change."),
      ""
    ],
    markdownDescription: localize("acceptSuggestionOnEnter", "Controls whether suggestions should be accepted on `Enter`, in addition to `Tab`. Helps to avoid ambiguity between inserting new lines or accepting suggestions.")
  })),
  accessibilitySupport: register$1(new EditorAccessibilitySupport()),
  accessibilityPageSize: register$1(new EditorIntOption(3, "accessibilityPageSize", 10, 1, 1073741824, {
    description: localize("accessibilityPageSize", "Controls the number of lines in the editor that can be read out by a screen reader at once. When we detect a screen reader we automatically set the default to be 500. Warning: this has a performance implication for numbers larger than the default."),
    tags: ["accessibility"]
  })),
  ariaLabel: register$1(new EditorStringOption(4, "ariaLabel", localize("editorViewAccessibleLabel", "Editor content"))),
  ariaRequired: register$1(new EditorBooleanOption(5, "ariaRequired", false, void 0)),
  screenReaderAnnounceInlineSuggestion: register$1(new EditorBooleanOption(7, "screenReaderAnnounceInlineSuggestion", true, {
    description: localize("screenReaderAnnounceInlineSuggestion", "Control whether inline suggestions are announced by a screen reader."),
    tags: ["accessibility"]
  })),
  autoClosingBrackets: register$1(new EditorStringEnumOption(6, "autoClosingBrackets", "languageDefined", ["always", "languageDefined", "beforeWhitespace", "never"], {
    enumDescriptions: [
      "",
      localize("editor.autoClosingBrackets.languageDefined", "Use language configurations to determine when to autoclose brackets."),
      localize("editor.autoClosingBrackets.beforeWhitespace", "Autoclose brackets only when the cursor is to the left of whitespace."),
      ""
    ],
    description: localize("autoClosingBrackets", "Controls whether the editor should automatically close brackets after the user adds an opening bracket.")
  })),
  autoClosingDelete: register$1(new EditorStringEnumOption(8, "autoClosingDelete", "auto", ["always", "auto", "never"], {
    enumDescriptions: [
      "",
      localize("editor.autoClosingDelete.auto", "Remove adjacent closing quotes or brackets only if they were automatically inserted."),
      ""
    ],
    description: localize("autoClosingDelete", "Controls whether the editor should remove adjacent closing quotes or brackets when deleting.")
  })),
  autoClosingOvertype: register$1(new EditorStringEnumOption(9, "autoClosingOvertype", "auto", ["always", "auto", "never"], {
    enumDescriptions: [
      "",
      localize("editor.autoClosingOvertype.auto", "Type over closing quotes or brackets only if they were automatically inserted."),
      ""
    ],
    description: localize("autoClosingOvertype", "Controls whether the editor should type over closing quotes or brackets.")
  })),
  autoClosingQuotes: register$1(new EditorStringEnumOption(10, "autoClosingQuotes", "languageDefined", ["always", "languageDefined", "beforeWhitespace", "never"], {
    enumDescriptions: [
      "",
      localize("editor.autoClosingQuotes.languageDefined", "Use language configurations to determine when to autoclose quotes."),
      localize("editor.autoClosingQuotes.beforeWhitespace", "Autoclose quotes only when the cursor is to the left of whitespace."),
      ""
    ],
    description: localize("autoClosingQuotes", "Controls whether the editor should automatically close quotes after the user adds an opening quote.")
  })),
  autoIndent: register$1(new EditorEnumOption(11, "autoIndent", 4, "full", ["none", "keep", "brackets", "advanced", "full"], _autoIndentFromString, {
    enumDescriptions: [
      localize("editor.autoIndent.none", "The editor will not insert indentation automatically."),
      localize("editor.autoIndent.keep", "The editor will keep the current line's indentation."),
      localize("editor.autoIndent.brackets", "The editor will keep the current line's indentation and honor language defined brackets."),
      localize("editor.autoIndent.advanced", "The editor will keep the current line's indentation, honor language defined brackets and invoke special onEnterRules defined by languages."),
      localize("editor.autoIndent.full", "The editor will keep the current line's indentation, honor language defined brackets, invoke special onEnterRules defined by languages, and honor indentationRules defined by languages.")
    ],
    description: localize("autoIndent", "Controls whether the editor should automatically adjust the indentation when users type, paste, move or indent lines.")
  })),
  automaticLayout: register$1(new EditorBooleanOption(12, "automaticLayout", false)),
  autoSurround: register$1(new EditorStringEnumOption(13, "autoSurround", "languageDefined", ["languageDefined", "quotes", "brackets", "never"], {
    enumDescriptions: [
      localize("editor.autoSurround.languageDefined", "Use language configurations to determine when to automatically surround selections."),
      localize("editor.autoSurround.quotes", "Surround with quotes but not brackets."),
      localize("editor.autoSurround.brackets", "Surround with brackets but not quotes."),
      ""
    ],
    description: localize("autoSurround", "Controls whether the editor should automatically surround selections when typing quotes or brackets.")
  })),
  bracketPairColorization: register$1(new BracketPairColorization()),
  bracketPairGuides: register$1(new GuideOptions()),
  stickyTabStops: register$1(new EditorBooleanOption(114, "stickyTabStops", false, { description: localize("stickyTabStops", "Emulate selection behavior of tab characters when using spaces for indentation. Selection will stick to tab stops.") })),
  codeLens: register$1(new EditorBooleanOption(16, "codeLens", true, { description: localize("codeLens", "Controls whether the editor shows CodeLens.") })),
  codeLensFontFamily: register$1(new EditorStringOption(17, "codeLensFontFamily", "", { description: localize("codeLensFontFamily", "Controls the font family for CodeLens.") })),
  codeLensFontSize: register$1(new EditorIntOption(18, "codeLensFontSize", 0, 0, 100, {
    type: "number",
    default: 0,
    minimum: 0,
    maximum: 100,
    markdownDescription: localize("codeLensFontSize", "Controls the font size in pixels for CodeLens. When set to 0, 90% of `#editor.fontSize#` is used.")
  })),
  colorDecorators: register$1(new EditorBooleanOption(19, "colorDecorators", true, { description: localize("colorDecorators", "Controls whether the editor should render the inline color decorators and color picker.") })),
  colorDecoratorActivatedOn: register$1(new EditorStringEnumOption(145, "colorDecoratorsActivatedOn", "clickAndHover", ["clickAndHover", "hover", "click"], {
    enumDescriptions: [
      localize("editor.colorDecoratorActivatedOn.clickAndHover", "Make the color picker appear both on click and hover of the color decorator"),
      localize("editor.colorDecoratorActivatedOn.hover", "Make the color picker appear on hover of the color decorator"),
      localize("editor.colorDecoratorActivatedOn.click", "Make the color picker appear on click of the color decorator")
    ],
    description: localize("colorDecoratorActivatedOn", "Controls the condition to make a color picker appear from a color decorator")
  })),
  colorDecoratorsLimit: register$1(new EditorIntOption(20, "colorDecoratorsLimit", 500, 1, 1e6, {
    markdownDescription: localize("colorDecoratorsLimit", "Controls the max number of color decorators that can be rendered in an editor at once.")
  })),
  columnSelection: register$1(new EditorBooleanOption(21, "columnSelection", false, { description: localize("columnSelection", "Enable that the selection with the mouse and keys is doing column selection.") })),
  comments: register$1(new EditorComments()),
  contextmenu: register$1(new EditorBooleanOption(23, "contextmenu", true)),
  copyWithSyntaxHighlighting: register$1(new EditorBooleanOption(24, "copyWithSyntaxHighlighting", true, { description: localize("copyWithSyntaxHighlighting", "Controls whether syntax highlighting should be copied into the clipboard.") })),
  cursorBlinking: register$1(new EditorEnumOption(25, "cursorBlinking", 1, "blink", ["blink", "smooth", "phase", "expand", "solid"], _cursorBlinkingStyleFromString, { description: localize("cursorBlinking", "Control the cursor animation style.") })),
  cursorSmoothCaretAnimation: register$1(new EditorStringEnumOption(26, "cursorSmoothCaretAnimation", "off", ["off", "explicit", "on"], {
    enumDescriptions: [
      localize("cursorSmoothCaretAnimation.off", "Smooth caret animation is disabled."),
      localize("cursorSmoothCaretAnimation.explicit", "Smooth caret animation is enabled only when the user moves the cursor with an explicit gesture."),
      localize("cursorSmoothCaretAnimation.on", "Smooth caret animation is always enabled.")
    ],
    description: localize("cursorSmoothCaretAnimation", "Controls whether the smooth caret animation should be enabled.")
  })),
  cursorStyle: register$1(new EditorEnumOption(27, "cursorStyle", TextEditorCursorStyle$1.Line, "line", ["line", "block", "underline", "line-thin", "block-outline", "underline-thin"], _cursorStyleFromString, { description: localize("cursorStyle", "Controls the cursor style.") })),
  cursorSurroundingLines: register$1(new EditorIntOption(28, "cursorSurroundingLines", 0, 0, 1073741824, { description: localize("cursorSurroundingLines", "Controls the minimal number of visible leading lines (minimum 0) and trailing lines (minimum 1) surrounding the cursor. Known as 'scrollOff' or 'scrollOffset' in some other editors.") })),
  cursorSurroundingLinesStyle: register$1(new EditorStringEnumOption(29, "cursorSurroundingLinesStyle", "default", ["default", "all"], {
    enumDescriptions: [
      localize("cursorSurroundingLinesStyle.default", "`cursorSurroundingLines` is enforced only when triggered via the keyboard or API."),
      localize("cursorSurroundingLinesStyle.all", "`cursorSurroundingLines` is enforced always.")
    ],
    description: localize("cursorSurroundingLinesStyle", "Controls when `cursorSurroundingLines` should be enforced.")
  })),
  cursorWidth: register$1(new EditorIntOption(30, "cursorWidth", 0, 0, 1073741824, { markdownDescription: localize("cursorWidth", "Controls the width of the cursor when `#editor.cursorStyle#` is set to `line`.") })),
  disableLayerHinting: register$1(new EditorBooleanOption(31, "disableLayerHinting", false)),
  disableMonospaceOptimizations: register$1(new EditorBooleanOption(32, "disableMonospaceOptimizations", false)),
  domReadOnly: register$1(new EditorBooleanOption(33, "domReadOnly", false)),
  dragAndDrop: register$1(new EditorBooleanOption(34, "dragAndDrop", true, { description: localize("dragAndDrop", "Controls whether the editor should allow moving selections via drag and drop.") })),
  emptySelectionClipboard: register$1(new EditorEmptySelectionClipboard()),
  dropIntoEditor: register$1(new EditorDropIntoEditor()),
  stickyScroll: register$1(new EditorStickyScroll()),
  experimentalWhitespaceRendering: register$1(new EditorStringEnumOption(37, "experimentalWhitespaceRendering", "svg", ["svg", "font", "off"], {
    enumDescriptions: [
      localize("experimentalWhitespaceRendering.svg", "Use a new rendering method with svgs."),
      localize("experimentalWhitespaceRendering.font", "Use a new rendering method with font characters."),
      localize("experimentalWhitespaceRendering.off", "Use the stable rendering method.")
    ],
    description: localize("experimentalWhitespaceRendering", "Controls whether whitespace is rendered with a new, experimental method.")
  })),
  extraEditorClassName: register$1(new EditorStringOption(38, "extraEditorClassName", "")),
  fastScrollSensitivity: register$1(new EditorFloatOption(39, "fastScrollSensitivity", 5, (x) => x <= 0 ? 5 : x, { markdownDescription: localize("fastScrollSensitivity", "Scrolling speed multiplier when pressing `Alt`.") })),
  find: register$1(new EditorFind()),
  fixedOverflowWidgets: register$1(new EditorBooleanOption(41, "fixedOverflowWidgets", false)),
  folding: register$1(new EditorBooleanOption(42, "folding", true, { description: localize("folding", "Controls whether the editor has code folding enabled.") })),
  foldingStrategy: register$1(new EditorStringEnumOption(43, "foldingStrategy", "auto", ["auto", "indentation"], {
    enumDescriptions: [
      localize("foldingStrategy.auto", "Use a language-specific folding strategy if available, else the indentation-based one."),
      localize("foldingStrategy.indentation", "Use the indentation-based folding strategy.")
    ],
    description: localize("foldingStrategy", "Controls the strategy for computing folding ranges.")
  })),
  foldingHighlight: register$1(new EditorBooleanOption(44, "foldingHighlight", true, { description: localize("foldingHighlight", "Controls whether the editor should highlight folded ranges.") })),
  foldingImportsByDefault: register$1(new EditorBooleanOption(45, "foldingImportsByDefault", false, { description: localize("foldingImportsByDefault", "Controls whether the editor automatically collapses import ranges.") })),
  foldingMaximumRegions: register$1(new EditorIntOption(
    46,
    "foldingMaximumRegions",
    5e3,
    10,
    65e3,
    // limit must be less than foldingRanges MAX_FOLDING_REGIONS
    { description: localize("foldingMaximumRegions", "The maximum number of foldable regions. Increasing this value may result in the editor becoming less responsive when the current source has a large number of foldable regions.") }
  )),
  unfoldOnClickAfterEndOfLine: register$1(new EditorBooleanOption(47, "unfoldOnClickAfterEndOfLine", false, { description: localize("unfoldOnClickAfterEndOfLine", "Controls whether clicking on the empty content after a folded line will unfold the line.") })),
  fontFamily: register$1(new EditorStringOption(48, "fontFamily", EDITOR_FONT_DEFAULTS.fontFamily, { description: localize("fontFamily", "Controls the font family.") })),
  fontInfo: register$1(new EditorFontInfo()),
  fontLigatures2: register$1(new EditorFontLigatures()),
  fontSize: register$1(new EditorFontSize()),
  fontWeight: register$1(new EditorFontWeight()),
  fontVariations: register$1(new EditorFontVariations()),
  formatOnPaste: register$1(new EditorBooleanOption(54, "formatOnPaste", false, { description: localize("formatOnPaste", "Controls whether the editor should automatically format the pasted content. A formatter must be available and the formatter should be able to format a range in a document.") })),
  formatOnType: register$1(new EditorBooleanOption(55, "formatOnType", false, { description: localize("formatOnType", "Controls whether the editor should automatically format the line after typing.") })),
  glyphMargin: register$1(new EditorBooleanOption(56, "glyphMargin", true, { description: localize("glyphMargin", "Controls whether the editor should render the vertical glyph margin. Glyph margin is mostly used for debugging.") })),
  gotoLocation: register$1(new EditorGoToLocation()),
  hideCursorInOverviewRuler: register$1(new EditorBooleanOption(58, "hideCursorInOverviewRuler", false, { description: localize("hideCursorInOverviewRuler", "Controls whether the cursor should be hidden in the overview ruler.") })),
  hover: register$1(new EditorHover()),
  inDiffEditor: register$1(new EditorBooleanOption(60, "inDiffEditor", false)),
  letterSpacing: register$1(new EditorFloatOption(62, "letterSpacing", EDITOR_FONT_DEFAULTS.letterSpacing, (x) => EditorFloatOption.clamp(x, -5, 20), { description: localize("letterSpacing", "Controls the letter spacing in pixels.") })),
  lightbulb: register$1(new EditorLightbulb()),
  lineDecorationsWidth: register$1(new EditorLineDecorationsWidth()),
  lineHeight: register$1(new EditorLineHeight()),
  lineNumbers: register$1(new EditorRenderLineNumbersOption()),
  lineNumbersMinChars: register$1(new EditorIntOption(67, "lineNumbersMinChars", 5, 1, 300)),
  linkedEditing: register$1(new EditorBooleanOption(68, "linkedEditing", false, { description: localize("linkedEditing", "Controls whether the editor has linked editing enabled. Depending on the language, related symbols such as HTML tags, are updated while editing.") })),
  links: register$1(new EditorBooleanOption(69, "links", true, { description: localize("links", "Controls whether the editor should detect links and make them clickable.") })),
  matchBrackets: register$1(new EditorStringEnumOption(70, "matchBrackets", "always", ["always", "near", "never"], { description: localize("matchBrackets", "Highlight matching brackets.") })),
  minimap: register$1(new EditorMinimap()),
  mouseStyle: register$1(new EditorStringEnumOption(72, "mouseStyle", "text", ["text", "default", "copy"])),
  mouseWheelScrollSensitivity: register$1(new EditorFloatOption(73, "mouseWheelScrollSensitivity", 1, (x) => x === 0 ? 1 : x, { markdownDescription: localize("mouseWheelScrollSensitivity", "A multiplier to be used on the `deltaX` and `deltaY` of mouse wheel scroll events.") })),
  mouseWheelZoom: register$1(new EditorBooleanOption(74, "mouseWheelZoom", false, { markdownDescription: localize("mouseWheelZoom", "Zoom the font of the editor when using mouse wheel and holding `Ctrl`.") })),
  multiCursorMergeOverlapping: register$1(new EditorBooleanOption(75, "multiCursorMergeOverlapping", true, { description: localize("multiCursorMergeOverlapping", "Merge multiple cursors when they are overlapping.") })),
  multiCursorModifier: register$1(new EditorEnumOption(76, "multiCursorModifier", "altKey", "alt", ["ctrlCmd", "alt"], _multiCursorModifierFromString, {
    markdownEnumDescriptions: [
      localize("multiCursorModifier.ctrlCmd", "Maps to `Control` on Windows and Linux and to `Command` on macOS."),
      localize("multiCursorModifier.alt", "Maps to `Alt` on Windows and Linux and to `Option` on macOS.")
    ],
    markdownDescription: localize({
      key: "multiCursorModifier",
      comment: [
        "- `ctrlCmd` refers to a value the setting can take and should not be localized.",
        "- `Control` and `Command` refer to the modifier keys Ctrl or Cmd on the keyboard and can be localized."
      ]
    }, "The modifier to be used to add multiple cursors with the mouse. The Go to Definition and Open Link mouse gestures will adapt such that they do not conflict with the [multicursor modifier](https://code.visualstudio.com/docs/editor/codebasics#_multicursor-modifier).")
  })),
  multiCursorPaste: register$1(new EditorStringEnumOption(77, "multiCursorPaste", "spread", ["spread", "full"], {
    markdownEnumDescriptions: [
      localize("multiCursorPaste.spread", "Each cursor pastes a single line of the text."),
      localize("multiCursorPaste.full", "Each cursor pastes the full text.")
    ],
    markdownDescription: localize("multiCursorPaste", "Controls pasting when the line count of the pasted text matches the cursor count.")
  })),
  multiCursorLimit: register$1(new EditorIntOption(78, "multiCursorLimit", 1e4, 1, 1e5, {
    markdownDescription: localize("multiCursorLimit", "Controls the max number of cursors that can be in an active editor at once.")
  })),
  occurrencesHighlight: register$1(new EditorBooleanOption(79, "occurrencesHighlight", true, { description: localize("occurrencesHighlight", "Controls whether the editor should highlight semantic symbol occurrences.") })),
  overviewRulerBorder: register$1(new EditorBooleanOption(80, "overviewRulerBorder", true, { description: localize("overviewRulerBorder", "Controls whether a border should be drawn around the overview ruler.") })),
  overviewRulerLanes: register$1(new EditorIntOption(81, "overviewRulerLanes", 3, 0, 3)),
  padding: register$1(new EditorPadding()),
  pasteAs: register$1(new EditorPasteAs()),
  parameterHints: register$1(new EditorParameterHints()),
  peekWidgetDefaultFocus: register$1(new EditorStringEnumOption(85, "peekWidgetDefaultFocus", "tree", ["tree", "editor"], {
    enumDescriptions: [
      localize("peekWidgetDefaultFocus.tree", "Focus the tree when opening peek"),
      localize("peekWidgetDefaultFocus.editor", "Focus the editor when opening peek")
    ],
    description: localize("peekWidgetDefaultFocus", "Controls whether to focus the inline editor or the tree in the peek widget.")
  })),
  definitionLinkOpensInPeek: register$1(new EditorBooleanOption(86, "definitionLinkOpensInPeek", false, { description: localize("definitionLinkOpensInPeek", "Controls whether the Go to Definition mouse gesture always opens the peek widget.") })),
  quickSuggestions: register$1(new EditorQuickSuggestions()),
  quickSuggestionsDelay: register$1(new EditorIntOption(88, "quickSuggestionsDelay", 10, 0, 1073741824, { description: localize("quickSuggestionsDelay", "Controls the delay in milliseconds after which quick suggestions will show up.") })),
  readOnly: register$1(new EditorBooleanOption(89, "readOnly", false)),
  readOnlyMessage: register$1(new ReadonlyMessage()),
  renameOnType: register$1(new EditorBooleanOption(91, "renameOnType", false, { description: localize("renameOnType", "Controls whether the editor auto renames on type."), markdownDeprecationMessage: localize("renameOnTypeDeprecate", "Deprecated, use `editor.linkedEditing` instead.") })),
  renderControlCharacters: register$1(new EditorBooleanOption(92, "renderControlCharacters", true, { description: localize("renderControlCharacters", "Controls whether the editor should render control characters."), restricted: true })),
  renderFinalNewline: register$1(new EditorStringEnumOption(93, "renderFinalNewline", isLinux ? "dimmed" : "on", ["off", "on", "dimmed"], { description: localize("renderFinalNewline", "Render last line number when the file ends with a newline.") })),
  renderLineHighlight: register$1(new EditorStringEnumOption(94, "renderLineHighlight", "line", ["none", "gutter", "line", "all"], {
    enumDescriptions: [
      "",
      "",
      "",
      localize("renderLineHighlight.all", "Highlights both the gutter and the current line.")
    ],
    description: localize("renderLineHighlight", "Controls how the editor should render the current line highlight.")
  })),
  renderLineHighlightOnlyWhenFocus: register$1(new EditorBooleanOption(95, "renderLineHighlightOnlyWhenFocus", false, { description: localize("renderLineHighlightOnlyWhenFocus", "Controls if the editor should render the current line highlight only when the editor is focused.") })),
  renderValidationDecorations: register$1(new EditorStringEnumOption(96, "renderValidationDecorations", "editable", ["editable", "on", "off"])),
  renderWhitespace: register$1(new EditorStringEnumOption(97, "renderWhitespace", "selection", ["none", "boundary", "selection", "trailing", "all"], {
    enumDescriptions: [
      "",
      localize("renderWhitespace.boundary", "Render whitespace characters except for single spaces between words."),
      localize("renderWhitespace.selection", "Render whitespace characters only on selected text."),
      localize("renderWhitespace.trailing", "Render only trailing whitespace characters."),
      ""
    ],
    description: localize("renderWhitespace", "Controls how the editor should render whitespace characters.")
  })),
  revealHorizontalRightPadding: register$1(new EditorIntOption(98, "revealHorizontalRightPadding", 15, 0, 1e3)),
  roundedSelection: register$1(new EditorBooleanOption(99, "roundedSelection", true, { description: localize("roundedSelection", "Controls whether selections should have rounded corners.") })),
  rulers: register$1(new EditorRulers()),
  scrollbar: register$1(new EditorScrollbar$1()),
  scrollBeyondLastColumn: register$1(new EditorIntOption(102, "scrollBeyondLastColumn", 4, 0, 1073741824, { description: localize("scrollBeyondLastColumn", "Controls the number of extra characters beyond which the editor will scroll horizontally.") })),
  scrollBeyondLastLine: register$1(new EditorBooleanOption(103, "scrollBeyondLastLine", true, { description: localize("scrollBeyondLastLine", "Controls whether the editor will scroll beyond the last line.") })),
  scrollPredominantAxis: register$1(new EditorBooleanOption(104, "scrollPredominantAxis", true, { description: localize("scrollPredominantAxis", "Scroll only along the predominant axis when scrolling both vertically and horizontally at the same time. Prevents horizontal drift when scrolling vertically on a trackpad.") })),
  selectionClipboard: register$1(new EditorBooleanOption(105, "selectionClipboard", true, {
    description: localize("selectionClipboard", "Controls whether the Linux primary clipboard should be supported."),
    included: isLinux
  })),
  selectionHighlight: register$1(new EditorBooleanOption(106, "selectionHighlight", true, { description: localize("selectionHighlight", "Controls whether the editor should highlight matches similar to the selection.") })),
  selectOnLineNumbers: register$1(new EditorBooleanOption(107, "selectOnLineNumbers", true)),
  showFoldingControls: register$1(new EditorStringEnumOption(108, "showFoldingControls", "mouseover", ["always", "never", "mouseover"], {
    enumDescriptions: [
      localize("showFoldingControls.always", "Always show the folding controls."),
      localize("showFoldingControls.never", "Never show the folding controls and reduce the gutter size."),
      localize("showFoldingControls.mouseover", "Only show the folding controls when the mouse is over the gutter.")
    ],
    description: localize("showFoldingControls", "Controls when the folding controls on the gutter are shown.")
  })),
  showUnused: register$1(new EditorBooleanOption(109, "showUnused", true, { description: localize("showUnused", "Controls fading out of unused code.") })),
  showDeprecated: register$1(new EditorBooleanOption(137, "showDeprecated", true, { description: localize("showDeprecated", "Controls strikethrough deprecated variables.") })),
  inlayHints: register$1(new EditorInlayHints()),
  snippetSuggestions: register$1(new EditorStringEnumOption(110, "snippetSuggestions", "inline", ["top", "bottom", "inline", "none"], {
    enumDescriptions: [
      localize("snippetSuggestions.top", "Show snippet suggestions on top of other suggestions."),
      localize("snippetSuggestions.bottom", "Show snippet suggestions below other suggestions."),
      localize("snippetSuggestions.inline", "Show snippets suggestions with other suggestions."),
      localize("snippetSuggestions.none", "Do not show snippet suggestions.")
    ],
    description: localize("snippetSuggestions", "Controls whether snippets are shown with other suggestions and how they are sorted.")
  })),
  smartSelect: register$1(new SmartSelect()),
  smoothScrolling: register$1(new EditorBooleanOption(112, "smoothScrolling", false, { description: localize("smoothScrolling", "Controls whether the editor will scroll using an animation.") })),
  stopRenderingLineAfter: register$1(new EditorIntOption(
    115,
    "stopRenderingLineAfter",
    1e4,
    -1,
    1073741824
    /* Constants.MAX_SAFE_SMALL_INTEGER */
  )),
  suggest: register$1(new EditorSuggest()),
  inlineSuggest: register$1(new InlineEditorSuggest()),
  suggestFontSize: register$1(new EditorIntOption(117, "suggestFontSize", 0, 0, 1e3, { markdownDescription: localize("suggestFontSize", "Font size for the suggest widget. When set to {0}, the value of {1} is used.", "`0`", "`#editor.fontSize#`") })),
  suggestLineHeight: register$1(new EditorIntOption(118, "suggestLineHeight", 0, 0, 1e3, { markdownDescription: localize("suggestLineHeight", "Line height for the suggest widget. When set to {0}, the value of {1} is used. The minimum value is 8.", "`0`", "`#editor.lineHeight#`") })),
  suggestOnTriggerCharacters: register$1(new EditorBooleanOption(119, "suggestOnTriggerCharacters", true, { description: localize("suggestOnTriggerCharacters", "Controls whether suggestions should automatically show up when typing trigger characters.") })),
  suggestSelection: register$1(new EditorStringEnumOption(120, "suggestSelection", "first", ["first", "recentlyUsed", "recentlyUsedByPrefix"], {
    markdownEnumDescriptions: [
      localize("suggestSelection.first", "Always select the first suggestion."),
      localize("suggestSelection.recentlyUsed", "Select recent suggestions unless further typing selects one, e.g. `console.| -> console.log` because `log` has been completed recently."),
      localize("suggestSelection.recentlyUsedByPrefix", "Select suggestions based on previous prefixes that have completed those suggestions, e.g. `co -> console` and `con -> const`.")
    ],
    description: localize("suggestSelection", "Controls how suggestions are pre-selected when showing the suggest list.")
  })),
  tabCompletion: register$1(new EditorStringEnumOption(121, "tabCompletion", "off", ["on", "off", "onlySnippets"], {
    enumDescriptions: [
      localize("tabCompletion.on", "Tab complete will insert the best matching suggestion when pressing tab."),
      localize("tabCompletion.off", "Disable tab completions."),
      localize("tabCompletion.onlySnippets", "Tab complete snippets when their prefix match. Works best when 'quickSuggestions' aren't enabled.")
    ],
    description: localize("tabCompletion", "Enables tab completions.")
  })),
  tabIndex: register$1(new EditorIntOption(
    122,
    "tabIndex",
    0,
    -1,
    1073741824
    /* Constants.MAX_SAFE_SMALL_INTEGER */
  )),
  unicodeHighlight: register$1(new UnicodeHighlight()),
  unusualLineTerminators: register$1(new EditorStringEnumOption(124, "unusualLineTerminators", "prompt", ["auto", "off", "prompt"], {
    enumDescriptions: [
      localize("unusualLineTerminators.auto", "Unusual line terminators are automatically removed."),
      localize("unusualLineTerminators.off", "Unusual line terminators are ignored."),
      localize("unusualLineTerminators.prompt", "Unusual line terminators prompt to be removed.")
    ],
    description: localize("unusualLineTerminators", "Remove unusual line terminators that might cause problems.")
  })),
  useShadowDOM: register$1(new EditorBooleanOption(125, "useShadowDOM", true)),
  useTabStops: register$1(new EditorBooleanOption(126, "useTabStops", true, { description: localize("useTabStops", "Inserting and deleting whitespace follows tab stops.") })),
  wordBreak: register$1(new EditorStringEnumOption(127, "wordBreak", "normal", ["normal", "keepAll"], {
    markdownEnumDescriptions: [
      localize("wordBreak.normal", "Use the default line break rule."),
      localize("wordBreak.keepAll", "Word breaks should not be used for Chinese/Japanese/Korean (CJK) text. Non-CJK text behavior is the same as for normal.")
    ],
    description: localize("wordBreak", "Controls the word break rules used for Chinese/Japanese/Korean (CJK) text.")
  })),
  wordSeparators: register$1(new EditorStringOption(128, "wordSeparators", USUAL_WORD_SEPARATORS, { description: localize("wordSeparators", "Characters that will be used as word separators when doing word related navigations or operations.") })),
  wordWrap: register$1(new EditorStringEnumOption(129, "wordWrap", "off", ["off", "on", "wordWrapColumn", "bounded"], {
    markdownEnumDescriptions: [
      localize("wordWrap.off", "Lines will never wrap."),
      localize("wordWrap.on", "Lines will wrap at the viewport width."),
      localize({
        key: "wordWrap.wordWrapColumn",
        comment: [
          "- `editor.wordWrapColumn` refers to a different setting and should not be localized."
        ]
      }, "Lines will wrap at `#editor.wordWrapColumn#`."),
      localize({
        key: "wordWrap.bounded",
        comment: [
          "- viewport means the edge of the visible window size.",
          "- `editor.wordWrapColumn` refers to a different setting and should not be localized."
        ]
      }, "Lines will wrap at the minimum of viewport and `#editor.wordWrapColumn#`.")
    ],
    description: localize({
      key: "wordWrap",
      comment: [
        "- 'off', 'on', 'wordWrapColumn' and 'bounded' refer to values the setting can take and should not be localized.",
        "- `editor.wordWrapColumn` refers to a different setting and should not be localized."
      ]
    }, "Controls how lines should wrap.")
  })),
  wordWrapBreakAfterCharacters: register$1(new EditorStringOption(
    130,
    "wordWrapBreakAfterCharacters",
    // allow-any-unicode-next-line
    " 	})]?|/&.,;¢°′″‰℃、。｡､￠，．：；？！％・･ゝゞヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻ｧｨｩｪｫｬｭｮｯｰ”〉》」』】〕）］｝｣"
  )),
  wordWrapBreakBeforeCharacters: register$1(new EditorStringOption(
    131,
    "wordWrapBreakBeforeCharacters",
    // allow-any-unicode-next-line
    "([{‘“〈《「『【〔（［｛｢£¥＄￡￥+＋"
  )),
  wordWrapColumn: register$1(new EditorIntOption(132, "wordWrapColumn", 80, 1, 1073741824, {
    markdownDescription: localize({
      key: "wordWrapColumn",
      comment: [
        "- `editor.wordWrap` refers to a different setting and should not be localized.",
        "- 'wordWrapColumn' and 'bounded' refer to values the different setting can take and should not be localized."
      ]
    }, "Controls the wrapping column of the editor when `#editor.wordWrap#` is `wordWrapColumn` or `bounded`.")
  })),
  wordWrapOverride1: register$1(new EditorStringEnumOption(133, "wordWrapOverride1", "inherit", ["off", "on", "inherit"])),
  wordWrapOverride2: register$1(new EditorStringEnumOption(134, "wordWrapOverride2", "inherit", ["off", "on", "inherit"])),
  // Leave these at the end (because they have dependencies!)
  editorClassName: register$1(new EditorClassName()),
  defaultColorDecorators: register$1(new EditorBooleanOption(144, "defaultColorDecorators", false, { markdownDescription: localize("defaultColorDecorators", "Controls whether inline color decorations should be shown using the default document color provider") })),
  pixelRatio: register$1(new EditorPixelRatio()),
  tabFocusMode: register$1(new EditorBooleanOption(141, "tabFocusMode", false, { markdownDescription: localize("tabFocusMode", "Controls whether the editor receives tabs or defers them to the workbench for navigation.") })),
  layoutInfo: register$1(new EditorLayoutInfoComputer()),
  wrappingInfo: register$1(new EditorWrappingInfoComputer()),
  wrappingIndent: register$1(new WrappingIndentOption()),
  wrappingStrategy: register$1(new WrappingStrategy())
};
const EditorZoom = new class {
  constructor() {
    this._zoomLevel = 0;
    this._onDidChangeZoomLevel = new Emitter$1();
    this.onDidChangeZoomLevel = this._onDidChangeZoomLevel.event;
  }
  getZoomLevel() {
    return this._zoomLevel;
  }
  setZoomLevel(zoomLevel) {
    zoomLevel = Math.min(Math.max(-5, zoomLevel), 20);
    if (this._zoomLevel === zoomLevel) {
      return;
    }
    this._zoomLevel = zoomLevel;
    this._onDidChangeZoomLevel.fire(this._zoomLevel);
  }
}();
const GOLDEN_LINE_HEIGHT_RATIO = isMacintosh ? 1.5 : 1.35;
const MINIMUM_LINE_HEIGHT = 8;
class BareFontInfo {
  /**
   * @internal
   */
  static createFromValidatedSettings(options, pixelRatio, ignoreEditorZoom) {
    const fontFamily = options.get(
      48
      /* EditorOption.fontFamily */
    );
    const fontWeight = options.get(
      52
      /* EditorOption.fontWeight */
    );
    const fontSize = options.get(
      51
      /* EditorOption.fontSize */
    );
    const fontFeatureSettings = options.get(
      50
      /* EditorOption.fontLigatures */
    );
    const fontVariationSettings = options.get(
      53
      /* EditorOption.fontVariations */
    );
    const lineHeight = options.get(
      65
      /* EditorOption.lineHeight */
    );
    const letterSpacing = options.get(
      62
      /* EditorOption.letterSpacing */
    );
    return BareFontInfo._create(fontFamily, fontWeight, fontSize, fontFeatureSettings, fontVariationSettings, lineHeight, letterSpacing, pixelRatio, ignoreEditorZoom);
  }
  /**
   * @internal
   */
  static _create(fontFamily, fontWeight, fontSize, fontFeatureSettings, fontVariationSettings, lineHeight, letterSpacing, pixelRatio, ignoreEditorZoom) {
    if (lineHeight === 0) {
      lineHeight = GOLDEN_LINE_HEIGHT_RATIO * fontSize;
    } else if (lineHeight < MINIMUM_LINE_HEIGHT) {
      lineHeight = lineHeight * fontSize;
    }
    lineHeight = Math.round(lineHeight);
    if (lineHeight < MINIMUM_LINE_HEIGHT) {
      lineHeight = MINIMUM_LINE_HEIGHT;
    }
    const editorZoomLevelMultiplier = 1 + (ignoreEditorZoom ? 0 : EditorZoom.getZoomLevel() * 0.1);
    fontSize *= editorZoomLevelMultiplier;
    lineHeight *= editorZoomLevelMultiplier;
    if (fontVariationSettings === EditorFontVariations.TRANSLATE) {
      if (fontWeight === "normal" || fontWeight === "bold") {
        fontVariationSettings = EditorFontVariations.OFF;
      } else {
        const fontWeightAsNumber = parseInt(fontWeight, 10);
        fontVariationSettings = `'wght' ${fontWeightAsNumber}`;
        fontWeight = "normal";
      }
    }
    return new BareFontInfo({
      pixelRatio,
      fontFamily,
      fontWeight,
      fontSize,
      fontFeatureSettings,
      fontVariationSettings,
      lineHeight,
      letterSpacing
    });
  }
  /**
   * @internal
   */
  constructor(opts) {
    this._bareFontInfoBrand = void 0;
    this.pixelRatio = opts.pixelRatio;
    this.fontFamily = String(opts.fontFamily);
    this.fontWeight = String(opts.fontWeight);
    this.fontSize = opts.fontSize;
    this.fontFeatureSettings = opts.fontFeatureSettings;
    this.fontVariationSettings = opts.fontVariationSettings;
    this.lineHeight = opts.lineHeight | 0;
    this.letterSpacing = opts.letterSpacing;
  }
  /**
   * @internal
   */
  getId() {
    return `${this.pixelRatio}-${this.fontFamily}-${this.fontWeight}-${this.fontSize}-${this.fontFeatureSettings}-${this.fontVariationSettings}-${this.lineHeight}-${this.letterSpacing}`;
  }
  /**
   * @internal
   */
  getMassagedFontFamily() {
    const fallbackFontFamily = EDITOR_FONT_DEFAULTS.fontFamily;
    const fontFamily = BareFontInfo._wrapInQuotes(this.fontFamily);
    if (fallbackFontFamily && this.fontFamily !== fallbackFontFamily) {
      return `${fontFamily}, ${fallbackFontFamily}`;
    }
    return fontFamily;
  }
  static _wrapInQuotes(fontFamily) {
    if (/[,"']/.test(fontFamily)) {
      return fontFamily;
    }
    if (/[+ ]/.test(fontFamily)) {
      return `"${fontFamily}"`;
    }
    return fontFamily;
  }
}
const SERIALIZED_FONT_INFO_VERSION = 2;
class FontInfo extends BareFontInfo {
  /**
   * @internal
   */
  constructor(opts, isTrusted) {
    super(opts);
    this._editorStylingBrand = void 0;
    this.version = SERIALIZED_FONT_INFO_VERSION;
    this.isTrusted = isTrusted;
    this.isMonospace = opts.isMonospace;
    this.typicalHalfwidthCharacterWidth = opts.typicalHalfwidthCharacterWidth;
    this.typicalFullwidthCharacterWidth = opts.typicalFullwidthCharacterWidth;
    this.canUseHalfwidthRightwardsArrow = opts.canUseHalfwidthRightwardsArrow;
    this.spaceWidth = opts.spaceWidth;
    this.middotWidth = opts.middotWidth;
    this.wsmiddotWidth = opts.wsmiddotWidth;
    this.maxDigitWidth = opts.maxDigitWidth;
  }
  /**
   * @internal
   */
  equals(other) {
    return this.fontFamily === other.fontFamily && this.fontWeight === other.fontWeight && this.fontSize === other.fontSize && this.fontFeatureSettings === other.fontFeatureSettings && this.fontVariationSettings === other.fontVariationSettings && this.lineHeight === other.lineHeight && this.letterSpacing === other.letterSpacing && this.typicalHalfwidthCharacterWidth === other.typicalHalfwidthCharacterWidth && this.typicalFullwidthCharacterWidth === other.typicalFullwidthCharacterWidth && this.canUseHalfwidthRightwardsArrow === other.canUseHalfwidthRightwardsArrow && this.spaceWidth === other.spaceWidth && this.middotWidth === other.middotWidth && this.wsmiddotWidth === other.wsmiddotWidth && this.maxDigitWidth === other.maxDigitWidth;
  }
}
class FontMeasurementsImpl extends Disposable {
  constructor() {
    super();
    this._onDidChange = this._register(new Emitter$1());
    this.onDidChange = this._onDidChange.event;
    this._cache = new FontMeasurementsCache();
    this._evictUntrustedReadingsTimeout = -1;
  }
  dispose() {
    if (this._evictUntrustedReadingsTimeout !== -1) {
      window.clearTimeout(this._evictUntrustedReadingsTimeout);
      this._evictUntrustedReadingsTimeout = -1;
    }
    super.dispose();
  }
  /**
   * Clear all cached font information and trigger a change event.
   */
  clearAllFontInfos() {
    this._cache = new FontMeasurementsCache();
    this._onDidChange.fire();
  }
  _writeToCache(item, value) {
    this._cache.put(item, value);
    if (!value.isTrusted && this._evictUntrustedReadingsTimeout === -1) {
      this._evictUntrustedReadingsTimeout = window.setTimeout(() => {
        this._evictUntrustedReadingsTimeout = -1;
        this._evictUntrustedReadings();
      }, 5e3);
    }
  }
  _evictUntrustedReadings() {
    const values = this._cache.getValues();
    let somethingRemoved = false;
    for (const item of values) {
      if (!item.isTrusted) {
        somethingRemoved = true;
        this._cache.remove(item);
      }
    }
    if (somethingRemoved) {
      this._onDidChange.fire();
    }
  }
  /**
   * Read font information.
   */
  readFontInfo(bareFontInfo) {
    if (!this._cache.has(bareFontInfo)) {
      let readConfig = this._actualReadFontInfo(bareFontInfo);
      if (readConfig.typicalHalfwidthCharacterWidth <= 2 || readConfig.typicalFullwidthCharacterWidth <= 2 || readConfig.spaceWidth <= 2 || readConfig.maxDigitWidth <= 2) {
        readConfig = new FontInfo({
          pixelRatio: PixelRatio.value,
          fontFamily: readConfig.fontFamily,
          fontWeight: readConfig.fontWeight,
          fontSize: readConfig.fontSize,
          fontFeatureSettings: readConfig.fontFeatureSettings,
          fontVariationSettings: readConfig.fontVariationSettings,
          lineHeight: readConfig.lineHeight,
          letterSpacing: readConfig.letterSpacing,
          isMonospace: readConfig.isMonospace,
          typicalHalfwidthCharacterWidth: Math.max(readConfig.typicalHalfwidthCharacterWidth, 5),
          typicalFullwidthCharacterWidth: Math.max(readConfig.typicalFullwidthCharacterWidth, 5),
          canUseHalfwidthRightwardsArrow: readConfig.canUseHalfwidthRightwardsArrow,
          spaceWidth: Math.max(readConfig.spaceWidth, 5),
          middotWidth: Math.max(readConfig.middotWidth, 5),
          wsmiddotWidth: Math.max(readConfig.wsmiddotWidth, 5),
          maxDigitWidth: Math.max(readConfig.maxDigitWidth, 5)
        }, false);
      }
      this._writeToCache(bareFontInfo, readConfig);
    }
    return this._cache.get(bareFontInfo);
  }
  _createRequest(chr, type, all, monospace) {
    const result2 = new CharWidthRequest(chr, type);
    all.push(result2);
    monospace === null || monospace === void 0 ? void 0 : monospace.push(result2);
    return result2;
  }
  _actualReadFontInfo(bareFontInfo) {
    const all = [];
    const monospace = [];
    const typicalHalfwidthCharacter = this._createRequest("n", 0, all, monospace);
    const typicalFullwidthCharacter = this._createRequest("ｍ", 0, all, null);
    const space2 = this._createRequest(" ", 0, all, monospace);
    const digit0 = this._createRequest("0", 0, all, monospace);
    const digit1 = this._createRequest("1", 0, all, monospace);
    const digit2 = this._createRequest("2", 0, all, monospace);
    const digit3 = this._createRequest("3", 0, all, monospace);
    const digit4 = this._createRequest("4", 0, all, monospace);
    const digit5 = this._createRequest("5", 0, all, monospace);
    const digit6 = this._createRequest("6", 0, all, monospace);
    const digit7 = this._createRequest("7", 0, all, monospace);
    const digit8 = this._createRequest("8", 0, all, monospace);
    const digit9 = this._createRequest("9", 0, all, monospace);
    const rightwardsArrow = this._createRequest("→", 0, all, monospace);
    const halfwidthRightwardsArrow = this._createRequest("￫", 0, all, null);
    const middot = this._createRequest("·", 0, all, monospace);
    const wsmiddotWidth = this._createRequest(String.fromCharCode(11825), 0, all, null);
    const monospaceTestChars = "|/-_ilm%";
    for (let i = 0, len = monospaceTestChars.length; i < len; i++) {
      this._createRequest(monospaceTestChars.charAt(i), 0, all, monospace);
      this._createRequest(monospaceTestChars.charAt(i), 1, all, monospace);
      this._createRequest(monospaceTestChars.charAt(i), 2, all, monospace);
    }
    readCharWidths(bareFontInfo, all);
    const maxDigitWidth = Math.max(digit0.width, digit1.width, digit2.width, digit3.width, digit4.width, digit5.width, digit6.width, digit7.width, digit8.width, digit9.width);
    let isMonospace = bareFontInfo.fontFeatureSettings === EditorFontLigatures.OFF;
    const referenceWidth = monospace[0].width;
    for (let i = 1, len = monospace.length; isMonospace && i < len; i++) {
      const diff = referenceWidth - monospace[i].width;
      if (diff < -1e-3 || diff > 1e-3) {
        isMonospace = false;
        break;
      }
    }
    let canUseHalfwidthRightwardsArrow = true;
    if (isMonospace && halfwidthRightwardsArrow.width !== referenceWidth) {
      canUseHalfwidthRightwardsArrow = false;
    }
    if (halfwidthRightwardsArrow.width > rightwardsArrow.width) {
      canUseHalfwidthRightwardsArrow = false;
    }
    return new FontInfo({
      pixelRatio: PixelRatio.value,
      fontFamily: bareFontInfo.fontFamily,
      fontWeight: bareFontInfo.fontWeight,
      fontSize: bareFontInfo.fontSize,
      fontFeatureSettings: bareFontInfo.fontFeatureSettings,
      fontVariationSettings: bareFontInfo.fontVariationSettings,
      lineHeight: bareFontInfo.lineHeight,
      letterSpacing: bareFontInfo.letterSpacing,
      isMonospace,
      typicalHalfwidthCharacterWidth: typicalHalfwidthCharacter.width,
      typicalFullwidthCharacterWidth: typicalFullwidthCharacter.width,
      canUseHalfwidthRightwardsArrow,
      spaceWidth: space2.width,
      middotWidth: middot.width,
      wsmiddotWidth: wsmiddotWidth.width,
      maxDigitWidth
    }, true);
  }
}
class FontMeasurementsCache {
  constructor() {
    this._keys = /* @__PURE__ */ Object.create(null);
    this._values = /* @__PURE__ */ Object.create(null);
  }
  has(item) {
    const itemId = item.getId();
    return !!this._values[itemId];
  }
  get(item) {
    const itemId = item.getId();
    return this._values[itemId];
  }
  put(item, value) {
    const itemId = item.getId();
    this._keys[itemId] = item;
    this._values[itemId] = value;
  }
  remove(item) {
    const itemId = item.getId();
    delete this._keys[itemId];
    delete this._values[itemId];
  }
  getValues() {
    return Object.keys(this._keys).map((id3) => this._values[id3]);
  }
}
const FontMeasurements = new FontMeasurementsImpl();
class EditorSettingMigration {
  constructor(key, migrate) {
    this.key = key;
    this.migrate = migrate;
  }
  apply(options) {
    const value = EditorSettingMigration._read(options, this.key);
    const read2 = (key) => EditorSettingMigration._read(options, key);
    const write3 = (key, value2) => EditorSettingMigration._write(options, key, value2);
    this.migrate(value, read2, write3);
  }
  static _read(source, key) {
    if (typeof source === "undefined") {
      return void 0;
    }
    const firstDotIndex = key.indexOf(".");
    if (firstDotIndex >= 0) {
      const firstSegment = key.substring(0, firstDotIndex);
      return this._read(source[firstSegment], key.substring(firstDotIndex + 1));
    }
    return source[key];
  }
  static _write(target, key, value) {
    const firstDotIndex = key.indexOf(".");
    if (firstDotIndex >= 0) {
      const firstSegment = key.substring(0, firstDotIndex);
      target[firstSegment] = target[firstSegment] || {};
      this._write(target[firstSegment], key.substring(firstDotIndex + 1), value);
      return;
    }
    target[key] = value;
  }
}
EditorSettingMigration.items = [];
function registerEditorSettingMigration(key, migrate) {
  EditorSettingMigration.items.push(new EditorSettingMigration(key, migrate));
}
function registerSimpleEditorSettingMigration(key, values) {
  registerEditorSettingMigration(key, (value, read2, write3) => {
    if (typeof value !== "undefined") {
      for (const [oldValue, newValue] of values) {
        if (value === oldValue) {
          write3(key, newValue);
          return;
        }
      }
    }
  });
}
function migrateOptions(options) {
  EditorSettingMigration.items.forEach((migration) => migration.apply(options));
}
registerSimpleEditorSettingMigration("wordWrap", [[true, "on"], [false, "off"]]);
registerSimpleEditorSettingMigration("lineNumbers", [[true, "on"], [false, "off"]]);
registerSimpleEditorSettingMigration("cursorBlinking", [["visible", "solid"]]);
registerSimpleEditorSettingMigration("renderWhitespace", [[true, "boundary"], [false, "none"]]);
registerSimpleEditorSettingMigration("renderLineHighlight", [[true, "line"], [false, "none"]]);
registerSimpleEditorSettingMigration("acceptSuggestionOnEnter", [[true, "on"], [false, "off"]]);
registerSimpleEditorSettingMigration("tabCompletion", [[false, "off"], [true, "onlySnippets"]]);
registerSimpleEditorSettingMigration("hover", [[true, { enabled: true }], [false, { enabled: false }]]);
registerSimpleEditorSettingMigration("parameterHints", [[true, { enabled: true }], [false, { enabled: false }]]);
registerSimpleEditorSettingMigration("autoIndent", [[false, "advanced"], [true, "full"]]);
registerSimpleEditorSettingMigration("matchBrackets", [[true, "always"], [false, "never"]]);
registerSimpleEditorSettingMigration("renderFinalNewline", [[true, "on"], [false, "off"]]);
registerSimpleEditorSettingMigration("cursorSmoothCaretAnimation", [[true, "on"], [false, "off"]]);
registerEditorSettingMigration("autoClosingBrackets", (value, read2, write3) => {
  if (value === false) {
    write3("autoClosingBrackets", "never");
    if (typeof read2("autoClosingQuotes") === "undefined") {
      write3("autoClosingQuotes", "never");
    }
    if (typeof read2("autoSurround") === "undefined") {
      write3("autoSurround", "never");
    }
  }
});
registerEditorSettingMigration("renderIndentGuides", (value, read2, write3) => {
  if (typeof value !== "undefined") {
    write3("renderIndentGuides", void 0);
    if (typeof read2("guides.indentation") === "undefined") {
      write3("guides.indentation", !!value);
    }
  }
});
registerEditorSettingMigration("highlightActiveIndentGuide", (value, read2, write3) => {
  if (typeof value !== "undefined") {
    write3("highlightActiveIndentGuide", void 0);
    if (typeof read2("guides.highlightActiveIndentation") === "undefined") {
      write3("guides.highlightActiveIndentation", !!value);
    }
  }
});
const suggestFilteredTypesMapping = {
  method: "showMethods",
  function: "showFunctions",
  constructor: "showConstructors",
  deprecated: "showDeprecated",
  field: "showFields",
  variable: "showVariables",
  class: "showClasses",
  struct: "showStructs",
  interface: "showInterfaces",
  module: "showModules",
  property: "showProperties",
  event: "showEvents",
  operator: "showOperators",
  unit: "showUnits",
  value: "showValues",
  constant: "showConstants",
  enum: "showEnums",
  enumMember: "showEnumMembers",
  keyword: "showKeywords",
  text: "showWords",
  color: "showColors",
  file: "showFiles",
  reference: "showReferences",
  folder: "showFolders",
  typeParameter: "showTypeParameters",
  snippet: "showSnippets"
};
registerEditorSettingMigration("suggest.filteredTypes", (value, read2, write3) => {
  if (value && typeof value === "object") {
    for (const entry of Object.entries(suggestFilteredTypesMapping)) {
      const v = value[entry[0]];
      if (v === false) {
        if (typeof read2(`suggest.${entry[1]}`) === "undefined") {
          write3(`suggest.${entry[1]}`, false);
        }
      }
    }
    write3("suggest.filteredTypes", void 0);
  }
});
registerEditorSettingMigration("quickSuggestions", (input2, read2, write3) => {
  if (typeof input2 === "boolean") {
    const value = input2 ? "on" : "off";
    const newValue = { comments: value, strings: value, other: value };
    write3("quickSuggestions", newValue);
  }
});
registerEditorSettingMigration("experimental.stickyScroll.enabled", (value, read2, write3) => {
  if (typeof value === "boolean") {
    write3("experimental.stickyScroll.enabled", void 0);
    if (typeof read2("stickyScroll.enabled") === "undefined") {
      write3("stickyScroll.enabled", value);
    }
  }
});
registerEditorSettingMigration("experimental.stickyScroll.maxLineCount", (value, read2, write3) => {
  if (typeof value === "number") {
    write3("experimental.stickyScroll.maxLineCount", void 0);
    if (typeof read2("stickyScroll.maxLineCount") === "undefined") {
      write3("stickyScroll.maxLineCount", value);
    }
  }
});
class TabFocusImpl {
  constructor() {
    this._tabFocusTerminal = false;
    this._tabFocusEditor = false;
    this._onDidChangeTabFocus = new Emitter$1();
    this.onDidChangeTabFocus = this._onDidChangeTabFocus.event;
  }
  getTabFocusMode(context) {
    return context === "terminalFocus" ? this._tabFocusTerminal : this._tabFocusEditor;
  }
  setTabFocusMode(tabFocusMode, context) {
    if (context === "terminalFocus") {
      this._tabFocusTerminal = tabFocusMode;
    } else {
      this._tabFocusEditor = tabFocusMode;
    }
    this._onDidChangeTabFocus.fire();
  }
}
const TabFocus = new TabFocusImpl();
const IAccessibilityService = createDecorator("accessibilityService");
const CONTEXT_ACCESSIBILITY_MODE_ENABLED = new RawContextKey("accessibilityModeEnabled", false);
var __decorate$27 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$20 = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let EditorConfiguration = class EditorConfiguration2 extends Disposable {
  constructor(isSimpleWidget, options, container2, _accessibilityService) {
    super();
    this._accessibilityService = _accessibilityService;
    this._onDidChange = this._register(new Emitter$1());
    this.onDidChange = this._onDidChange.event;
    this._onDidChangeFast = this._register(new Emitter$1());
    this.onDidChangeFast = this._onDidChangeFast.event;
    this._isDominatedByLongLines = false;
    this._viewLineCount = 1;
    this._lineNumbersDigitCount = 1;
    this._reservedHeight = 0;
    this._glyphMarginDecorationLaneCount = 1;
    this._computeOptionsMemory = new ComputeOptionsMemory();
    this.isSimpleWidget = isSimpleWidget;
    this._containerObserver = this._register(new ElementSizeObserver(container2, options.dimension));
    this._rawOptions = deepCloneAndMigrateOptions(options);
    this._validatedOptions = EditorOptionsUtil.validateOptions(this._rawOptions);
    this.options = this._computeOptions();
    if (this.options.get(
      12
      /* EditorOption.automaticLayout */
    )) {
      this._containerObserver.startObserving();
    }
    this._register(EditorZoom.onDidChangeZoomLevel(() => this._recomputeOptions()));
    this._register(TabFocus.onDidChangeTabFocus(() => this._recomputeOptions()));
    this._register(this._containerObserver.onDidChange(() => this._recomputeOptions()));
    this._register(FontMeasurements.onDidChange(() => this._recomputeOptions()));
    this._register(PixelRatio.onDidChange(() => this._recomputeOptions()));
    this._register(this._accessibilityService.onDidChangeScreenReaderOptimized(() => this._recomputeOptions()));
  }
  _recomputeOptions() {
    const newOptions = this._computeOptions();
    const changeEvent = EditorOptionsUtil.checkEquals(this.options, newOptions);
    if (changeEvent === null) {
      return;
    }
    this.options = newOptions;
    this._onDidChangeFast.fire(changeEvent);
    this._onDidChange.fire(changeEvent);
  }
  _computeOptions() {
    const partialEnv = this._readEnvConfiguration();
    const bareFontInfo = BareFontInfo.createFromValidatedSettings(this._validatedOptions, partialEnv.pixelRatio, this.isSimpleWidget);
    const fontInfo = this._readFontInfo(bareFontInfo);
    const env2 = {
      memory: this._computeOptionsMemory,
      outerWidth: partialEnv.outerWidth,
      outerHeight: partialEnv.outerHeight - this._reservedHeight,
      fontInfo,
      extraEditorClassName: partialEnv.extraEditorClassName,
      isDominatedByLongLines: this._isDominatedByLongLines,
      viewLineCount: this._viewLineCount,
      lineNumbersDigitCount: this._lineNumbersDigitCount,
      emptySelectionClipboard: partialEnv.emptySelectionClipboard,
      pixelRatio: partialEnv.pixelRatio,
      tabFocusMode: TabFocus.getTabFocusMode(
        "editorFocus"
        /* TabFocusContext.Editor */
      ),
      accessibilitySupport: partialEnv.accessibilitySupport,
      glyphMarginDecorationLaneCount: this._glyphMarginDecorationLaneCount
    };
    return EditorOptionsUtil.computeOptions(this._validatedOptions, env2);
  }
  _readEnvConfiguration() {
    return {
      extraEditorClassName: getExtraEditorClassName(),
      outerWidth: this._containerObserver.getWidth(),
      outerHeight: this._containerObserver.getHeight(),
      emptySelectionClipboard: isWebKit || isFirefox$1,
      pixelRatio: PixelRatio.value,
      accessibilitySupport: this._accessibilityService.isScreenReaderOptimized() ? 2 : this._accessibilityService.getAccessibilitySupport()
    };
  }
  _readFontInfo(bareFontInfo) {
    return FontMeasurements.readFontInfo(bareFontInfo);
  }
  getRawOptions() {
    return this._rawOptions;
  }
  updateOptions(_newOptions) {
    const newOptions = deepCloneAndMigrateOptions(_newOptions);
    const didChange = EditorOptionsUtil.applyUpdate(this._rawOptions, newOptions);
    if (!didChange) {
      return;
    }
    this._validatedOptions = EditorOptionsUtil.validateOptions(this._rawOptions);
    this._recomputeOptions();
  }
  observeContainer(dimension) {
    this._containerObserver.observe(dimension);
  }
  setIsDominatedByLongLines(isDominatedByLongLines) {
    if (this._isDominatedByLongLines === isDominatedByLongLines) {
      return;
    }
    this._isDominatedByLongLines = isDominatedByLongLines;
    this._recomputeOptions();
  }
  setModelLineCount(modelLineCount) {
    const lineNumbersDigitCount = digitCount(modelLineCount);
    if (this._lineNumbersDigitCount === lineNumbersDigitCount) {
      return;
    }
    this._lineNumbersDigitCount = lineNumbersDigitCount;
    this._recomputeOptions();
  }
  setViewLineCount(viewLineCount) {
    if (this._viewLineCount === viewLineCount) {
      return;
    }
    this._viewLineCount = viewLineCount;
    this._recomputeOptions();
  }
  setReservedHeight(reservedHeight) {
    if (this._reservedHeight === reservedHeight) {
      return;
    }
    this._reservedHeight = reservedHeight;
    this._recomputeOptions();
  }
  setGlyphMarginDecorationLaneCount(decorationLaneCount) {
    if (this._glyphMarginDecorationLaneCount === decorationLaneCount) {
      return;
    }
    this._glyphMarginDecorationLaneCount = decorationLaneCount;
    this._recomputeOptions();
  }
};
EditorConfiguration = __decorate$27([
  __param$20(3, IAccessibilityService)
], EditorConfiguration);
function digitCount(n2) {
  let r = 0;
  while (n2) {
    n2 = Math.floor(n2 / 10);
    r++;
  }
  return r ? r : 1;
}
function getExtraEditorClassName() {
  let extra = "";
  if (!isSafari$1 && !isWebkitWebView) {
    extra += "no-user-select ";
  }
  if (isSafari$1) {
    extra += "no-minimap-shadow ";
    extra += "enable-user-select ";
  }
  if (isMacintosh) {
    extra += "mac ";
  }
  return extra;
}
class ValidatedEditorOptions {
  constructor() {
    this._values = [];
  }
  _read(option) {
    return this._values[option];
  }
  get(id3) {
    return this._values[id3];
  }
  _write(option, value) {
    this._values[option] = value;
  }
}
class ComputedEditorOptions {
  constructor() {
    this._values = [];
  }
  _read(id3) {
    if (id3 >= this._values.length) {
      throw new Error("Cannot read uninitialized value");
    }
    return this._values[id3];
  }
  get(id3) {
    return this._read(id3);
  }
  _write(id3, value) {
    this._values[id3] = value;
  }
}
class EditorOptionsUtil {
  static validateOptions(options) {
    const result2 = new ValidatedEditorOptions();
    for (const editorOption of editorOptionsRegistry) {
      const value = editorOption.name === "_never_" ? void 0 : options[editorOption.name];
      result2._write(editorOption.id, editorOption.validate(value));
    }
    return result2;
  }
  static computeOptions(options, env2) {
    const result2 = new ComputedEditorOptions();
    for (const editorOption of editorOptionsRegistry) {
      result2._write(editorOption.id, editorOption.compute(env2, result2, options._read(editorOption.id)));
    }
    return result2;
  }
  static _deepEquals(a, b) {
    if (typeof a !== "object" || typeof b !== "object" || !a || !b) {
      return a === b;
    }
    if (Array.isArray(a) || Array.isArray(b)) {
      return Array.isArray(a) && Array.isArray(b) ? equals$3(a, b) : false;
    }
    if (Object.keys(a).length !== Object.keys(b).length) {
      return false;
    }
    for (const key in a) {
      if (!EditorOptionsUtil._deepEquals(a[key], b[key])) {
        return false;
      }
    }
    return true;
  }
  static checkEquals(a, b) {
    const result2 = [];
    let somethingChanged = false;
    for (const editorOption of editorOptionsRegistry) {
      const changed = !EditorOptionsUtil._deepEquals(a._read(editorOption.id), b._read(editorOption.id));
      result2[editorOption.id] = changed;
      if (changed) {
        somethingChanged = true;
      }
    }
    return somethingChanged ? new ConfigurationChangedEvent(result2) : null;
  }
  /**
   * Returns true if something changed.
   * Modifies `options`.
  */
  static applyUpdate(options, update) {
    let changed = false;
    for (const editorOption of editorOptionsRegistry) {
      if (update.hasOwnProperty(editorOption.name)) {
        const result2 = editorOption.applyUpdate(options[editorOption.name], update[editorOption.name]);
        options[editorOption.name] = result2.newValue;
        changed = changed || result2.didChange;
      }
    }
    return changed;
  }
}
function deepCloneAndMigrateOptions(_options) {
  const options = deepClone(_options);
  migrateOptions(options);
  return options;
}
function memoize(_target, key, descriptor) {
  let fnKey = null;
  let fn = null;
  if (typeof descriptor.value === "function") {
    fnKey = "value";
    fn = descriptor.value;
    if (fn.length !== 0) {
      console.warn("Memoize should only be used in functions with zero parameters");
    }
  } else if (typeof descriptor.get === "function") {
    fnKey = "get";
    fn = descriptor.get;
  }
  if (!fn) {
    throw new Error("not supported");
  }
  const memoizeKey = `$memoize$${key}`;
  descriptor[fnKey] = function(...args) {
    if (!this.hasOwnProperty(memoizeKey)) {
      Object.defineProperty(this, memoizeKey, {
        configurable: false,
        enumerable: false,
        writable: false,
        value: fn.apply(this, args)
      });
    }
    return this[memoizeKey];
  };
}
var __decorate$26 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var EventType;
(function(EventType2) {
  EventType2.Tap = "-monaco-gesturetap";
  EventType2.Change = "-monaco-gesturechange";
  EventType2.Start = "-monaco-gesturestart";
  EventType2.End = "-monaco-gesturesend";
  EventType2.Contextmenu = "-monaco-gesturecontextmenu";
})(EventType || (EventType = {}));
class Gesture extends Disposable {
  constructor() {
    super();
    this.dispatched = false;
    this.targets = new LinkedList();
    this.ignoreTargets = new LinkedList();
    this.activeTouches = {};
    this.handle = null;
    this._lastSetTapCountTime = 0;
    this._register(addDisposableListener(document, "touchstart", (e) => this.onTouchStart(e), { passive: false }));
    this._register(addDisposableListener(document, "touchend", (e) => this.onTouchEnd(e)));
    this._register(addDisposableListener(document, "touchmove", (e) => this.onTouchMove(e), { passive: false }));
  }
  static addTarget(element) {
    if (!Gesture.isTouchDevice()) {
      return Disposable.None;
    }
    if (!Gesture.INSTANCE) {
      Gesture.INSTANCE = new Gesture();
    }
    const remove2 = Gesture.INSTANCE.targets.push(element);
    return toDisposable(remove2);
  }
  static ignoreTarget(element) {
    if (!Gesture.isTouchDevice()) {
      return Disposable.None;
    }
    if (!Gesture.INSTANCE) {
      Gesture.INSTANCE = new Gesture();
    }
    const remove2 = Gesture.INSTANCE.ignoreTargets.push(element);
    return toDisposable(remove2);
  }
  static isTouchDevice() {
    return "ontouchstart" in window || navigator.maxTouchPoints > 0;
  }
  dispose() {
    if (this.handle) {
      this.handle.dispose();
      this.handle = null;
    }
    super.dispose();
  }
  onTouchStart(e) {
    const timestamp2 = Date.now();
    if (this.handle) {
      this.handle.dispose();
      this.handle = null;
    }
    for (let i = 0, len = e.targetTouches.length; i < len; i++) {
      const touch = e.targetTouches.item(i);
      this.activeTouches[touch.identifier] = {
        id: touch.identifier,
        initialTarget: touch.target,
        initialTimeStamp: timestamp2,
        initialPageX: touch.pageX,
        initialPageY: touch.pageY,
        rollingTimestamps: [timestamp2],
        rollingPageX: [touch.pageX],
        rollingPageY: [touch.pageY]
      };
      const evt = this.newGestureEvent(EventType.Start, touch.target);
      evt.pageX = touch.pageX;
      evt.pageY = touch.pageY;
      this.dispatchEvent(evt);
    }
    if (this.dispatched) {
      e.preventDefault();
      e.stopPropagation();
      this.dispatched = false;
    }
  }
  onTouchEnd(e) {
    const timestamp2 = Date.now();
    const activeTouchCount = Object.keys(this.activeTouches).length;
    for (let i = 0, len = e.changedTouches.length; i < len; i++) {
      const touch = e.changedTouches.item(i);
      if (!this.activeTouches.hasOwnProperty(String(touch.identifier))) {
        console.warn("move of an UNKNOWN touch", touch);
        continue;
      }
      const data = this.activeTouches[touch.identifier], holdTime = Date.now() - data.initialTimeStamp;
      if (holdTime < Gesture.HOLD_DELAY && Math.abs(data.initialPageX - tail(data.rollingPageX)) < 30 && Math.abs(data.initialPageY - tail(data.rollingPageY)) < 30) {
        const evt = this.newGestureEvent(EventType.Tap, data.initialTarget);
        evt.pageX = tail(data.rollingPageX);
        evt.pageY = tail(data.rollingPageY);
        this.dispatchEvent(evt);
      } else if (holdTime >= Gesture.HOLD_DELAY && Math.abs(data.initialPageX - tail(data.rollingPageX)) < 30 && Math.abs(data.initialPageY - tail(data.rollingPageY)) < 30) {
        const evt = this.newGestureEvent(EventType.Contextmenu, data.initialTarget);
        evt.pageX = tail(data.rollingPageX);
        evt.pageY = tail(data.rollingPageY);
        this.dispatchEvent(evt);
      } else if (activeTouchCount === 1) {
        const finalX = tail(data.rollingPageX);
        const finalY = tail(data.rollingPageY);
        const deltaT = tail(data.rollingTimestamps) - data.rollingTimestamps[0];
        const deltaX = finalX - data.rollingPageX[0];
        const deltaY = finalY - data.rollingPageY[0];
        const dispatchTo = [...this.targets].filter((t) => data.initialTarget instanceof Node && t.contains(data.initialTarget));
        this.inertia(
          dispatchTo,
          timestamp2,
          // time now
          Math.abs(deltaX) / deltaT,
          // speed
          deltaX > 0 ? 1 : -1,
          // x direction
          finalX,
          // x now
          Math.abs(deltaY) / deltaT,
          // y speed
          deltaY > 0 ? 1 : -1,
          // y direction
          finalY
          // y now
        );
      }
      this.dispatchEvent(this.newGestureEvent(EventType.End, data.initialTarget));
      delete this.activeTouches[touch.identifier];
    }
    if (this.dispatched) {
      e.preventDefault();
      e.stopPropagation();
      this.dispatched = false;
    }
  }
  newGestureEvent(type, initialTarget) {
    const event = document.createEvent("CustomEvent");
    event.initEvent(type, false, true);
    event.initialTarget = initialTarget;
    event.tapCount = 0;
    return event;
  }
  dispatchEvent(event) {
    if (event.type === EventType.Tap) {
      const currentTime = (/* @__PURE__ */ new Date()).getTime();
      let setTapCount = 0;
      if (currentTime - this._lastSetTapCountTime > Gesture.CLEAR_TAP_COUNT_TIME) {
        setTapCount = 1;
      } else {
        setTapCount = 2;
      }
      this._lastSetTapCountTime = currentTime;
      event.tapCount = setTapCount;
    } else if (event.type === EventType.Change || event.type === EventType.Contextmenu) {
      this._lastSetTapCountTime = 0;
    }
    if (event.initialTarget instanceof Node) {
      for (const ignoreTarget of this.ignoreTargets) {
        if (ignoreTarget.contains(event.initialTarget)) {
          return;
        }
      }
      for (const target of this.targets) {
        if (target.contains(event.initialTarget)) {
          target.dispatchEvent(event);
          this.dispatched = true;
        }
      }
    }
  }
  inertia(dispatchTo, t1, vX, dirX, x, vY, dirY, y) {
    this.handle = scheduleAtNextAnimationFrame(() => {
      const now = Date.now();
      const deltaT = now - t1;
      let delta_pos_x = 0, delta_pos_y = 0;
      let stopped = true;
      vX += Gesture.SCROLL_FRICTION * deltaT;
      vY += Gesture.SCROLL_FRICTION * deltaT;
      if (vX > 0) {
        stopped = false;
        delta_pos_x = dirX * vX * deltaT;
      }
      if (vY > 0) {
        stopped = false;
        delta_pos_y = dirY * vY * deltaT;
      }
      const evt = this.newGestureEvent(EventType.Change);
      evt.translationX = delta_pos_x;
      evt.translationY = delta_pos_y;
      dispatchTo.forEach((d) => d.dispatchEvent(evt));
      if (!stopped) {
        this.inertia(dispatchTo, now, vX, dirX, x + delta_pos_x, vY, dirY, y + delta_pos_y);
      }
    });
  }
  onTouchMove(e) {
    const timestamp2 = Date.now();
    for (let i = 0, len = e.changedTouches.length; i < len; i++) {
      const touch = e.changedTouches.item(i);
      if (!this.activeTouches.hasOwnProperty(String(touch.identifier))) {
        console.warn("end of an UNKNOWN touch", touch);
        continue;
      }
      const data = this.activeTouches[touch.identifier];
      const evt = this.newGestureEvent(EventType.Change, data.initialTarget);
      evt.translationX = touch.pageX - tail(data.rollingPageX);
      evt.translationY = touch.pageY - tail(data.rollingPageY);
      evt.pageX = touch.pageX;
      evt.pageY = touch.pageY;
      this.dispatchEvent(evt);
      if (data.rollingPageX.length > 3) {
        data.rollingPageX.shift();
        data.rollingPageY.shift();
        data.rollingTimestamps.shift();
      }
      data.rollingPageX.push(touch.pageX);
      data.rollingPageY.push(touch.pageY);
      data.rollingTimestamps.push(timestamp2);
    }
    if (this.dispatched) {
      e.preventDefault();
      e.stopPropagation();
      this.dispatched = false;
    }
  }
}
Gesture.SCROLL_FRICTION = -5e-3;
Gesture.HOLD_DELAY = 700;
Gesture.CLEAR_TAP_COUNT_TIME = 400;
__decorate$26([
  memoize
], Gesture, "isTouchDevice", null);
class GlobalPointerMoveMonitor {
  constructor() {
    this._hooks = new DisposableStore();
    this._pointerMoveCallback = null;
    this._onStopCallback = null;
  }
  dispose() {
    this.stopMonitoring(false);
    this._hooks.dispose();
  }
  stopMonitoring(invokeStopCallback, browserEvent) {
    if (!this.isMonitoring()) {
      return;
    }
    this._hooks.clear();
    this._pointerMoveCallback = null;
    const onStopCallback = this._onStopCallback;
    this._onStopCallback = null;
    if (invokeStopCallback && onStopCallback) {
      onStopCallback(browserEvent);
    }
  }
  isMonitoring() {
    return !!this._pointerMoveCallback;
  }
  startMonitoring(initialElement, pointerId, initialButtons, pointerMoveCallback, onStopCallback) {
    if (this.isMonitoring()) {
      this.stopMonitoring(false);
    }
    this._pointerMoveCallback = pointerMoveCallback;
    this._onStopCallback = onStopCallback;
    let eventSource = initialElement;
    try {
      initialElement.setPointerCapture(pointerId);
      this._hooks.add(toDisposable(() => {
        try {
          initialElement.releasePointerCapture(pointerId);
        } catch (err) {
        }
      }));
    } catch (err) {
      eventSource = window;
    }
    this._hooks.add(addDisposableListener(eventSource, EventType$1.POINTER_MOVE, (e) => {
      if (e.buttons !== initialButtons) {
        this.stopMonitoring(true);
        return;
      }
      e.preventDefault();
      this._pointerMoveCallback(e);
    }));
    this._hooks.add(addDisposableListener(eventSource, EventType$1.POINTER_UP, (e) => this.stopMonitoring(true)));
  }
}
const shortcutEvent = Object.freeze(function(callback, context) {
  const handle = setTimeout(callback.bind(context), 0);
  return { dispose() {
    clearTimeout(handle);
  } };
});
var CancellationToken;
(function(CancellationToken2) {
  function isCancellationToken(thing) {
    if (thing === CancellationToken2.None || thing === CancellationToken2.Cancelled) {
      return true;
    }
    if (thing instanceof MutableToken) {
      return true;
    }
    if (!thing || typeof thing !== "object") {
      return false;
    }
    return typeof thing.isCancellationRequested === "boolean" && typeof thing.onCancellationRequested === "function";
  }
  CancellationToken2.isCancellationToken = isCancellationToken;
  CancellationToken2.None = Object.freeze({
    isCancellationRequested: false,
    onCancellationRequested: Event$1.None
  });
  CancellationToken2.Cancelled = Object.freeze({
    isCancellationRequested: true,
    onCancellationRequested: shortcutEvent
  });
})(CancellationToken || (CancellationToken = {}));
class MutableToken {
  constructor() {
    this._isCancelled = false;
    this._emitter = null;
  }
  cancel() {
    if (!this._isCancelled) {
      this._isCancelled = true;
      if (this._emitter) {
        this._emitter.fire(void 0);
        this.dispose();
      }
    }
  }
  get isCancellationRequested() {
    return this._isCancelled;
  }
  get onCancellationRequested() {
    if (this._isCancelled) {
      return shortcutEvent;
    }
    if (!this._emitter) {
      this._emitter = new Emitter$1();
    }
    return this._emitter.event;
  }
  dispose() {
    if (this._emitter) {
      this._emitter.dispose();
      this._emitter = null;
    }
  }
}
let CancellationTokenSource$1 = class CancellationTokenSource {
  constructor(parent) {
    this._token = void 0;
    this._parentListener = void 0;
    this._parentListener = parent && parent.onCancellationRequested(this.cancel, this);
  }
  get token() {
    if (!this._token) {
      this._token = new MutableToken();
    }
    return this._token;
  }
  cancel() {
    if (!this._token) {
      this._token = CancellationToken.Cancelled;
    } else if (this._token instanceof MutableToken) {
      this._token.cancel();
    }
  }
  dispose(cancel = false) {
    var _a2;
    if (cancel) {
      this.cancel();
    }
    (_a2 = this._parentListener) === null || _a2 === void 0 ? void 0 : _a2.dispose();
    if (!this._token) {
      this._token = CancellationToken.None;
    } else if (this._token instanceof MutableToken) {
      this._token.dispose();
    }
  }
};
const MicrotaskDelay = Symbol("MicrotaskDelay");
var __awaiter$1z = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var __asyncValues$2 = globalThis && globalThis.__asyncValues || function(o) {
  if (!Symbol.asyncIterator)
    throw new TypeError("Symbol.asyncIterator is not defined.");
  var m = o[Symbol.asyncIterator], i;
  return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
    return this;
  }, i);
  function verb(n2) {
    i[n2] = o[n2] && function(v) {
      return new Promise(function(resolve2, reject) {
        v = o[n2](v), settle(resolve2, reject, v.done, v.value);
      });
    };
  }
  function settle(resolve2, reject, d, v) {
    Promise.resolve(v).then(function(v2) {
      resolve2({ value: v2, done: d });
    }, reject);
  }
};
function isThenable$1(obj) {
  return !!obj && typeof obj.then === "function";
}
function createCancelablePromise(callback) {
  const source = new CancellationTokenSource$1();
  const thenable = callback(source.token);
  const promise = new Promise((resolve2, reject) => {
    const subscription = source.token.onCancellationRequested(() => {
      subscription.dispose();
      source.dispose();
      reject(new CancellationError());
    });
    Promise.resolve(thenable).then((value) => {
      subscription.dispose();
      source.dispose();
      resolve2(value);
    }, (err) => {
      subscription.dispose();
      source.dispose();
      reject(err);
    });
  });
  return new class {
    cancel() {
      source.cancel();
    }
    then(resolve2, reject) {
      return promise.then(resolve2, reject);
    }
    catch(reject) {
      return this.then(void 0, reject);
    }
    finally(onfinally) {
      return promise.finally(onfinally);
    }
  }();
}
function raceCancellation(promise, token, defaultValue) {
  return new Promise((resolve2, reject) => {
    const ref2 = token.onCancellationRequested(() => {
      ref2.dispose();
      resolve2(defaultValue);
    });
    promise.then(resolve2, reject).finally(() => ref2.dispose());
  });
}
class Throttler {
  constructor() {
    this.isDisposed = false;
    this.activePromise = null;
    this.queuedPromise = null;
    this.queuedPromiseFactory = null;
  }
  queue(promiseFactory) {
    if (this.isDisposed) {
      throw new Error("Throttler is disposed");
    }
    if (this.activePromise) {
      this.queuedPromiseFactory = promiseFactory;
      if (!this.queuedPromise) {
        const onComplete = () => {
          this.queuedPromise = null;
          if (this.isDisposed) {
            return;
          }
          const result2 = this.queue(this.queuedPromiseFactory);
          this.queuedPromiseFactory = null;
          return result2;
        };
        this.queuedPromise = new Promise((resolve2) => {
          this.activePromise.then(onComplete, onComplete).then(resolve2);
        });
      }
      return new Promise((resolve2, reject) => {
        this.queuedPromise.then(resolve2, reject);
      });
    }
    this.activePromise = promiseFactory();
    return new Promise((resolve2, reject) => {
      this.activePromise.then((result2) => {
        this.activePromise = null;
        resolve2(result2);
      }, (err) => {
        this.activePromise = null;
        reject(err);
      });
    });
  }
  dispose() {
    this.isDisposed = true;
  }
}
const timeoutDeferred = (timeout2, fn) => {
  let scheduled = true;
  const handle = setTimeout(() => {
    scheduled = false;
    fn();
  }, timeout2);
  return {
    isTriggered: () => scheduled,
    dispose: () => {
      clearTimeout(handle);
      scheduled = false;
    }
  };
};
const microtaskDeferred = (fn) => {
  let scheduled = true;
  queueMicrotask(() => {
    if (scheduled) {
      scheduled = false;
      fn();
    }
  });
  return {
    isTriggered: () => scheduled,
    dispose: () => {
      scheduled = false;
    }
  };
};
class Delayer {
  constructor(defaultDelay) {
    this.defaultDelay = defaultDelay;
    this.deferred = null;
    this.completionPromise = null;
    this.doResolve = null;
    this.doReject = null;
    this.task = null;
  }
  trigger(task, delay = this.defaultDelay) {
    this.task = task;
    this.cancelTimeout();
    if (!this.completionPromise) {
      this.completionPromise = new Promise((resolve2, reject) => {
        this.doResolve = resolve2;
        this.doReject = reject;
      }).then(() => {
        this.completionPromise = null;
        this.doResolve = null;
        if (this.task) {
          const task2 = this.task;
          this.task = null;
          return task2();
        }
        return void 0;
      });
    }
    const fn = () => {
      var _a2;
      this.deferred = null;
      (_a2 = this.doResolve) === null || _a2 === void 0 ? void 0 : _a2.call(this, null);
    };
    this.deferred = delay === MicrotaskDelay ? microtaskDeferred(fn) : timeoutDeferred(delay, fn);
    return this.completionPromise;
  }
  isTriggered() {
    var _a2;
    return !!((_a2 = this.deferred) === null || _a2 === void 0 ? void 0 : _a2.isTriggered());
  }
  cancel() {
    var _a2;
    this.cancelTimeout();
    if (this.completionPromise) {
      (_a2 = this.doReject) === null || _a2 === void 0 ? void 0 : _a2.call(this, new CancellationError());
      this.completionPromise = null;
    }
  }
  cancelTimeout() {
    var _a2;
    (_a2 = this.deferred) === null || _a2 === void 0 ? void 0 : _a2.dispose();
    this.deferred = null;
  }
  dispose() {
    this.cancel();
  }
}
class ThrottledDelayer {
  constructor(defaultDelay) {
    this.delayer = new Delayer(defaultDelay);
    this.throttler = new Throttler();
  }
  trigger(promiseFactory, delay) {
    return this.delayer.trigger(() => this.throttler.queue(promiseFactory), delay);
  }
  cancel() {
    this.delayer.cancel();
  }
  dispose() {
    this.delayer.dispose();
    this.throttler.dispose();
  }
}
function timeout(millis, token) {
  if (!token) {
    return createCancelablePromise((token2) => timeout(millis, token2));
  }
  return new Promise((resolve2, reject) => {
    const handle = setTimeout(() => {
      disposable.dispose();
      resolve2();
    }, millis);
    const disposable = token.onCancellationRequested(() => {
      clearTimeout(handle);
      disposable.dispose();
      reject(new CancellationError());
    });
  });
}
function disposableTimeout(handler, timeout2 = 0) {
  const timer = setTimeout(handler, timeout2);
  return toDisposable(() => clearTimeout(timer));
}
function first(promiseFactories, shouldStop = (t) => !!t, defaultValue = null) {
  let index = 0;
  const len = promiseFactories.length;
  const loop = () => {
    if (index >= len) {
      return Promise.resolve(defaultValue);
    }
    const factory = promiseFactories[index++];
    const promise = Promise.resolve(factory());
    return promise.then((result2) => {
      if (shouldStop(result2)) {
        return Promise.resolve(result2);
      }
      return loop();
    });
  };
  return loop();
}
class TimeoutTimer {
  constructor(runner, timeout2) {
    this._token = -1;
    if (typeof runner === "function" && typeof timeout2 === "number") {
      this.setIfNotSet(runner, timeout2);
    }
  }
  dispose() {
    this.cancel();
  }
  cancel() {
    if (this._token !== -1) {
      clearTimeout(this._token);
      this._token = -1;
    }
  }
  cancelAndSet(runner, timeout2) {
    this.cancel();
    this._token = setTimeout(() => {
      this._token = -1;
      runner();
    }, timeout2);
  }
  setIfNotSet(runner, timeout2) {
    if (this._token !== -1) {
      return;
    }
    this._token = setTimeout(() => {
      this._token = -1;
      runner();
    }, timeout2);
  }
}
class IntervalTimer {
  constructor() {
    this._token = -1;
  }
  dispose() {
    this.cancel();
  }
  cancel() {
    if (this._token !== -1) {
      clearInterval(this._token);
      this._token = -1;
    }
  }
  cancelAndSet(runner, interval) {
    this.cancel();
    this._token = setInterval(() => {
      runner();
    }, interval);
  }
}
class RunOnceScheduler {
  constructor(runner, delay) {
    this.timeoutToken = -1;
    this.runner = runner;
    this.timeout = delay;
    this.timeoutHandler = this.onTimeout.bind(this);
  }
  /**
   * Dispose RunOnceScheduler
   */
  dispose() {
    this.cancel();
    this.runner = null;
  }
  /**
   * Cancel current scheduled runner (if any).
   */
  cancel() {
    if (this.isScheduled()) {
      clearTimeout(this.timeoutToken);
      this.timeoutToken = -1;
    }
  }
  /**
   * Cancel previous runner (if any) & schedule a new runner.
   */
  schedule(delay = this.timeout) {
    this.cancel();
    this.timeoutToken = setTimeout(this.timeoutHandler, delay);
  }
  get delay() {
    return this.timeout;
  }
  set delay(value) {
    this.timeout = value;
  }
  /**
   * Returns true if scheduled.
   */
  isScheduled() {
    return this.timeoutToken !== -1;
  }
  onTimeout() {
    this.timeoutToken = -1;
    if (this.runner) {
      this.doRun();
    }
  }
  doRun() {
    var _a2;
    (_a2 = this.runner) === null || _a2 === void 0 ? void 0 : _a2.call(this);
  }
}
let runWhenIdle;
(function() {
  if (typeof requestIdleCallback !== "function" || typeof cancelIdleCallback !== "function") {
    runWhenIdle = (runner) => {
      setTimeout0(() => {
        if (disposed) {
          return;
        }
        const end = Date.now() + 15;
        runner(Object.freeze({
          didTimeout: true,
          timeRemaining() {
            return Math.max(0, end - Date.now());
          }
        }));
      });
      let disposed = false;
      return {
        dispose() {
          if (disposed) {
            return;
          }
          disposed = true;
        }
      };
    };
  } else {
    runWhenIdle = (runner, timeout2) => {
      const handle = requestIdleCallback(runner, typeof timeout2 === "number" ? { timeout: timeout2 } : void 0);
      let disposed = false;
      return {
        dispose() {
          if (disposed) {
            return;
          }
          disposed = true;
          cancelIdleCallback(handle);
        }
      };
    };
  }
})();
class IdleValue {
  constructor(executor) {
    this._didRun = false;
    this._executor = () => {
      try {
        this._value = executor();
      } catch (err) {
        this._error = err;
      } finally {
        this._didRun = true;
      }
    };
    this._handle = runWhenIdle(() => this._executor());
  }
  dispose() {
    this._handle.dispose();
  }
  get value() {
    if (!this._didRun) {
      this._handle.dispose();
      this._executor();
    }
    if (this._error) {
      throw this._error;
    }
    return this._value;
  }
  get isInitialized() {
    return this._didRun;
  }
}
class DeferredPromise {
  get isRejected() {
    var _a2;
    return ((_a2 = this.outcome) === null || _a2 === void 0 ? void 0 : _a2.outcome) === 1;
  }
  get isSettled() {
    return !!this.outcome;
  }
  constructor() {
    this.p = new Promise((c, e) => {
      this.completeCallback = c;
      this.errorCallback = e;
    });
  }
  complete(value) {
    return new Promise((resolve2) => {
      this.completeCallback(value);
      this.outcome = { outcome: 0, value };
      resolve2();
    });
  }
  error(err) {
    return new Promise((resolve2) => {
      this.errorCallback(err);
      this.outcome = { outcome: 1, value: err };
      resolve2();
    });
  }
  cancel() {
    return this.error(new CancellationError());
  }
}
var Promises;
(function(Promises2) {
  function settled(promises) {
    return __awaiter$1z(this, void 0, void 0, function* () {
      let firstError = void 0;
      const result2 = yield Promise.all(promises.map((promise) => promise.then((value) => value, (error2) => {
        if (!firstError) {
          firstError = error2;
        }
        return void 0;
      })));
      if (typeof firstError !== "undefined") {
        throw firstError;
      }
      return result2;
    });
  }
  Promises2.settled = settled;
  function withAsyncBody(bodyFn) {
    return new Promise((resolve2, reject) => __awaiter$1z(this, void 0, void 0, function* () {
      try {
        yield bodyFn(resolve2, reject);
      } catch (error2) {
        reject(error2);
      }
    }));
  }
  Promises2.withAsyncBody = withAsyncBody;
})(Promises || (Promises = {}));
class AsyncIterableObject {
  static fromArray(items) {
    return new AsyncIterableObject((writer) => {
      writer.emitMany(items);
    });
  }
  static fromPromise(promise) {
    return new AsyncIterableObject((emitter) => __awaiter$1z(this, void 0, void 0, function* () {
      emitter.emitMany(yield promise);
    }));
  }
  static fromPromises(promises) {
    return new AsyncIterableObject((emitter) => __awaiter$1z(this, void 0, void 0, function* () {
      yield Promise.all(promises.map((p2) => __awaiter$1z(this, void 0, void 0, function* () {
        return emitter.emitOne(yield p2);
      })));
    }));
  }
  static merge(iterables) {
    return new AsyncIterableObject((emitter) => __awaiter$1z(this, void 0, void 0, function* () {
      yield Promise.all(iterables.map((iterable) => {
        var _a2, iterable_1, iterable_1_1;
        return __awaiter$1z(this, void 0, void 0, function* () {
          var _b2, e_1, _c2, _d2;
          try {
            for (_a2 = true, iterable_1 = __asyncValues$2(iterable); iterable_1_1 = yield iterable_1.next(), _b2 = iterable_1_1.done, !_b2; _a2 = true) {
              _d2 = iterable_1_1.value;
              _a2 = false;
              const item = _d2;
              emitter.emitOne(item);
            }
          } catch (e_1_1) {
            e_1 = { error: e_1_1 };
          } finally {
            try {
              if (!_a2 && !_b2 && (_c2 = iterable_1.return))
                yield _c2.call(iterable_1);
            } finally {
              if (e_1)
                throw e_1.error;
            }
          }
        });
      }));
    }));
  }
  constructor(executor) {
    this._state = 0;
    this._results = [];
    this._error = null;
    this._onStateChanged = new Emitter$1();
    queueMicrotask(() => __awaiter$1z(this, void 0, void 0, function* () {
      const writer = {
        emitOne: (item) => this.emitOne(item),
        emitMany: (items) => this.emitMany(items),
        reject: (error2) => this.reject(error2)
      };
      try {
        yield Promise.resolve(executor(writer));
        this.resolve();
      } catch (err) {
        this.reject(err);
      } finally {
        writer.emitOne = void 0;
        writer.emitMany = void 0;
        writer.reject = void 0;
      }
    }));
  }
  [Symbol.asyncIterator]() {
    let i = 0;
    return {
      next: () => __awaiter$1z(this, void 0, void 0, function* () {
        do {
          if (this._state === 2) {
            throw this._error;
          }
          if (i < this._results.length) {
            return { done: false, value: this._results[i++] };
          }
          if (this._state === 1) {
            return { done: true, value: void 0 };
          }
          yield Event$1.toPromise(this._onStateChanged.event);
        } while (true);
      })
    };
  }
  static map(iterable, mapFn) {
    return new AsyncIterableObject((emitter) => __awaiter$1z(this, void 0, void 0, function* () {
      var _a2, e_2, _b2, _c2;
      try {
        for (var _d2 = true, iterable_2 = __asyncValues$2(iterable), iterable_2_1; iterable_2_1 = yield iterable_2.next(), _a2 = iterable_2_1.done, !_a2; _d2 = true) {
          _c2 = iterable_2_1.value;
          _d2 = false;
          const item = _c2;
          emitter.emitOne(mapFn(item));
        }
      } catch (e_2_1) {
        e_2 = { error: e_2_1 };
      } finally {
        try {
          if (!_d2 && !_a2 && (_b2 = iterable_2.return))
            yield _b2.call(iterable_2);
        } finally {
          if (e_2)
            throw e_2.error;
        }
      }
    }));
  }
  map(mapFn) {
    return AsyncIterableObject.map(this, mapFn);
  }
  static filter(iterable, filterFn) {
    return new AsyncIterableObject((emitter) => __awaiter$1z(this, void 0, void 0, function* () {
      var _a2, e_3, _b2, _c2;
      try {
        for (var _d2 = true, iterable_3 = __asyncValues$2(iterable), iterable_3_1; iterable_3_1 = yield iterable_3.next(), _a2 = iterable_3_1.done, !_a2; _d2 = true) {
          _c2 = iterable_3_1.value;
          _d2 = false;
          const item = _c2;
          if (filterFn(item)) {
            emitter.emitOne(item);
          }
        }
      } catch (e_3_1) {
        e_3 = { error: e_3_1 };
      } finally {
        try {
          if (!_d2 && !_a2 && (_b2 = iterable_3.return))
            yield _b2.call(iterable_3);
        } finally {
          if (e_3)
            throw e_3.error;
        }
      }
    }));
  }
  filter(filterFn) {
    return AsyncIterableObject.filter(this, filterFn);
  }
  static coalesce(iterable) {
    return AsyncIterableObject.filter(iterable, (item) => !!item);
  }
  coalesce() {
    return AsyncIterableObject.coalesce(this);
  }
  static toPromise(iterable) {
    var _a2, iterable_4, iterable_4_1;
    var _b2, e_4, _c2, _d2;
    return __awaiter$1z(this, void 0, void 0, function* () {
      const result2 = [];
      try {
        for (_a2 = true, iterable_4 = __asyncValues$2(iterable); iterable_4_1 = yield iterable_4.next(), _b2 = iterable_4_1.done, !_b2; _a2 = true) {
          _d2 = iterable_4_1.value;
          _a2 = false;
          const item = _d2;
          result2.push(item);
        }
      } catch (e_4_1) {
        e_4 = { error: e_4_1 };
      } finally {
        try {
          if (!_a2 && !_b2 && (_c2 = iterable_4.return))
            yield _c2.call(iterable_4);
        } finally {
          if (e_4)
            throw e_4.error;
        }
      }
      return result2;
    });
  }
  toPromise() {
    return AsyncIterableObject.toPromise(this);
  }
  /**
   * The value will be appended at the end.
   *
   * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.
   */
  emitOne(value) {
    if (this._state !== 0) {
      return;
    }
    this._results.push(value);
    this._onStateChanged.fire();
  }
  /**
   * The values will be appended at the end.
   *
   * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.
   */
  emitMany(values) {
    if (this._state !== 0) {
      return;
    }
    this._results = this._results.concat(values);
    this._onStateChanged.fire();
  }
  /**
   * Calling `resolve()` will mark the result array as complete.
   *
   * **NOTE** `resolve()` must be called, otherwise all consumers of this iterable will hang indefinitely, similar to a non-resolved promise.
   * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.
   */
  resolve() {
    if (this._state !== 0) {
      return;
    }
    this._state = 1;
    this._onStateChanged.fire();
  }
  /**
   * Writing an error will permanently invalidate this iterable.
   * The current users will receive an error thrown, as will all future users.
   *
   * **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.
   */
  reject(error2) {
    if (this._state !== 0) {
      return;
    }
    this._state = 2;
    this._error = error2;
    this._onStateChanged.fire();
  }
}
AsyncIterableObject.EMPTY = AsyncIterableObject.fromArray([]);
class CancelableAsyncIterableObject extends AsyncIterableObject {
  constructor(_source, executor) {
    super(executor);
    this._source = _source;
  }
  cancel() {
    this._source.cancel();
  }
}
function createCancelableAsyncIterable(callback) {
  const source = new CancellationTokenSource$1();
  const innerIterable = callback(source.token);
  return new CancelableAsyncIterableObject(source, (emitter) => __awaiter$1z(this, void 0, void 0, function* () {
    var _a2, e_5, _b2, _c2;
    const subscription = source.token.onCancellationRequested(() => {
      subscription.dispose();
      source.dispose();
      emitter.reject(new CancellationError());
    });
    try {
      try {
        for (var _d2 = true, innerIterable_1 = __asyncValues$2(innerIterable), innerIterable_1_1; innerIterable_1_1 = yield innerIterable_1.next(), _a2 = innerIterable_1_1.done, !_a2; _d2 = true) {
          _c2 = innerIterable_1_1.value;
          _d2 = false;
          const item = _c2;
          if (source.token.isCancellationRequested) {
            return;
          }
          emitter.emitOne(item);
        }
      } catch (e_5_1) {
        e_5 = { error: e_5_1 };
      } finally {
        try {
          if (!_d2 && !_a2 && (_b2 = innerIterable_1.return))
            yield _b2.call(innerIterable_1);
        } finally {
          if (e_5)
            throw e_5.error;
        }
      }
      subscription.dispose();
      source.dispose();
    } catch (err) {
      subscription.dispose();
      source.dispose();
      emitter.reject(err);
    }
  }));
}
function roundFloat(number, decimalPoints) {
  const decimal = Math.pow(10, decimalPoints);
  return Math.round(number * decimal) / decimal;
}
class RGBA {
  constructor(r, g, b, a = 1) {
    this._rgbaBrand = void 0;
    this.r = Math.min(255, Math.max(0, r)) | 0;
    this.g = Math.min(255, Math.max(0, g)) | 0;
    this.b = Math.min(255, Math.max(0, b)) | 0;
    this.a = roundFloat(Math.max(Math.min(1, a), 0), 3);
  }
  static equals(a, b) {
    return a.r === b.r && a.g === b.g && a.b === b.b && a.a === b.a;
  }
}
class HSLA {
  constructor(h2, s, l, a) {
    this._hslaBrand = void 0;
    this.h = Math.max(Math.min(360, h2), 0) | 0;
    this.s = roundFloat(Math.max(Math.min(1, s), 0), 3);
    this.l = roundFloat(Math.max(Math.min(1, l), 0), 3);
    this.a = roundFloat(Math.max(Math.min(1, a), 0), 3);
  }
  static equals(a, b) {
    return a.h === b.h && a.s === b.s && a.l === b.l && a.a === b.a;
  }
  /**
   * Converts an RGB color value to HSL. Conversion formula
   * adapted from http://en.wikipedia.org/wiki/HSL_color_space.
   * Assumes r, g, and b are contained in the set [0, 255] and
   * returns h in the set [0, 360], s, and l in the set [0, 1].
   */
  static fromRGBA(rgba) {
    const r = rgba.r / 255;
    const g = rgba.g / 255;
    const b = rgba.b / 255;
    const a = rgba.a;
    const max = Math.max(r, g, b);
    const min = Math.min(r, g, b);
    let h2 = 0;
    let s = 0;
    const l = (min + max) / 2;
    const chroma = max - min;
    if (chroma > 0) {
      s = Math.min(l <= 0.5 ? chroma / (2 * l) : chroma / (2 - 2 * l), 1);
      switch (max) {
        case r:
          h2 = (g - b) / chroma + (g < b ? 6 : 0);
          break;
        case g:
          h2 = (b - r) / chroma + 2;
          break;
        case b:
          h2 = (r - g) / chroma + 4;
          break;
      }
      h2 *= 60;
      h2 = Math.round(h2);
    }
    return new HSLA(h2, s, l, a);
  }
  static _hue2rgb(p2, q, t) {
    if (t < 0) {
      t += 1;
    }
    if (t > 1) {
      t -= 1;
    }
    if (t < 1 / 6) {
      return p2 + (q - p2) * 6 * t;
    }
    if (t < 1 / 2) {
      return q;
    }
    if (t < 2 / 3) {
      return p2 + (q - p2) * (2 / 3 - t) * 6;
    }
    return p2;
  }
  /**
   * Converts an HSL color value to RGB. Conversion formula
   * adapted from http://en.wikipedia.org/wiki/HSL_color_space.
   * Assumes h in the set [0, 360] s, and l are contained in the set [0, 1] and
   * returns r, g, and b in the set [0, 255].
   */
  static toRGBA(hsla) {
    const h2 = hsla.h / 360;
    const { s, l, a } = hsla;
    let r, g, b;
    if (s === 0) {
      r = g = b = l;
    } else {
      const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
      const p2 = 2 * l - q;
      r = HSLA._hue2rgb(p2, q, h2 + 1 / 3);
      g = HSLA._hue2rgb(p2, q, h2);
      b = HSLA._hue2rgb(p2, q, h2 - 1 / 3);
    }
    return new RGBA(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), a);
  }
}
class HSVA {
  constructor(h2, s, v, a) {
    this._hsvaBrand = void 0;
    this.h = Math.max(Math.min(360, h2), 0) | 0;
    this.s = roundFloat(Math.max(Math.min(1, s), 0), 3);
    this.v = roundFloat(Math.max(Math.min(1, v), 0), 3);
    this.a = roundFloat(Math.max(Math.min(1, a), 0), 3);
  }
  static equals(a, b) {
    return a.h === b.h && a.s === b.s && a.v === b.v && a.a === b.a;
  }
  // from http://www.rapidtables.com/convert/color/rgb-to-hsv.htm
  static fromRGBA(rgba) {
    const r = rgba.r / 255;
    const g = rgba.g / 255;
    const b = rgba.b / 255;
    const cmax = Math.max(r, g, b);
    const cmin = Math.min(r, g, b);
    const delta = cmax - cmin;
    const s = cmax === 0 ? 0 : delta / cmax;
    let m;
    if (delta === 0) {
      m = 0;
    } else if (cmax === r) {
      m = ((g - b) / delta % 6 + 6) % 6;
    } else if (cmax === g) {
      m = (b - r) / delta + 2;
    } else {
      m = (r - g) / delta + 4;
    }
    return new HSVA(Math.round(m * 60), s, cmax, rgba.a);
  }
  // from http://www.rapidtables.com/convert/color/hsv-to-rgb.htm
  static toRGBA(hsva) {
    const { h: h2, s, v, a } = hsva;
    const c = v * s;
    const x = c * (1 - Math.abs(h2 / 60 % 2 - 1));
    const m = v - c;
    let [r, g, b] = [0, 0, 0];
    if (h2 < 60) {
      r = c;
      g = x;
    } else if (h2 < 120) {
      r = x;
      g = c;
    } else if (h2 < 180) {
      g = c;
      b = x;
    } else if (h2 < 240) {
      g = x;
      b = c;
    } else if (h2 < 300) {
      r = x;
      b = c;
    } else if (h2 <= 360) {
      r = c;
      b = x;
    }
    r = Math.round((r + m) * 255);
    g = Math.round((g + m) * 255);
    b = Math.round((b + m) * 255);
    return new RGBA(r, g, b, a);
  }
}
class Color {
  static fromHex(hex) {
    return Color.Format.CSS.parseHex(hex) || Color.red;
  }
  static equals(a, b) {
    if (!a && !b) {
      return true;
    }
    if (!a || !b) {
      return false;
    }
    return a.equals(b);
  }
  get hsla() {
    if (this._hsla) {
      return this._hsla;
    } else {
      return HSLA.fromRGBA(this.rgba);
    }
  }
  get hsva() {
    if (this._hsva) {
      return this._hsva;
    }
    return HSVA.fromRGBA(this.rgba);
  }
  constructor(arg) {
    if (!arg) {
      throw new Error("Color needs a value");
    } else if (arg instanceof RGBA) {
      this.rgba = arg;
    } else if (arg instanceof HSLA) {
      this._hsla = arg;
      this.rgba = HSLA.toRGBA(arg);
    } else if (arg instanceof HSVA) {
      this._hsva = arg;
      this.rgba = HSVA.toRGBA(arg);
    } else {
      throw new Error("Invalid color ctor argument");
    }
  }
  equals(other) {
    return !!other && RGBA.equals(this.rgba, other.rgba) && HSLA.equals(this.hsla, other.hsla) && HSVA.equals(this.hsva, other.hsva);
  }
  /**
   * http://www.w3.org/TR/WCAG20/#relativeluminancedef
   * Returns the number in the set [0, 1]. O => Darkest Black. 1 => Lightest white.
   */
  getRelativeLuminance() {
    const R = Color._relativeLuminanceForComponent(this.rgba.r);
    const G = Color._relativeLuminanceForComponent(this.rgba.g);
    const B = Color._relativeLuminanceForComponent(this.rgba.b);
    const luminance = 0.2126 * R + 0.7152 * G + 0.0722 * B;
    return roundFloat(luminance, 4);
  }
  static _relativeLuminanceForComponent(color) {
    const c = color / 255;
    return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
  }
  /**
   *	http://24ways.org/2010/calculating-color-contrast
   *  Return 'true' if lighter color otherwise 'false'
   */
  isLighter() {
    const yiq = (this.rgba.r * 299 + this.rgba.g * 587 + this.rgba.b * 114) / 1e3;
    return yiq >= 128;
  }
  isLighterThan(another) {
    const lum1 = this.getRelativeLuminance();
    const lum2 = another.getRelativeLuminance();
    return lum1 > lum2;
  }
  isDarkerThan(another) {
    const lum1 = this.getRelativeLuminance();
    const lum2 = another.getRelativeLuminance();
    return lum1 < lum2;
  }
  lighten(factor2) {
    return new Color(new HSLA(this.hsla.h, this.hsla.s, this.hsla.l + this.hsla.l * factor2, this.hsla.a));
  }
  darken(factor2) {
    return new Color(new HSLA(this.hsla.h, this.hsla.s, this.hsla.l - this.hsla.l * factor2, this.hsla.a));
  }
  transparent(factor2) {
    const { r, g, b, a } = this.rgba;
    return new Color(new RGBA(r, g, b, a * factor2));
  }
  isTransparent() {
    return this.rgba.a === 0;
  }
  isOpaque() {
    return this.rgba.a === 1;
  }
  opposite() {
    return new Color(new RGBA(255 - this.rgba.r, 255 - this.rgba.g, 255 - this.rgba.b, this.rgba.a));
  }
  makeOpaque(opaqueBackground) {
    if (this.isOpaque() || opaqueBackground.rgba.a !== 1) {
      return this;
    }
    const { r, g, b, a } = this.rgba;
    return new Color(new RGBA(opaqueBackground.rgba.r - a * (opaqueBackground.rgba.r - r), opaqueBackground.rgba.g - a * (opaqueBackground.rgba.g - g), opaqueBackground.rgba.b - a * (opaqueBackground.rgba.b - b), 1));
  }
  toString() {
    if (!this._toString) {
      this._toString = Color.Format.CSS.format(this);
    }
    return this._toString;
  }
  static getLighterColor(of, relative2, factor2) {
    if (of.isLighterThan(relative2)) {
      return of;
    }
    factor2 = factor2 ? factor2 : 0.5;
    const lum1 = of.getRelativeLuminance();
    const lum2 = relative2.getRelativeLuminance();
    factor2 = factor2 * (lum2 - lum1) / lum2;
    return of.lighten(factor2);
  }
  static getDarkerColor(of, relative2, factor2) {
    if (of.isDarkerThan(relative2)) {
      return of;
    }
    factor2 = factor2 ? factor2 : 0.5;
    const lum1 = of.getRelativeLuminance();
    const lum2 = relative2.getRelativeLuminance();
    factor2 = factor2 * (lum1 - lum2) / lum1;
    return of.darken(factor2);
  }
}
Color.white = new Color(new RGBA(255, 255, 255, 1));
Color.black = new Color(new RGBA(0, 0, 0, 1));
Color.red = new Color(new RGBA(255, 0, 0, 1));
Color.blue = new Color(new RGBA(0, 0, 255, 1));
Color.green = new Color(new RGBA(0, 255, 0, 1));
Color.cyan = new Color(new RGBA(0, 255, 255, 1));
Color.lightgrey = new Color(new RGBA(211, 211, 211, 1));
Color.transparent = new Color(new RGBA(0, 0, 0, 0));
(function(Color2) {
  (function(Format) {
    (function(CSS) {
      function formatRGB(color) {
        if (color.rgba.a === 1) {
          return `rgb(${color.rgba.r}, ${color.rgba.g}, ${color.rgba.b})`;
        }
        return Color2.Format.CSS.formatRGBA(color);
      }
      CSS.formatRGB = formatRGB;
      function formatRGBA(color) {
        return `rgba(${color.rgba.r}, ${color.rgba.g}, ${color.rgba.b}, ${+color.rgba.a.toFixed(2)})`;
      }
      CSS.formatRGBA = formatRGBA;
      function formatHSL(color) {
        if (color.hsla.a === 1) {
          return `hsl(${color.hsla.h}, ${(color.hsla.s * 100).toFixed(2)}%, ${(color.hsla.l * 100).toFixed(2)}%)`;
        }
        return Color2.Format.CSS.formatHSLA(color);
      }
      CSS.formatHSL = formatHSL;
      function formatHSLA(color) {
        return `hsla(${color.hsla.h}, ${(color.hsla.s * 100).toFixed(2)}%, ${(color.hsla.l * 100).toFixed(2)}%, ${color.hsla.a.toFixed(2)})`;
      }
      CSS.formatHSLA = formatHSLA;
      function _toTwoDigitHex(n2) {
        const r = n2.toString(16);
        return r.length !== 2 ? "0" + r : r;
      }
      function formatHex(color) {
        return `#${_toTwoDigitHex(color.rgba.r)}${_toTwoDigitHex(color.rgba.g)}${_toTwoDigitHex(color.rgba.b)}`;
      }
      CSS.formatHex = formatHex;
      function formatHexA(color, compact = false) {
        if (compact && color.rgba.a === 1) {
          return Color2.Format.CSS.formatHex(color);
        }
        return `#${_toTwoDigitHex(color.rgba.r)}${_toTwoDigitHex(color.rgba.g)}${_toTwoDigitHex(color.rgba.b)}${_toTwoDigitHex(Math.round(color.rgba.a * 255))}`;
      }
      CSS.formatHexA = formatHexA;
      function format2(color) {
        if (color.isOpaque()) {
          return Color2.Format.CSS.formatHex(color);
        }
        return Color2.Format.CSS.formatRGBA(color);
      }
      CSS.format = format2;
      function parseHex(hex) {
        const length2 = hex.length;
        if (length2 === 0) {
          return null;
        }
        if (hex.charCodeAt(0) !== 35) {
          return null;
        }
        if (length2 === 7) {
          const r = 16 * _parseHexDigit(hex.charCodeAt(1)) + _parseHexDigit(hex.charCodeAt(2));
          const g = 16 * _parseHexDigit(hex.charCodeAt(3)) + _parseHexDigit(hex.charCodeAt(4));
          const b = 16 * _parseHexDigit(hex.charCodeAt(5)) + _parseHexDigit(hex.charCodeAt(6));
          return new Color2(new RGBA(r, g, b, 1));
        }
        if (length2 === 9) {
          const r = 16 * _parseHexDigit(hex.charCodeAt(1)) + _parseHexDigit(hex.charCodeAt(2));
          const g = 16 * _parseHexDigit(hex.charCodeAt(3)) + _parseHexDigit(hex.charCodeAt(4));
          const b = 16 * _parseHexDigit(hex.charCodeAt(5)) + _parseHexDigit(hex.charCodeAt(6));
          const a = 16 * _parseHexDigit(hex.charCodeAt(7)) + _parseHexDigit(hex.charCodeAt(8));
          return new Color2(new RGBA(r, g, b, a / 255));
        }
        if (length2 === 4) {
          const r = _parseHexDigit(hex.charCodeAt(1));
          const g = _parseHexDigit(hex.charCodeAt(2));
          const b = _parseHexDigit(hex.charCodeAt(3));
          return new Color2(new RGBA(16 * r + r, 16 * g + g, 16 * b + b));
        }
        if (length2 === 5) {
          const r = _parseHexDigit(hex.charCodeAt(1));
          const g = _parseHexDigit(hex.charCodeAt(2));
          const b = _parseHexDigit(hex.charCodeAt(3));
          const a = _parseHexDigit(hex.charCodeAt(4));
          return new Color2(new RGBA(16 * r + r, 16 * g + g, 16 * b + b, (16 * a + a) / 255));
        }
        return null;
      }
      CSS.parseHex = parseHex;
      function _parseHexDigit(charCode) {
        switch (charCode) {
          case 48:
            return 0;
          case 49:
            return 1;
          case 50:
            return 2;
          case 51:
            return 3;
          case 52:
            return 4;
          case 53:
            return 5;
          case 54:
            return 6;
          case 55:
            return 7;
          case 56:
            return 8;
          case 57:
            return 9;
          case 97:
            return 10;
          case 65:
            return 10;
          case 98:
            return 11;
          case 66:
            return 11;
          case 99:
            return 12;
          case 67:
            return 12;
          case 100:
            return 13;
          case 68:
            return 13;
          case 101:
            return 14;
          case 69:
            return 14;
          case 102:
            return 15;
          case 70:
            return 15;
        }
        return 0;
      }
    })(Format.CSS || (Format.CSS = {}));
  })(Color2.Format || (Color2.Format = {}));
})(Color || (Color = {}));
function asCssVariableName(colorIdent) {
  return `--vscode-${colorIdent.replace(/\./g, "-")}`;
}
function asCssVariable(color) {
  return `var(${asCssVariableName(color)})`;
}
function asCssVariableWithDefault(color, defaultCssValue) {
  return `var(${asCssVariableName(color)}, ${defaultCssValue})`;
}
const Extensions$4 = {
  ColorContribution: "base.contributions.colors"
};
class ColorRegistry {
  constructor() {
    this._onDidChangeSchema = new Emitter$1();
    this.onDidChangeSchema = this._onDidChangeSchema.event;
    this.colorSchema = { type: "object", properties: {} };
    this.colorReferenceSchema = { type: "string", enum: [], enumDescriptions: [] };
    this.colorsById = {};
  }
  registerColor(id3, defaults, description, needsTransparency = false, deprecationMessage) {
    const colorContribution = { id: id3, description, defaults, needsTransparency, deprecationMessage };
    this.colorsById[id3] = colorContribution;
    const propertySchema = { type: "string", description, format: "color-hex", defaultSnippets: [{ body: "${1:#ff0000}" }] };
    if (deprecationMessage) {
      propertySchema.deprecationMessage = deprecationMessage;
    }
    this.colorSchema.properties[id3] = propertySchema;
    this.colorReferenceSchema.enum.push(id3);
    this.colorReferenceSchema.enumDescriptions.push(description);
    this._onDidChangeSchema.fire();
    return id3;
  }
  getColors() {
    return Object.keys(this.colorsById).map((id3) => this.colorsById[id3]);
  }
  resolveDefaultColor(id3, theme) {
    const colorDesc = this.colorsById[id3];
    if (colorDesc && colorDesc.defaults) {
      const colorValue = colorDesc.defaults[theme.type];
      return resolveColorValue(colorValue, theme);
    }
    return void 0;
  }
  getColorSchema() {
    return this.colorSchema;
  }
  toString() {
    const sorter2 = (a, b) => {
      const cat1 = a.indexOf(".") === -1 ? 0 : 1;
      const cat2 = b.indexOf(".") === -1 ? 0 : 1;
      if (cat1 !== cat2) {
        return cat1 - cat2;
      }
      return a.localeCompare(b);
    };
    return Object.keys(this.colorsById).sort(sorter2).map((k) => `- \`${k}\`: ${this.colorsById[k].description}`).join("\n");
  }
}
const colorRegistry$1 = new ColorRegistry();
Registry.add(Extensions$4.ColorContribution, colorRegistry$1);
function registerColor(id3, defaults, description, needsTransparency, deprecationMessage) {
  return colorRegistry$1.registerColor(id3, defaults, description, needsTransparency, deprecationMessage);
}
const foreground = registerColor("foreground", { dark: "#CCCCCC", light: "#616161", hcDark: "#FFFFFF", hcLight: "#292929" }, localize("foreground", "Overall foreground color. This color is only used if not overridden by a component."));
registerColor("disabledForeground", { dark: "#CCCCCC80", light: "#61616180", hcDark: "#A5A5A5", hcLight: "#7F7F7F" }, localize("disabledForeground", "Overall foreground for disabled elements. This color is only used if not overridden by a component."));
const errorForeground = registerColor("errorForeground", { dark: "#F48771", light: "#A1260D", hcDark: "#F48771", hcLight: "#B5200D" }, localize("errorForeground", "Overall foreground color for error messages. This color is only used if not overridden by a component."));
registerColor("descriptionForeground", { light: "#717171", dark: transparent(foreground, 0.7), hcDark: transparent(foreground, 0.7), hcLight: transparent(foreground, 0.7) }, localize("descriptionForeground", "Foreground color for description text providing additional information, for example for a label."));
const iconForeground = registerColor("icon.foreground", { dark: "#C5C5C5", light: "#424242", hcDark: "#FFFFFF", hcLight: "#292929" }, localize("iconForeground", "The default color for icons in the workbench."));
const focusBorder = registerColor("focusBorder", { dark: "#007FD4", light: "#0090F1", hcDark: "#F38518", hcLight: "#006BBD" }, localize("focusBorder", "Overall border color for focused elements. This color is only used if not overridden by a component."));
const contrastBorder = registerColor("contrastBorder", { light: null, dark: null, hcDark: "#6FC3DF", hcLight: "#0F4A85" }, localize("contrastBorder", "An extra border around elements to separate them from others for greater contrast."));
const activeContrastBorder = registerColor("contrastActiveBorder", { light: null, dark: null, hcDark: focusBorder, hcLight: focusBorder }, localize("activeContrastBorder", "An extra border around active elements to separate them from others for greater contrast."));
registerColor("selection.background", { light: null, dark: null, hcDark: null, hcLight: null }, localize("selectionBackground", "The background color of text selections in the workbench (e.g. for input fields or text areas). Note that this does not apply to selections within the editor."));
registerColor("textSeparator.foreground", { light: "#0000002e", dark: "#ffffff2e", hcDark: Color.black, hcLight: "#292929" }, localize("textSeparatorForeground", "Color for text separators."));
const textLinkForeground = registerColor("textLink.foreground", { light: "#006AB1", dark: "#3794FF", hcDark: "#3794FF", hcLight: "#0F4A85" }, localize("textLinkForeground", "Foreground color for links in text."));
registerColor("textLink.activeForeground", { light: "#006AB1", dark: "#3794FF", hcDark: "#3794FF", hcLight: "#0F4A85" }, localize("textLinkActiveForeground", "Foreground color for links in text when clicked on and on mouse hover."));
registerColor("textPreformat.foreground", { light: "#A31515", dark: "#D7BA7D", hcDark: "#D7BA7D", hcLight: "#292929" }, localize("textPreformatForeground", "Foreground color for preformatted text segments."));
registerColor("textBlockQuote.background", { light: "#7f7f7f1a", dark: "#7f7f7f1a", hcDark: null, hcLight: "#F2F2F2" }, localize("textBlockQuoteBackground", "Background color for block quotes in text."));
registerColor("textBlockQuote.border", { light: "#007acc80", dark: "#007acc80", hcDark: Color.white, hcLight: "#292929" }, localize("textBlockQuoteBorder", "Border color for block quotes in text."));
registerColor("textCodeBlock.background", { light: "#dcdcdc66", dark: "#0a0a0a66", hcDark: Color.black, hcLight: "#F2F2F2" }, localize("textCodeBlockBackground", "Background color for code blocks in text."));
const widgetShadow = registerColor("widget.shadow", { dark: transparent(Color.black, 0.36), light: transparent(Color.black, 0.16), hcDark: null, hcLight: null }, localize("widgetShadow", "Shadow color of widgets such as find/replace inside the editor."));
const widgetBorder = registerColor("widget.border", { dark: null, light: null, hcDark: contrastBorder, hcLight: contrastBorder }, localize("widgetBorder", "Border color of widgets such as find/replace inside the editor."));
const inputBackground = registerColor("input.background", { dark: "#3C3C3C", light: Color.white, hcDark: Color.black, hcLight: Color.white }, localize("inputBoxBackground", "Input box background."));
const inputForeground = registerColor("input.foreground", { dark: foreground, light: foreground, hcDark: foreground, hcLight: foreground }, localize("inputBoxForeground", "Input box foreground."));
const inputBorder = registerColor("input.border", { dark: null, light: null, hcDark: contrastBorder, hcLight: contrastBorder }, localize("inputBoxBorder", "Input box border."));
const inputActiveOptionBorder = registerColor("inputOption.activeBorder", { dark: "#007ACC", light: "#007ACC", hcDark: contrastBorder, hcLight: contrastBorder }, localize("inputBoxActiveOptionBorder", "Border color of activated options in input fields."));
registerColor("inputOption.hoverBackground", { dark: "#5a5d5e80", light: "#b8b8b850", hcDark: null, hcLight: null }, localize("inputOption.hoverBackground", "Background color of activated options in input fields."));
const inputActiveOptionBackground = registerColor("inputOption.activeBackground", { dark: transparent(focusBorder, 0.4), light: transparent(focusBorder, 0.2), hcDark: Color.transparent, hcLight: Color.transparent }, localize("inputOption.activeBackground", "Background hover color of options in input fields."));
const inputActiveOptionForeground = registerColor("inputOption.activeForeground", { dark: Color.white, light: Color.black, hcDark: foreground, hcLight: foreground }, localize("inputOption.activeForeground", "Foreground color of activated options in input fields."));
registerColor("input.placeholderForeground", { light: transparent(foreground, 0.5), dark: transparent(foreground, 0.5), hcDark: transparent(foreground, 0.7), hcLight: transparent(foreground, 0.7) }, localize("inputPlaceholderForeground", "Input box foreground color for placeholder text."));
const inputValidationInfoBackground = registerColor("inputValidation.infoBackground", { dark: "#063B49", light: "#D6ECF2", hcDark: Color.black, hcLight: Color.white }, localize("inputValidationInfoBackground", "Input validation background color for information severity."));
const inputValidationInfoForeground = registerColor("inputValidation.infoForeground", { dark: null, light: null, hcDark: null, hcLight: foreground }, localize("inputValidationInfoForeground", "Input validation foreground color for information severity."));
const inputValidationInfoBorder = registerColor("inputValidation.infoBorder", { dark: "#007acc", light: "#007acc", hcDark: contrastBorder, hcLight: contrastBorder }, localize("inputValidationInfoBorder", "Input validation border color for information severity."));
const inputValidationWarningBackground = registerColor("inputValidation.warningBackground", { dark: "#352A05", light: "#F6F5D2", hcDark: Color.black, hcLight: Color.white }, localize("inputValidationWarningBackground", "Input validation background color for warning severity."));
const inputValidationWarningForeground = registerColor("inputValidation.warningForeground", { dark: null, light: null, hcDark: null, hcLight: foreground }, localize("inputValidationWarningForeground", "Input validation foreground color for warning severity."));
const inputValidationWarningBorder = registerColor("inputValidation.warningBorder", { dark: "#B89500", light: "#B89500", hcDark: contrastBorder, hcLight: contrastBorder }, localize("inputValidationWarningBorder", "Input validation border color for warning severity."));
const inputValidationErrorBackground = registerColor("inputValidation.errorBackground", { dark: "#5A1D1D", light: "#F2DEDE", hcDark: Color.black, hcLight: Color.white }, localize("inputValidationErrorBackground", "Input validation background color for error severity."));
const inputValidationErrorForeground = registerColor("inputValidation.errorForeground", { dark: null, light: null, hcDark: null, hcLight: foreground }, localize("inputValidationErrorForeground", "Input validation foreground color for error severity."));
const inputValidationErrorBorder = registerColor("inputValidation.errorBorder", { dark: "#BE1100", light: "#BE1100", hcDark: contrastBorder, hcLight: contrastBorder }, localize("inputValidationErrorBorder", "Input validation border color for error severity."));
const selectBackground = registerColor("dropdown.background", { dark: "#3C3C3C", light: Color.white, hcDark: Color.black, hcLight: Color.white }, localize("dropdownBackground", "Dropdown background."));
const selectListBackground = registerColor("dropdown.listBackground", { dark: null, light: null, hcDark: Color.black, hcLight: Color.white }, localize("dropdownListBackground", "Dropdown list background."));
const selectForeground = registerColor("dropdown.foreground", { dark: "#F0F0F0", light: foreground, hcDark: Color.white, hcLight: foreground }, localize("dropdownForeground", "Dropdown foreground."));
const selectBorder = registerColor("dropdown.border", { dark: selectBackground, light: "#CECECE", hcDark: contrastBorder, hcLight: contrastBorder }, localize("dropdownBorder", "Dropdown border."));
const buttonForeground = registerColor("button.foreground", { dark: Color.white, light: Color.white, hcDark: Color.white, hcLight: Color.white }, localize("buttonForeground", "Button foreground color."));
const buttonSeparator = registerColor("button.separator", { dark: transparent(buttonForeground, 0.4), light: transparent(buttonForeground, 0.4), hcDark: transparent(buttonForeground, 0.4), hcLight: transparent(buttonForeground, 0.4) }, localize("buttonSeparator", "Button separator color."));
const buttonBackground = registerColor("button.background", { dark: "#0E639C", light: "#007ACC", hcDark: null, hcLight: "#0F4A85" }, localize("buttonBackground", "Button background color."));
const buttonHoverBackground = registerColor("button.hoverBackground", { dark: lighten(buttonBackground, 0.2), light: darken(buttonBackground, 0.2), hcDark: buttonBackground, hcLight: buttonBackground }, localize("buttonHoverBackground", "Button background color when hovering."));
const buttonBorder = registerColor("button.border", { dark: contrastBorder, light: contrastBorder, hcDark: contrastBorder, hcLight: contrastBorder }, localize("buttonBorder", "Button border color."));
const buttonSecondaryForeground = registerColor("button.secondaryForeground", { dark: Color.white, light: Color.white, hcDark: Color.white, hcLight: foreground }, localize("buttonSecondaryForeground", "Secondary button foreground color."));
const buttonSecondaryBackground = registerColor("button.secondaryBackground", { dark: "#3A3D41", light: "#5F6A79", hcDark: null, hcLight: Color.white }, localize("buttonSecondaryBackground", "Secondary button background color."));
const buttonSecondaryHoverBackground = registerColor("button.secondaryHoverBackground", { dark: lighten(buttonSecondaryBackground, 0.2), light: darken(buttonSecondaryBackground, 0.2), hcDark: null, hcLight: null }, localize("buttonSecondaryHoverBackground", "Secondary button background color when hovering."));
const badgeBackground = registerColor("badge.background", { dark: "#4D4D4D", light: "#C4C4C4", hcDark: Color.black, hcLight: "#0F4A85" }, localize("badgeBackground", "Badge background color. Badges are small information labels, e.g. for search results count."));
const badgeForeground = registerColor("badge.foreground", { dark: Color.white, light: "#333", hcDark: Color.white, hcLight: Color.white }, localize("badgeForeground", "Badge foreground color. Badges are small information labels, e.g. for search results count."));
const scrollbarShadow = registerColor("scrollbar.shadow", { dark: "#000000", light: "#DDDDDD", hcDark: null, hcLight: null }, localize("scrollbarShadow", "Scrollbar shadow to indicate that the view is scrolled."));
const scrollbarSliderBackground = registerColor("scrollbarSlider.background", { dark: Color.fromHex("#797979").transparent(0.4), light: Color.fromHex("#646464").transparent(0.4), hcDark: transparent(contrastBorder, 0.6), hcLight: transparent(contrastBorder, 0.4) }, localize("scrollbarSliderBackground", "Scrollbar slider background color."));
const scrollbarSliderHoverBackground = registerColor("scrollbarSlider.hoverBackground", { dark: Color.fromHex("#646464").transparent(0.7), light: Color.fromHex("#646464").transparent(0.7), hcDark: transparent(contrastBorder, 0.8), hcLight: transparent(contrastBorder, 0.8) }, localize("scrollbarSliderHoverBackground", "Scrollbar slider background color when hovering."));
const scrollbarSliderActiveBackground = registerColor("scrollbarSlider.activeBackground", { dark: Color.fromHex("#BFBFBF").transparent(0.4), light: Color.fromHex("#000000").transparent(0.6), hcDark: contrastBorder, hcLight: contrastBorder }, localize("scrollbarSliderActiveBackground", "Scrollbar slider background color when clicked on."));
const progressBarBackground = registerColor("progressBar.background", { dark: Color.fromHex("#0E70C0"), light: Color.fromHex("#0E70C0"), hcDark: contrastBorder, hcLight: contrastBorder }, localize("progressBarBackground", "Background color of the progress bar that can show for long running operations."));
registerColor("editorError.background", { dark: null, light: null, hcDark: null, hcLight: null }, localize("editorError.background", "Background color of error text in the editor. The color must not be opaque so as not to hide underlying decorations."), true);
const editorErrorForeground = registerColor("editorError.foreground", { dark: "#F14C4C", light: "#E51400", hcDark: "#F48771", hcLight: "#B5200D" }, localize("editorError.foreground", "Foreground color of error squigglies in the editor."));
const editorErrorBorder = registerColor("editorError.border", { dark: null, light: null, hcDark: Color.fromHex("#E47777").transparent(0.8), hcLight: "#B5200D" }, localize("errorBorder", "If set, color of double underlines for errors in the editor."));
registerColor("editorWarning.background", { dark: null, light: null, hcDark: null, hcLight: null }, localize("editorWarning.background", "Background color of warning text in the editor. The color must not be opaque so as not to hide underlying decorations."), true);
const editorWarningForeground = registerColor("editorWarning.foreground", { dark: "#CCA700", light: "#BF8803", hcDark: "#FFD370", hcLight: "#895503" }, localize("editorWarning.foreground", "Foreground color of warning squigglies in the editor."));
const editorWarningBorder = registerColor("editorWarning.border", { dark: null, light: null, hcDark: Color.fromHex("#FFCC00").transparent(0.8), hcLight: Color.fromHex("#FFCC00").transparent(0.8) }, localize("warningBorder", "If set, color of double underlines for warnings in the editor."));
registerColor("editorInfo.background", { dark: null, light: null, hcDark: null, hcLight: null }, localize("editorInfo.background", "Background color of info text in the editor. The color must not be opaque so as not to hide underlying decorations."), true);
const editorInfoForeground = registerColor("editorInfo.foreground", { dark: "#3794FF", light: "#1a85ff", hcDark: "#3794FF", hcLight: "#1a85ff" }, localize("editorInfo.foreground", "Foreground color of info squigglies in the editor."));
const editorInfoBorder = registerColor("editorInfo.border", { dark: null, light: null, hcDark: Color.fromHex("#3794FF").transparent(0.8), hcLight: "#292929" }, localize("infoBorder", "If set, color of double underlines for infos in the editor."));
const editorHintForeground = registerColor("editorHint.foreground", { dark: Color.fromHex("#eeeeee").transparent(0.7), light: "#6c6c6c", hcDark: null, hcLight: null }, localize("editorHint.foreground", "Foreground color of hint squigglies in the editor."));
registerColor("editorHint.border", { dark: null, light: null, hcDark: Color.fromHex("#eeeeee").transparent(0.8), hcLight: "#292929" }, localize("hintBorder", "If set, color of double underlines for hints in the editor."));
registerColor("sash.hoverBorder", { dark: focusBorder, light: focusBorder, hcDark: focusBorder, hcLight: focusBorder }, localize("sashActiveBorder", "Border color of active sashes."));
const editorBackground = registerColor("editor.background", { light: "#ffffff", dark: "#1E1E1E", hcDark: Color.black, hcLight: Color.white }, localize("editorBackground", "Editor background color."));
const editorForeground = registerColor("editor.foreground", { light: "#333333", dark: "#BBBBBB", hcDark: Color.white, hcLight: foreground }, localize("editorForeground", "Editor default foreground color."));
registerColor("editorStickyScroll.background", { light: editorBackground, dark: editorBackground, hcDark: editorBackground, hcLight: editorBackground }, localize("editorStickyScrollBackground", "Sticky scroll background color for the editor"));
registerColor("editorStickyScrollHover.background", { dark: "#2A2D2E", light: "#F0F0F0", hcDark: null, hcLight: Color.fromHex("#0F4A85").transparent(0.1) }, localize("editorStickyScrollHoverBackground", "Sticky scroll on hover background color for the editor"));
const editorWidgetBackground = registerColor("editorWidget.background", { dark: "#252526", light: "#F3F3F3", hcDark: "#0C141F", hcLight: Color.white }, localize("editorWidgetBackground", "Background color of editor widgets, such as find/replace."));
const editorWidgetForeground = registerColor("editorWidget.foreground", { dark: foreground, light: foreground, hcDark: foreground, hcLight: foreground }, localize("editorWidgetForeground", "Foreground color of editor widgets, such as find/replace."));
const editorWidgetBorder = registerColor("editorWidget.border", { dark: "#454545", light: "#C8C8C8", hcDark: contrastBorder, hcLight: contrastBorder }, localize("editorWidgetBorder", "Border color of editor widgets. The color is only used if the widget chooses to have a border and if the color is not overridden by a widget."));
const editorWidgetResizeBorder = registerColor("editorWidget.resizeBorder", { light: null, dark: null, hcDark: null, hcLight: null }, localize("editorWidgetResizeBorder", "Border color of the resize bar of editor widgets. The color is only used if the widget chooses to have a resize border and if the color is not overridden by a widget."));
const quickInputBackground = registerColor("quickInput.background", { dark: editorWidgetBackground, light: editorWidgetBackground, hcDark: editorWidgetBackground, hcLight: editorWidgetBackground }, localize("pickerBackground", "Quick picker background color. The quick picker widget is the container for pickers like the command palette."));
const quickInputForeground = registerColor("quickInput.foreground", { dark: editorWidgetForeground, light: editorWidgetForeground, hcDark: editorWidgetForeground, hcLight: editorWidgetForeground }, localize("pickerForeground", "Quick picker foreground color. The quick picker widget is the container for pickers like the command palette."));
const quickInputTitleBackground = registerColor("quickInputTitle.background", { dark: new Color(new RGBA(255, 255, 255, 0.105)), light: new Color(new RGBA(0, 0, 0, 0.06)), hcDark: "#000000", hcLight: Color.white }, localize("pickerTitleBackground", "Quick picker title background color. The quick picker widget is the container for pickers like the command palette."));
const pickerGroupForeground = registerColor("pickerGroup.foreground", { dark: "#3794FF", light: "#0066BF", hcDark: Color.white, hcLight: "#0F4A85" }, localize("pickerGroupForeground", "Quick picker color for grouping labels."));
const pickerGroupBorder = registerColor("pickerGroup.border", { dark: "#3F3F46", light: "#CCCEDB", hcDark: Color.white, hcLight: "#0F4A85" }, localize("pickerGroupBorder", "Quick picker color for grouping borders."));
const keybindingLabelBackground = registerColor("keybindingLabel.background", { dark: new Color(new RGBA(128, 128, 128, 0.17)), light: new Color(new RGBA(221, 221, 221, 0.4)), hcDark: Color.transparent, hcLight: Color.transparent }, localize("keybindingLabelBackground", "Keybinding label background color. The keybinding label is used to represent a keyboard shortcut."));
const keybindingLabelForeground = registerColor("keybindingLabel.foreground", { dark: Color.fromHex("#CCCCCC"), light: Color.fromHex("#555555"), hcDark: Color.white, hcLight: foreground }, localize("keybindingLabelForeground", "Keybinding label foreground color. The keybinding label is used to represent a keyboard shortcut."));
const keybindingLabelBorder = registerColor("keybindingLabel.border", { dark: new Color(new RGBA(51, 51, 51, 0.6)), light: new Color(new RGBA(204, 204, 204, 0.4)), hcDark: new Color(new RGBA(111, 195, 223)), hcLight: contrastBorder }, localize("keybindingLabelBorder", "Keybinding label border color. The keybinding label is used to represent a keyboard shortcut."));
const keybindingLabelBottomBorder = registerColor("keybindingLabel.bottomBorder", { dark: new Color(new RGBA(68, 68, 68, 0.6)), light: new Color(new RGBA(187, 187, 187, 0.4)), hcDark: new Color(new RGBA(111, 195, 223)), hcLight: foreground }, localize("keybindingLabelBottomBorder", "Keybinding label border bottom color. The keybinding label is used to represent a keyboard shortcut."));
const editorSelectionBackground = registerColor("editor.selectionBackground", { light: "#ADD6FF", dark: "#264F78", hcDark: "#f3f518", hcLight: "#0F4A85" }, localize("editorSelectionBackground", "Color of the editor selection."));
const editorSelectionForeground = registerColor("editor.selectionForeground", { light: null, dark: null, hcDark: "#000000", hcLight: Color.white }, localize("editorSelectionForeground", "Color of the selected text for high contrast."));
const editorInactiveSelection = registerColor("editor.inactiveSelectionBackground", { light: transparent(editorSelectionBackground, 0.5), dark: transparent(editorSelectionBackground, 0.5), hcDark: transparent(editorSelectionBackground, 0.7), hcLight: transparent(editorSelectionBackground, 0.5) }, localize("editorInactiveSelection", "Color of the selection in an inactive editor. The color must not be opaque so as not to hide underlying decorations."), true);
const editorSelectionHighlight = registerColor("editor.selectionHighlightBackground", { light: lessProminent(editorSelectionBackground, editorBackground, 0.3, 0.6), dark: lessProminent(editorSelectionBackground, editorBackground, 0.3, 0.6), hcDark: null, hcLight: null }, localize("editorSelectionHighlight", "Color for regions with the same content as the selection. The color must not be opaque so as not to hide underlying decorations."), true);
registerColor("editor.selectionHighlightBorder", { light: null, dark: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize("editorSelectionHighlightBorder", "Border color for regions with the same content as the selection."));
const editorFindMatch = registerColor("editor.findMatchBackground", { light: "#A8AC94", dark: "#515C6A", hcDark: null, hcLight: null }, localize("editorFindMatch", "Color of the current search match."));
const editorFindMatchHighlight = registerColor("editor.findMatchHighlightBackground", { light: "#EA5C0055", dark: "#EA5C0055", hcDark: null, hcLight: null }, localize("findMatchHighlight", "Color of the other search matches. The color must not be opaque so as not to hide underlying decorations."), true);
const editorFindRangeHighlight = registerColor("editor.findRangeHighlightBackground", { dark: "#3a3d4166", light: "#b4b4b44d", hcDark: null, hcLight: null }, localize("findRangeHighlight", "Color of the range limiting the search. The color must not be opaque so as not to hide underlying decorations."), true);
const editorFindMatchBorder = registerColor("editor.findMatchBorder", { light: null, dark: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize("editorFindMatchBorder", "Border color of the current search match."));
const editorFindMatchHighlightBorder = registerColor("editor.findMatchHighlightBorder", { light: null, dark: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize("findMatchHighlightBorder", "Border color of the other search matches."));
const editorFindRangeHighlightBorder = registerColor("editor.findRangeHighlightBorder", { dark: null, light: null, hcDark: transparent(activeContrastBorder, 0.4), hcLight: transparent(activeContrastBorder, 0.4) }, localize("findRangeHighlightBorder", "Border color of the range limiting the search. The color must not be opaque so as not to hide underlying decorations."), true);
registerColor("searchEditor.findMatchBackground", { light: transparent(editorFindMatchHighlight, 0.66), dark: transparent(editorFindMatchHighlight, 0.66), hcDark: editorFindMatchHighlight, hcLight: editorFindMatchHighlight }, localize("searchEditor.queryMatch", "Color of the Search Editor query matches."));
registerColor("searchEditor.findMatchBorder", { light: transparent(editorFindMatchHighlightBorder, 0.66), dark: transparent(editorFindMatchHighlightBorder, 0.66), hcDark: editorFindMatchHighlightBorder, hcLight: editorFindMatchHighlightBorder }, localize("searchEditor.editorFindMatchBorder", "Border color of the Search Editor query matches."));
registerColor("search.resultsInfoForeground", { light: foreground, dark: transparent(foreground, 0.65), hcDark: foreground, hcLight: foreground }, localize("search.resultsInfoForeground", "Color of the text in the search viewlet's completion message."));
registerColor("editor.hoverHighlightBackground", { light: "#ADD6FF26", dark: "#264f7840", hcDark: "#ADD6FF26", hcLight: null }, localize("hoverHighlight", "Highlight below the word for which a hover is shown. The color must not be opaque so as not to hide underlying decorations."), true);
const editorHoverBackground = registerColor("editorHoverWidget.background", { light: editorWidgetBackground, dark: editorWidgetBackground, hcDark: editorWidgetBackground, hcLight: editorWidgetBackground }, localize("hoverBackground", "Background color of the editor hover."));
registerColor("editorHoverWidget.foreground", { light: editorWidgetForeground, dark: editorWidgetForeground, hcDark: editorWidgetForeground, hcLight: editorWidgetForeground }, localize("hoverForeground", "Foreground color of the editor hover."));
const editorHoverBorder = registerColor("editorHoverWidget.border", { light: editorWidgetBorder, dark: editorWidgetBorder, hcDark: editorWidgetBorder, hcLight: editorWidgetBorder }, localize("hoverBorder", "Border color of the editor hover."));
registerColor("editorHoverWidget.statusBarBackground", { dark: lighten(editorHoverBackground, 0.2), light: darken(editorHoverBackground, 0.05), hcDark: editorWidgetBackground, hcLight: editorWidgetBackground }, localize("statusBarBackground", "Background color of the editor hover status bar."));
const editorActiveLinkForeground = registerColor("editorLink.activeForeground", { dark: "#4E94CE", light: Color.blue, hcDark: Color.cyan, hcLight: "#292929" }, localize("activeLinkForeground", "Color of active links."));
const editorInlayHintForeground = registerColor("editorInlayHint.foreground", { dark: foreground, light: foreground, hcDark: Color.black, hcLight: badgeForeground }, localize("editorInlayHintForeground", "Foreground color of inline hints"));
const editorInlayHintBackground = registerColor("editorInlayHint.background", { dark: transparent(badgeBackground, 0.25), light: transparent(badgeBackground, 0.3), hcDark: "#f38518", hcLight: badgeBackground }, localize("editorInlayHintBackground", "Background color of inline hints"));
const editorInlayHintTypeForeground = registerColor("editorInlayHint.typeForeground", { dark: editorInlayHintForeground, light: editorInlayHintForeground, hcDark: editorInlayHintForeground, hcLight: editorInlayHintForeground }, localize("editorInlayHintForegroundTypes", "Foreground color of inline hints for types"));
const editorInlayHintTypeBackground = registerColor("editorInlayHint.typeBackground", { dark: editorInlayHintBackground, light: editorInlayHintBackground, hcDark: editorInlayHintBackground, hcLight: editorInlayHintBackground }, localize("editorInlayHintBackgroundTypes", "Background color of inline hints for types"));
const editorInlayHintParameterForeground = registerColor("editorInlayHint.parameterForeground", { dark: editorInlayHintForeground, light: editorInlayHintForeground, hcDark: editorInlayHintForeground, hcLight: editorInlayHintForeground }, localize("editorInlayHintForegroundParameter", "Foreground color of inline hints for parameters"));
const editorInlayHintParameterBackground = registerColor("editorInlayHint.parameterBackground", { dark: editorInlayHintBackground, light: editorInlayHintBackground, hcDark: editorInlayHintBackground, hcLight: editorInlayHintBackground }, localize("editorInlayHintBackgroundParameter", "Background color of inline hints for parameters"));
registerColor("editorLightBulb.foreground", { dark: "#FFCC00", light: "#DDB100", hcDark: "#FFCC00", hcLight: "#007ACC" }, localize("editorLightBulbForeground", "The color used for the lightbulb actions icon."));
registerColor("editorLightBulbAutoFix.foreground", { dark: "#75BEFF", light: "#007ACC", hcDark: "#75BEFF", hcLight: "#007ACC" }, localize("editorLightBulbAutoFixForeground", "The color used for the lightbulb auto fix actions icon."));
const defaultInsertColor = new Color(new RGBA(155, 185, 85, 0.2));
const defaultRemoveColor = new Color(new RGBA(255, 0, 0, 0.2));
const diffInserted = registerColor("diffEditor.insertedTextBackground", { dark: "#9ccc2c33", light: "#9ccc2c40", hcDark: null, hcLight: null }, localize("diffEditorInserted", "Background color for text that got inserted. The color must not be opaque so as not to hide underlying decorations."), true);
const diffRemoved = registerColor("diffEditor.removedTextBackground", { dark: "#ff000033", light: "#ff000033", hcDark: null, hcLight: null }, localize("diffEditorRemoved", "Background color for text that got removed. The color must not be opaque so as not to hide underlying decorations."), true);
registerColor("diffEditor.insertedLineBackground", { dark: defaultInsertColor, light: defaultInsertColor, hcDark: null, hcLight: null }, localize("diffEditorInsertedLines", "Background color for lines that got inserted. The color must not be opaque so as not to hide underlying decorations."), true);
registerColor("diffEditor.removedLineBackground", { dark: defaultRemoveColor, light: defaultRemoveColor, hcDark: null, hcLight: null }, localize("diffEditorRemovedLines", "Background color for lines that got removed. The color must not be opaque so as not to hide underlying decorations."), true);
registerColor("diffEditorGutter.insertedLineBackground", { dark: null, light: null, hcDark: null, hcLight: null }, localize("diffEditorInsertedLineGutter", "Background color for the margin where lines got inserted."));
registerColor("diffEditorGutter.removedLineBackground", { dark: null, light: null, hcDark: null, hcLight: null }, localize("diffEditorRemovedLineGutter", "Background color for the margin where lines got removed."));
const diffOverviewRulerInserted = registerColor("diffEditorOverview.insertedForeground", { dark: null, light: null, hcDark: null, hcLight: null }, localize("diffEditorOverviewInserted", "Diff overview ruler foreground for inserted content."));
const diffOverviewRulerRemoved = registerColor("diffEditorOverview.removedForeground", { dark: null, light: null, hcDark: null, hcLight: null }, localize("diffEditorOverviewRemoved", "Diff overview ruler foreground for removed content."));
registerColor("diffEditor.insertedTextBorder", { dark: null, light: null, hcDark: "#33ff2eff", hcLight: "#374E06" }, localize("diffEditorInsertedOutline", "Outline color for the text that got inserted."));
registerColor("diffEditor.removedTextBorder", { dark: null, light: null, hcDark: "#FF008F", hcLight: "#AD0707" }, localize("diffEditorRemovedOutline", "Outline color for text that got removed."));
registerColor("diffEditor.border", { dark: null, light: null, hcDark: contrastBorder, hcLight: contrastBorder }, localize("diffEditorBorder", "Border color between the two text editors."));
const diffDiagonalFill = registerColor("diffEditor.diagonalFill", { dark: "#cccccc33", light: "#22222233", hcDark: null, hcLight: null }, localize("diffDiagonalFill", "Color of the diff editor's diagonal fill. The diagonal fill is used in side-by-side diff views."));
registerColor("diffEditor.unchangedRegionBackground", { dark: "#3e3e3e", light: "#e4e4e4", hcDark: null, hcLight: null }, localize("diffEditor.unchangedRegionBackground", "The background color of unchanged blocks in the diff editor."));
registerColor("diffEditor.unchangedRegionForeground", { dark: "#a3a2a2", light: "#4d4c4c", hcDark: null, hcLight: null }, localize("diffEditor.unchangedRegionForeground", "The foreground color of unchanged blocks in the diff editor."));
registerColor("diffEditor.unchangedCodeBackground", { dark: "#74747429", light: "#b8b8b829", hcDark: null, hcLight: null }, localize("diffEditor.unchangedCodeBackground", "The background color of unchanged code in the diff editor."));
const listFocusBackground = registerColor("list.focusBackground", { dark: null, light: null, hcDark: null, hcLight: null }, localize("listFocusBackground", "List/Tree background color for the focused item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
const listFocusForeground = registerColor("list.focusForeground", { dark: null, light: null, hcDark: null, hcLight: null }, localize("listFocusForeground", "List/Tree foreground color for the focused item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
const listFocusOutline = registerColor("list.focusOutline", { dark: focusBorder, light: focusBorder, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize("listFocusOutline", "List/Tree outline color for the focused item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
const listFocusAndSelectionOutline = registerColor("list.focusAndSelectionOutline", { dark: null, light: null, hcDark: null, hcLight: null }, localize("listFocusAndSelectionOutline", "List/Tree outline color for the focused item when the list/tree is active and selected. An active list/tree has keyboard focus, an inactive does not."));
const listActiveSelectionBackground = registerColor("list.activeSelectionBackground", { dark: "#04395E", light: "#0060C0", hcDark: null, hcLight: Color.fromHex("#0F4A85").transparent(0.1) }, localize("listActiveSelectionBackground", "List/Tree background color for the selected item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
const listActiveSelectionForeground = registerColor("list.activeSelectionForeground", { dark: Color.white, light: Color.white, hcDark: null, hcLight: null }, localize("listActiveSelectionForeground", "List/Tree foreground color for the selected item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
const listActiveSelectionIconForeground = registerColor("list.activeSelectionIconForeground", { dark: null, light: null, hcDark: null, hcLight: null }, localize("listActiveSelectionIconForeground", "List/Tree icon foreground color for the selected item when the list/tree is active. An active list/tree has keyboard focus, an inactive does not."));
const listInactiveSelectionBackground = registerColor("list.inactiveSelectionBackground", { dark: "#37373D", light: "#E4E6F1", hcDark: null, hcLight: Color.fromHex("#0F4A85").transparent(0.1) }, localize("listInactiveSelectionBackground", "List/Tree background color for the selected item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not."));
const listInactiveSelectionForeground = registerColor("list.inactiveSelectionForeground", { dark: null, light: null, hcDark: null, hcLight: null }, localize("listInactiveSelectionForeground", "List/Tree foreground color for the selected item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not."));
const listInactiveSelectionIconForeground = registerColor("list.inactiveSelectionIconForeground", { dark: null, light: null, hcDark: null, hcLight: null }, localize("listInactiveSelectionIconForeground", "List/Tree icon foreground color for the selected item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not."));
const listInactiveFocusBackground = registerColor("list.inactiveFocusBackground", { dark: null, light: null, hcDark: null, hcLight: null }, localize("listInactiveFocusBackground", "List/Tree background color for the focused item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not."));
const listInactiveFocusOutline = registerColor("list.inactiveFocusOutline", { dark: null, light: null, hcDark: null, hcLight: null }, localize("listInactiveFocusOutline", "List/Tree outline color for the focused item when the list/tree is inactive. An active list/tree has keyboard focus, an inactive does not."));
const listHoverBackground = registerColor("list.hoverBackground", { dark: "#2A2D2E", light: "#F0F0F0", hcDark: Color.white.transparent(0.1), hcLight: Color.fromHex("#0F4A85").transparent(0.1) }, localize("listHoverBackground", "List/Tree background when hovering over items using the mouse."));
const listHoverForeground = registerColor("list.hoverForeground", { dark: null, light: null, hcDark: null, hcLight: null }, localize("listHoverForeground", "List/Tree foreground when hovering over items using the mouse."));
const listDropBackground = registerColor("list.dropBackground", { dark: "#062F4A", light: "#D6EBFF", hcDark: null, hcLight: null }, localize("listDropBackground", "List/Tree drag and drop background when moving items around using the mouse."));
const listHighlightForeground = registerColor("list.highlightForeground", { dark: "#2AAAFF", light: "#0066BF", hcDark: focusBorder, hcLight: focusBorder }, localize("highlight", "List/Tree foreground color of the match highlights when searching inside the list/tree."));
const listFocusHighlightForeground = registerColor("list.focusHighlightForeground", { dark: listHighlightForeground, light: ifDefinedThenElse(listActiveSelectionBackground, listHighlightForeground, "#BBE7FF"), hcDark: listHighlightForeground, hcLight: listHighlightForeground }, localize("listFocusHighlightForeground", "List/Tree foreground color of the match highlights on actively focused items when searching inside the list/tree."));
registerColor("list.invalidItemForeground", { dark: "#B89500", light: "#B89500", hcDark: "#B89500", hcLight: "#B5200D" }, localize("invalidItemForeground", "List/Tree foreground color for invalid items, for example an unresolved root in explorer."));
registerColor("list.errorForeground", { dark: "#F88070", light: "#B01011", hcDark: null, hcLight: null }, localize("listErrorForeground", "Foreground color of list items containing errors."));
registerColor("list.warningForeground", { dark: "#CCA700", light: "#855F00", hcDark: null, hcLight: null }, localize("listWarningForeground", "Foreground color of list items containing warnings."));
const listFilterWidgetBackground = registerColor("listFilterWidget.background", { light: darken(editorWidgetBackground, 0), dark: lighten(editorWidgetBackground, 0), hcDark: editorWidgetBackground, hcLight: editorWidgetBackground }, localize("listFilterWidgetBackground", "Background color of the type filter widget in lists and trees."));
const listFilterWidgetOutline = registerColor("listFilterWidget.outline", { dark: Color.transparent, light: Color.transparent, hcDark: "#f38518", hcLight: "#007ACC" }, localize("listFilterWidgetOutline", "Outline color of the type filter widget in lists and trees."));
const listFilterWidgetNoMatchesOutline = registerColor("listFilterWidget.noMatchesOutline", { dark: "#BE1100", light: "#BE1100", hcDark: contrastBorder, hcLight: contrastBorder }, localize("listFilterWidgetNoMatchesOutline", "Outline color of the type filter widget in lists and trees, when there are no matches."));
const listFilterWidgetShadow = registerColor("listFilterWidget.shadow", { dark: widgetShadow, light: widgetShadow, hcDark: widgetShadow, hcLight: widgetShadow }, localize("listFilterWidgetShadow", "Shadow color of the type filter widget in lists and trees."));
registerColor("list.filterMatchBackground", { dark: editorFindMatchHighlight, light: editorFindMatchHighlight, hcDark: null, hcLight: null }, localize("listFilterMatchHighlight", "Background color of the filtered match."));
registerColor("list.filterMatchBorder", { dark: editorFindMatchHighlightBorder, light: editorFindMatchHighlightBorder, hcDark: contrastBorder, hcLight: activeContrastBorder }, localize("listFilterMatchHighlightBorder", "Border color of the filtered match."));
const treeIndentGuidesStroke = registerColor("tree.indentGuidesStroke", { dark: "#585858", light: "#a9a9a9", hcDark: "#a9a9a9", hcLight: "#a5a5a5" }, localize("treeIndentGuidesStroke", "Tree stroke color for the indentation guides."));
const treeInactiveIndentGuidesStroke = registerColor("tree.inactiveIndentGuidesStroke", { dark: transparent(treeIndentGuidesStroke, 0.4), light: transparent(treeIndentGuidesStroke, 0.4), hcDark: transparent(treeIndentGuidesStroke, 0.4), hcLight: transparent(treeIndentGuidesStroke, 0.4) }, localize("treeInactiveIndentGuidesStroke", "Tree stroke color for the indentation guides that are not active."));
const tableColumnsBorder = registerColor("tree.tableColumnsBorder", { dark: "#CCCCCC20", light: "#61616120", hcDark: null, hcLight: null }, localize("tableColumnsBorder", "Table border color between columns."));
const tableOddRowsBackgroundColor = registerColor("tree.tableOddRowsBackground", { dark: transparent(foreground, 0.04), light: transparent(foreground, 0.04), hcDark: null, hcLight: null }, localize("tableOddRowsBackgroundColor", "Background color for odd table rows."));
registerColor("list.deemphasizedForeground", { dark: "#8C8C8C", light: "#8E8E90", hcDark: "#A7A8A9", hcLight: "#666666" }, localize("listDeemphasizedForeground", "List/Tree foreground color for items that are deemphasized. "));
const checkboxBackground = registerColor("checkbox.background", { dark: selectBackground, light: selectBackground, hcDark: selectBackground, hcLight: selectBackground }, localize("checkbox.background", "Background color of checkbox widget."));
registerColor("checkbox.selectBackground", { dark: editorWidgetBackground, light: editorWidgetBackground, hcDark: editorWidgetBackground, hcLight: editorWidgetBackground }, localize("checkbox.select.background", "Background color of checkbox widget when the element it's in is selected."));
const checkboxForeground = registerColor("checkbox.foreground", { dark: selectForeground, light: selectForeground, hcDark: selectForeground, hcLight: selectForeground }, localize("checkbox.foreground", "Foreground color of checkbox widget."));
const checkboxBorder = registerColor("checkbox.border", { dark: selectBorder, light: selectBorder, hcDark: selectBorder, hcLight: selectBorder }, localize("checkbox.border", "Border color of checkbox widget."));
registerColor("checkbox.selectBorder", { dark: iconForeground, light: iconForeground, hcDark: iconForeground, hcLight: iconForeground }, localize("checkbox.select.border", "Border color of checkbox widget when the element it's in is selected."));
const _deprecatedQuickInputListFocusBackground = registerColor("quickInput.list.focusBackground", { dark: null, light: null, hcDark: null, hcLight: null }, "", void 0, localize("quickInput.list.focusBackground deprecation", "Please use quickInputList.focusBackground instead"));
const quickInputListFocusForeground = registerColor("quickInputList.focusForeground", { dark: listActiveSelectionForeground, light: listActiveSelectionForeground, hcDark: listActiveSelectionForeground, hcLight: listActiveSelectionForeground }, localize("quickInput.listFocusForeground", "Quick picker foreground color for the focused item."));
const quickInputListFocusIconForeground = registerColor("quickInputList.focusIconForeground", { dark: listActiveSelectionIconForeground, light: listActiveSelectionIconForeground, hcDark: listActiveSelectionIconForeground, hcLight: listActiveSelectionIconForeground }, localize("quickInput.listFocusIconForeground", "Quick picker icon foreground color for the focused item."));
const quickInputListFocusBackground = registerColor("quickInputList.focusBackground", { dark: oneOf(_deprecatedQuickInputListFocusBackground, listActiveSelectionBackground), light: oneOf(_deprecatedQuickInputListFocusBackground, listActiveSelectionBackground), hcDark: null, hcLight: null }, localize("quickInput.listFocusBackground", "Quick picker background color for the focused item."));
const menuBorder = registerColor("menu.border", { dark: null, light: null, hcDark: contrastBorder, hcLight: contrastBorder }, localize("menuBorder", "Border color of menus."));
const menuForeground = registerColor("menu.foreground", { dark: selectForeground, light: selectForeground, hcDark: selectForeground, hcLight: selectForeground }, localize("menuForeground", "Foreground color of menu items."));
const menuBackground = registerColor("menu.background", { dark: selectBackground, light: selectBackground, hcDark: selectBackground, hcLight: selectBackground }, localize("menuBackground", "Background color of menu items."));
const menuSelectionForeground = registerColor("menu.selectionForeground", { dark: listActiveSelectionForeground, light: listActiveSelectionForeground, hcDark: listActiveSelectionForeground, hcLight: listActiveSelectionForeground }, localize("menuSelectionForeground", "Foreground color of the selected menu item in menus."));
const menuSelectionBackground = registerColor("menu.selectionBackground", { dark: listActiveSelectionBackground, light: listActiveSelectionBackground, hcDark: listActiveSelectionBackground, hcLight: listActiveSelectionBackground }, localize("menuSelectionBackground", "Background color of the selected menu item in menus."));
const menuSelectionBorder = registerColor("menu.selectionBorder", { dark: null, light: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize("menuSelectionBorder", "Border color of the selected menu item in menus."));
const menuSeparatorBackground = registerColor("menu.separatorBackground", { dark: "#606060", light: "#D4D4D4", hcDark: contrastBorder, hcLight: contrastBorder }, localize("menuSeparatorBackground", "Color of a separator menu item in menus."));
const toolbarHoverBackground = registerColor("toolbar.hoverBackground", { dark: "#5a5d5e50", light: "#b8b8b850", hcDark: null, hcLight: null }, localize("toolbarHoverBackground", "Toolbar background when hovering over actions using the mouse"));
registerColor("toolbar.hoverOutline", { dark: null, light: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize("toolbarHoverOutline", "Toolbar outline when hovering over actions using the mouse"));
registerColor("toolbar.activeBackground", { dark: lighten(toolbarHoverBackground, 0.1), light: darken(toolbarHoverBackground, 0.1), hcDark: null, hcLight: null }, localize("toolbarActiveBackground", "Toolbar background when holding the mouse over actions"));
registerColor("editor.snippetTabstopHighlightBackground", { dark: new Color(new RGBA(124, 124, 124, 0.3)), light: new Color(new RGBA(10, 50, 100, 0.2)), hcDark: new Color(new RGBA(124, 124, 124, 0.3)), hcLight: new Color(new RGBA(10, 50, 100, 0.2)) }, localize("snippetTabstopHighlightBackground", "Highlight background color of a snippet tabstop."));
registerColor("editor.snippetTabstopHighlightBorder", { dark: null, light: null, hcDark: null, hcLight: null }, localize("snippetTabstopHighlightBorder", "Highlight border color of a snippet tabstop."));
registerColor("editor.snippetFinalTabstopHighlightBackground", { dark: null, light: null, hcDark: null, hcLight: null }, localize("snippetFinalTabstopHighlightBackground", "Highlight background color of the final tabstop of a snippet."));
registerColor("editor.snippetFinalTabstopHighlightBorder", { dark: "#525252", light: new Color(new RGBA(10, 50, 100, 0.5)), hcDark: "#525252", hcLight: "#292929" }, localize("snippetFinalTabstopHighlightBorder", "Highlight border color of the final tabstop of a snippet."));
const breadcrumbsForeground = registerColor("breadcrumb.foreground", { light: transparent(foreground, 0.8), dark: transparent(foreground, 0.8), hcDark: transparent(foreground, 0.8), hcLight: transparent(foreground, 0.8) }, localize("breadcrumbsFocusForeground", "Color of focused breadcrumb items."));
const breadcrumbsBackground = registerColor("breadcrumb.background", { light: editorBackground, dark: editorBackground, hcDark: editorBackground, hcLight: editorBackground }, localize("breadcrumbsBackground", "Background color of breadcrumb items."));
const breadcrumbsFocusForeground = registerColor("breadcrumb.focusForeground", { light: darken(foreground, 0.2), dark: lighten(foreground, 0.1), hcDark: lighten(foreground, 0.1), hcLight: lighten(foreground, 0.1) }, localize("breadcrumbsFocusForeground", "Color of focused breadcrumb items."));
const breadcrumbsActiveSelectionForeground = registerColor("breadcrumb.activeSelectionForeground", { light: darken(foreground, 0.2), dark: lighten(foreground, 0.1), hcDark: lighten(foreground, 0.1), hcLight: lighten(foreground, 0.1) }, localize("breadcrumbsSelectedForeground", "Color of selected breadcrumb items."));
registerColor("breadcrumbPicker.background", { light: editorWidgetBackground, dark: editorWidgetBackground, hcDark: editorWidgetBackground, hcLight: editorWidgetBackground }, localize("breadcrumbsSelectedBackground", "Background color of breadcrumb item picker."));
const headerTransparency = 0.5;
const currentBaseColor = Color.fromHex("#40C8AE").transparent(headerTransparency);
const incomingBaseColor = Color.fromHex("#40A6FF").transparent(headerTransparency);
const commonBaseColor = Color.fromHex("#606060").transparent(0.4);
const contentTransparency = 0.4;
const rulerTransparency = 1;
const mergeCurrentHeaderBackground = registerColor("merge.currentHeaderBackground", { dark: currentBaseColor, light: currentBaseColor, hcDark: null, hcLight: null }, localize("mergeCurrentHeaderBackground", "Current header background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations."), true);
registerColor("merge.currentContentBackground", { dark: transparent(mergeCurrentHeaderBackground, contentTransparency), light: transparent(mergeCurrentHeaderBackground, contentTransparency), hcDark: transparent(mergeCurrentHeaderBackground, contentTransparency), hcLight: transparent(mergeCurrentHeaderBackground, contentTransparency) }, localize("mergeCurrentContentBackground", "Current content background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations."), true);
const mergeIncomingHeaderBackground = registerColor("merge.incomingHeaderBackground", { dark: incomingBaseColor, light: incomingBaseColor, hcDark: null, hcLight: null }, localize("mergeIncomingHeaderBackground", "Incoming header background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations."), true);
registerColor("merge.incomingContentBackground", { dark: transparent(mergeIncomingHeaderBackground, contentTransparency), light: transparent(mergeIncomingHeaderBackground, contentTransparency), hcDark: transparent(mergeIncomingHeaderBackground, contentTransparency), hcLight: transparent(mergeIncomingHeaderBackground, contentTransparency) }, localize("mergeIncomingContentBackground", "Incoming content background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations."), true);
const mergeCommonHeaderBackground = registerColor("merge.commonHeaderBackground", { dark: commonBaseColor, light: commonBaseColor, hcDark: null, hcLight: null }, localize("mergeCommonHeaderBackground", "Common ancestor header background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations."), true);
registerColor("merge.commonContentBackground", { dark: transparent(mergeCommonHeaderBackground, contentTransparency), light: transparent(mergeCommonHeaderBackground, contentTransparency), hcDark: transparent(mergeCommonHeaderBackground, contentTransparency), hcLight: transparent(mergeCommonHeaderBackground, contentTransparency) }, localize("mergeCommonContentBackground", "Common ancestor content background in inline merge-conflicts. The color must not be opaque so as not to hide underlying decorations."), true);
const mergeBorder = registerColor("merge.border", { dark: null, light: null, hcDark: "#C3DF6F", hcLight: "#007ACC" }, localize("mergeBorder", "Border color on headers and the splitter in inline merge-conflicts."));
registerColor("editorOverviewRuler.currentContentForeground", { dark: transparent(mergeCurrentHeaderBackground, rulerTransparency), light: transparent(mergeCurrentHeaderBackground, rulerTransparency), hcDark: mergeBorder, hcLight: mergeBorder }, localize("overviewRulerCurrentContentForeground", "Current overview ruler foreground for inline merge-conflicts."));
registerColor("editorOverviewRuler.incomingContentForeground", { dark: transparent(mergeIncomingHeaderBackground, rulerTransparency), light: transparent(mergeIncomingHeaderBackground, rulerTransparency), hcDark: mergeBorder, hcLight: mergeBorder }, localize("overviewRulerIncomingContentForeground", "Incoming overview ruler foreground for inline merge-conflicts."));
registerColor("editorOverviewRuler.commonContentForeground", { dark: transparent(mergeCommonHeaderBackground, rulerTransparency), light: transparent(mergeCommonHeaderBackground, rulerTransparency), hcDark: mergeBorder, hcLight: mergeBorder }, localize("overviewRulerCommonContentForeground", "Common ancestor overview ruler foreground for inline merge-conflicts."));
const overviewRulerFindMatchForeground = registerColor("editorOverviewRuler.findMatchForeground", { dark: "#d186167e", light: "#d186167e", hcDark: "#AB5A00", hcLight: "" }, localize("overviewRulerFindMatchForeground", "Overview ruler marker color for find matches. The color must not be opaque so as not to hide underlying decorations."), true);
const overviewRulerSelectionHighlightForeground = registerColor("editorOverviewRuler.selectionHighlightForeground", { dark: "#A0A0A0CC", light: "#A0A0A0CC", hcDark: "#A0A0A0CC", hcLight: "#A0A0A0CC" }, localize("overviewRulerSelectionHighlightForeground", "Overview ruler marker color for selection highlights. The color must not be opaque so as not to hide underlying decorations."), true);
const minimapFindMatch = registerColor("minimap.findMatchHighlight", { light: "#d18616", dark: "#d18616", hcDark: "#AB5A00", hcLight: "#0F4A85" }, localize("minimapFindMatchHighlight", "Minimap marker color for find matches."), true);
const minimapSelectionOccurrenceHighlight = registerColor("minimap.selectionOccurrenceHighlight", { light: "#c9c9c9", dark: "#676767", hcDark: "#ffffff", hcLight: "#0F4A85" }, localize("minimapSelectionOccurrenceHighlight", "Minimap marker color for repeating editor selections."), true);
const minimapSelection = registerColor("minimap.selectionHighlight", { light: "#ADD6FF", dark: "#264F78", hcDark: "#ffffff", hcLight: "#0F4A85" }, localize("minimapSelectionHighlight", "Minimap marker color for the editor selection."), true);
const minimapError = registerColor("minimap.errorHighlight", { dark: new Color(new RGBA(255, 18, 18, 0.7)), light: new Color(new RGBA(255, 18, 18, 0.7)), hcDark: new Color(new RGBA(255, 50, 50, 1)), hcLight: "#B5200D" }, localize("minimapError", "Minimap marker color for errors."));
const minimapWarning = registerColor("minimap.warningHighlight", { dark: editorWarningForeground, light: editorWarningForeground, hcDark: editorWarningBorder, hcLight: editorWarningBorder }, localize("overviewRuleWarning", "Minimap marker color for warnings."));
const minimapBackground = registerColor("minimap.background", { dark: null, light: null, hcDark: null, hcLight: null }, localize("minimapBackground", "Minimap background color."));
const minimapForegroundOpacity = registerColor("minimap.foregroundOpacity", { dark: Color.fromHex("#000f"), light: Color.fromHex("#000f"), hcDark: Color.fromHex("#000f"), hcLight: Color.fromHex("#000f") }, localize("minimapForegroundOpacity", 'Opacity of foreground elements rendered in the minimap. For example, "#000000c0" will render the elements with 75% opacity.'));
registerColor("minimapSlider.background", { light: transparent(scrollbarSliderBackground, 0.5), dark: transparent(scrollbarSliderBackground, 0.5), hcDark: transparent(scrollbarSliderBackground, 0.5), hcLight: transparent(scrollbarSliderBackground, 0.5) }, localize("minimapSliderBackground", "Minimap slider background color."));
registerColor("minimapSlider.hoverBackground", { light: transparent(scrollbarSliderHoverBackground, 0.5), dark: transparent(scrollbarSliderHoverBackground, 0.5), hcDark: transparent(scrollbarSliderHoverBackground, 0.5), hcLight: transparent(scrollbarSliderHoverBackground, 0.5) }, localize("minimapSliderHoverBackground", "Minimap slider background color when hovering."));
registerColor("minimapSlider.activeBackground", { light: transparent(scrollbarSliderActiveBackground, 0.5), dark: transparent(scrollbarSliderActiveBackground, 0.5), hcDark: transparent(scrollbarSliderActiveBackground, 0.5), hcLight: transparent(scrollbarSliderActiveBackground, 0.5) }, localize("minimapSliderActiveBackground", "Minimap slider background color when clicked on."));
const problemsErrorIconForeground = registerColor("problemsErrorIcon.foreground", { dark: editorErrorForeground, light: editorErrorForeground, hcDark: editorErrorForeground, hcLight: editorErrorForeground }, localize("problemsErrorIconForeground", "The color used for the problems error icon."));
const problemsWarningIconForeground = registerColor("problemsWarningIcon.foreground", { dark: editorWarningForeground, light: editorWarningForeground, hcDark: editorWarningForeground, hcLight: editorWarningForeground }, localize("problemsWarningIconForeground", "The color used for the problems warning icon."));
const problemsInfoIconForeground = registerColor("problemsInfoIcon.foreground", { dark: editorInfoForeground, light: editorInfoForeground, hcDark: editorInfoForeground, hcLight: editorInfoForeground }, localize("problemsInfoIconForeground", "The color used for the problems info icon."));
registerColor("charts.foreground", { dark: foreground, light: foreground, hcDark: foreground, hcLight: foreground }, localize("chartsForeground", "The foreground color used in charts."));
registerColor("charts.lines", { dark: transparent(foreground, 0.5), light: transparent(foreground, 0.5), hcDark: transparent(foreground, 0.5), hcLight: transparent(foreground, 0.5) }, localize("chartsLines", "The color used for horizontal lines in charts."));
registerColor("charts.red", { dark: editorErrorForeground, light: editorErrorForeground, hcDark: editorErrorForeground, hcLight: editorErrorForeground }, localize("chartsRed", "The red color used in chart visualizations."));
registerColor("charts.blue", { dark: editorInfoForeground, light: editorInfoForeground, hcDark: editorInfoForeground, hcLight: editorInfoForeground }, localize("chartsBlue", "The blue color used in chart visualizations."));
registerColor("charts.yellow", { dark: editorWarningForeground, light: editorWarningForeground, hcDark: editorWarningForeground, hcLight: editorWarningForeground }, localize("chartsYellow", "The yellow color used in chart visualizations."));
registerColor("charts.orange", { dark: minimapFindMatch, light: minimapFindMatch, hcDark: minimapFindMatch, hcLight: minimapFindMatch }, localize("chartsOrange", "The orange color used in chart visualizations."));
registerColor("charts.green", { dark: "#89D185", light: "#388A34", hcDark: "#89D185", hcLight: "#374e06" }, localize("chartsGreen", "The green color used in chart visualizations."));
registerColor("charts.purple", { dark: "#B180D7", light: "#652D90", hcDark: "#B180D7", hcLight: "#652D90" }, localize("chartsPurple", "The purple color used in chart visualizations."));
function executeTransform(transform, theme) {
  var _a2, _b2, _c2, _d2;
  switch (transform.op) {
    case 0:
      return (_a2 = resolveColorValue(transform.value, theme)) === null || _a2 === void 0 ? void 0 : _a2.darken(transform.factor);
    case 1:
      return (_b2 = resolveColorValue(transform.value, theme)) === null || _b2 === void 0 ? void 0 : _b2.lighten(transform.factor);
    case 2:
      return (_c2 = resolveColorValue(transform.value, theme)) === null || _c2 === void 0 ? void 0 : _c2.transparent(transform.factor);
    case 3: {
      const backgroundColor = resolveColorValue(transform.background, theme);
      if (!backgroundColor) {
        return resolveColorValue(transform.value, theme);
      }
      return (_d2 = resolveColorValue(transform.value, theme)) === null || _d2 === void 0 ? void 0 : _d2.makeOpaque(backgroundColor);
    }
    case 4:
      for (const candidate of transform.values) {
        const color = resolveColorValue(candidate, theme);
        if (color) {
          return color;
        }
      }
      return void 0;
    case 6:
      return resolveColorValue(theme.defines(transform.if) ? transform.then : transform.else, theme);
    case 5: {
      const from2 = resolveColorValue(transform.value, theme);
      if (!from2) {
        return void 0;
      }
      const backgroundColor = resolveColorValue(transform.background, theme);
      if (!backgroundColor) {
        return from2.transparent(transform.factor * transform.transparency);
      }
      return from2.isDarkerThan(backgroundColor) ? Color.getLighterColor(from2, backgroundColor, transform.factor).transparent(transform.transparency) : Color.getDarkerColor(from2, backgroundColor, transform.factor).transparent(transform.transparency);
    }
    default:
      throw assertNever();
  }
}
function darken(colorValue, factor2) {
  return { op: 0, value: colorValue, factor: factor2 };
}
function lighten(colorValue, factor2) {
  return { op: 1, value: colorValue, factor: factor2 };
}
function transparent(colorValue, factor2) {
  return { op: 2, value: colorValue, factor: factor2 };
}
function oneOf(...colorValues) {
  return { op: 4, values: colorValues };
}
function ifDefinedThenElse(ifArg, thenArg, elseArg) {
  return { op: 6, if: ifArg, then: thenArg, else: elseArg };
}
function lessProminent(colorValue, backgroundColorValue, factor2, transparency) {
  return { op: 5, value: colorValue, background: backgroundColorValue, factor: factor2, transparency };
}
function resolveColorValue(colorValue, theme) {
  if (colorValue === null) {
    return void 0;
  } else if (typeof colorValue === "string") {
    if (colorValue[0] === "#") {
      return Color.fromHex(colorValue);
    }
    return theme.getColor(colorValue);
  } else if (colorValue instanceof Color) {
    return colorValue;
  } else if (typeof colorValue === "object") {
    return executeTransform(colorValue, theme);
  }
  return void 0;
}
const workbenchColorsSchemaId = "vscode://schemas/workbench-colors";
const schemaRegistry$1 = Registry.as(Extensions$7.JSONContribution);
schemaRegistry$1.registerSchema(workbenchColorsSchemaId, colorRegistry$1.getColorSchema());
const delayer$1 = new RunOnceScheduler(() => schemaRegistry$1.notifySchemaChanged(workbenchColorsSchemaId), 200);
colorRegistry$1.onDidChangeSchema(() => {
  if (!delayer$1.isScheduled()) {
    delayer$1.schedule();
  }
});
class PageCoordinates {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this._pageCoordinatesBrand = void 0;
  }
  toClientCoordinates() {
    return new ClientCoordinates(this.x - window.scrollX, this.y - window.scrollY);
  }
}
class ClientCoordinates {
  constructor(clientX, clientY) {
    this.clientX = clientX;
    this.clientY = clientY;
    this._clientCoordinatesBrand = void 0;
  }
  toPageCoordinates() {
    return new PageCoordinates(this.clientX + window.scrollX, this.clientY + window.scrollY);
  }
}
class EditorPagePosition {
  constructor(x, y, width, height) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    this._editorPagePositionBrand = void 0;
  }
}
class CoordinatesRelativeToEditor {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this._positionRelativeToEditorBrand = void 0;
  }
}
function createEditorPagePosition(editorViewDomNode) {
  const editorPos = getDomNodePagePosition(editorViewDomNode);
  return new EditorPagePosition(editorPos.left, editorPos.top, editorPos.width, editorPos.height);
}
function createCoordinatesRelativeToEditor(editorViewDomNode, editorPagePosition, pos) {
  const scaleX = editorPagePosition.width / editorViewDomNode.offsetWidth;
  const scaleY = editorPagePosition.height / editorViewDomNode.offsetHeight;
  const relativeX = (pos.x - editorPagePosition.x) / scaleX;
  const relativeY = (pos.y - editorPagePosition.y) / scaleY;
  return new CoordinatesRelativeToEditor(relativeX, relativeY);
}
class EditorMouseEvent extends StandardMouseEvent {
  constructor(e, isFromPointerCapture, editorViewDomNode) {
    super(e);
    this._editorMouseEventBrand = void 0;
    this.isFromPointerCapture = isFromPointerCapture;
    this.pos = new PageCoordinates(this.posx, this.posy);
    this.editorPos = createEditorPagePosition(editorViewDomNode);
    this.relativePos = createCoordinatesRelativeToEditor(editorViewDomNode, this.editorPos, this.pos);
  }
}
class EditorMouseEventFactory {
  constructor(editorViewDomNode) {
    this._editorViewDomNode = editorViewDomNode;
  }
  _create(e) {
    return new EditorMouseEvent(e, false, this._editorViewDomNode);
  }
  onContextMenu(target, callback) {
    return addDisposableListener(target, "contextmenu", (e) => {
      callback(this._create(e));
    });
  }
  onMouseUp(target, callback) {
    return addDisposableListener(target, "mouseup", (e) => {
      callback(this._create(e));
    });
  }
  onMouseDown(target, callback) {
    return addDisposableListener(target, EventType$1.MOUSE_DOWN, (e) => {
      callback(this._create(e));
    });
  }
  onPointerDown(target, callback) {
    return addDisposableListener(target, EventType$1.POINTER_DOWN, (e) => {
      callback(this._create(e), e.pointerId);
    });
  }
  onMouseLeave(target, callback) {
    return addDisposableListener(target, EventType$1.MOUSE_LEAVE, (e) => {
      callback(this._create(e));
    });
  }
  onMouseMove(target, callback) {
    return addDisposableListener(target, "mousemove", (e) => callback(this._create(e)));
  }
}
class EditorPointerEventFactory {
  constructor(editorViewDomNode) {
    this._editorViewDomNode = editorViewDomNode;
  }
  _create(e) {
    return new EditorMouseEvent(e, false, this._editorViewDomNode);
  }
  onPointerUp(target, callback) {
    return addDisposableListener(target, "pointerup", (e) => {
      callback(this._create(e));
    });
  }
  onPointerDown(target, callback) {
    return addDisposableListener(target, EventType$1.POINTER_DOWN, (e) => {
      callback(this._create(e), e.pointerId);
    });
  }
  onPointerLeave(target, callback) {
    return addDisposableListener(target, EventType$1.POINTER_LEAVE, (e) => {
      callback(this._create(e));
    });
  }
  onPointerMove(target, callback) {
    return addDisposableListener(target, "pointermove", (e) => callback(this._create(e)));
  }
}
class GlobalEditorPointerMoveMonitor extends Disposable {
  constructor(editorViewDomNode) {
    super();
    this._editorViewDomNode = editorViewDomNode;
    this._globalPointerMoveMonitor = this._register(new GlobalPointerMoveMonitor());
    this._keydownListener = null;
  }
  startMonitoring(initialElement, pointerId, initialButtons, pointerMoveCallback, onStopCallback) {
    this._keydownListener = addStandardDisposableListener(document, "keydown", (e) => {
      const chord = e.toKeyCodeChord();
      if (chord.isModifierKey()) {
        return;
      }
      this._globalPointerMoveMonitor.stopMonitoring(true, e.browserEvent);
    }, true);
    this._globalPointerMoveMonitor.startMonitoring(initialElement, pointerId, initialButtons, (e) => {
      pointerMoveCallback(new EditorMouseEvent(e, true, this._editorViewDomNode));
    }, (e) => {
      this._keydownListener.dispose();
      onStopCallback(e);
    });
  }
  stopMonitoring() {
    this._globalPointerMoveMonitor.stopMonitoring(true);
  }
}
class DynamicCssRules {
  constructor(_editor) {
    this._editor = _editor;
    this._instanceId = ++DynamicCssRules._idPool;
    this._counter = 0;
    this._rules = /* @__PURE__ */ new Map();
    this._garbageCollectionScheduler = new RunOnceScheduler(() => this.garbageCollect(), 1e3);
  }
  createClassNameRef(options) {
    const rule2 = this.getOrCreateRule(options);
    rule2.increaseRefCount();
    return {
      className: rule2.className,
      dispose: () => {
        rule2.decreaseRefCount();
        this._garbageCollectionScheduler.schedule();
      }
    };
  }
  getOrCreateRule(properties) {
    const key = this.computeUniqueKey(properties);
    let existingRule = this._rules.get(key);
    if (!existingRule) {
      const counter = this._counter++;
      existingRule = new RefCountedCssRule(key, `dyn-rule-${this._instanceId}-${counter}`, isInShadowDOM(this._editor.getContainerDomNode()) ? this._editor.getContainerDomNode() : void 0, properties);
      this._rules.set(key, existingRule);
    }
    return existingRule;
  }
  computeUniqueKey(properties) {
    return JSON.stringify(properties);
  }
  garbageCollect() {
    for (const rule2 of this._rules.values()) {
      if (!rule2.hasReferences()) {
        this._rules.delete(rule2.key);
        rule2.dispose();
      }
    }
  }
}
DynamicCssRules._idPool = 0;
class RefCountedCssRule {
  constructor(key, className3, _containerElement, properties) {
    this.key = key;
    this.className = className3;
    this.properties = properties;
    this._referenceCount = 0;
    this._styleElement = createStyleSheet(_containerElement);
    this._styleElement.textContent = this.getCssText(this.className, this.properties);
  }
  getCssText(className3, properties) {
    let str2 = `.${className3} {`;
    for (const prop in properties) {
      const value = properties[prop];
      let cssValue;
      if (typeof value === "object") {
        cssValue = asCssVariable(value.id);
      } else {
        cssValue = value;
      }
      const cssPropName = camelToDashes(prop);
      str2 += `
	${cssPropName}: ${cssValue};`;
    }
    str2 += `
}`;
    return str2;
  }
  dispose() {
    this._styleElement.remove();
  }
  increaseRefCount() {
    this._referenceCount++;
  }
  decreaseRefCount() {
    this._referenceCount--;
  }
  hasReferences() {
    return this._referenceCount > 0;
  }
}
function camelToDashes(str2) {
  return str2.replace(/(^[A-Z])/, ([first2]) => first2.toLowerCase()).replace(/([A-Z])/g, ([letter]) => `-${letter.toLowerCase()}`);
}
class ViewEventHandler extends Disposable {
  constructor() {
    super();
    this._shouldRender = true;
  }
  shouldRender() {
    return this._shouldRender;
  }
  forceShouldRender() {
    this._shouldRender = true;
  }
  setShouldRender() {
    this._shouldRender = true;
  }
  onDidRender() {
    this._shouldRender = false;
  }
  // --- begin event handlers
  onCompositionStart(e) {
    return false;
  }
  onCompositionEnd(e) {
    return false;
  }
  onConfigurationChanged(e) {
    return false;
  }
  onCursorStateChanged(e) {
    return false;
  }
  onDecorationsChanged(e) {
    return false;
  }
  onFlushed(e) {
    return false;
  }
  onFocusChanged(e) {
    return false;
  }
  onLanguageConfigurationChanged(e) {
    return false;
  }
  onLineMappingChanged(e) {
    return false;
  }
  onLinesChanged(e) {
    return false;
  }
  onLinesDeleted(e) {
    return false;
  }
  onLinesInserted(e) {
    return false;
  }
  onRevealRangeRequest(e) {
    return false;
  }
  onScrollChanged(e) {
    return false;
  }
  onThemeChanged(e) {
    return false;
  }
  onTokensChanged(e) {
    return false;
  }
  onTokensColorsChanged(e) {
    return false;
  }
  onZonesChanged(e) {
    return false;
  }
  // --- end event handlers
  handleEvents(events) {
    let shouldRender = false;
    for (let i = 0, len = events.length; i < len; i++) {
      const e = events[i];
      switch (e.type) {
        case 0:
          if (this.onCompositionStart(e)) {
            shouldRender = true;
          }
          break;
        case 1:
          if (this.onCompositionEnd(e)) {
            shouldRender = true;
          }
          break;
        case 2:
          if (this.onConfigurationChanged(e)) {
            shouldRender = true;
          }
          break;
        case 3:
          if (this.onCursorStateChanged(e)) {
            shouldRender = true;
          }
          break;
        case 4:
          if (this.onDecorationsChanged(e)) {
            shouldRender = true;
          }
          break;
        case 5:
          if (this.onFlushed(e)) {
            shouldRender = true;
          }
          break;
        case 6:
          if (this.onFocusChanged(e)) {
            shouldRender = true;
          }
          break;
        case 7:
          if (this.onLanguageConfigurationChanged(e)) {
            shouldRender = true;
          }
          break;
        case 8:
          if (this.onLineMappingChanged(e)) {
            shouldRender = true;
          }
          break;
        case 9:
          if (this.onLinesChanged(e)) {
            shouldRender = true;
          }
          break;
        case 10:
          if (this.onLinesDeleted(e)) {
            shouldRender = true;
          }
          break;
        case 11:
          if (this.onLinesInserted(e)) {
            shouldRender = true;
          }
          break;
        case 12:
          if (this.onRevealRangeRequest(e)) {
            shouldRender = true;
          }
          break;
        case 13:
          if (this.onScrollChanged(e)) {
            shouldRender = true;
          }
          break;
        case 15:
          if (this.onTokensChanged(e)) {
            shouldRender = true;
          }
          break;
        case 14:
          if (this.onThemeChanged(e)) {
            shouldRender = true;
          }
          break;
        case 16:
          if (this.onTokensColorsChanged(e)) {
            shouldRender = true;
          }
          break;
        case 17:
          if (this.onZonesChanged(e)) {
            shouldRender = true;
          }
          break;
        default:
          console.info("View received unknown event: ");
          console.info(e);
      }
    }
    if (shouldRender) {
      this._shouldRender = true;
    }
  }
}
class ViewPart extends ViewEventHandler {
  constructor(context) {
    super();
    this._context = context;
    this._context.addEventHandler(this);
  }
  dispose() {
    this._context.removeEventHandler(this);
    super.dispose();
  }
}
class PartFingerprints {
  static write(target, partId) {
    target.setAttribute("data-mprt", String(partId));
  }
  static read(target) {
    const r = target.getAttribute("data-mprt");
    if (r === null) {
      return 0;
    }
    return parseInt(r, 10);
  }
  static collect(child, stopAt) {
    const result2 = [];
    let resultLen = 0;
    while (child && child !== document.body) {
      if (child === stopAt) {
        break;
      }
      if (child.nodeType === child.ELEMENT_NODE) {
        result2[resultLen++] = this.read(child);
      }
      child = child.parentElement;
    }
    const r = new Uint8Array(resultLen);
    for (let i = 0; i < resultLen; i++) {
      r[i] = result2[resultLen - i - 1];
    }
    return r;
  }
}
class RestrictedRenderingContext {
  constructor(viewLayout, viewportData) {
    this._restrictedRenderingContextBrand = void 0;
    this._viewLayout = viewLayout;
    this.viewportData = viewportData;
    this.scrollWidth = this._viewLayout.getScrollWidth();
    this.scrollHeight = this._viewLayout.getScrollHeight();
    this.visibleRange = this.viewportData.visibleRange;
    this.bigNumbersDelta = this.viewportData.bigNumbersDelta;
    const vInfo = this._viewLayout.getCurrentViewport();
    this.scrollTop = vInfo.top;
    this.scrollLeft = vInfo.left;
    this.viewportWidth = vInfo.width;
    this.viewportHeight = vInfo.height;
  }
  getScrolledTopFromAbsoluteTop(absoluteTop) {
    return absoluteTop - this.scrollTop;
  }
  getVerticalOffsetForLineNumber(lineNumber, includeViewZones) {
    return this._viewLayout.getVerticalOffsetForLineNumber(lineNumber, includeViewZones);
  }
  getVerticalOffsetAfterLineNumber(lineNumber, includeViewZones) {
    return this._viewLayout.getVerticalOffsetAfterLineNumber(lineNumber, includeViewZones);
  }
  getDecorationsInViewport() {
    return this.viewportData.getDecorationsInViewport();
  }
}
class RenderingContext extends RestrictedRenderingContext {
  constructor(viewLayout, viewportData, viewLines2) {
    super(viewLayout, viewportData);
    this._renderingContextBrand = void 0;
    this._viewLines = viewLines2;
  }
  linesVisibleRangesForRange(range2, includeNewLines) {
    return this._viewLines.linesVisibleRangesForRange(range2, includeNewLines);
  }
  visibleRangeForPosition(position) {
    return this._viewLines.visibleRangeForPosition(position);
  }
}
class LineVisibleRanges {
  constructor(outsideRenderedLine, lineNumber, ranges, continuesOnNextLine) {
    this.outsideRenderedLine = outsideRenderedLine;
    this.lineNumber = lineNumber;
    this.ranges = ranges;
    this.continuesOnNextLine = continuesOnNextLine;
  }
}
class HorizontalRange {
  static from(ranges) {
    const result2 = new Array(ranges.length);
    for (let i = 0, len = ranges.length; i < len; i++) {
      const range2 = ranges[i];
      result2[i] = new HorizontalRange(range2.left, range2.width);
    }
    return result2;
  }
  constructor(left, width) {
    this._horizontalRangeBrand = void 0;
    this.left = Math.round(left);
    this.width = Math.round(width);
  }
  toString() {
    return `[${this.left},${this.width}]`;
  }
}
class FloatHorizontalRange {
  constructor(left, width) {
    this._floatHorizontalRangeBrand = void 0;
    this.left = left;
    this.width = width;
  }
  toString() {
    return `[${this.left},${this.width}]`;
  }
  static compare(a, b) {
    return a.left - b.left;
  }
}
class HorizontalPosition {
  constructor(outsideRenderedLine, left) {
    this.outsideRenderedLine = outsideRenderedLine;
    this.originalLeft = left;
    this.left = Math.round(this.originalLeft);
  }
}
class VisibleRanges {
  constructor(outsideRenderedLine, ranges) {
    this.outsideRenderedLine = outsideRenderedLine;
    this.ranges = ranges;
  }
}
class RangeUtil {
  static _createRange() {
    if (!this._handyReadyRange) {
      this._handyReadyRange = document.createRange();
    }
    return this._handyReadyRange;
  }
  static _detachRange(range2, endNode) {
    range2.selectNodeContents(endNode);
  }
  static _readClientRects(startElement, startOffset, endElement, endOffset, endNode) {
    const range2 = this._createRange();
    try {
      range2.setStart(startElement, startOffset);
      range2.setEnd(endElement, endOffset);
      return range2.getClientRects();
    } catch (e) {
      return null;
    } finally {
      this._detachRange(range2, endNode);
    }
  }
  static _mergeAdjacentRanges(ranges) {
    if (ranges.length === 1) {
      return ranges;
    }
    ranges.sort(FloatHorizontalRange.compare);
    const result2 = [];
    let resultLen = 0;
    let prev = ranges[0];
    for (let i = 1, len = ranges.length; i < len; i++) {
      const range2 = ranges[i];
      if (prev.left + prev.width + 0.9 >= range2.left) {
        prev.width = Math.max(prev.width, range2.left + range2.width - prev.left);
      } else {
        result2[resultLen++] = prev;
        prev = range2;
      }
    }
    result2[resultLen++] = prev;
    return result2;
  }
  static _createHorizontalRangesFromClientRects(clientRects, clientRectDeltaLeft, clientRectScale) {
    if (!clientRects || clientRects.length === 0) {
      return null;
    }
    const result2 = [];
    for (let i = 0, len = clientRects.length; i < len; i++) {
      const clientRect = clientRects[i];
      result2[i] = new FloatHorizontalRange(Math.max(0, (clientRect.left - clientRectDeltaLeft) / clientRectScale), clientRect.width / clientRectScale);
    }
    return this._mergeAdjacentRanges(result2);
  }
  static readHorizontalRanges(domNode, startChildIndex, startOffset, endChildIndex, endOffset, context) {
    const min = 0;
    const max = domNode.children.length - 1;
    if (min > max) {
      return null;
    }
    startChildIndex = Math.min(max, Math.max(min, startChildIndex));
    endChildIndex = Math.min(max, Math.max(min, endChildIndex));
    if (startChildIndex === endChildIndex && startOffset === endOffset && startOffset === 0 && !domNode.children[startChildIndex].firstChild) {
      const clientRects2 = domNode.children[startChildIndex].getClientRects();
      context.markDidDomLayout();
      return this._createHorizontalRangesFromClientRects(clientRects2, context.clientRectDeltaLeft, context.clientRectScale);
    }
    if (startChildIndex !== endChildIndex) {
      if (endChildIndex > 0 && endOffset === 0) {
        endChildIndex--;
        endOffset = 1073741824;
      }
    }
    let startElement = domNode.children[startChildIndex].firstChild;
    let endElement = domNode.children[endChildIndex].firstChild;
    if (!startElement || !endElement) {
      if (!startElement && startOffset === 0 && startChildIndex > 0) {
        startElement = domNode.children[startChildIndex - 1].firstChild;
        startOffset = 1073741824;
      }
      if (!endElement && endOffset === 0 && endChildIndex > 0) {
        endElement = domNode.children[endChildIndex - 1].firstChild;
        endOffset = 1073741824;
      }
    }
    if (!startElement || !endElement) {
      return null;
    }
    startOffset = Math.min(startElement.textContent.length, Math.max(0, startOffset));
    endOffset = Math.min(endElement.textContent.length, Math.max(0, endOffset));
    const clientRects = this._readClientRects(startElement, startOffset, endElement, endOffset, context.endNode);
    context.markDidDomLayout();
    return this._createHorizontalRangesFromClientRects(clientRects, context.clientRectDeltaLeft, context.clientRectScale);
  }
}
class LineDecoration {
  constructor(startColumn, endColumn, className3, type) {
    this.startColumn = startColumn;
    this.endColumn = endColumn;
    this.className = className3;
    this.type = type;
    this._lineDecorationBrand = void 0;
  }
  static _equals(a, b) {
    return a.startColumn === b.startColumn && a.endColumn === b.endColumn && a.className === b.className && a.type === b.type;
  }
  static equalsArr(a, b) {
    const aLen = a.length;
    const bLen = b.length;
    if (aLen !== bLen) {
      return false;
    }
    for (let i = 0; i < aLen; i++) {
      if (!LineDecoration._equals(a[i], b[i])) {
        return false;
      }
    }
    return true;
  }
  static extractWrapped(arr, startOffset, endOffset) {
    if (arr.length === 0) {
      return arr;
    }
    const startColumn = startOffset + 1;
    const endColumn = endOffset + 1;
    const lineLength = endOffset - startOffset;
    const r = [];
    let rLength = 0;
    for (const dec of arr) {
      if (dec.endColumn <= startColumn || dec.startColumn >= endColumn) {
        continue;
      }
      r[rLength++] = new LineDecoration(Math.max(1, dec.startColumn - startColumn + 1), Math.min(lineLength + 1, dec.endColumn - startColumn + 1), dec.className, dec.type);
    }
    return r;
  }
  static filter(lineDecorations, lineNumber, minLineColumn, maxLineColumn) {
    if (lineDecorations.length === 0) {
      return [];
    }
    const result2 = [];
    let resultLen = 0;
    for (let i = 0, len = lineDecorations.length; i < len; i++) {
      const d = lineDecorations[i];
      const range2 = d.range;
      if (range2.endLineNumber < lineNumber || range2.startLineNumber > lineNumber) {
        continue;
      }
      if (range2.isEmpty() && (d.type === 0 || d.type === 3)) {
        continue;
      }
      const startColumn = range2.startLineNumber === lineNumber ? range2.startColumn : minLineColumn;
      const endColumn = range2.endLineNumber === lineNumber ? range2.endColumn : maxLineColumn;
      result2[resultLen++] = new LineDecoration(startColumn, endColumn, d.inlineClassName, d.type);
    }
    return result2;
  }
  static _typeCompare(a, b) {
    const ORDER = [2, 0, 1, 3];
    return ORDER[a] - ORDER[b];
  }
  static compare(a, b) {
    if (a.startColumn !== b.startColumn) {
      return a.startColumn - b.startColumn;
    }
    if (a.endColumn !== b.endColumn) {
      return a.endColumn - b.endColumn;
    }
    const typeCmp = LineDecoration._typeCompare(a.type, b.type);
    if (typeCmp !== 0) {
      return typeCmp;
    }
    if (a.className !== b.className) {
      return a.className < b.className ? -1 : 1;
    }
    return 0;
  }
}
class DecorationSegment {
  constructor(startOffset, endOffset, className3, metadata) {
    this.startOffset = startOffset;
    this.endOffset = endOffset;
    this.className = className3;
    this.metadata = metadata;
  }
}
class Stack {
  constructor() {
    this.stopOffsets = [];
    this.classNames = [];
    this.metadata = [];
    this.count = 0;
  }
  static _metadata(metadata) {
    let result2 = 0;
    for (let i = 0, len = metadata.length; i < len; i++) {
      result2 |= metadata[i];
    }
    return result2;
  }
  consumeLowerThan(maxStopOffset, nextStartOffset, result2) {
    while (this.count > 0 && this.stopOffsets[0] < maxStopOffset) {
      let i = 0;
      while (i + 1 < this.count && this.stopOffsets[i] === this.stopOffsets[i + 1]) {
        i++;
      }
      result2.push(new DecorationSegment(nextStartOffset, this.stopOffsets[i], this.classNames.join(" "), Stack._metadata(this.metadata)));
      nextStartOffset = this.stopOffsets[i] + 1;
      this.stopOffsets.splice(0, i + 1);
      this.classNames.splice(0, i + 1);
      this.metadata.splice(0, i + 1);
      this.count -= i + 1;
    }
    if (this.count > 0 && nextStartOffset < maxStopOffset) {
      result2.push(new DecorationSegment(nextStartOffset, maxStopOffset - 1, this.classNames.join(" "), Stack._metadata(this.metadata)));
      nextStartOffset = maxStopOffset;
    }
    return nextStartOffset;
  }
  insert(stopOffset, className3, metadata) {
    if (this.count === 0 || this.stopOffsets[this.count - 1] <= stopOffset) {
      this.stopOffsets.push(stopOffset);
      this.classNames.push(className3);
      this.metadata.push(metadata);
    } else {
      for (let i = 0; i < this.count; i++) {
        if (this.stopOffsets[i] >= stopOffset) {
          this.stopOffsets.splice(i, 0, stopOffset);
          this.classNames.splice(i, 0, className3);
          this.metadata.splice(i, 0, metadata);
          break;
        }
      }
    }
    this.count++;
    return;
  }
}
class LineDecorationsNormalizer {
  /**
   * Normalize line decorations. Overlapping decorations will generate multiple segments
   */
  static normalize(lineContent, lineDecorations) {
    if (lineDecorations.length === 0) {
      return [];
    }
    const result2 = [];
    const stack = new Stack();
    let nextStartOffset = 0;
    for (let i = 0, len = lineDecorations.length; i < len; i++) {
      const d = lineDecorations[i];
      let startColumn = d.startColumn;
      let endColumn = d.endColumn;
      const className3 = d.className;
      const metadata = d.type === 1 ? 2 : d.type === 2 ? 4 : 0;
      if (startColumn > 1) {
        const charCodeBefore = lineContent.charCodeAt(startColumn - 2);
        if (isHighSurrogate(charCodeBefore)) {
          startColumn--;
        }
      }
      if (endColumn > 1) {
        const charCodeBefore = lineContent.charCodeAt(endColumn - 2);
        if (isHighSurrogate(charCodeBefore)) {
          endColumn--;
        }
      }
      const currentStartOffset = startColumn - 1;
      const currentEndOffset = endColumn - 2;
      nextStartOffset = stack.consumeLowerThan(currentStartOffset, nextStartOffset, result2);
      if (stack.count === 0) {
        nextStartOffset = currentStartOffset;
      }
      stack.insert(currentEndOffset, className3, metadata);
    }
    stack.consumeLowerThan(1073741824, nextStartOffset, result2);
    return result2;
  }
}
class LinePart {
  constructor(endIndex, type, metadata, containsRTL2) {
    this.endIndex = endIndex;
    this.type = type;
    this.metadata = metadata;
    this.containsRTL = containsRTL2;
    this._linePartBrand = void 0;
  }
  isWhitespace() {
    return this.metadata & 1 ? true : false;
  }
  isPseudoAfter() {
    return this.metadata & 4 ? true : false;
  }
}
let LineRange$1 = class LineRange {
  constructor(startIndex, endIndex) {
    this.startOffset = startIndex;
    this.endOffset = endIndex;
  }
  equals(otherLineRange) {
    return this.startOffset === otherLineRange.startOffset && this.endOffset === otherLineRange.endOffset;
  }
};
class RenderLineInput {
  constructor(useMonospaceOptimizations, canUseHalfwidthRightwardsArrow, lineContent, continuesWithWrappedLine, isBasicASCII2, containsRTL2, fauxIndentLength, lineTokens, lineDecorations, tabSize, startVisibleColumn, spaceWidth, middotWidth, wsmiddotWidth, stopRenderingLineAfter, renderWhitespace, renderControlCharacters, fontLigatures, selectionsOnLine) {
    this.useMonospaceOptimizations = useMonospaceOptimizations;
    this.canUseHalfwidthRightwardsArrow = canUseHalfwidthRightwardsArrow;
    this.lineContent = lineContent;
    this.continuesWithWrappedLine = continuesWithWrappedLine;
    this.isBasicASCII = isBasicASCII2;
    this.containsRTL = containsRTL2;
    this.fauxIndentLength = fauxIndentLength;
    this.lineTokens = lineTokens;
    this.lineDecorations = lineDecorations.sort(LineDecoration.compare);
    this.tabSize = tabSize;
    this.startVisibleColumn = startVisibleColumn;
    this.spaceWidth = spaceWidth;
    this.stopRenderingLineAfter = stopRenderingLineAfter;
    this.renderWhitespace = renderWhitespace === "all" ? 4 : renderWhitespace === "boundary" ? 1 : renderWhitespace === "selection" ? 2 : renderWhitespace === "trailing" ? 3 : 0;
    this.renderControlCharacters = renderControlCharacters;
    this.fontLigatures = fontLigatures;
    this.selectionsOnLine = selectionsOnLine && selectionsOnLine.sort((a, b) => a.startOffset < b.startOffset ? -1 : 1);
    const wsmiddotDiff = Math.abs(wsmiddotWidth - spaceWidth);
    const middotDiff = Math.abs(middotWidth - spaceWidth);
    if (wsmiddotDiff < middotDiff) {
      this.renderSpaceWidth = wsmiddotWidth;
      this.renderSpaceCharCode = 11825;
    } else {
      this.renderSpaceWidth = middotWidth;
      this.renderSpaceCharCode = 183;
    }
  }
  sameSelection(otherSelections) {
    if (this.selectionsOnLine === null) {
      return otherSelections === null;
    }
    if (otherSelections === null) {
      return false;
    }
    if (otherSelections.length !== this.selectionsOnLine.length) {
      return false;
    }
    for (let i = 0; i < this.selectionsOnLine.length; i++) {
      if (!this.selectionsOnLine[i].equals(otherSelections[i])) {
        return false;
      }
    }
    return true;
  }
  equals(other) {
    return this.useMonospaceOptimizations === other.useMonospaceOptimizations && this.canUseHalfwidthRightwardsArrow === other.canUseHalfwidthRightwardsArrow && this.lineContent === other.lineContent && this.continuesWithWrappedLine === other.continuesWithWrappedLine && this.isBasicASCII === other.isBasicASCII && this.containsRTL === other.containsRTL && this.fauxIndentLength === other.fauxIndentLength && this.tabSize === other.tabSize && this.startVisibleColumn === other.startVisibleColumn && this.spaceWidth === other.spaceWidth && this.renderSpaceWidth === other.renderSpaceWidth && this.renderSpaceCharCode === other.renderSpaceCharCode && this.stopRenderingLineAfter === other.stopRenderingLineAfter && this.renderWhitespace === other.renderWhitespace && this.renderControlCharacters === other.renderControlCharacters && this.fontLigatures === other.fontLigatures && LineDecoration.equalsArr(this.lineDecorations, other.lineDecorations) && this.lineTokens.equals(other.lineTokens) && this.sameSelection(other.selectionsOnLine);
  }
}
class DomPosition {
  constructor(partIndex, charIndex) {
    this.partIndex = partIndex;
    this.charIndex = charIndex;
  }
}
class CharacterMapping {
  static getPartIndex(partData) {
    return (partData & 4294901760) >>> 16;
  }
  static getCharIndex(partData) {
    return (partData & 65535) >>> 0;
  }
  constructor(length2, partCount) {
    this.length = length2;
    this._data = new Uint32Array(this.length);
    this._horizontalOffset = new Uint32Array(this.length);
  }
  setColumnInfo(column, partIndex, charIndex, horizontalOffset) {
    const partData = (partIndex << 16 | charIndex << 0) >>> 0;
    this._data[column - 1] = partData;
    this._horizontalOffset[column - 1] = horizontalOffset;
  }
  getHorizontalOffset(column) {
    if (this._horizontalOffset.length === 0) {
      return 0;
    }
    return this._horizontalOffset[column - 1];
  }
  charOffsetToPartData(charOffset) {
    if (this.length === 0) {
      return 0;
    }
    if (charOffset < 0) {
      return this._data[0];
    }
    if (charOffset >= this.length) {
      return this._data[this.length - 1];
    }
    return this._data[charOffset];
  }
  getDomPosition(column) {
    const partData = this.charOffsetToPartData(column - 1);
    const partIndex = CharacterMapping.getPartIndex(partData);
    const charIndex = CharacterMapping.getCharIndex(partData);
    return new DomPosition(partIndex, charIndex);
  }
  getColumn(domPosition, partLength) {
    const charOffset = this.partDataToCharOffset(domPosition.partIndex, partLength, domPosition.charIndex);
    return charOffset + 1;
  }
  partDataToCharOffset(partIndex, partLength, charIndex) {
    if (this.length === 0) {
      return 0;
    }
    const searchEntry = (partIndex << 16 | charIndex << 0) >>> 0;
    let min = 0;
    let max = this.length - 1;
    while (min + 1 < max) {
      const mid = min + max >>> 1;
      const midEntry = this._data[mid];
      if (midEntry === searchEntry) {
        return mid;
      } else if (midEntry > searchEntry) {
        max = mid;
      } else {
        min = mid;
      }
    }
    if (min === max) {
      return min;
    }
    const minEntry = this._data[min];
    const maxEntry = this._data[max];
    if (minEntry === searchEntry) {
      return min;
    }
    if (maxEntry === searchEntry) {
      return max;
    }
    const minPartIndex = CharacterMapping.getPartIndex(minEntry);
    const minCharIndex = CharacterMapping.getCharIndex(minEntry);
    const maxPartIndex = CharacterMapping.getPartIndex(maxEntry);
    let maxCharIndex;
    if (minPartIndex !== maxPartIndex) {
      maxCharIndex = partLength;
    } else {
      maxCharIndex = CharacterMapping.getCharIndex(maxEntry);
    }
    const minEntryDistance = charIndex - minCharIndex;
    const maxEntryDistance = maxCharIndex - charIndex;
    if (minEntryDistance <= maxEntryDistance) {
      return min;
    }
    return max;
  }
}
class RenderLineOutput {
  constructor(characterMapping, containsRTL2, containsForeignElements) {
    this._renderLineOutputBrand = void 0;
    this.characterMapping = characterMapping;
    this.containsRTL = containsRTL2;
    this.containsForeignElements = containsForeignElements;
  }
}
function renderViewLine(input2, sb) {
  if (input2.lineContent.length === 0) {
    if (input2.lineDecorations.length > 0) {
      sb.appendString(`<span>`);
      let beforeCount = 0;
      let afterCount = 0;
      let containsForeignElements = 0;
      for (const lineDecoration of input2.lineDecorations) {
        if (lineDecoration.type === 1 || lineDecoration.type === 2) {
          sb.appendString(`<span class="`);
          sb.appendString(lineDecoration.className);
          sb.appendString(`"></span>`);
          if (lineDecoration.type === 1) {
            containsForeignElements |= 1;
            beforeCount++;
          }
          if (lineDecoration.type === 2) {
            containsForeignElements |= 2;
            afterCount++;
          }
        }
      }
      sb.appendString(`</span>`);
      const characterMapping = new CharacterMapping(1, beforeCount + afterCount);
      characterMapping.setColumnInfo(1, beforeCount, 0, 0);
      return new RenderLineOutput(characterMapping, false, containsForeignElements);
    }
    sb.appendString("<span><span></span></span>");
    return new RenderLineOutput(
      new CharacterMapping(0, 0),
      false,
      0
      /* ForeignElementType.None */
    );
  }
  return _renderLine(resolveRenderLineInput(input2), sb);
}
class RenderLineOutput2 {
  constructor(characterMapping, html2, containsRTL2, containsForeignElements) {
    this.characterMapping = characterMapping;
    this.html = html2;
    this.containsRTL = containsRTL2;
    this.containsForeignElements = containsForeignElements;
  }
}
function renderViewLine2(input2) {
  const sb = new StringBuilder(1e4);
  const out = renderViewLine(input2, sb);
  return new RenderLineOutput2(out.characterMapping, sb.build(), out.containsRTL, out.containsForeignElements);
}
class ResolvedRenderLineInput {
  constructor(fontIsMonospace, canUseHalfwidthRightwardsArrow, lineContent, len, isOverflowing, overflowingCharCount, parts, containsForeignElements, fauxIndentLength, tabSize, startVisibleColumn, containsRTL2, spaceWidth, renderSpaceCharCode, renderWhitespace, renderControlCharacters) {
    this.fontIsMonospace = fontIsMonospace;
    this.canUseHalfwidthRightwardsArrow = canUseHalfwidthRightwardsArrow;
    this.lineContent = lineContent;
    this.len = len;
    this.isOverflowing = isOverflowing;
    this.overflowingCharCount = overflowingCharCount;
    this.parts = parts;
    this.containsForeignElements = containsForeignElements;
    this.fauxIndentLength = fauxIndentLength;
    this.tabSize = tabSize;
    this.startVisibleColumn = startVisibleColumn;
    this.containsRTL = containsRTL2;
    this.spaceWidth = spaceWidth;
    this.renderSpaceCharCode = renderSpaceCharCode;
    this.renderWhitespace = renderWhitespace;
    this.renderControlCharacters = renderControlCharacters;
  }
}
function resolveRenderLineInput(input2) {
  const lineContent = input2.lineContent;
  let isOverflowing;
  let overflowingCharCount;
  let len;
  if (input2.stopRenderingLineAfter !== -1 && input2.stopRenderingLineAfter < lineContent.length) {
    isOverflowing = true;
    overflowingCharCount = lineContent.length - input2.stopRenderingLineAfter;
    len = input2.stopRenderingLineAfter;
  } else {
    isOverflowing = false;
    overflowingCharCount = 0;
    len = lineContent.length;
  }
  let tokens = transformAndRemoveOverflowing(lineContent, input2.containsRTL, input2.lineTokens, input2.fauxIndentLength, len);
  if (input2.renderControlCharacters && !input2.isBasicASCII) {
    tokens = extractControlCharacters(lineContent, tokens);
  }
  if (input2.renderWhitespace === 4 || input2.renderWhitespace === 1 || input2.renderWhitespace === 2 && !!input2.selectionsOnLine || input2.renderWhitespace === 3 && !input2.continuesWithWrappedLine) {
    tokens = _applyRenderWhitespace(input2, lineContent, len, tokens);
  }
  let containsForeignElements = 0;
  if (input2.lineDecorations.length > 0) {
    for (let i = 0, len2 = input2.lineDecorations.length; i < len2; i++) {
      const lineDecoration = input2.lineDecorations[i];
      if (lineDecoration.type === 3) {
        containsForeignElements |= 1;
      } else if (lineDecoration.type === 1) {
        containsForeignElements |= 1;
      } else if (lineDecoration.type === 2) {
        containsForeignElements |= 2;
      }
    }
    tokens = _applyInlineDecorations(lineContent, len, tokens, input2.lineDecorations);
  }
  if (!input2.containsRTL) {
    tokens = splitLargeTokens(lineContent, tokens, !input2.isBasicASCII || input2.fontLigatures);
  }
  return new ResolvedRenderLineInput(input2.useMonospaceOptimizations, input2.canUseHalfwidthRightwardsArrow, lineContent, len, isOverflowing, overflowingCharCount, tokens, containsForeignElements, input2.fauxIndentLength, input2.tabSize, input2.startVisibleColumn, input2.containsRTL, input2.spaceWidth, input2.renderSpaceCharCode, input2.renderWhitespace, input2.renderControlCharacters);
}
function transformAndRemoveOverflowing(lineContent, lineContainsRTL, tokens, fauxIndentLength, len) {
  const result2 = [];
  let resultLen = 0;
  if (fauxIndentLength > 0) {
    result2[resultLen++] = new LinePart(fauxIndentLength, "", 0, false);
  }
  let startOffset = fauxIndentLength;
  for (let tokenIndex = 0, tokensLen = tokens.getCount(); tokenIndex < tokensLen; tokenIndex++) {
    const endIndex = tokens.getEndOffset(tokenIndex);
    if (endIndex <= fauxIndentLength) {
      continue;
    }
    const type = tokens.getClassName(tokenIndex);
    if (endIndex >= len) {
      const tokenContainsRTL2 = lineContainsRTL ? containsRTL(lineContent.substring(startOffset, len)) : false;
      result2[resultLen++] = new LinePart(len, type, 0, tokenContainsRTL2);
      break;
    }
    const tokenContainsRTL = lineContainsRTL ? containsRTL(lineContent.substring(startOffset, endIndex)) : false;
    result2[resultLen++] = new LinePart(endIndex, type, 0, tokenContainsRTL);
    startOffset = endIndex;
  }
  return result2;
}
function splitLargeTokens(lineContent, tokens, onlyAtSpaces) {
  let lastTokenEndIndex = 0;
  const result2 = [];
  let resultLen = 0;
  if (onlyAtSpaces) {
    for (let i = 0, len = tokens.length; i < len; i++) {
      const token = tokens[i];
      const tokenEndIndex = token.endIndex;
      if (lastTokenEndIndex + 50 < tokenEndIndex) {
        const tokenType = token.type;
        const tokenMetadata = token.metadata;
        const tokenContainsRTL = token.containsRTL;
        let lastSpaceOffset = -1;
        let currTokenStart = lastTokenEndIndex;
        for (let j = lastTokenEndIndex; j < tokenEndIndex; j++) {
          if (lineContent.charCodeAt(j) === 32) {
            lastSpaceOffset = j;
          }
          if (lastSpaceOffset !== -1 && j - currTokenStart >= 50) {
            result2[resultLen++] = new LinePart(lastSpaceOffset + 1, tokenType, tokenMetadata, tokenContainsRTL);
            currTokenStart = lastSpaceOffset + 1;
            lastSpaceOffset = -1;
          }
        }
        if (currTokenStart !== tokenEndIndex) {
          result2[resultLen++] = new LinePart(tokenEndIndex, tokenType, tokenMetadata, tokenContainsRTL);
        }
      } else {
        result2[resultLen++] = token;
      }
      lastTokenEndIndex = tokenEndIndex;
    }
  } else {
    for (let i = 0, len = tokens.length; i < len; i++) {
      const token = tokens[i];
      const tokenEndIndex = token.endIndex;
      const diff = tokenEndIndex - lastTokenEndIndex;
      if (diff > 50) {
        const tokenType = token.type;
        const tokenMetadata = token.metadata;
        const tokenContainsRTL = token.containsRTL;
        const piecesCount = Math.ceil(
          diff / 50
          /* Constants.LongToken */
        );
        for (let j = 1; j < piecesCount; j++) {
          const pieceEndIndex = lastTokenEndIndex + j * 50;
          result2[resultLen++] = new LinePart(pieceEndIndex, tokenType, tokenMetadata, tokenContainsRTL);
        }
        result2[resultLen++] = new LinePart(tokenEndIndex, tokenType, tokenMetadata, tokenContainsRTL);
      } else {
        result2[resultLen++] = token;
      }
      lastTokenEndIndex = tokenEndIndex;
    }
  }
  return result2;
}
function isControlCharacter(charCode) {
  if (charCode < 32) {
    return charCode !== 9;
  }
  if (charCode === 127) {
    return true;
  }
  if (charCode >= 8234 && charCode <= 8238 || charCode >= 8294 && charCode <= 8297 || charCode >= 8206 && charCode <= 8207 || charCode === 1564) {
    return true;
  }
  return false;
}
function extractControlCharacters(lineContent, tokens) {
  const result2 = [];
  let lastLinePart = new LinePart(0, "", 0, false);
  let charOffset = 0;
  for (const token of tokens) {
    const tokenEndIndex = token.endIndex;
    for (; charOffset < tokenEndIndex; charOffset++) {
      const charCode = lineContent.charCodeAt(charOffset);
      if (isControlCharacter(charCode)) {
        if (charOffset > lastLinePart.endIndex) {
          lastLinePart = new LinePart(charOffset, token.type, token.metadata, token.containsRTL);
          result2.push(lastLinePart);
        }
        lastLinePart = new LinePart(charOffset + 1, "mtkcontrol", token.metadata, false);
        result2.push(lastLinePart);
      }
    }
    if (charOffset > lastLinePart.endIndex) {
      lastLinePart = new LinePart(tokenEndIndex, token.type, token.metadata, token.containsRTL);
      result2.push(lastLinePart);
    }
  }
  return result2;
}
function _applyRenderWhitespace(input2, lineContent, len, tokens) {
  const continuesWithWrappedLine = input2.continuesWithWrappedLine;
  const fauxIndentLength = input2.fauxIndentLength;
  const tabSize = input2.tabSize;
  const startVisibleColumn = input2.startVisibleColumn;
  const useMonospaceOptimizations = input2.useMonospaceOptimizations;
  const selections2 = input2.selectionsOnLine;
  const onlyBoundary = input2.renderWhitespace === 1;
  const onlyTrailing = input2.renderWhitespace === 3;
  const generateLinePartForEachWhitespace = input2.renderSpaceWidth !== input2.spaceWidth;
  const result2 = [];
  let resultLen = 0;
  let tokenIndex = 0;
  let tokenType = tokens[tokenIndex].type;
  let tokenContainsRTL = tokens[tokenIndex].containsRTL;
  let tokenEndIndex = tokens[tokenIndex].endIndex;
  const tokensLength = tokens.length;
  let lineIsEmptyOrWhitespace = false;
  let firstNonWhitespaceIndex$1 = firstNonWhitespaceIndex(lineContent);
  let lastNonWhitespaceIndex$1;
  if (firstNonWhitespaceIndex$1 === -1) {
    lineIsEmptyOrWhitespace = true;
    firstNonWhitespaceIndex$1 = len;
    lastNonWhitespaceIndex$1 = len;
  } else {
    lastNonWhitespaceIndex$1 = lastNonWhitespaceIndex(lineContent);
  }
  let wasInWhitespace = false;
  let currentSelectionIndex = 0;
  let currentSelection = selections2 && selections2[currentSelectionIndex];
  let tmpIndent = startVisibleColumn % tabSize;
  for (let charIndex = fauxIndentLength; charIndex < len; charIndex++) {
    const chCode = lineContent.charCodeAt(charIndex);
    if (currentSelection && charIndex >= currentSelection.endOffset) {
      currentSelectionIndex++;
      currentSelection = selections2 && selections2[currentSelectionIndex];
    }
    let isInWhitespace;
    if (charIndex < firstNonWhitespaceIndex$1 || charIndex > lastNonWhitespaceIndex$1) {
      isInWhitespace = true;
    } else if (chCode === 9) {
      isInWhitespace = true;
    } else if (chCode === 32) {
      if (onlyBoundary) {
        if (wasInWhitespace) {
          isInWhitespace = true;
        } else {
          const nextChCode = charIndex + 1 < len ? lineContent.charCodeAt(charIndex + 1) : 0;
          isInWhitespace = nextChCode === 32 || nextChCode === 9;
        }
      } else {
        isInWhitespace = true;
      }
    } else {
      isInWhitespace = false;
    }
    if (isInWhitespace && selections2) {
      isInWhitespace = !!currentSelection && currentSelection.startOffset <= charIndex && currentSelection.endOffset > charIndex;
    }
    if (isInWhitespace && onlyTrailing) {
      isInWhitespace = lineIsEmptyOrWhitespace || charIndex > lastNonWhitespaceIndex$1;
    }
    if (isInWhitespace && tokenContainsRTL) {
      if (charIndex >= firstNonWhitespaceIndex$1 && charIndex <= lastNonWhitespaceIndex$1) {
        isInWhitespace = false;
      }
    }
    if (wasInWhitespace) {
      if (!isInWhitespace || !useMonospaceOptimizations && tmpIndent >= tabSize) {
        if (generateLinePartForEachWhitespace) {
          const lastEndIndex = resultLen > 0 ? result2[resultLen - 1].endIndex : fauxIndentLength;
          for (let i = lastEndIndex + 1; i <= charIndex; i++) {
            result2[resultLen++] = new LinePart(i, "mtkw", 1, false);
          }
        } else {
          result2[resultLen++] = new LinePart(charIndex, "mtkw", 1, false);
        }
        tmpIndent = tmpIndent % tabSize;
      }
    } else {
      if (charIndex === tokenEndIndex || isInWhitespace && charIndex > fauxIndentLength) {
        result2[resultLen++] = new LinePart(charIndex, tokenType, 0, tokenContainsRTL);
        tmpIndent = tmpIndent % tabSize;
      }
    }
    if (chCode === 9) {
      tmpIndent = tabSize;
    } else if (isFullWidthCharacter(chCode)) {
      tmpIndent += 2;
    } else {
      tmpIndent++;
    }
    wasInWhitespace = isInWhitespace;
    while (charIndex === tokenEndIndex) {
      tokenIndex++;
      if (tokenIndex < tokensLength) {
        tokenType = tokens[tokenIndex].type;
        tokenContainsRTL = tokens[tokenIndex].containsRTL;
        tokenEndIndex = tokens[tokenIndex].endIndex;
      } else {
        break;
      }
    }
  }
  let generateWhitespace = false;
  if (wasInWhitespace) {
    if (continuesWithWrappedLine && onlyBoundary) {
      const lastCharCode = len > 0 ? lineContent.charCodeAt(len - 1) : 0;
      const prevCharCode = len > 1 ? lineContent.charCodeAt(len - 2) : 0;
      const isSingleTrailingSpace = lastCharCode === 32 && (prevCharCode !== 32 && prevCharCode !== 9);
      if (!isSingleTrailingSpace) {
        generateWhitespace = true;
      }
    } else {
      generateWhitespace = true;
    }
  }
  if (generateWhitespace) {
    if (generateLinePartForEachWhitespace) {
      const lastEndIndex = resultLen > 0 ? result2[resultLen - 1].endIndex : fauxIndentLength;
      for (let i = lastEndIndex + 1; i <= len; i++) {
        result2[resultLen++] = new LinePart(i, "mtkw", 1, false);
      }
    } else {
      result2[resultLen++] = new LinePart(len, "mtkw", 1, false);
    }
  } else {
    result2[resultLen++] = new LinePart(len, tokenType, 0, tokenContainsRTL);
  }
  return result2;
}
function _applyInlineDecorations(lineContent, len, tokens, _lineDecorations) {
  _lineDecorations.sort(LineDecoration.compare);
  const lineDecorations = LineDecorationsNormalizer.normalize(lineContent, _lineDecorations);
  const lineDecorationsLen = lineDecorations.length;
  let lineDecorationIndex = 0;
  const result2 = [];
  let resultLen = 0;
  let lastResultEndIndex = 0;
  for (let tokenIndex = 0, len2 = tokens.length; tokenIndex < len2; tokenIndex++) {
    const token = tokens[tokenIndex];
    const tokenEndIndex = token.endIndex;
    const tokenType = token.type;
    const tokenMetadata = token.metadata;
    const tokenContainsRTL = token.containsRTL;
    while (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset < tokenEndIndex) {
      const lineDecoration = lineDecorations[lineDecorationIndex];
      if (lineDecoration.startOffset > lastResultEndIndex) {
        lastResultEndIndex = lineDecoration.startOffset;
        result2[resultLen++] = new LinePart(lastResultEndIndex, tokenType, tokenMetadata, tokenContainsRTL);
      }
      if (lineDecoration.endOffset + 1 <= tokenEndIndex) {
        lastResultEndIndex = lineDecoration.endOffset + 1;
        result2[resultLen++] = new LinePart(lastResultEndIndex, tokenType + " " + lineDecoration.className, tokenMetadata | lineDecoration.metadata, tokenContainsRTL);
        lineDecorationIndex++;
      } else {
        lastResultEndIndex = tokenEndIndex;
        result2[resultLen++] = new LinePart(lastResultEndIndex, tokenType + " " + lineDecoration.className, tokenMetadata | lineDecoration.metadata, tokenContainsRTL);
        break;
      }
    }
    if (tokenEndIndex > lastResultEndIndex) {
      lastResultEndIndex = tokenEndIndex;
      result2[resultLen++] = new LinePart(lastResultEndIndex, tokenType, tokenMetadata, tokenContainsRTL);
    }
  }
  const lastTokenEndIndex = tokens[tokens.length - 1].endIndex;
  if (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset === lastTokenEndIndex) {
    while (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset === lastTokenEndIndex) {
      const lineDecoration = lineDecorations[lineDecorationIndex];
      result2[resultLen++] = new LinePart(lastResultEndIndex, lineDecoration.className, lineDecoration.metadata, false);
      lineDecorationIndex++;
    }
  }
  return result2;
}
function _renderLine(input2, sb) {
  const fontIsMonospace = input2.fontIsMonospace;
  const canUseHalfwidthRightwardsArrow = input2.canUseHalfwidthRightwardsArrow;
  const containsForeignElements = input2.containsForeignElements;
  const lineContent = input2.lineContent;
  const len = input2.len;
  const isOverflowing = input2.isOverflowing;
  const overflowingCharCount = input2.overflowingCharCount;
  const parts = input2.parts;
  const fauxIndentLength = input2.fauxIndentLength;
  const tabSize = input2.tabSize;
  const startVisibleColumn = input2.startVisibleColumn;
  const containsRTL2 = input2.containsRTL;
  const spaceWidth = input2.spaceWidth;
  const renderSpaceCharCode = input2.renderSpaceCharCode;
  const renderWhitespace = input2.renderWhitespace;
  const renderControlCharacters = input2.renderControlCharacters;
  const characterMapping = new CharacterMapping(len + 1, parts.length);
  let lastCharacterMappingDefined = false;
  let charIndex = 0;
  let visibleColumn = startVisibleColumn;
  let charOffsetInPart = 0;
  let charHorizontalOffset = 0;
  let partDisplacement = 0;
  if (containsRTL2) {
    sb.appendString('<span dir="ltr">');
  } else {
    sb.appendString("<span>");
  }
  for (let partIndex = 0, tokensLen = parts.length; partIndex < tokensLen; partIndex++) {
    const part = parts[partIndex];
    const partEndIndex = part.endIndex;
    const partType = part.type;
    const partContainsRTL = part.containsRTL;
    const partRendersWhitespace = renderWhitespace !== 0 && part.isWhitespace();
    const partRendersWhitespaceWithWidth = partRendersWhitespace && !fontIsMonospace && (partType === "mtkw" || !containsForeignElements);
    const partIsEmptyAndHasPseudoAfter = charIndex === partEndIndex && part.isPseudoAfter();
    charOffsetInPart = 0;
    sb.appendString("<span ");
    if (partContainsRTL) {
      sb.appendString('style="unicode-bidi:isolate" ');
    }
    sb.appendString('class="');
    sb.appendString(partRendersWhitespaceWithWidth ? "mtkz" : partType);
    sb.appendASCIICharCode(
      34
      /* CharCode.DoubleQuote */
    );
    if (partRendersWhitespace) {
      let partWidth = 0;
      {
        let _charIndex = charIndex;
        let _visibleColumn = visibleColumn;
        for (; _charIndex < partEndIndex; _charIndex++) {
          const charCode = lineContent.charCodeAt(_charIndex);
          const charWidth = (charCode === 9 ? tabSize - _visibleColumn % tabSize : 1) | 0;
          partWidth += charWidth;
          if (_charIndex >= fauxIndentLength) {
            _visibleColumn += charWidth;
          }
        }
      }
      if (partRendersWhitespaceWithWidth) {
        sb.appendString(' style="width:');
        sb.appendString(String(spaceWidth * partWidth));
        sb.appendString('px"');
      }
      sb.appendASCIICharCode(
        62
        /* CharCode.GreaterThan */
      );
      for (; charIndex < partEndIndex; charIndex++) {
        characterMapping.setColumnInfo(charIndex + 1, partIndex - partDisplacement, charOffsetInPart, charHorizontalOffset);
        partDisplacement = 0;
        const charCode = lineContent.charCodeAt(charIndex);
        let producedCharacters;
        let charWidth;
        if (charCode === 9) {
          producedCharacters = tabSize - visibleColumn % tabSize | 0;
          charWidth = producedCharacters;
          if (!canUseHalfwidthRightwardsArrow || charWidth > 1) {
            sb.appendCharCode(8594);
          } else {
            sb.appendCharCode(65515);
          }
          for (let space2 = 2; space2 <= charWidth; space2++) {
            sb.appendCharCode(160);
          }
        } else {
          producedCharacters = 2;
          charWidth = 1;
          sb.appendCharCode(renderSpaceCharCode);
          sb.appendCharCode(8204);
        }
        charOffsetInPart += producedCharacters;
        charHorizontalOffset += charWidth;
        if (charIndex >= fauxIndentLength) {
          visibleColumn += charWidth;
        }
      }
    } else {
      sb.appendASCIICharCode(
        62
        /* CharCode.GreaterThan */
      );
      for (; charIndex < partEndIndex; charIndex++) {
        characterMapping.setColumnInfo(charIndex + 1, partIndex - partDisplacement, charOffsetInPart, charHorizontalOffset);
        partDisplacement = 0;
        const charCode = lineContent.charCodeAt(charIndex);
        let producedCharacters = 1;
        let charWidth = 1;
        switch (charCode) {
          case 9:
            producedCharacters = tabSize - visibleColumn % tabSize;
            charWidth = producedCharacters;
            for (let space2 = 1; space2 <= producedCharacters; space2++) {
              sb.appendCharCode(160);
            }
            break;
          case 32:
            sb.appendCharCode(160);
            break;
          case 60:
            sb.appendString("&lt;");
            break;
          case 62:
            sb.appendString("&gt;");
            break;
          case 38:
            sb.appendString("&amp;");
            break;
          case 0:
            if (renderControlCharacters) {
              sb.appendCharCode(9216);
            } else {
              sb.appendString("&#00;");
            }
            break;
          case 65279:
          case 8232:
          case 8233:
          case 133:
            sb.appendCharCode(65533);
            break;
          default:
            if (isFullWidthCharacter(charCode)) {
              charWidth++;
            }
            if (renderControlCharacters && charCode < 32) {
              sb.appendCharCode(9216 + charCode);
            } else if (renderControlCharacters && charCode === 127) {
              sb.appendCharCode(9249);
            } else if (renderControlCharacters && isControlCharacter(charCode)) {
              sb.appendString("[U+");
              sb.appendString(to4CharHex(charCode));
              sb.appendString("]");
              producedCharacters = 8;
              charWidth = producedCharacters;
            } else {
              sb.appendCharCode(charCode);
            }
        }
        charOffsetInPart += producedCharacters;
        charHorizontalOffset += charWidth;
        if (charIndex >= fauxIndentLength) {
          visibleColumn += charWidth;
        }
      }
    }
    if (partIsEmptyAndHasPseudoAfter) {
      partDisplacement++;
    } else {
      partDisplacement = 0;
    }
    if (charIndex >= len && !lastCharacterMappingDefined && part.isPseudoAfter()) {
      lastCharacterMappingDefined = true;
      characterMapping.setColumnInfo(charIndex + 1, partIndex, charOffsetInPart, charHorizontalOffset);
    }
    sb.appendString("</span>");
  }
  if (!lastCharacterMappingDefined) {
    characterMapping.setColumnInfo(len + 1, parts.length - 1, charOffsetInPart, charHorizontalOffset);
  }
  if (isOverflowing) {
    sb.appendString('<span class="mtkoverflow">');
    sb.appendString(localize("showMore", "Show more ({0})", renderOverflowingCharCount(overflowingCharCount)));
    sb.appendString("</span>");
  }
  sb.appendString("</span>");
  return new RenderLineOutput(characterMapping, containsRTL2, containsForeignElements);
}
function to4CharHex(n2) {
  return n2.toString(16).toUpperCase().padStart(4, "0");
}
function renderOverflowingCharCount(n2) {
  if (n2 < 1024) {
    return localize("overflow.chars", "{0} chars", n2);
  }
  if (n2 < 1024 * 1024) {
    return `${(n2 / 1024).toFixed(1)} KB`;
  }
  return `${(n2 / 1024 / 1024).toFixed(1)} MB`;
}
var ColorScheme;
(function(ColorScheme2) {
  ColorScheme2["DARK"] = "dark";
  ColorScheme2["LIGHT"] = "light";
  ColorScheme2["HIGH_CONTRAST_DARK"] = "hcDark";
  ColorScheme2["HIGH_CONTRAST_LIGHT"] = "hcLight";
})(ColorScheme || (ColorScheme = {}));
function isHighContrast(scheme) {
  return scheme === ColorScheme.HIGH_CONTRAST_DARK || scheme === ColorScheme.HIGH_CONTRAST_LIGHT;
}
function isDark(scheme) {
  return scheme === ColorScheme.DARK || scheme === ColorScheme.HIGH_CONTRAST_DARK;
}
const canUseFastRenderedViewLine = function() {
  if (isNative) {
    return true;
  }
  if (isLinux || isFirefox$1 || isSafari$1) {
    return false;
  }
  return true;
}();
let monospaceAssumptionsAreValid = true;
class ViewLineOptions {
  constructor(config2, themeType) {
    this.themeType = themeType;
    const options = config2.options;
    const fontInfo = options.get(
      49
      /* EditorOption.fontInfo */
    );
    const experimentalWhitespaceRendering = options.get(
      37
      /* EditorOption.experimentalWhitespaceRendering */
    );
    if (experimentalWhitespaceRendering === "off") {
      this.renderWhitespace = options.get(
        97
        /* EditorOption.renderWhitespace */
      );
    } else {
      this.renderWhitespace = "none";
    }
    this.renderControlCharacters = options.get(
      92
      /* EditorOption.renderControlCharacters */
    );
    this.spaceWidth = fontInfo.spaceWidth;
    this.middotWidth = fontInfo.middotWidth;
    this.wsmiddotWidth = fontInfo.wsmiddotWidth;
    this.useMonospaceOptimizations = fontInfo.isMonospace && !options.get(
      32
      /* EditorOption.disableMonospaceOptimizations */
    );
    this.canUseHalfwidthRightwardsArrow = fontInfo.canUseHalfwidthRightwardsArrow;
    this.lineHeight = options.get(
      65
      /* EditorOption.lineHeight */
    );
    this.stopRenderingLineAfter = options.get(
      115
      /* EditorOption.stopRenderingLineAfter */
    );
    this.fontLigatures = options.get(
      50
      /* EditorOption.fontLigatures */
    );
  }
  equals(other) {
    return this.themeType === other.themeType && this.renderWhitespace === other.renderWhitespace && this.renderControlCharacters === other.renderControlCharacters && this.spaceWidth === other.spaceWidth && this.middotWidth === other.middotWidth && this.wsmiddotWidth === other.wsmiddotWidth && this.useMonospaceOptimizations === other.useMonospaceOptimizations && this.canUseHalfwidthRightwardsArrow === other.canUseHalfwidthRightwardsArrow && this.lineHeight === other.lineHeight && this.stopRenderingLineAfter === other.stopRenderingLineAfter && this.fontLigatures === other.fontLigatures;
  }
}
class ViewLine {
  constructor(options) {
    this._options = options;
    this._isMaybeInvalid = true;
    this._renderedViewLine = null;
  }
  // --- begin IVisibleLineData
  getDomNode() {
    if (this._renderedViewLine && this._renderedViewLine.domNode) {
      return this._renderedViewLine.domNode.domNode;
    }
    return null;
  }
  setDomNode(domNode) {
    if (this._renderedViewLine) {
      this._renderedViewLine.domNode = createFastDomNode(domNode);
    } else {
      throw new Error("I have no rendered view line to set the dom node to...");
    }
  }
  onContentChanged() {
    this._isMaybeInvalid = true;
  }
  onTokensChanged() {
    this._isMaybeInvalid = true;
  }
  onDecorationsChanged() {
    this._isMaybeInvalid = true;
  }
  onOptionsChanged(newOptions) {
    this._isMaybeInvalid = true;
    this._options = newOptions;
  }
  onSelectionChanged() {
    if (isHighContrast(this._options.themeType) || this._options.renderWhitespace === "selection") {
      this._isMaybeInvalid = true;
      return true;
    }
    return false;
  }
  renderLine(lineNumber, deltaTop, viewportData, sb) {
    if (this._isMaybeInvalid === false) {
      return false;
    }
    this._isMaybeInvalid = false;
    const lineData = viewportData.getViewLineRenderingData(lineNumber);
    const options = this._options;
    const actualInlineDecorations = LineDecoration.filter(lineData.inlineDecorations, lineNumber, lineData.minColumn, lineData.maxColumn);
    let selectionsOnLine = null;
    if (isHighContrast(options.themeType) || this._options.renderWhitespace === "selection") {
      const selections2 = viewportData.selections;
      for (const selection of selections2) {
        if (selection.endLineNumber < lineNumber || selection.startLineNumber > lineNumber) {
          continue;
        }
        const startColumn = selection.startLineNumber === lineNumber ? selection.startColumn : lineData.minColumn;
        const endColumn = selection.endLineNumber === lineNumber ? selection.endColumn : lineData.maxColumn;
        if (startColumn < endColumn) {
          if (isHighContrast(options.themeType)) {
            actualInlineDecorations.push(new LineDecoration(
              startColumn,
              endColumn,
              "inline-selected-text",
              0
              /* InlineDecorationType.Regular */
            ));
          }
          if (this._options.renderWhitespace === "selection") {
            if (!selectionsOnLine) {
              selectionsOnLine = [];
            }
            selectionsOnLine.push(new LineRange$1(startColumn - 1, endColumn - 1));
          }
        }
      }
    }
    const renderLineInput = new RenderLineInput(options.useMonospaceOptimizations, options.canUseHalfwidthRightwardsArrow, lineData.content, lineData.continuesWithWrappedLine, lineData.isBasicASCII, lineData.containsRTL, lineData.minColumn - 1, lineData.tokens, actualInlineDecorations, lineData.tabSize, lineData.startVisibleColumn, options.spaceWidth, options.middotWidth, options.wsmiddotWidth, options.stopRenderingLineAfter, options.renderWhitespace, options.renderControlCharacters, options.fontLigatures !== EditorFontLigatures.OFF, selectionsOnLine);
    if (this._renderedViewLine && this._renderedViewLine.input.equals(renderLineInput)) {
      return false;
    }
    sb.appendString('<div style="top:');
    sb.appendString(String(deltaTop));
    sb.appendString("px;height:");
    sb.appendString(String(this._options.lineHeight));
    sb.appendString('px;" class="');
    sb.appendString(ViewLine.CLASS_NAME);
    sb.appendString('">');
    const output = renderViewLine(renderLineInput, sb);
    sb.appendString("</div>");
    let renderedViewLine = null;
    if (monospaceAssumptionsAreValid && canUseFastRenderedViewLine && lineData.isBasicASCII && options.useMonospaceOptimizations && output.containsForeignElements === 0) {
      renderedViewLine = new FastRenderedViewLine(this._renderedViewLine ? this._renderedViewLine.domNode : null, renderLineInput, output.characterMapping);
    }
    if (!renderedViewLine) {
      renderedViewLine = createRenderedLine(this._renderedViewLine ? this._renderedViewLine.domNode : null, renderLineInput, output.characterMapping, output.containsRTL, output.containsForeignElements);
    }
    this._renderedViewLine = renderedViewLine;
    return true;
  }
  layoutLine(lineNumber, deltaTop) {
    if (this._renderedViewLine && this._renderedViewLine.domNode) {
      this._renderedViewLine.domNode.setTop(deltaTop);
      this._renderedViewLine.domNode.setHeight(this._options.lineHeight);
    }
  }
  // --- end IVisibleLineData
  getWidth(context) {
    if (!this._renderedViewLine) {
      return 0;
    }
    return this._renderedViewLine.getWidth(context);
  }
  getWidthIsFast() {
    if (!this._renderedViewLine) {
      return true;
    }
    return this._renderedViewLine.getWidthIsFast();
  }
  needsMonospaceFontCheck() {
    if (!this._renderedViewLine) {
      return false;
    }
    return this._renderedViewLine instanceof FastRenderedViewLine;
  }
  monospaceAssumptionsAreValid() {
    if (!this._renderedViewLine) {
      return monospaceAssumptionsAreValid;
    }
    if (this._renderedViewLine instanceof FastRenderedViewLine) {
      return this._renderedViewLine.monospaceAssumptionsAreValid();
    }
    return monospaceAssumptionsAreValid;
  }
  onMonospaceAssumptionsInvalidated() {
    if (this._renderedViewLine && this._renderedViewLine instanceof FastRenderedViewLine) {
      this._renderedViewLine = this._renderedViewLine.toSlowRenderedLine();
    }
  }
  getVisibleRangesForRange(lineNumber, startColumn, endColumn, context) {
    if (!this._renderedViewLine) {
      return null;
    }
    startColumn = Math.min(this._renderedViewLine.input.lineContent.length + 1, Math.max(1, startColumn));
    endColumn = Math.min(this._renderedViewLine.input.lineContent.length + 1, Math.max(1, endColumn));
    const stopRenderingLineAfter = this._renderedViewLine.input.stopRenderingLineAfter;
    if (stopRenderingLineAfter !== -1 && startColumn > stopRenderingLineAfter + 1 && endColumn > stopRenderingLineAfter + 1) {
      return new VisibleRanges(true, [new FloatHorizontalRange(this.getWidth(context), 0)]);
    }
    if (stopRenderingLineAfter !== -1 && startColumn > stopRenderingLineAfter + 1) {
      startColumn = stopRenderingLineAfter + 1;
    }
    if (stopRenderingLineAfter !== -1 && endColumn > stopRenderingLineAfter + 1) {
      endColumn = stopRenderingLineAfter + 1;
    }
    const horizontalRanges = this._renderedViewLine.getVisibleRangesForRange(lineNumber, startColumn, endColumn, context);
    if (horizontalRanges && horizontalRanges.length > 0) {
      return new VisibleRanges(false, horizontalRanges);
    }
    return null;
  }
  getColumnOfNodeOffset(lineNumber, spanNode, offset) {
    if (!this._renderedViewLine) {
      return 1;
    }
    return this._renderedViewLine.getColumnOfNodeOffset(lineNumber, spanNode, offset);
  }
}
ViewLine.CLASS_NAME = "view-line";
class FastRenderedViewLine {
  constructor(domNode, renderLineInput, characterMapping) {
    this._cachedWidth = -1;
    this.domNode = domNode;
    this.input = renderLineInput;
    const keyColumnCount = Math.floor(
      renderLineInput.lineContent.length / 300
      /* Constants.MaxMonospaceDistance */
    );
    if (keyColumnCount > 0) {
      this._keyColumnPixelOffsetCache = new Float32Array(keyColumnCount);
      for (let i = 0; i < keyColumnCount; i++) {
        this._keyColumnPixelOffsetCache[i] = -1;
      }
    } else {
      this._keyColumnPixelOffsetCache = null;
    }
    this._characterMapping = characterMapping;
    this._charWidth = renderLineInput.spaceWidth;
  }
  getWidth(context) {
    if (!this.domNode || this.input.lineContent.length < 300) {
      const horizontalOffset = this._characterMapping.getHorizontalOffset(this._characterMapping.length);
      return Math.round(this._charWidth * horizontalOffset);
    }
    if (this._cachedWidth === -1) {
      this._cachedWidth = this._getReadingTarget(this.domNode).offsetWidth;
      context === null || context === void 0 ? void 0 : context.markDidDomLayout();
    }
    return this._cachedWidth;
  }
  getWidthIsFast() {
    return this.input.lineContent.length < 300 || this._cachedWidth !== -1;
  }
  monospaceAssumptionsAreValid() {
    if (!this.domNode) {
      return monospaceAssumptionsAreValid;
    }
    if (this.input.lineContent.length < 300) {
      const expectedWidth = this.getWidth(null);
      const actualWidth = this.domNode.domNode.firstChild.offsetWidth;
      if (Math.abs(expectedWidth - actualWidth) >= 2) {
        console.warn(`monospace assumptions have been violated, therefore disabling monospace optimizations!`);
        monospaceAssumptionsAreValid = false;
      }
    }
    return monospaceAssumptionsAreValid;
  }
  toSlowRenderedLine() {
    return createRenderedLine(
      this.domNode,
      this.input,
      this._characterMapping,
      false,
      0
      /* ForeignElementType.None */
    );
  }
  getVisibleRangesForRange(lineNumber, startColumn, endColumn, context) {
    const startPosition = this._getColumnPixelOffset(lineNumber, startColumn, context);
    const endPosition = this._getColumnPixelOffset(lineNumber, endColumn, context);
    return [new FloatHorizontalRange(startPosition, endPosition - startPosition)];
  }
  _getColumnPixelOffset(lineNumber, column, context) {
    if (column <= 300) {
      const horizontalOffset2 = this._characterMapping.getHorizontalOffset(column);
      return this._charWidth * horizontalOffset2;
    }
    const keyColumnOrdinal = Math.floor(
      (column - 1) / 300
      /* Constants.MaxMonospaceDistance */
    ) - 1;
    const keyColumn = (keyColumnOrdinal + 1) * 300 + 1;
    let keyColumnPixelOffset = -1;
    if (this._keyColumnPixelOffsetCache) {
      keyColumnPixelOffset = this._keyColumnPixelOffsetCache[keyColumnOrdinal];
      if (keyColumnPixelOffset === -1) {
        keyColumnPixelOffset = this._actualReadPixelOffset(lineNumber, keyColumn, context);
        this._keyColumnPixelOffsetCache[keyColumnOrdinal] = keyColumnPixelOffset;
      }
    }
    if (keyColumnPixelOffset === -1) {
      const horizontalOffset2 = this._characterMapping.getHorizontalOffset(column);
      return this._charWidth * horizontalOffset2;
    }
    const keyColumnHorizontalOffset = this._characterMapping.getHorizontalOffset(keyColumn);
    const horizontalOffset = this._characterMapping.getHorizontalOffset(column);
    return keyColumnPixelOffset + this._charWidth * (horizontalOffset - keyColumnHorizontalOffset);
  }
  _getReadingTarget(myDomNode) {
    return myDomNode.domNode.firstChild;
  }
  _actualReadPixelOffset(lineNumber, column, context) {
    if (!this.domNode) {
      return -1;
    }
    const domPosition = this._characterMapping.getDomPosition(column);
    const r = RangeUtil.readHorizontalRanges(this._getReadingTarget(this.domNode), domPosition.partIndex, domPosition.charIndex, domPosition.partIndex, domPosition.charIndex, context);
    if (!r || r.length === 0) {
      return -1;
    }
    return r[0].left;
  }
  getColumnOfNodeOffset(lineNumber, spanNode, offset) {
    const spanNodeTextContentLength = spanNode.textContent.length;
    let spanIndex = -1;
    while (spanNode) {
      spanNode = spanNode.previousSibling;
      spanIndex++;
    }
    return this._characterMapping.getColumn(new DomPosition(spanIndex, offset), spanNodeTextContentLength);
  }
}
class RenderedViewLine {
  constructor(domNode, renderLineInput, characterMapping, containsRTL2, containsForeignElements) {
    this.domNode = domNode;
    this.input = renderLineInput;
    this._characterMapping = characterMapping;
    this._isWhitespaceOnly = /^\s*$/.test(renderLineInput.lineContent);
    this._containsForeignElements = containsForeignElements;
    this._cachedWidth = -1;
    this._pixelOffsetCache = null;
    if (!containsRTL2 || this._characterMapping.length === 0) {
      this._pixelOffsetCache = new Float32Array(Math.max(2, this._characterMapping.length + 1));
      for (let column = 0, len = this._characterMapping.length; column <= len; column++) {
        this._pixelOffsetCache[column] = -1;
      }
    }
  }
  // --- Reading from the DOM methods
  _getReadingTarget(myDomNode) {
    return myDomNode.domNode.firstChild;
  }
  /**
   * Width of the line in pixels
   */
  getWidth(context) {
    if (!this.domNode) {
      return 0;
    }
    if (this._cachedWidth === -1) {
      this._cachedWidth = this._getReadingTarget(this.domNode).offsetWidth;
      context === null || context === void 0 ? void 0 : context.markDidDomLayout();
    }
    return this._cachedWidth;
  }
  getWidthIsFast() {
    if (this._cachedWidth === -1) {
      return false;
    }
    return true;
  }
  /**
   * Visible ranges for a model range
   */
  getVisibleRangesForRange(lineNumber, startColumn, endColumn, context) {
    if (!this.domNode) {
      return null;
    }
    if (this._pixelOffsetCache !== null) {
      const startOffset = this._readPixelOffset(this.domNode, lineNumber, startColumn, context);
      if (startOffset === -1) {
        return null;
      }
      const endOffset = this._readPixelOffset(this.domNode, lineNumber, endColumn, context);
      if (endOffset === -1) {
        return null;
      }
      return [new FloatHorizontalRange(startOffset, endOffset - startOffset)];
    }
    return this._readVisibleRangesForRange(this.domNode, lineNumber, startColumn, endColumn, context);
  }
  _readVisibleRangesForRange(domNode, lineNumber, startColumn, endColumn, context) {
    if (startColumn === endColumn) {
      const pixelOffset = this._readPixelOffset(domNode, lineNumber, startColumn, context);
      if (pixelOffset === -1) {
        return null;
      } else {
        return [new FloatHorizontalRange(pixelOffset, 0)];
      }
    } else {
      return this._readRawVisibleRangesForRange(domNode, startColumn, endColumn, context);
    }
  }
  _readPixelOffset(domNode, lineNumber, column, context) {
    if (this._characterMapping.length === 0) {
      if (this._containsForeignElements === 0) {
        return 0;
      }
      if (this._containsForeignElements === 2) {
        return 0;
      }
      if (this._containsForeignElements === 1) {
        return this.getWidth(context);
      }
      const readingTarget = this._getReadingTarget(domNode);
      if (readingTarget.firstChild) {
        context.markDidDomLayout();
        return readingTarget.firstChild.offsetWidth;
      } else {
        return 0;
      }
    }
    if (this._pixelOffsetCache !== null) {
      const cachedPixelOffset = this._pixelOffsetCache[column];
      if (cachedPixelOffset !== -1) {
        return cachedPixelOffset;
      }
      const result2 = this._actualReadPixelOffset(domNode, lineNumber, column, context);
      this._pixelOffsetCache[column] = result2;
      return result2;
    }
    return this._actualReadPixelOffset(domNode, lineNumber, column, context);
  }
  _actualReadPixelOffset(domNode, lineNumber, column, context) {
    if (this._characterMapping.length === 0) {
      const r2 = RangeUtil.readHorizontalRanges(this._getReadingTarget(domNode), 0, 0, 0, 0, context);
      if (!r2 || r2.length === 0) {
        return -1;
      }
      return r2[0].left;
    }
    if (column === this._characterMapping.length && this._isWhitespaceOnly && this._containsForeignElements === 0) {
      return this.getWidth(context);
    }
    const domPosition = this._characterMapping.getDomPosition(column);
    const r = RangeUtil.readHorizontalRanges(this._getReadingTarget(domNode), domPosition.partIndex, domPosition.charIndex, domPosition.partIndex, domPosition.charIndex, context);
    if (!r || r.length === 0) {
      return -1;
    }
    const result2 = r[0].left;
    if (this.input.isBasicASCII) {
      const horizontalOffset = this._characterMapping.getHorizontalOffset(column);
      const expectedResult = Math.round(this.input.spaceWidth * horizontalOffset);
      if (Math.abs(expectedResult - result2) <= 1) {
        return expectedResult;
      }
    }
    return result2;
  }
  _readRawVisibleRangesForRange(domNode, startColumn, endColumn, context) {
    if (startColumn === 1 && endColumn === this._characterMapping.length) {
      return [new FloatHorizontalRange(0, this.getWidth(context))];
    }
    const startDomPosition = this._characterMapping.getDomPosition(startColumn);
    const endDomPosition = this._characterMapping.getDomPosition(endColumn);
    return RangeUtil.readHorizontalRanges(this._getReadingTarget(domNode), startDomPosition.partIndex, startDomPosition.charIndex, endDomPosition.partIndex, endDomPosition.charIndex, context);
  }
  /**
   * Returns the column for the text found at a specific offset inside a rendered dom node
   */
  getColumnOfNodeOffset(lineNumber, spanNode, offset) {
    const spanNodeTextContentLength = spanNode.textContent.length;
    let spanIndex = -1;
    while (spanNode) {
      spanNode = spanNode.previousSibling;
      spanIndex++;
    }
    return this._characterMapping.getColumn(new DomPosition(spanIndex, offset), spanNodeTextContentLength);
  }
}
class WebKitRenderedViewLine extends RenderedViewLine {
  _readVisibleRangesForRange(domNode, lineNumber, startColumn, endColumn, context) {
    const output = super._readVisibleRangesForRange(domNode, lineNumber, startColumn, endColumn, context);
    if (!output || output.length === 0 || startColumn === endColumn || startColumn === 1 && endColumn === this._characterMapping.length) {
      return output;
    }
    if (!this.input.containsRTL) {
      const endPixelOffset = this._readPixelOffset(domNode, lineNumber, endColumn, context);
      if (endPixelOffset !== -1) {
        const lastRange = output[output.length - 1];
        if (lastRange.left < endPixelOffset) {
          lastRange.width = endPixelOffset - lastRange.left;
        }
      }
    }
    return output;
  }
}
const createRenderedLine = function() {
  if (isWebKit) {
    return createWebKitRenderedLine;
  }
  return createNormalRenderedLine;
}();
function createWebKitRenderedLine(domNode, renderLineInput, characterMapping, containsRTL2, containsForeignElements) {
  return new WebKitRenderedViewLine(domNode, renderLineInput, characterMapping, containsRTL2, containsForeignElements);
}
function createNormalRenderedLine(domNode, renderLineInput, characterMapping, containsRTL2, containsForeignElements) {
  return new RenderedViewLine(domNode, renderLineInput, characterMapping, containsRTL2, containsForeignElements);
}
class UnknownHitTestResult {
  constructor(hitTarget = null) {
    this.hitTarget = hitTarget;
    this.type = 0;
  }
}
class ContentHitTestResult {
  constructor(position, spanNode, injectedText) {
    this.position = position;
    this.spanNode = spanNode;
    this.injectedText = injectedText;
    this.type = 1;
  }
}
var HitTestResult;
(function(HitTestResult2) {
  function createFromDOMInfo(ctx, spanNode, offset) {
    const position = ctx.getPositionFromDOMInfo(spanNode, offset);
    if (position) {
      return new ContentHitTestResult(position, spanNode, null);
    }
    return new UnknownHitTestResult(spanNode);
  }
  HitTestResult2.createFromDOMInfo = createFromDOMInfo;
})(HitTestResult || (HitTestResult = {}));
class PointerHandlerLastRenderData {
  constructor(lastViewCursorsRenderData, lastTextareaPosition) {
    this.lastViewCursorsRenderData = lastViewCursorsRenderData;
    this.lastTextareaPosition = lastTextareaPosition;
  }
}
class MouseTarget {
  static _deduceRage(position, range2 = null) {
    if (!range2 && position) {
      return new Range$2(position.lineNumber, position.column, position.lineNumber, position.column);
    }
    return range2 !== null && range2 !== void 0 ? range2 : null;
  }
  static createUnknown(element, mouseColumn, position) {
    return { type: 0, element, mouseColumn, position, range: this._deduceRage(position) };
  }
  static createTextarea(element, mouseColumn) {
    return { type: 1, element, mouseColumn, position: null, range: null };
  }
  static createMargin(type, element, mouseColumn, position, range2, detail) {
    return { type, element, mouseColumn, position, range: range2, detail };
  }
  static createViewZone(type, element, mouseColumn, position, detail) {
    return { type, element, mouseColumn, position, range: this._deduceRage(position), detail };
  }
  static createContentText(element, mouseColumn, position, range2, detail) {
    return { type: 6, element, mouseColumn, position, range: this._deduceRage(position, range2), detail };
  }
  static createContentEmpty(element, mouseColumn, position, detail) {
    return { type: 7, element, mouseColumn, position, range: this._deduceRage(position), detail };
  }
  static createContentWidget(element, mouseColumn, detail) {
    return { type: 9, element, mouseColumn, position: null, range: null, detail };
  }
  static createScrollbar(element, mouseColumn, position) {
    return { type: 11, element, mouseColumn, position, range: this._deduceRage(position) };
  }
  static createOverlayWidget(element, mouseColumn, detail) {
    return { type: 12, element, mouseColumn, position: null, range: null, detail };
  }
  static createOutsideEditor(mouseColumn, position, outsidePosition, outsideDistance) {
    return { type: 13, element: null, mouseColumn, position, range: this._deduceRage(position), outsidePosition, outsideDistance };
  }
  static _typeToString(type) {
    if (type === 1) {
      return "TEXTAREA";
    }
    if (type === 2) {
      return "GUTTER_GLYPH_MARGIN";
    }
    if (type === 3) {
      return "GUTTER_LINE_NUMBERS";
    }
    if (type === 4) {
      return "GUTTER_LINE_DECORATIONS";
    }
    if (type === 5) {
      return "GUTTER_VIEW_ZONE";
    }
    if (type === 6) {
      return "CONTENT_TEXT";
    }
    if (type === 7) {
      return "CONTENT_EMPTY";
    }
    if (type === 8) {
      return "CONTENT_VIEW_ZONE";
    }
    if (type === 9) {
      return "CONTENT_WIDGET";
    }
    if (type === 10) {
      return "OVERVIEW_RULER";
    }
    if (type === 11) {
      return "SCROLLBAR";
    }
    if (type === 12) {
      return "OVERLAY_WIDGET";
    }
    return "UNKNOWN";
  }
  static toString(target) {
    return this._typeToString(target.type) + ": " + target.position + " - " + target.range + " - " + JSON.stringify(target.detail);
  }
}
class ElementPath {
  static isTextArea(path2) {
    return path2.length === 2 && path2[0] === 3 && path2[1] === 6;
  }
  static isChildOfViewLines(path2) {
    return path2.length >= 4 && path2[0] === 3 && path2[3] === 7;
  }
  static isStrictChildOfViewLines(path2) {
    return path2.length > 4 && path2[0] === 3 && path2[3] === 7;
  }
  static isChildOfScrollableElement(path2) {
    return path2.length >= 2 && path2[0] === 3 && path2[1] === 5;
  }
  static isChildOfMinimap(path2) {
    return path2.length >= 2 && path2[0] === 3 && path2[1] === 8;
  }
  static isChildOfContentWidgets(path2) {
    return path2.length >= 4 && path2[0] === 3 && path2[3] === 1;
  }
  static isChildOfOverflowingContentWidgets(path2) {
    return path2.length >= 1 && path2[0] === 2;
  }
  static isChildOfOverlayWidgets(path2) {
    return path2.length >= 2 && path2[0] === 3 && path2[1] === 4;
  }
}
class HitTestContext {
  constructor(context, viewHelper, lastRenderData) {
    this.viewModel = context.viewModel;
    const options = context.configuration.options;
    this.layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    this.viewDomNode = viewHelper.viewDomNode;
    this.lineHeight = options.get(
      65
      /* EditorOption.lineHeight */
    );
    this.stickyTabStops = options.get(
      114
      /* EditorOption.stickyTabStops */
    );
    this.typicalHalfwidthCharacterWidth = options.get(
      49
      /* EditorOption.fontInfo */
    ).typicalHalfwidthCharacterWidth;
    this.lastRenderData = lastRenderData;
    this._context = context;
    this._viewHelper = viewHelper;
  }
  getZoneAtCoord(mouseVerticalOffset) {
    return HitTestContext.getZoneAtCoord(this._context, mouseVerticalOffset);
  }
  static getZoneAtCoord(context, mouseVerticalOffset) {
    const viewZoneWhitespace = context.viewLayout.getWhitespaceAtVerticalOffset(mouseVerticalOffset);
    if (viewZoneWhitespace) {
      const viewZoneMiddle = viewZoneWhitespace.verticalOffset + viewZoneWhitespace.height / 2;
      const lineCount = context.viewModel.getLineCount();
      let positionBefore = null;
      let position;
      let positionAfter = null;
      if (viewZoneWhitespace.afterLineNumber !== lineCount) {
        positionAfter = new Position$2(viewZoneWhitespace.afterLineNumber + 1, 1);
      }
      if (viewZoneWhitespace.afterLineNumber > 0) {
        positionBefore = new Position$2(viewZoneWhitespace.afterLineNumber, context.viewModel.getLineMaxColumn(viewZoneWhitespace.afterLineNumber));
      }
      if (positionAfter === null) {
        position = positionBefore;
      } else if (positionBefore === null) {
        position = positionAfter;
      } else if (mouseVerticalOffset < viewZoneMiddle) {
        position = positionBefore;
      } else {
        position = positionAfter;
      }
      return {
        viewZoneId: viewZoneWhitespace.id,
        afterLineNumber: viewZoneWhitespace.afterLineNumber,
        positionBefore,
        positionAfter,
        position
      };
    }
    return null;
  }
  getFullLineRangeAtCoord(mouseVerticalOffset) {
    if (this._context.viewLayout.isAfterLines(mouseVerticalOffset)) {
      const lineNumber2 = this._context.viewModel.getLineCount();
      const maxLineColumn2 = this._context.viewModel.getLineMaxColumn(lineNumber2);
      return {
        range: new Range$2(lineNumber2, maxLineColumn2, lineNumber2, maxLineColumn2),
        isAfterLines: true
      };
    }
    const lineNumber = this._context.viewLayout.getLineNumberAtVerticalOffset(mouseVerticalOffset);
    const maxLineColumn = this._context.viewModel.getLineMaxColumn(lineNumber);
    return {
      range: new Range$2(lineNumber, 1, lineNumber, maxLineColumn),
      isAfterLines: false
    };
  }
  getLineNumberAtVerticalOffset(mouseVerticalOffset) {
    return this._context.viewLayout.getLineNumberAtVerticalOffset(mouseVerticalOffset);
  }
  isAfterLines(mouseVerticalOffset) {
    return this._context.viewLayout.isAfterLines(mouseVerticalOffset);
  }
  isInTopPadding(mouseVerticalOffset) {
    return this._context.viewLayout.isInTopPadding(mouseVerticalOffset);
  }
  isInBottomPadding(mouseVerticalOffset) {
    return this._context.viewLayout.isInBottomPadding(mouseVerticalOffset);
  }
  getVerticalOffsetForLineNumber(lineNumber) {
    return this._context.viewLayout.getVerticalOffsetForLineNumber(lineNumber);
  }
  findAttribute(element, attr) {
    return HitTestContext._findAttribute(element, attr, this._viewHelper.viewDomNode);
  }
  static _findAttribute(element, attr, stopAt) {
    while (element && element !== document.body) {
      if (element.hasAttribute && element.hasAttribute(attr)) {
        return element.getAttribute(attr);
      }
      if (element === stopAt) {
        return null;
      }
      element = element.parentNode;
    }
    return null;
  }
  getLineWidth(lineNumber) {
    return this._viewHelper.getLineWidth(lineNumber);
  }
  visibleRangeForPosition(lineNumber, column) {
    return this._viewHelper.visibleRangeForPosition(lineNumber, column);
  }
  getPositionFromDOMInfo(spanNode, offset) {
    return this._viewHelper.getPositionFromDOMInfo(spanNode, offset);
  }
  getCurrentScrollTop() {
    return this._context.viewLayout.getCurrentScrollTop();
  }
  getCurrentScrollLeft() {
    return this._context.viewLayout.getCurrentScrollLeft();
  }
}
class BareHitTestRequest {
  constructor(ctx, editorPos, pos, relativePos) {
    this.editorPos = editorPos;
    this.pos = pos;
    this.relativePos = relativePos;
    this.mouseVerticalOffset = Math.max(0, ctx.getCurrentScrollTop() + this.relativePos.y);
    this.mouseContentHorizontalOffset = ctx.getCurrentScrollLeft() + this.relativePos.x - ctx.layoutInfo.contentLeft;
    this.isInMarginArea = this.relativePos.x < ctx.layoutInfo.contentLeft && this.relativePos.x >= ctx.layoutInfo.glyphMarginLeft;
    this.isInContentArea = !this.isInMarginArea;
    this.mouseColumn = Math.max(0, MouseTargetFactory._getMouseColumn(this.mouseContentHorizontalOffset, ctx.typicalHalfwidthCharacterWidth));
  }
}
class HitTestRequest extends BareHitTestRequest {
  constructor(ctx, editorPos, pos, relativePos, target) {
    super(ctx, editorPos, pos, relativePos);
    this._ctx = ctx;
    if (target) {
      this.target = target;
      this.targetPath = PartFingerprints.collect(target, ctx.viewDomNode);
    } else {
      this.target = null;
      this.targetPath = new Uint8Array(0);
    }
  }
  toString() {
    return `pos(${this.pos.x},${this.pos.y}), editorPos(${this.editorPos.x},${this.editorPos.y}), relativePos(${this.relativePos.x},${this.relativePos.y}), mouseVerticalOffset: ${this.mouseVerticalOffset}, mouseContentHorizontalOffset: ${this.mouseContentHorizontalOffset}
	target: ${this.target ? this.target.outerHTML : null}`;
  }
  _getMouseColumn(position = null) {
    if (position && position.column < this._ctx.viewModel.getLineMaxColumn(position.lineNumber)) {
      return CursorColumns.visibleColumnFromColumn(this._ctx.viewModel.getLineContent(position.lineNumber), position.column, this._ctx.viewModel.model.getOptions().tabSize) + 1;
    }
    return this.mouseColumn;
  }
  fulfillUnknown(position = null) {
    return MouseTarget.createUnknown(this.target, this._getMouseColumn(position), position);
  }
  fulfillTextarea() {
    return MouseTarget.createTextarea(this.target, this._getMouseColumn());
  }
  fulfillMargin(type, position, range2, detail) {
    return MouseTarget.createMargin(type, this.target, this._getMouseColumn(position), position, range2, detail);
  }
  fulfillViewZone(type, position, detail) {
    return MouseTarget.createViewZone(type, this.target, this._getMouseColumn(position), position, detail);
  }
  fulfillContentText(position, range2, detail) {
    return MouseTarget.createContentText(this.target, this._getMouseColumn(position), position, range2, detail);
  }
  fulfillContentEmpty(position, detail) {
    return MouseTarget.createContentEmpty(this.target, this._getMouseColumn(position), position, detail);
  }
  fulfillContentWidget(detail) {
    return MouseTarget.createContentWidget(this.target, this._getMouseColumn(), detail);
  }
  fulfillScrollbar(position) {
    return MouseTarget.createScrollbar(this.target, this._getMouseColumn(position), position);
  }
  fulfillOverlayWidget(detail) {
    return MouseTarget.createOverlayWidget(this.target, this._getMouseColumn(), detail);
  }
  withTarget(target) {
    return new HitTestRequest(this._ctx, this.editorPos, this.pos, this.relativePos, target);
  }
}
const EMPTY_CONTENT_AFTER_LINES = { isAfterLines: true };
function createEmptyContentDataInLines(horizontalDistanceToText) {
  return {
    isAfterLines: false,
    horizontalDistanceToText
  };
}
class MouseTargetFactory {
  constructor(context, viewHelper) {
    this._context = context;
    this._viewHelper = viewHelper;
  }
  mouseTargetIsWidget(e) {
    const t = e.target;
    const path2 = PartFingerprints.collect(t, this._viewHelper.viewDomNode);
    if (ElementPath.isChildOfContentWidgets(path2) || ElementPath.isChildOfOverflowingContentWidgets(path2)) {
      return true;
    }
    if (ElementPath.isChildOfOverlayWidgets(path2)) {
      return true;
    }
    return false;
  }
  createMouseTarget(lastRenderData, editorPos, pos, relativePos, target) {
    const ctx = new HitTestContext(this._context, this._viewHelper, lastRenderData);
    const request = new HitTestRequest(ctx, editorPos, pos, relativePos, target);
    try {
      const r = MouseTargetFactory._createMouseTarget(ctx, request, false);
      if (r.type === 6) {
        if (ctx.stickyTabStops && r.position !== null) {
          const position = MouseTargetFactory._snapToSoftTabBoundary(r.position, ctx.viewModel);
          const range2 = Range$2.fromPositions(position, position).plusRange(r.range);
          return request.fulfillContentText(position, range2, r.detail);
        }
      }
      return r;
    } catch (err) {
      return request.fulfillUnknown();
    }
  }
  static _createMouseTarget(ctx, request, domHitTestExecuted) {
    if (request.target === null) {
      if (domHitTestExecuted) {
        return request.fulfillUnknown();
      }
      const hitTestResult = MouseTargetFactory._doHitTest(ctx, request);
      if (hitTestResult.type === 1) {
        return MouseTargetFactory.createMouseTargetFromHitTestPosition(ctx, request, hitTestResult.spanNode, hitTestResult.position, hitTestResult.injectedText);
      }
      return this._createMouseTarget(ctx, request.withTarget(hitTestResult.hitTarget), true);
    }
    const resolvedRequest = request;
    let result2 = null;
    result2 = result2 || MouseTargetFactory._hitTestContentWidget(ctx, resolvedRequest);
    result2 = result2 || MouseTargetFactory._hitTestOverlayWidget(ctx, resolvedRequest);
    result2 = result2 || MouseTargetFactory._hitTestMinimap(ctx, resolvedRequest);
    result2 = result2 || MouseTargetFactory._hitTestScrollbarSlider(ctx, resolvedRequest);
    result2 = result2 || MouseTargetFactory._hitTestViewZone(ctx, resolvedRequest);
    result2 = result2 || MouseTargetFactory._hitTestMargin(ctx, resolvedRequest);
    result2 = result2 || MouseTargetFactory._hitTestViewCursor(ctx, resolvedRequest);
    result2 = result2 || MouseTargetFactory._hitTestTextArea(ctx, resolvedRequest);
    result2 = result2 || MouseTargetFactory._hitTestViewLines(ctx, resolvedRequest, domHitTestExecuted);
    result2 = result2 || MouseTargetFactory._hitTestScrollbar(ctx, resolvedRequest);
    return result2 || request.fulfillUnknown();
  }
  static _hitTestContentWidget(ctx, request) {
    if (ElementPath.isChildOfContentWidgets(request.targetPath) || ElementPath.isChildOfOverflowingContentWidgets(request.targetPath)) {
      const widgetId = ctx.findAttribute(request.target, "widgetId");
      if (widgetId) {
        return request.fulfillContentWidget(widgetId);
      } else {
        return request.fulfillUnknown();
      }
    }
    return null;
  }
  static _hitTestOverlayWidget(ctx, request) {
    if (ElementPath.isChildOfOverlayWidgets(request.targetPath)) {
      const widgetId = ctx.findAttribute(request.target, "widgetId");
      if (widgetId) {
        return request.fulfillOverlayWidget(widgetId);
      } else {
        return request.fulfillUnknown();
      }
    }
    return null;
  }
  static _hitTestViewCursor(ctx, request) {
    if (request.target) {
      const lastViewCursorsRenderData = ctx.lastRenderData.lastViewCursorsRenderData;
      for (const d of lastViewCursorsRenderData) {
        if (request.target === d.domNode) {
          return request.fulfillContentText(d.position, null, { mightBeForeignElement: false, injectedText: null });
        }
      }
    }
    if (request.isInContentArea) {
      const lastViewCursorsRenderData = ctx.lastRenderData.lastViewCursorsRenderData;
      const mouseContentHorizontalOffset = request.mouseContentHorizontalOffset;
      const mouseVerticalOffset = request.mouseVerticalOffset;
      for (const d of lastViewCursorsRenderData) {
        if (mouseContentHorizontalOffset < d.contentLeft) {
          continue;
        }
        if (mouseContentHorizontalOffset > d.contentLeft + d.width) {
          continue;
        }
        const cursorVerticalOffset = ctx.getVerticalOffsetForLineNumber(d.position.lineNumber);
        if (cursorVerticalOffset <= mouseVerticalOffset && mouseVerticalOffset <= cursorVerticalOffset + d.height) {
          return request.fulfillContentText(d.position, null, { mightBeForeignElement: false, injectedText: null });
        }
      }
    }
    return null;
  }
  static _hitTestViewZone(ctx, request) {
    const viewZoneData = ctx.getZoneAtCoord(request.mouseVerticalOffset);
    if (viewZoneData) {
      const mouseTargetType = request.isInContentArea ? 8 : 5;
      return request.fulfillViewZone(mouseTargetType, viewZoneData.position, viewZoneData);
    }
    return null;
  }
  static _hitTestTextArea(ctx, request) {
    if (ElementPath.isTextArea(request.targetPath)) {
      if (ctx.lastRenderData.lastTextareaPosition) {
        return request.fulfillContentText(ctx.lastRenderData.lastTextareaPosition, null, { mightBeForeignElement: false, injectedText: null });
      }
      return request.fulfillTextarea();
    }
    return null;
  }
  static _hitTestMargin(ctx, request) {
    if (request.isInMarginArea) {
      const res = ctx.getFullLineRangeAtCoord(request.mouseVerticalOffset);
      const pos = res.range.getStartPosition();
      let offset = Math.abs(request.relativePos.x);
      const detail = {
        isAfterLines: res.isAfterLines,
        glyphMarginLeft: ctx.layoutInfo.glyphMarginLeft,
        glyphMarginWidth: ctx.layoutInfo.glyphMarginWidth,
        lineNumbersWidth: ctx.layoutInfo.lineNumbersWidth,
        offsetX: offset
      };
      offset -= ctx.layoutInfo.glyphMarginLeft;
      if (offset <= ctx.layoutInfo.glyphMarginWidth) {
        return request.fulfillMargin(2, pos, res.range, detail);
      }
      offset -= ctx.layoutInfo.glyphMarginWidth;
      if (offset <= ctx.layoutInfo.lineNumbersWidth) {
        return request.fulfillMargin(3, pos, res.range, detail);
      }
      offset -= ctx.layoutInfo.lineNumbersWidth;
      return request.fulfillMargin(4, pos, res.range, detail);
    }
    return null;
  }
  static _hitTestViewLines(ctx, request, domHitTestExecuted) {
    if (!ElementPath.isChildOfViewLines(request.targetPath)) {
      return null;
    }
    if (ctx.isInTopPadding(request.mouseVerticalOffset)) {
      return request.fulfillContentEmpty(new Position$2(1, 1), EMPTY_CONTENT_AFTER_LINES);
    }
    if (ctx.isAfterLines(request.mouseVerticalOffset) || ctx.isInBottomPadding(request.mouseVerticalOffset)) {
      const lineCount = ctx.viewModel.getLineCount();
      const maxLineColumn = ctx.viewModel.getLineMaxColumn(lineCount);
      return request.fulfillContentEmpty(new Position$2(lineCount, maxLineColumn), EMPTY_CONTENT_AFTER_LINES);
    }
    if (domHitTestExecuted) {
      if (ElementPath.isStrictChildOfViewLines(request.targetPath)) {
        const lineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset);
        if (ctx.viewModel.getLineLength(lineNumber) === 0) {
          const lineWidth2 = ctx.getLineWidth(lineNumber);
          const detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth2);
          return request.fulfillContentEmpty(new Position$2(lineNumber, 1), detail);
        }
        const lineWidth = ctx.getLineWidth(lineNumber);
        if (request.mouseContentHorizontalOffset >= lineWidth) {
          const detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth);
          const pos = new Position$2(lineNumber, ctx.viewModel.getLineMaxColumn(lineNumber));
          return request.fulfillContentEmpty(pos, detail);
        }
      }
      return request.fulfillUnknown();
    }
    const hitTestResult = MouseTargetFactory._doHitTest(ctx, request);
    if (hitTestResult.type === 1) {
      return MouseTargetFactory.createMouseTargetFromHitTestPosition(ctx, request, hitTestResult.spanNode, hitTestResult.position, hitTestResult.injectedText);
    }
    return this._createMouseTarget(ctx, request.withTarget(hitTestResult.hitTarget), true);
  }
  static _hitTestMinimap(ctx, request) {
    if (ElementPath.isChildOfMinimap(request.targetPath)) {
      const possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset);
      const maxColumn = ctx.viewModel.getLineMaxColumn(possibleLineNumber);
      return request.fulfillScrollbar(new Position$2(possibleLineNumber, maxColumn));
    }
    return null;
  }
  static _hitTestScrollbarSlider(ctx, request) {
    if (ElementPath.isChildOfScrollableElement(request.targetPath)) {
      if (request.target && request.target.nodeType === 1) {
        const className3 = request.target.className;
        if (className3 && /\b(slider|scrollbar)\b/.test(className3)) {
          const possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset);
          const maxColumn = ctx.viewModel.getLineMaxColumn(possibleLineNumber);
          return request.fulfillScrollbar(new Position$2(possibleLineNumber, maxColumn));
        }
      }
    }
    return null;
  }
  static _hitTestScrollbar(ctx, request) {
    if (ElementPath.isChildOfScrollableElement(request.targetPath)) {
      const possibleLineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset);
      const maxColumn = ctx.viewModel.getLineMaxColumn(possibleLineNumber);
      return request.fulfillScrollbar(new Position$2(possibleLineNumber, maxColumn));
    }
    return null;
  }
  getMouseColumn(relativePos) {
    const options = this._context.configuration.options;
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    const mouseContentHorizontalOffset = this._context.viewLayout.getCurrentScrollLeft() + relativePos.x - layoutInfo.contentLeft;
    return MouseTargetFactory._getMouseColumn(mouseContentHorizontalOffset, options.get(
      49
      /* EditorOption.fontInfo */
    ).typicalHalfwidthCharacterWidth);
  }
  static _getMouseColumn(mouseContentHorizontalOffset, typicalHalfwidthCharacterWidth) {
    if (mouseContentHorizontalOffset < 0) {
      return 1;
    }
    const chars2 = Math.round(mouseContentHorizontalOffset / typicalHalfwidthCharacterWidth);
    return chars2 + 1;
  }
  static createMouseTargetFromHitTestPosition(ctx, request, spanNode, pos, injectedText) {
    const lineNumber = pos.lineNumber;
    const column = pos.column;
    const lineWidth = ctx.getLineWidth(lineNumber);
    if (request.mouseContentHorizontalOffset > lineWidth) {
      const detail = createEmptyContentDataInLines(request.mouseContentHorizontalOffset - lineWidth);
      return request.fulfillContentEmpty(pos, detail);
    }
    const visibleRange = ctx.visibleRangeForPosition(lineNumber, column);
    if (!visibleRange) {
      return request.fulfillUnknown(pos);
    }
    const columnHorizontalOffset = visibleRange.left;
    if (Math.abs(request.mouseContentHorizontalOffset - columnHorizontalOffset) < 1) {
      return request.fulfillContentText(pos, null, { mightBeForeignElement: !!injectedText, injectedText });
    }
    const points = [];
    points.push({ offset: visibleRange.left, column });
    if (column > 1) {
      const visibleRange2 = ctx.visibleRangeForPosition(lineNumber, column - 1);
      if (visibleRange2) {
        points.push({ offset: visibleRange2.left, column: column - 1 });
      }
    }
    const lineMaxColumn = ctx.viewModel.getLineMaxColumn(lineNumber);
    if (column < lineMaxColumn) {
      const visibleRange2 = ctx.visibleRangeForPosition(lineNumber, column + 1);
      if (visibleRange2) {
        points.push({ offset: visibleRange2.left, column: column + 1 });
      }
    }
    points.sort((a, b) => a.offset - b.offset);
    const mouseCoordinates = request.pos.toClientCoordinates();
    const spanNodeClientRect = spanNode.getBoundingClientRect();
    const mouseIsOverSpanNode = spanNodeClientRect.left <= mouseCoordinates.clientX && mouseCoordinates.clientX <= spanNodeClientRect.right;
    let rng = null;
    for (let i = 1; i < points.length; i++) {
      const prev = points[i - 1];
      const curr = points[i];
      if (prev.offset <= request.mouseContentHorizontalOffset && request.mouseContentHorizontalOffset <= curr.offset) {
        rng = new Range$2(lineNumber, prev.column, lineNumber, curr.column);
        const prevDelta = Math.abs(prev.offset - request.mouseContentHorizontalOffset);
        const nextDelta = Math.abs(curr.offset - request.mouseContentHorizontalOffset);
        pos = prevDelta < nextDelta ? new Position$2(lineNumber, prev.column) : new Position$2(lineNumber, curr.column);
        break;
      }
    }
    return request.fulfillContentText(pos, rng, { mightBeForeignElement: !mouseIsOverSpanNode || !!injectedText, injectedText });
  }
  /**
   * Most probably WebKit browsers and Edge
   */
  static _doHitTestWithCaretRangeFromPoint(ctx, request) {
    const lineNumber = ctx.getLineNumberAtVerticalOffset(request.mouseVerticalOffset);
    const lineStartVerticalOffset = ctx.getVerticalOffsetForLineNumber(lineNumber);
    const lineEndVerticalOffset = lineStartVerticalOffset + ctx.lineHeight;
    const isBelowLastLine = lineNumber === ctx.viewModel.getLineCount() && request.mouseVerticalOffset > lineEndVerticalOffset;
    if (!isBelowLastLine) {
      const lineCenteredVerticalOffset = Math.floor((lineStartVerticalOffset + lineEndVerticalOffset) / 2);
      let adjustedPageY = request.pos.y + (lineCenteredVerticalOffset - request.mouseVerticalOffset);
      if (adjustedPageY <= request.editorPos.y) {
        adjustedPageY = request.editorPos.y + 1;
      }
      if (adjustedPageY >= request.editorPos.y + request.editorPos.height) {
        adjustedPageY = request.editorPos.y + request.editorPos.height - 1;
      }
      const adjustedPage = new PageCoordinates(request.pos.x, adjustedPageY);
      const r = this._actualDoHitTestWithCaretRangeFromPoint(ctx, adjustedPage.toClientCoordinates());
      if (r.type === 1) {
        return r;
      }
    }
    return this._actualDoHitTestWithCaretRangeFromPoint(ctx, request.pos.toClientCoordinates());
  }
  static _actualDoHitTestWithCaretRangeFromPoint(ctx, coords) {
    const shadowRoot = getShadowRoot(ctx.viewDomNode);
    let range2;
    if (shadowRoot) {
      if (typeof shadowRoot.caretRangeFromPoint === "undefined") {
        range2 = shadowCaretRangeFromPoint(shadowRoot, coords.clientX, coords.clientY);
      } else {
        range2 = shadowRoot.caretRangeFromPoint(coords.clientX, coords.clientY);
      }
    } else {
      range2 = document.caretRangeFromPoint(coords.clientX, coords.clientY);
    }
    if (!range2 || !range2.startContainer) {
      return new UnknownHitTestResult();
    }
    const startContainer = range2.startContainer;
    if (startContainer.nodeType === startContainer.TEXT_NODE) {
      const parent1 = startContainer.parentNode;
      const parent2 = parent1 ? parent1.parentNode : null;
      const parent3 = parent2 ? parent2.parentNode : null;
      const parent3ClassName = parent3 && parent3.nodeType === parent3.ELEMENT_NODE ? parent3.className : null;
      if (parent3ClassName === ViewLine.CLASS_NAME) {
        return HitTestResult.createFromDOMInfo(ctx, parent1, range2.startOffset);
      } else {
        return new UnknownHitTestResult(startContainer.parentNode);
      }
    } else if (startContainer.nodeType === startContainer.ELEMENT_NODE) {
      const parent1 = startContainer.parentNode;
      const parent2 = parent1 ? parent1.parentNode : null;
      const parent2ClassName = parent2 && parent2.nodeType === parent2.ELEMENT_NODE ? parent2.className : null;
      if (parent2ClassName === ViewLine.CLASS_NAME) {
        return HitTestResult.createFromDOMInfo(ctx, startContainer, startContainer.textContent.length);
      } else {
        return new UnknownHitTestResult(startContainer);
      }
    }
    return new UnknownHitTestResult();
  }
  /**
   * Most probably Gecko
   */
  static _doHitTestWithCaretPositionFromPoint(ctx, coords) {
    const hitResult = document.caretPositionFromPoint(coords.clientX, coords.clientY);
    if (hitResult.offsetNode.nodeType === hitResult.offsetNode.TEXT_NODE) {
      const parent1 = hitResult.offsetNode.parentNode;
      const parent2 = parent1 ? parent1.parentNode : null;
      const parent3 = parent2 ? parent2.parentNode : null;
      const parent3ClassName = parent3 && parent3.nodeType === parent3.ELEMENT_NODE ? parent3.className : null;
      if (parent3ClassName === ViewLine.CLASS_NAME) {
        return HitTestResult.createFromDOMInfo(ctx, hitResult.offsetNode.parentNode, hitResult.offset);
      } else {
        return new UnknownHitTestResult(hitResult.offsetNode.parentNode);
      }
    }
    if (hitResult.offsetNode.nodeType === hitResult.offsetNode.ELEMENT_NODE) {
      const parent1 = hitResult.offsetNode.parentNode;
      const parent1ClassName = parent1 && parent1.nodeType === parent1.ELEMENT_NODE ? parent1.className : null;
      const parent2 = parent1 ? parent1.parentNode : null;
      const parent2ClassName = parent2 && parent2.nodeType === parent2.ELEMENT_NODE ? parent2.className : null;
      if (parent1ClassName === ViewLine.CLASS_NAME) {
        const tokenSpan = hitResult.offsetNode.childNodes[Math.min(hitResult.offset, hitResult.offsetNode.childNodes.length - 1)];
        if (tokenSpan) {
          return HitTestResult.createFromDOMInfo(ctx, tokenSpan, 0);
        }
      } else if (parent2ClassName === ViewLine.CLASS_NAME) {
        return HitTestResult.createFromDOMInfo(ctx, hitResult.offsetNode, 0);
      }
    }
    return new UnknownHitTestResult(hitResult.offsetNode);
  }
  static _snapToSoftTabBoundary(position, viewModel) {
    const lineContent = viewModel.getLineContent(position.lineNumber);
    const { tabSize } = viewModel.model.getOptions();
    const newPosition = AtomicTabMoveOperations.atomicPosition(
      lineContent,
      position.column - 1,
      tabSize,
      2
      /* Direction.Nearest */
    );
    if (newPosition !== -1) {
      return new Position$2(position.lineNumber, newPosition + 1);
    }
    return position;
  }
  static _doHitTest(ctx, request) {
    let result2 = new UnknownHitTestResult();
    if (typeof document.caretRangeFromPoint === "function") {
      result2 = this._doHitTestWithCaretRangeFromPoint(ctx, request);
    } else if (document.caretPositionFromPoint) {
      result2 = this._doHitTestWithCaretPositionFromPoint(ctx, request.pos.toClientCoordinates());
    }
    if (result2.type === 1) {
      const injectedText = ctx.viewModel.getInjectedTextAt(result2.position);
      const normalizedPosition = ctx.viewModel.normalizePosition(
        result2.position,
        2
        /* PositionAffinity.None */
      );
      if (injectedText || !normalizedPosition.equals(result2.position)) {
        result2 = new ContentHitTestResult(normalizedPosition, result2.spanNode, injectedText);
      }
    }
    return result2;
  }
}
function shadowCaretRangeFromPoint(shadowRoot, x, y) {
  const range2 = document.createRange();
  let el = shadowRoot.elementFromPoint(x, y);
  if (el !== null) {
    while (el && el.firstChild && el.firstChild.nodeType !== el.firstChild.TEXT_NODE && el.lastChild && el.lastChild.firstChild) {
      el = el.lastChild;
    }
    const rect = el.getBoundingClientRect();
    const fontStyle = window.getComputedStyle(el, null).getPropertyValue("font-style");
    const fontVariant = window.getComputedStyle(el, null).getPropertyValue("font-variant");
    const fontWeight = window.getComputedStyle(el, null).getPropertyValue("font-weight");
    const fontSize = window.getComputedStyle(el, null).getPropertyValue("font-size");
    const lineHeight = window.getComputedStyle(el, null).getPropertyValue("line-height");
    const fontFamily = window.getComputedStyle(el, null).getPropertyValue("font-family");
    const font = `${fontStyle} ${fontVariant} ${fontWeight} ${fontSize}/${lineHeight} ${fontFamily}`;
    const text2 = el.innerText;
    let pixelCursor = rect.left;
    let offset = 0;
    let step;
    if (x > rect.left + rect.width) {
      offset = text2.length;
    } else {
      const charWidthReader = CharWidthReader.getInstance();
      for (let i = 0; i < text2.length + 1; i++) {
        step = charWidthReader.getCharWidth(text2.charAt(i), font) / 2;
        pixelCursor += step;
        if (x < pixelCursor) {
          offset = i;
          break;
        }
        pixelCursor += step;
      }
    }
    range2.setStart(el.firstChild, offset);
    range2.setEnd(el.firstChild, offset);
  }
  return range2;
}
class CharWidthReader {
  static getInstance() {
    if (!CharWidthReader._INSTANCE) {
      CharWidthReader._INSTANCE = new CharWidthReader();
    }
    return CharWidthReader._INSTANCE;
  }
  constructor() {
    this._cache = {};
    this._canvas = document.createElement("canvas");
  }
  getCharWidth(char, font) {
    const cacheKey = char + font;
    if (this._cache[cacheKey]) {
      return this._cache[cacheKey];
    }
    const context = this._canvas.getContext("2d");
    context.font = font;
    const metrics = context.measureText(char);
    const width = metrics.width;
    this._cache[cacheKey] = width;
    return width;
  }
}
CharWidthReader._INSTANCE = null;
let Widget$1 = class Widget extends Disposable {
  onclick(domNode, listener) {
    this._register(addDisposableListener(domNode, EventType$1.CLICK, (e) => listener(new StandardMouseEvent(e))));
  }
  onmousedown(domNode, listener) {
    this._register(addDisposableListener(domNode, EventType$1.MOUSE_DOWN, (e) => listener(new StandardMouseEvent(e))));
  }
  onmouseover(domNode, listener) {
    this._register(addDisposableListener(domNode, EventType$1.MOUSE_OVER, (e) => listener(new StandardMouseEvent(e))));
  }
  onmouseleave(domNode, listener) {
    this._register(addDisposableListener(domNode, EventType$1.MOUSE_LEAVE, (e) => listener(new StandardMouseEvent(e))));
  }
  onkeydown(domNode, listener) {
    this._register(addDisposableListener(domNode, EventType$1.KEY_DOWN, (e) => listener(new StandardKeyboardEvent(e))));
  }
  onkeyup(domNode, listener) {
    this._register(addDisposableListener(domNode, EventType$1.KEY_UP, (e) => listener(new StandardKeyboardEvent(e))));
  }
  oninput(domNode, listener) {
    this._register(addDisposableListener(domNode, EventType$1.INPUT, listener));
  }
  onblur(domNode, listener) {
    this._register(addDisposableListener(domNode, EventType$1.BLUR, listener));
  }
  onfocus(domNode, listener) {
    this._register(addDisposableListener(domNode, EventType$1.FOCUS, listener));
  }
  ignoreGesture(domNode) {
    return Gesture.ignoreTarget(domNode);
  }
};
const ARROW_IMG_SIZE = 11;
class ScrollbarArrow extends Widget$1 {
  constructor(opts) {
    super();
    this._onActivate = opts.onActivate;
    this.bgDomNode = document.createElement("div");
    this.bgDomNode.className = "arrow-background";
    this.bgDomNode.style.position = "absolute";
    this.bgDomNode.style.width = opts.bgWidth + "px";
    this.bgDomNode.style.height = opts.bgHeight + "px";
    if (typeof opts.top !== "undefined") {
      this.bgDomNode.style.top = "0px";
    }
    if (typeof opts.left !== "undefined") {
      this.bgDomNode.style.left = "0px";
    }
    if (typeof opts.bottom !== "undefined") {
      this.bgDomNode.style.bottom = "0px";
    }
    if (typeof opts.right !== "undefined") {
      this.bgDomNode.style.right = "0px";
    }
    this.domNode = document.createElement("div");
    this.domNode.className = opts.className;
    this.domNode.classList.add(...ThemeIcon.asClassNameArray(opts.icon));
    this.domNode.style.position = "absolute";
    this.domNode.style.width = ARROW_IMG_SIZE + "px";
    this.domNode.style.height = ARROW_IMG_SIZE + "px";
    if (typeof opts.top !== "undefined") {
      this.domNode.style.top = opts.top + "px";
    }
    if (typeof opts.left !== "undefined") {
      this.domNode.style.left = opts.left + "px";
    }
    if (typeof opts.bottom !== "undefined") {
      this.domNode.style.bottom = opts.bottom + "px";
    }
    if (typeof opts.right !== "undefined") {
      this.domNode.style.right = opts.right + "px";
    }
    this._pointerMoveMonitor = this._register(new GlobalPointerMoveMonitor());
    this._register(addStandardDisposableListener(this.bgDomNode, EventType$1.POINTER_DOWN, (e) => this._arrowPointerDown(e)));
    this._register(addStandardDisposableListener(this.domNode, EventType$1.POINTER_DOWN, (e) => this._arrowPointerDown(e)));
    this._pointerdownRepeatTimer = this._register(new IntervalTimer());
    this._pointerdownScheduleRepeatTimer = this._register(new TimeoutTimer());
  }
  _arrowPointerDown(e) {
    if (!e.target || !(e.target instanceof Element)) {
      return;
    }
    const scheduleRepeater = () => {
      this._pointerdownRepeatTimer.cancelAndSet(() => this._onActivate(), 1e3 / 24);
    };
    this._onActivate();
    this._pointerdownRepeatTimer.cancel();
    this._pointerdownScheduleRepeatTimer.cancelAndSet(scheduleRepeater, 200);
    this._pointerMoveMonitor.startMonitoring(e.target, e.pointerId, e.buttons, (pointerMoveData) => {
    }, () => {
      this._pointerdownRepeatTimer.cancel();
      this._pointerdownScheduleRepeatTimer.cancel();
    });
    e.preventDefault();
  }
}
class ScrollbarVisibilityController extends Disposable {
  constructor(visibility, visibleClassName, invisibleClassName) {
    super();
    this._visibility = visibility;
    this._visibleClassName = visibleClassName;
    this._invisibleClassName = invisibleClassName;
    this._domNode = null;
    this._isVisible = false;
    this._isNeeded = false;
    this._rawShouldBeVisible = false;
    this._shouldBeVisible = false;
    this._revealTimer = this._register(new TimeoutTimer());
  }
  setVisibility(visibility) {
    if (this._visibility !== visibility) {
      this._visibility = visibility;
      this._updateShouldBeVisible();
    }
  }
  // ----------------- Hide / Reveal
  setShouldBeVisible(rawShouldBeVisible) {
    this._rawShouldBeVisible = rawShouldBeVisible;
    this._updateShouldBeVisible();
  }
  _applyVisibilitySetting() {
    if (this._visibility === 2) {
      return false;
    }
    if (this._visibility === 3) {
      return true;
    }
    return this._rawShouldBeVisible;
  }
  _updateShouldBeVisible() {
    const shouldBeVisible = this._applyVisibilitySetting();
    if (this._shouldBeVisible !== shouldBeVisible) {
      this._shouldBeVisible = shouldBeVisible;
      this.ensureVisibility();
    }
  }
  setIsNeeded(isNeeded) {
    if (this._isNeeded !== isNeeded) {
      this._isNeeded = isNeeded;
      this.ensureVisibility();
    }
  }
  setDomNode(domNode) {
    this._domNode = domNode;
    this._domNode.setClassName(this._invisibleClassName);
    this.setShouldBeVisible(false);
  }
  ensureVisibility() {
    if (!this._isNeeded) {
      this._hide(false);
      return;
    }
    if (this._shouldBeVisible) {
      this._reveal();
    } else {
      this._hide(true);
    }
  }
  _reveal() {
    if (this._isVisible) {
      return;
    }
    this._isVisible = true;
    this._revealTimer.setIfNotSet(() => {
      var _a2;
      (_a2 = this._domNode) === null || _a2 === void 0 ? void 0 : _a2.setClassName(this._visibleClassName);
    }, 0);
  }
  _hide(withFadeAway) {
    var _a2;
    this._revealTimer.cancel();
    if (!this._isVisible) {
      return;
    }
    this._isVisible = false;
    (_a2 = this._domNode) === null || _a2 === void 0 ? void 0 : _a2.setClassName(this._invisibleClassName + (withFadeAway ? " fade" : ""));
  }
}
const POINTER_DRAG_RESET_DISTANCE$1 = 140;
class AbstractScrollbar extends Widget$1 {
  constructor(opts) {
    super();
    this._lazyRender = opts.lazyRender;
    this._host = opts.host;
    this._scrollable = opts.scrollable;
    this._scrollByPage = opts.scrollByPage;
    this._scrollbarState = opts.scrollbarState;
    this._visibilityController = this._register(new ScrollbarVisibilityController(opts.visibility, "visible scrollbar " + opts.extraScrollbarClassName, "invisible scrollbar " + opts.extraScrollbarClassName));
    this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());
    this._pointerMoveMonitor = this._register(new GlobalPointerMoveMonitor());
    this._shouldRender = true;
    this.domNode = createFastDomNode(document.createElement("div"));
    this.domNode.setAttribute("role", "presentation");
    this.domNode.setAttribute("aria-hidden", "true");
    this._visibilityController.setDomNode(this.domNode);
    this.domNode.setPosition("absolute");
    this._register(addDisposableListener(this.domNode.domNode, EventType$1.POINTER_DOWN, (e) => this._domNodePointerDown(e)));
  }
  // ----------------- creation
  /**
   * Creates the dom node for an arrow & adds it to the container
   */
  _createArrow(opts) {
    const arrow = this._register(new ScrollbarArrow(opts));
    this.domNode.domNode.appendChild(arrow.bgDomNode);
    this.domNode.domNode.appendChild(arrow.domNode);
  }
  /**
   * Creates the slider dom node, adds it to the container & hooks up the events
   */
  _createSlider(top, left, width, height) {
    this.slider = createFastDomNode(document.createElement("div"));
    this.slider.setClassName("slider");
    this.slider.setPosition("absolute");
    this.slider.setTop(top);
    this.slider.setLeft(left);
    if (typeof width === "number") {
      this.slider.setWidth(width);
    }
    if (typeof height === "number") {
      this.slider.setHeight(height);
    }
    this.slider.setLayerHinting(true);
    this.slider.setContain("strict");
    this.domNode.domNode.appendChild(this.slider.domNode);
    this._register(addDisposableListener(this.slider.domNode, EventType$1.POINTER_DOWN, (e) => {
      if (e.button === 0) {
        e.preventDefault();
        this._sliderPointerDown(e);
      }
    }));
    this.onclick(this.slider.domNode, (e) => {
      if (e.leftButton) {
        e.stopPropagation();
      }
    });
  }
  // ----------------- Update state
  _onElementSize(visibleSize) {
    if (this._scrollbarState.setVisibleSize(visibleSize)) {
      this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());
      this._shouldRender = true;
      if (!this._lazyRender) {
        this.render();
      }
    }
    return this._shouldRender;
  }
  _onElementScrollSize(elementScrollSize) {
    if (this._scrollbarState.setScrollSize(elementScrollSize)) {
      this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());
      this._shouldRender = true;
      if (!this._lazyRender) {
        this.render();
      }
    }
    return this._shouldRender;
  }
  _onElementScrollPosition(elementScrollPosition) {
    if (this._scrollbarState.setScrollPosition(elementScrollPosition)) {
      this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded());
      this._shouldRender = true;
      if (!this._lazyRender) {
        this.render();
      }
    }
    return this._shouldRender;
  }
  // ----------------- rendering
  beginReveal() {
    this._visibilityController.setShouldBeVisible(true);
  }
  beginHide() {
    this._visibilityController.setShouldBeVisible(false);
  }
  render() {
    if (!this._shouldRender) {
      return;
    }
    this._shouldRender = false;
    this._renderDomNode(this._scrollbarState.getRectangleLargeSize(), this._scrollbarState.getRectangleSmallSize());
    this._updateSlider(this._scrollbarState.getSliderSize(), this._scrollbarState.getArrowSize() + this._scrollbarState.getSliderPosition());
  }
  // ----------------- DOM events
  _domNodePointerDown(e) {
    if (e.target !== this.domNode.domNode) {
      return;
    }
    this._onPointerDown(e);
  }
  delegatePointerDown(e) {
    const domTop = this.domNode.domNode.getClientRects()[0].top;
    const sliderStart = domTop + this._scrollbarState.getSliderPosition();
    const sliderStop = domTop + this._scrollbarState.getSliderPosition() + this._scrollbarState.getSliderSize();
    const pointerPos = this._sliderPointerPosition(e);
    if (sliderStart <= pointerPos && pointerPos <= sliderStop) {
      if (e.button === 0) {
        e.preventDefault();
        this._sliderPointerDown(e);
      }
    } else {
      this._onPointerDown(e);
    }
  }
  _onPointerDown(e) {
    let offsetX;
    let offsetY;
    if (e.target === this.domNode.domNode && typeof e.offsetX === "number" && typeof e.offsetY === "number") {
      offsetX = e.offsetX;
      offsetY = e.offsetY;
    } else {
      const domNodePosition = getDomNodePagePosition(this.domNode.domNode);
      offsetX = e.pageX - domNodePosition.left;
      offsetY = e.pageY - domNodePosition.top;
    }
    const offset = this._pointerDownRelativePosition(offsetX, offsetY);
    this._setDesiredScrollPositionNow(this._scrollByPage ? this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(offset) : this._scrollbarState.getDesiredScrollPositionFromOffset(offset));
    if (e.button === 0) {
      e.preventDefault();
      this._sliderPointerDown(e);
    }
  }
  _sliderPointerDown(e) {
    if (!e.target || !(e.target instanceof Element)) {
      return;
    }
    const initialPointerPosition = this._sliderPointerPosition(e);
    const initialPointerOrthogonalPosition = this._sliderOrthogonalPointerPosition(e);
    const initialScrollbarState = this._scrollbarState.clone();
    this.slider.toggleClassName("active", true);
    this._pointerMoveMonitor.startMonitoring(e.target, e.pointerId, e.buttons, (pointerMoveData) => {
      const pointerOrthogonalPosition = this._sliderOrthogonalPointerPosition(pointerMoveData);
      const pointerOrthogonalDelta = Math.abs(pointerOrthogonalPosition - initialPointerOrthogonalPosition);
      if (isWindows && pointerOrthogonalDelta > POINTER_DRAG_RESET_DISTANCE$1) {
        this._setDesiredScrollPositionNow(initialScrollbarState.getScrollPosition());
        return;
      }
      const pointerPosition = this._sliderPointerPosition(pointerMoveData);
      const pointerDelta = pointerPosition - initialPointerPosition;
      this._setDesiredScrollPositionNow(initialScrollbarState.getDesiredScrollPositionFromDelta(pointerDelta));
    }, () => {
      this.slider.toggleClassName("active", false);
      this._host.onDragEnd();
    });
    this._host.onDragStart();
  }
  _setDesiredScrollPositionNow(_desiredScrollPosition) {
    const desiredScrollPosition = {};
    this.writeScrollPosition(desiredScrollPosition, _desiredScrollPosition);
    this._scrollable.setScrollPositionNow(desiredScrollPosition);
  }
  updateScrollbarSize(scrollbarSize) {
    this._updateScrollbarSize(scrollbarSize);
    this._scrollbarState.setScrollbarSize(scrollbarSize);
    this._shouldRender = true;
    if (!this._lazyRender) {
      this.render();
    }
  }
  isNeeded() {
    return this._scrollbarState.isNeeded();
  }
}
const MINIMUM_SLIDER_SIZE = 20;
class ScrollbarState {
  constructor(arrowSize, scrollbarSize, oppositeScrollbarSize, visibleSize, scrollSize, scrollPosition) {
    this._scrollbarSize = Math.round(scrollbarSize);
    this._oppositeScrollbarSize = Math.round(oppositeScrollbarSize);
    this._arrowSize = Math.round(arrowSize);
    this._visibleSize = visibleSize;
    this._scrollSize = scrollSize;
    this._scrollPosition = scrollPosition;
    this._computedAvailableSize = 0;
    this._computedIsNeeded = false;
    this._computedSliderSize = 0;
    this._computedSliderRatio = 0;
    this._computedSliderPosition = 0;
    this._refreshComputedValues();
  }
  clone() {
    return new ScrollbarState(this._arrowSize, this._scrollbarSize, this._oppositeScrollbarSize, this._visibleSize, this._scrollSize, this._scrollPosition);
  }
  setVisibleSize(visibleSize) {
    const iVisibleSize = Math.round(visibleSize);
    if (this._visibleSize !== iVisibleSize) {
      this._visibleSize = iVisibleSize;
      this._refreshComputedValues();
      return true;
    }
    return false;
  }
  setScrollSize(scrollSize) {
    const iScrollSize = Math.round(scrollSize);
    if (this._scrollSize !== iScrollSize) {
      this._scrollSize = iScrollSize;
      this._refreshComputedValues();
      return true;
    }
    return false;
  }
  setScrollPosition(scrollPosition) {
    const iScrollPosition = Math.round(scrollPosition);
    if (this._scrollPosition !== iScrollPosition) {
      this._scrollPosition = iScrollPosition;
      this._refreshComputedValues();
      return true;
    }
    return false;
  }
  setScrollbarSize(scrollbarSize) {
    this._scrollbarSize = Math.round(scrollbarSize);
  }
  setOppositeScrollbarSize(oppositeScrollbarSize) {
    this._oppositeScrollbarSize = Math.round(oppositeScrollbarSize);
  }
  static _computeValues(oppositeScrollbarSize, arrowSize, visibleSize, scrollSize, scrollPosition) {
    const computedAvailableSize = Math.max(0, visibleSize - oppositeScrollbarSize);
    const computedRepresentableSize = Math.max(0, computedAvailableSize - 2 * arrowSize);
    const computedIsNeeded = scrollSize > 0 && scrollSize > visibleSize;
    if (!computedIsNeeded) {
      return {
        computedAvailableSize: Math.round(computedAvailableSize),
        computedIsNeeded,
        computedSliderSize: Math.round(computedRepresentableSize),
        computedSliderRatio: 0,
        computedSliderPosition: 0
      };
    }
    const computedSliderSize = Math.round(Math.max(MINIMUM_SLIDER_SIZE, Math.floor(visibleSize * computedRepresentableSize / scrollSize)));
    const computedSliderRatio = (computedRepresentableSize - computedSliderSize) / (scrollSize - visibleSize);
    const computedSliderPosition = scrollPosition * computedSliderRatio;
    return {
      computedAvailableSize: Math.round(computedAvailableSize),
      computedIsNeeded,
      computedSliderSize: Math.round(computedSliderSize),
      computedSliderRatio,
      computedSliderPosition: Math.round(computedSliderPosition)
    };
  }
  _refreshComputedValues() {
    const r = ScrollbarState._computeValues(this._oppositeScrollbarSize, this._arrowSize, this._visibleSize, this._scrollSize, this._scrollPosition);
    this._computedAvailableSize = r.computedAvailableSize;
    this._computedIsNeeded = r.computedIsNeeded;
    this._computedSliderSize = r.computedSliderSize;
    this._computedSliderRatio = r.computedSliderRatio;
    this._computedSliderPosition = r.computedSliderPosition;
  }
  getArrowSize() {
    return this._arrowSize;
  }
  getScrollPosition() {
    return this._scrollPosition;
  }
  getRectangleLargeSize() {
    return this._computedAvailableSize;
  }
  getRectangleSmallSize() {
    return this._scrollbarSize;
  }
  isNeeded() {
    return this._computedIsNeeded;
  }
  getSliderSize() {
    return this._computedSliderSize;
  }
  getSliderPosition() {
    return this._computedSliderPosition;
  }
  /**
   * Compute a desired `scrollPosition` such that `offset` ends up in the center of the slider.
   * `offset` is based on the same coordinate system as the `sliderPosition`.
   */
  getDesiredScrollPositionFromOffset(offset) {
    if (!this._computedIsNeeded) {
      return 0;
    }
    const desiredSliderPosition = offset - this._arrowSize - this._computedSliderSize / 2;
    return Math.round(desiredSliderPosition / this._computedSliderRatio);
  }
  /**
   * Compute a desired `scrollPosition` from if offset is before or after the slider position.
   * If offset is before slider, treat as a page up (or left).  If after, page down (or right).
   * `offset` and `_computedSliderPosition` are based on the same coordinate system.
   * `_visibleSize` corresponds to a "page" of lines in the returned coordinate system.
   */
  getDesiredScrollPositionFromOffsetPaged(offset) {
    if (!this._computedIsNeeded) {
      return 0;
    }
    const correctedOffset = offset - this._arrowSize;
    let desiredScrollPosition = this._scrollPosition;
    if (correctedOffset < this._computedSliderPosition) {
      desiredScrollPosition -= this._visibleSize;
    } else {
      desiredScrollPosition += this._visibleSize;
    }
    return desiredScrollPosition;
  }
  /**
   * Compute a desired `scrollPosition` such that the slider moves by `delta`.
   */
  getDesiredScrollPositionFromDelta(delta) {
    if (!this._computedIsNeeded) {
      return 0;
    }
    const desiredSliderPosition = this._computedSliderPosition + delta;
    return Math.round(desiredSliderPosition / this._computedSliderRatio);
  }
}
class HorizontalScrollbar extends AbstractScrollbar {
  constructor(scrollable, options, host) {
    const scrollDimensions = scrollable.getScrollDimensions();
    const scrollPosition = scrollable.getCurrentScrollPosition();
    super({
      lazyRender: options.lazyRender,
      host,
      scrollbarState: new ScrollbarState(options.horizontalHasArrows ? options.arrowSize : 0, options.horizontal === 2 ? 0 : options.horizontalScrollbarSize, options.vertical === 2 ? 0 : options.verticalScrollbarSize, scrollDimensions.width, scrollDimensions.scrollWidth, scrollPosition.scrollLeft),
      visibility: options.horizontal,
      extraScrollbarClassName: "horizontal",
      scrollable,
      scrollByPage: options.scrollByPage
    });
    if (options.horizontalHasArrows) {
      const arrowDelta = (options.arrowSize - ARROW_IMG_SIZE) / 2;
      const scrollbarDelta = (options.horizontalScrollbarSize - ARROW_IMG_SIZE) / 2;
      this._createArrow({
        className: "scra",
        icon: Codicon.scrollbarButtonLeft,
        top: scrollbarDelta,
        left: arrowDelta,
        bottom: void 0,
        right: void 0,
        bgWidth: options.arrowSize,
        bgHeight: options.horizontalScrollbarSize,
        onActivate: () => this._host.onMouseWheel(new StandardWheelEvent(null, 1, 0))
      });
      this._createArrow({
        className: "scra",
        icon: Codicon.scrollbarButtonRight,
        top: scrollbarDelta,
        left: void 0,
        bottom: void 0,
        right: arrowDelta,
        bgWidth: options.arrowSize,
        bgHeight: options.horizontalScrollbarSize,
        onActivate: () => this._host.onMouseWheel(new StandardWheelEvent(null, -1, 0))
      });
    }
    this._createSlider(Math.floor((options.horizontalScrollbarSize - options.horizontalSliderSize) / 2), 0, void 0, options.horizontalSliderSize);
  }
  _updateSlider(sliderSize, sliderPosition) {
    this.slider.setWidth(sliderSize);
    this.slider.setLeft(sliderPosition);
  }
  _renderDomNode(largeSize, smallSize) {
    this.domNode.setWidth(largeSize);
    this.domNode.setHeight(smallSize);
    this.domNode.setLeft(0);
    this.domNode.setBottom(0);
  }
  onDidScroll(e) {
    this._shouldRender = this._onElementScrollSize(e.scrollWidth) || this._shouldRender;
    this._shouldRender = this._onElementScrollPosition(e.scrollLeft) || this._shouldRender;
    this._shouldRender = this._onElementSize(e.width) || this._shouldRender;
    return this._shouldRender;
  }
  _pointerDownRelativePosition(offsetX, offsetY) {
    return offsetX;
  }
  _sliderPointerPosition(e) {
    return e.pageX;
  }
  _sliderOrthogonalPointerPosition(e) {
    return e.pageY;
  }
  _updateScrollbarSize(size2) {
    this.slider.setHeight(size2);
  }
  writeScrollPosition(target, scrollPosition) {
    target.scrollLeft = scrollPosition;
  }
  updateOptions(options) {
    this.updateScrollbarSize(options.horizontal === 2 ? 0 : options.horizontalScrollbarSize);
    this._scrollbarState.setOppositeScrollbarSize(options.vertical === 2 ? 0 : options.verticalScrollbarSize);
    this._visibilityController.setVisibility(options.horizontal);
    this._scrollByPage = options.scrollByPage;
  }
}
class VerticalScrollbar extends AbstractScrollbar {
  constructor(scrollable, options, host) {
    const scrollDimensions = scrollable.getScrollDimensions();
    const scrollPosition = scrollable.getCurrentScrollPosition();
    super({
      lazyRender: options.lazyRender,
      host,
      scrollbarState: new ScrollbarState(
        options.verticalHasArrows ? options.arrowSize : 0,
        options.vertical === 2 ? 0 : options.verticalScrollbarSize,
        // give priority to vertical scroll bar over horizontal and let it scroll all the way to the bottom
        0,
        scrollDimensions.height,
        scrollDimensions.scrollHeight,
        scrollPosition.scrollTop
      ),
      visibility: options.vertical,
      extraScrollbarClassName: "vertical",
      scrollable,
      scrollByPage: options.scrollByPage
    });
    if (options.verticalHasArrows) {
      const arrowDelta = (options.arrowSize - ARROW_IMG_SIZE) / 2;
      const scrollbarDelta = (options.verticalScrollbarSize - ARROW_IMG_SIZE) / 2;
      this._createArrow({
        className: "scra",
        icon: Codicon.scrollbarButtonUp,
        top: arrowDelta,
        left: scrollbarDelta,
        bottom: void 0,
        right: void 0,
        bgWidth: options.verticalScrollbarSize,
        bgHeight: options.arrowSize,
        onActivate: () => this._host.onMouseWheel(new StandardWheelEvent(null, 0, 1))
      });
      this._createArrow({
        className: "scra",
        icon: Codicon.scrollbarButtonDown,
        top: void 0,
        left: scrollbarDelta,
        bottom: arrowDelta,
        right: void 0,
        bgWidth: options.verticalScrollbarSize,
        bgHeight: options.arrowSize,
        onActivate: () => this._host.onMouseWheel(new StandardWheelEvent(null, 0, -1))
      });
    }
    this._createSlider(0, Math.floor((options.verticalScrollbarSize - options.verticalSliderSize) / 2), options.verticalSliderSize, void 0);
  }
  _updateSlider(sliderSize, sliderPosition) {
    this.slider.setHeight(sliderSize);
    this.slider.setTop(sliderPosition);
  }
  _renderDomNode(largeSize, smallSize) {
    this.domNode.setWidth(smallSize);
    this.domNode.setHeight(largeSize);
    this.domNode.setRight(0);
    this.domNode.setTop(0);
  }
  onDidScroll(e) {
    this._shouldRender = this._onElementScrollSize(e.scrollHeight) || this._shouldRender;
    this._shouldRender = this._onElementScrollPosition(e.scrollTop) || this._shouldRender;
    this._shouldRender = this._onElementSize(e.height) || this._shouldRender;
    return this._shouldRender;
  }
  _pointerDownRelativePosition(offsetX, offsetY) {
    return offsetY;
  }
  _sliderPointerPosition(e) {
    return e.pageY;
  }
  _sliderOrthogonalPointerPosition(e) {
    return e.pageX;
  }
  _updateScrollbarSize(size2) {
    this.slider.setWidth(size2);
  }
  writeScrollPosition(target, scrollPosition) {
    target.scrollTop = scrollPosition;
  }
  updateOptions(options) {
    this.updateScrollbarSize(options.vertical === 2 ? 0 : options.verticalScrollbarSize);
    this._scrollbarState.setOppositeScrollbarSize(0);
    this._visibilityController.setVisibility(options.vertical);
    this._scrollByPage = options.scrollByPage;
  }
}
class ScrollState {
  constructor(_forceIntegerValues, width, scrollWidth, scrollLeft, height, scrollHeight, scrollTop) {
    this._forceIntegerValues = _forceIntegerValues;
    this._scrollStateBrand = void 0;
    if (this._forceIntegerValues) {
      width = width | 0;
      scrollWidth = scrollWidth | 0;
      scrollLeft = scrollLeft | 0;
      height = height | 0;
      scrollHeight = scrollHeight | 0;
      scrollTop = scrollTop | 0;
    }
    this.rawScrollLeft = scrollLeft;
    this.rawScrollTop = scrollTop;
    if (width < 0) {
      width = 0;
    }
    if (scrollLeft + width > scrollWidth) {
      scrollLeft = scrollWidth - width;
    }
    if (scrollLeft < 0) {
      scrollLeft = 0;
    }
    if (height < 0) {
      height = 0;
    }
    if (scrollTop + height > scrollHeight) {
      scrollTop = scrollHeight - height;
    }
    if (scrollTop < 0) {
      scrollTop = 0;
    }
    this.width = width;
    this.scrollWidth = scrollWidth;
    this.scrollLeft = scrollLeft;
    this.height = height;
    this.scrollHeight = scrollHeight;
    this.scrollTop = scrollTop;
  }
  equals(other) {
    return this.rawScrollLeft === other.rawScrollLeft && this.rawScrollTop === other.rawScrollTop && this.width === other.width && this.scrollWidth === other.scrollWidth && this.scrollLeft === other.scrollLeft && this.height === other.height && this.scrollHeight === other.scrollHeight && this.scrollTop === other.scrollTop;
  }
  withScrollDimensions(update, useRawScrollPositions) {
    return new ScrollState(this._forceIntegerValues, typeof update.width !== "undefined" ? update.width : this.width, typeof update.scrollWidth !== "undefined" ? update.scrollWidth : this.scrollWidth, useRawScrollPositions ? this.rawScrollLeft : this.scrollLeft, typeof update.height !== "undefined" ? update.height : this.height, typeof update.scrollHeight !== "undefined" ? update.scrollHeight : this.scrollHeight, useRawScrollPositions ? this.rawScrollTop : this.scrollTop);
  }
  withScrollPosition(update) {
    return new ScrollState(this._forceIntegerValues, this.width, this.scrollWidth, typeof update.scrollLeft !== "undefined" ? update.scrollLeft : this.rawScrollLeft, this.height, this.scrollHeight, typeof update.scrollTop !== "undefined" ? update.scrollTop : this.rawScrollTop);
  }
  createScrollEvent(previous, inSmoothScrolling) {
    const widthChanged = this.width !== previous.width;
    const scrollWidthChanged = this.scrollWidth !== previous.scrollWidth;
    const scrollLeftChanged = this.scrollLeft !== previous.scrollLeft;
    const heightChanged = this.height !== previous.height;
    const scrollHeightChanged = this.scrollHeight !== previous.scrollHeight;
    const scrollTopChanged = this.scrollTop !== previous.scrollTop;
    return {
      inSmoothScrolling,
      oldWidth: previous.width,
      oldScrollWidth: previous.scrollWidth,
      oldScrollLeft: previous.scrollLeft,
      width: this.width,
      scrollWidth: this.scrollWidth,
      scrollLeft: this.scrollLeft,
      oldHeight: previous.height,
      oldScrollHeight: previous.scrollHeight,
      oldScrollTop: previous.scrollTop,
      height: this.height,
      scrollHeight: this.scrollHeight,
      scrollTop: this.scrollTop,
      widthChanged,
      scrollWidthChanged,
      scrollLeftChanged,
      heightChanged,
      scrollHeightChanged,
      scrollTopChanged
    };
  }
}
class Scrollable extends Disposable {
  constructor(options) {
    super();
    this._scrollableBrand = void 0;
    this._onScroll = this._register(new Emitter$1());
    this.onScroll = this._onScroll.event;
    this._smoothScrollDuration = options.smoothScrollDuration;
    this._scheduleAtNextAnimationFrame = options.scheduleAtNextAnimationFrame;
    this._state = new ScrollState(options.forceIntegerValues, 0, 0, 0, 0, 0, 0);
    this._smoothScrolling = null;
  }
  dispose() {
    if (this._smoothScrolling) {
      this._smoothScrolling.dispose();
      this._smoothScrolling = null;
    }
    super.dispose();
  }
  setSmoothScrollDuration(smoothScrollDuration) {
    this._smoothScrollDuration = smoothScrollDuration;
  }
  validateScrollPosition(scrollPosition) {
    return this._state.withScrollPosition(scrollPosition);
  }
  getScrollDimensions() {
    return this._state;
  }
  setScrollDimensions(dimensions, useRawScrollPositions) {
    var _a2;
    const newState = this._state.withScrollDimensions(dimensions, useRawScrollPositions);
    this._setState(newState, Boolean(this._smoothScrolling));
    (_a2 = this._smoothScrolling) === null || _a2 === void 0 ? void 0 : _a2.acceptScrollDimensions(this._state);
  }
  /**
   * Returns the final scroll position that the instance will have once the smooth scroll animation concludes.
   * If no scroll animation is occurring, it will return the current scroll position instead.
   */
  getFutureScrollPosition() {
    if (this._smoothScrolling) {
      return this._smoothScrolling.to;
    }
    return this._state;
  }
  /**
   * Returns the current scroll position.
   * Note: This result might be an intermediate scroll position, as there might be an ongoing smooth scroll animation.
   */
  getCurrentScrollPosition() {
    return this._state;
  }
  setScrollPositionNow(update) {
    const newState = this._state.withScrollPosition(update);
    if (this._smoothScrolling) {
      this._smoothScrolling.dispose();
      this._smoothScrolling = null;
    }
    this._setState(newState, false);
  }
  setScrollPositionSmooth(update, reuseAnimation) {
    if (this._smoothScrollDuration === 0) {
      return this.setScrollPositionNow(update);
    }
    if (this._smoothScrolling) {
      update = {
        scrollLeft: typeof update.scrollLeft === "undefined" ? this._smoothScrolling.to.scrollLeft : update.scrollLeft,
        scrollTop: typeof update.scrollTop === "undefined" ? this._smoothScrolling.to.scrollTop : update.scrollTop
      };
      const validTarget = this._state.withScrollPosition(update);
      if (this._smoothScrolling.to.scrollLeft === validTarget.scrollLeft && this._smoothScrolling.to.scrollTop === validTarget.scrollTop) {
        return;
      }
      let newSmoothScrolling;
      if (reuseAnimation) {
        newSmoothScrolling = new SmoothScrollingOperation(this._smoothScrolling.from, validTarget, this._smoothScrolling.startTime, this._smoothScrolling.duration);
      } else {
        newSmoothScrolling = this._smoothScrolling.combine(this._state, validTarget, this._smoothScrollDuration);
      }
      this._smoothScrolling.dispose();
      this._smoothScrolling = newSmoothScrolling;
    } else {
      const validTarget = this._state.withScrollPosition(update);
      this._smoothScrolling = SmoothScrollingOperation.start(this._state, validTarget, this._smoothScrollDuration);
    }
    this._smoothScrolling.animationFrameDisposable = this._scheduleAtNextAnimationFrame(() => {
      if (!this._smoothScrolling) {
        return;
      }
      this._smoothScrolling.animationFrameDisposable = null;
      this._performSmoothScrolling();
    });
  }
  hasPendingScrollAnimation() {
    return Boolean(this._smoothScrolling);
  }
  _performSmoothScrolling() {
    if (!this._smoothScrolling) {
      return;
    }
    const update = this._smoothScrolling.tick();
    const newState = this._state.withScrollPosition(update);
    this._setState(newState, true);
    if (!this._smoothScrolling) {
      return;
    }
    if (update.isDone) {
      this._smoothScrolling.dispose();
      this._smoothScrolling = null;
      return;
    }
    this._smoothScrolling.animationFrameDisposable = this._scheduleAtNextAnimationFrame(() => {
      if (!this._smoothScrolling) {
        return;
      }
      this._smoothScrolling.animationFrameDisposable = null;
      this._performSmoothScrolling();
    });
  }
  _setState(newState, inSmoothScrolling) {
    const oldState = this._state;
    if (oldState.equals(newState)) {
      return;
    }
    this._state = newState;
    this._onScroll.fire(this._state.createScrollEvent(oldState, inSmoothScrolling));
  }
}
class SmoothScrollingUpdate {
  constructor(scrollLeft, scrollTop, isDone) {
    this.scrollLeft = scrollLeft;
    this.scrollTop = scrollTop;
    this.isDone = isDone;
  }
}
function createEaseOutCubic(from2, to) {
  const delta = to - from2;
  return function(completion) {
    return from2 + delta * easeOutCubic(completion);
  };
}
function createComposed(a, b, cut) {
  return function(completion) {
    if (completion < cut) {
      return a(completion / cut);
    }
    return b((completion - cut) / (1 - cut));
  };
}
class SmoothScrollingOperation {
  constructor(from2, to, startTime2, duration) {
    this.from = from2;
    this.to = to;
    this.duration = duration;
    this.startTime = startTime2;
    this.animationFrameDisposable = null;
    this._initAnimations();
  }
  _initAnimations() {
    this.scrollLeft = this._initAnimation(this.from.scrollLeft, this.to.scrollLeft, this.to.width);
    this.scrollTop = this._initAnimation(this.from.scrollTop, this.to.scrollTop, this.to.height);
  }
  _initAnimation(from2, to, viewportSize) {
    const delta = Math.abs(from2 - to);
    if (delta > 2.5 * viewportSize) {
      let stop1, stop2;
      if (from2 < to) {
        stop1 = from2 + 0.75 * viewportSize;
        stop2 = to - 0.75 * viewportSize;
      } else {
        stop1 = from2 - 0.75 * viewportSize;
        stop2 = to + 0.75 * viewportSize;
      }
      return createComposed(createEaseOutCubic(from2, stop1), createEaseOutCubic(stop2, to), 0.33);
    }
    return createEaseOutCubic(from2, to);
  }
  dispose() {
    if (this.animationFrameDisposable !== null) {
      this.animationFrameDisposable.dispose();
      this.animationFrameDisposable = null;
    }
  }
  acceptScrollDimensions(state) {
    this.to = state.withScrollPosition(this.to);
    this._initAnimations();
  }
  tick() {
    return this._tick(Date.now());
  }
  _tick(now) {
    const completion = (now - this.startTime) / this.duration;
    if (completion < 1) {
      const newScrollLeft = this.scrollLeft(completion);
      const newScrollTop = this.scrollTop(completion);
      return new SmoothScrollingUpdate(newScrollLeft, newScrollTop, false);
    }
    return new SmoothScrollingUpdate(this.to.scrollLeft, this.to.scrollTop, true);
  }
  combine(from2, to, duration) {
    return SmoothScrollingOperation.start(from2, to, duration);
  }
  static start(from2, to, duration) {
    duration = duration + 10;
    const startTime2 = Date.now() - 10;
    return new SmoothScrollingOperation(from2, to, startTime2, duration);
  }
}
function easeInCubic(t) {
  return Math.pow(t, 3);
}
function easeOutCubic(t) {
  return 1 - easeInCubic(1 - t);
}
const scrollbars = "";
const HIDE_TIMEOUT = 500;
const SCROLL_WHEEL_SENSITIVITY = 50;
class MouseWheelClassifierItem {
  constructor(timestamp2, deltaX, deltaY) {
    this.timestamp = timestamp2;
    this.deltaX = deltaX;
    this.deltaY = deltaY;
    this.score = 0;
  }
}
class MouseWheelClassifier {
  constructor() {
    this._capacity = 5;
    this._memory = [];
    this._front = -1;
    this._rear = -1;
  }
  isPhysicalMouseWheel() {
    if (this._front === -1 && this._rear === -1) {
      return false;
    }
    let remainingInfluence = 1;
    let score2 = 0;
    let iteration = 1;
    let index = this._rear;
    do {
      const influence = index === this._front ? remainingInfluence : Math.pow(2, -iteration);
      remainingInfluence -= influence;
      score2 += this._memory[index].score * influence;
      if (index === this._front) {
        break;
      }
      index = (this._capacity + index - 1) % this._capacity;
      iteration++;
    } while (true);
    return score2 <= 0.5;
  }
  acceptStandardWheelEvent(e) {
    const osZoomFactor = window.devicePixelRatio / getZoomFactor();
    if (isWindows || isLinux) {
      this.accept(Date.now(), e.deltaX / osZoomFactor, e.deltaY / osZoomFactor);
    } else {
      this.accept(Date.now(), e.deltaX, e.deltaY);
    }
  }
  accept(timestamp2, deltaX, deltaY) {
    const item = new MouseWheelClassifierItem(timestamp2, deltaX, deltaY);
    item.score = this._computeScore(item);
    if (this._front === -1 && this._rear === -1) {
      this._memory[0] = item;
      this._front = 0;
      this._rear = 0;
    } else {
      this._rear = (this._rear + 1) % this._capacity;
      if (this._rear === this._front) {
        this._front = (this._front + 1) % this._capacity;
      }
      this._memory[this._rear] = item;
    }
  }
  /**
   * A score between 0 and 1 for `item`.
   *  - a score towards 0 indicates that the source appears to be a physical mouse wheel
   *  - a score towards 1 indicates that the source appears to be a touchpad or magic mouse, etc.
   */
  _computeScore(item) {
    if (Math.abs(item.deltaX) > 0 && Math.abs(item.deltaY) > 0) {
      return 1;
    }
    let score2 = 0.5;
    this._front === -1 && this._rear === -1 ? null : this._memory[this._rear];
    if (!this._isAlmostInt(item.deltaX) || !this._isAlmostInt(item.deltaY)) {
      score2 += 0.25;
    }
    return Math.min(Math.max(score2, 0), 1);
  }
  _isAlmostInt(value) {
    const delta = Math.abs(Math.round(value) - value);
    return delta < 0.01;
  }
}
MouseWheelClassifier.INSTANCE = new MouseWheelClassifier();
class AbstractScrollableElement extends Widget$1 {
  get options() {
    return this._options;
  }
  constructor(element, options, scrollable) {
    super();
    this._onScroll = this._register(new Emitter$1());
    this.onScroll = this._onScroll.event;
    this._onWillScroll = this._register(new Emitter$1());
    element.style.overflow = "hidden";
    this._options = resolveOptions$1(options);
    this._scrollable = scrollable;
    this._register(this._scrollable.onScroll((e) => {
      this._onWillScroll.fire(e);
      this._onDidScroll(e);
      this._onScroll.fire(e);
    }));
    const scrollbarHost = {
      onMouseWheel: (mouseWheelEvent) => this._onMouseWheel(mouseWheelEvent),
      onDragStart: () => this._onDragStart(),
      onDragEnd: () => this._onDragEnd()
    };
    this._verticalScrollbar = this._register(new VerticalScrollbar(this._scrollable, this._options, scrollbarHost));
    this._horizontalScrollbar = this._register(new HorizontalScrollbar(this._scrollable, this._options, scrollbarHost));
    this._domNode = document.createElement("div");
    this._domNode.className = "monaco-scrollable-element " + this._options.className;
    this._domNode.setAttribute("role", "presentation");
    this._domNode.style.position = "relative";
    this._domNode.style.overflow = "hidden";
    this._domNode.appendChild(element);
    this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode);
    this._domNode.appendChild(this._verticalScrollbar.domNode.domNode);
    if (this._options.useShadows) {
      this._leftShadowDomNode = createFastDomNode(document.createElement("div"));
      this._leftShadowDomNode.setClassName("shadow");
      this._domNode.appendChild(this._leftShadowDomNode.domNode);
      this._topShadowDomNode = createFastDomNode(document.createElement("div"));
      this._topShadowDomNode.setClassName("shadow");
      this._domNode.appendChild(this._topShadowDomNode.domNode);
      this._topLeftShadowDomNode = createFastDomNode(document.createElement("div"));
      this._topLeftShadowDomNode.setClassName("shadow");
      this._domNode.appendChild(this._topLeftShadowDomNode.domNode);
    } else {
      this._leftShadowDomNode = null;
      this._topShadowDomNode = null;
      this._topLeftShadowDomNode = null;
    }
    this._listenOnDomNode = this._options.listenOnDomNode || this._domNode;
    this._mouseWheelToDispose = [];
    this._setListeningToMouseWheel(this._options.handleMouseWheel);
    this.onmouseover(this._listenOnDomNode, (e) => this._onMouseOver(e));
    this.onmouseleave(this._listenOnDomNode, (e) => this._onMouseLeave(e));
    this._hideTimeout = this._register(new TimeoutTimer());
    this._isDragging = false;
    this._mouseIsOver = false;
    this._shouldRender = true;
    this._revealOnScroll = true;
  }
  dispose() {
    this._mouseWheelToDispose = dispose(this._mouseWheelToDispose);
    super.dispose();
  }
  /**
   * Get the generated 'scrollable' dom node
   */
  getDomNode() {
    return this._domNode;
  }
  getOverviewRulerLayoutInfo() {
    return {
      parent: this._domNode,
      insertBefore: this._verticalScrollbar.domNode.domNode
    };
  }
  /**
   * Delegate a pointer down event to the vertical scrollbar.
   * This is to help with clicking somewhere else and having the scrollbar react.
   */
  delegateVerticalScrollbarPointerDown(browserEvent) {
    this._verticalScrollbar.delegatePointerDown(browserEvent);
  }
  getScrollDimensions() {
    return this._scrollable.getScrollDimensions();
  }
  setScrollDimensions(dimensions) {
    this._scrollable.setScrollDimensions(dimensions, false);
  }
  /**
   * Update the class name of the scrollable element.
   */
  updateClassName(newClassName) {
    this._options.className = newClassName;
    if (isMacintosh) {
      this._options.className += " mac";
    }
    this._domNode.className = "monaco-scrollable-element " + this._options.className;
  }
  /**
   * Update configuration options for the scrollbar.
   */
  updateOptions(newOptions) {
    if (typeof newOptions.handleMouseWheel !== "undefined") {
      this._options.handleMouseWheel = newOptions.handleMouseWheel;
      this._setListeningToMouseWheel(this._options.handleMouseWheel);
    }
    if (typeof newOptions.mouseWheelScrollSensitivity !== "undefined") {
      this._options.mouseWheelScrollSensitivity = newOptions.mouseWheelScrollSensitivity;
    }
    if (typeof newOptions.fastScrollSensitivity !== "undefined") {
      this._options.fastScrollSensitivity = newOptions.fastScrollSensitivity;
    }
    if (typeof newOptions.scrollPredominantAxis !== "undefined") {
      this._options.scrollPredominantAxis = newOptions.scrollPredominantAxis;
    }
    if (typeof newOptions.horizontal !== "undefined") {
      this._options.horizontal = newOptions.horizontal;
    }
    if (typeof newOptions.vertical !== "undefined") {
      this._options.vertical = newOptions.vertical;
    }
    if (typeof newOptions.horizontalScrollbarSize !== "undefined") {
      this._options.horizontalScrollbarSize = newOptions.horizontalScrollbarSize;
    }
    if (typeof newOptions.verticalScrollbarSize !== "undefined") {
      this._options.verticalScrollbarSize = newOptions.verticalScrollbarSize;
    }
    if (typeof newOptions.scrollByPage !== "undefined") {
      this._options.scrollByPage = newOptions.scrollByPage;
    }
    this._horizontalScrollbar.updateOptions(this._options);
    this._verticalScrollbar.updateOptions(this._options);
    if (!this._options.lazyRender) {
      this._render();
    }
  }
  delegateScrollFromMouseWheelEvent(browserEvent) {
    this._onMouseWheel(new StandardWheelEvent(browserEvent));
  }
  // -------------------- mouse wheel scrolling --------------------
  _setListeningToMouseWheel(shouldListen) {
    const isListening = this._mouseWheelToDispose.length > 0;
    if (isListening === shouldListen) {
      return;
    }
    this._mouseWheelToDispose = dispose(this._mouseWheelToDispose);
    if (shouldListen) {
      const onMouseWheel = (browserEvent) => {
        this._onMouseWheel(new StandardWheelEvent(browserEvent));
      };
      this._mouseWheelToDispose.push(addDisposableListener(this._listenOnDomNode, EventType$1.MOUSE_WHEEL, onMouseWheel, { passive: false }));
    }
  }
  _onMouseWheel(e) {
    var _a2;
    if ((_a2 = e.browserEvent) === null || _a2 === void 0 ? void 0 : _a2.defaultPrevented) {
      return;
    }
    const classifier = MouseWheelClassifier.INSTANCE;
    {
      classifier.acceptStandardWheelEvent(e);
    }
    let didScroll = false;
    if (e.deltaY || e.deltaX) {
      let deltaY = e.deltaY * this._options.mouseWheelScrollSensitivity;
      let deltaX = e.deltaX * this._options.mouseWheelScrollSensitivity;
      if (this._options.scrollPredominantAxis) {
        if (Math.abs(deltaY) >= Math.abs(deltaX)) {
          deltaX = 0;
        } else {
          deltaY = 0;
        }
      }
      if (this._options.flipAxes) {
        [deltaY, deltaX] = [deltaX, deltaY];
      }
      const shiftConvert = !isMacintosh && e.browserEvent && e.browserEvent.shiftKey;
      if ((this._options.scrollYToX || shiftConvert) && !deltaX) {
        deltaX = deltaY;
        deltaY = 0;
      }
      if (e.browserEvent && e.browserEvent.altKey) {
        deltaX = deltaX * this._options.fastScrollSensitivity;
        deltaY = deltaY * this._options.fastScrollSensitivity;
      }
      const futureScrollPosition = this._scrollable.getFutureScrollPosition();
      let desiredScrollPosition = {};
      if (deltaY) {
        const deltaScrollTop = SCROLL_WHEEL_SENSITIVITY * deltaY;
        const desiredScrollTop = futureScrollPosition.scrollTop - (deltaScrollTop < 0 ? Math.floor(deltaScrollTop) : Math.ceil(deltaScrollTop));
        this._verticalScrollbar.writeScrollPosition(desiredScrollPosition, desiredScrollTop);
      }
      if (deltaX) {
        const deltaScrollLeft = SCROLL_WHEEL_SENSITIVITY * deltaX;
        const desiredScrollLeft = futureScrollPosition.scrollLeft - (deltaScrollLeft < 0 ? Math.floor(deltaScrollLeft) : Math.ceil(deltaScrollLeft));
        this._horizontalScrollbar.writeScrollPosition(desiredScrollPosition, desiredScrollLeft);
      }
      desiredScrollPosition = this._scrollable.validateScrollPosition(desiredScrollPosition);
      if (futureScrollPosition.scrollLeft !== desiredScrollPosition.scrollLeft || futureScrollPosition.scrollTop !== desiredScrollPosition.scrollTop) {
        const canPerformSmoothScroll = this._options.mouseWheelSmoothScroll && classifier.isPhysicalMouseWheel();
        if (canPerformSmoothScroll) {
          this._scrollable.setScrollPositionSmooth(desiredScrollPosition);
        } else {
          this._scrollable.setScrollPositionNow(desiredScrollPosition);
        }
        didScroll = true;
      }
    }
    let consumeMouseWheel = didScroll;
    if (!consumeMouseWheel && this._options.alwaysConsumeMouseWheel) {
      consumeMouseWheel = true;
    }
    if (!consumeMouseWheel && this._options.consumeMouseWheelIfScrollbarIsNeeded && (this._verticalScrollbar.isNeeded() || this._horizontalScrollbar.isNeeded())) {
      consumeMouseWheel = true;
    }
    if (consumeMouseWheel) {
      e.preventDefault();
      e.stopPropagation();
    }
  }
  _onDidScroll(e) {
    this._shouldRender = this._horizontalScrollbar.onDidScroll(e) || this._shouldRender;
    this._shouldRender = this._verticalScrollbar.onDidScroll(e) || this._shouldRender;
    if (this._options.useShadows) {
      this._shouldRender = true;
    }
    if (this._revealOnScroll) {
      this._reveal();
    }
    if (!this._options.lazyRender) {
      this._render();
    }
  }
  /**
   * Render / mutate the DOM now.
   * Should be used together with the ctor option `lazyRender`.
   */
  renderNow() {
    if (!this._options.lazyRender) {
      throw new Error("Please use `lazyRender` together with `renderNow`!");
    }
    this._render();
  }
  _render() {
    if (!this._shouldRender) {
      return;
    }
    this._shouldRender = false;
    this._horizontalScrollbar.render();
    this._verticalScrollbar.render();
    if (this._options.useShadows) {
      const scrollState = this._scrollable.getCurrentScrollPosition();
      const enableTop = scrollState.scrollTop > 0;
      const enableLeft = scrollState.scrollLeft > 0;
      const leftClassName = enableLeft ? " left" : "";
      const topClassName = enableTop ? " top" : "";
      const topLeftClassName = enableLeft || enableTop ? " top-left-corner" : "";
      this._leftShadowDomNode.setClassName(`shadow${leftClassName}`);
      this._topShadowDomNode.setClassName(`shadow${topClassName}`);
      this._topLeftShadowDomNode.setClassName(`shadow${topLeftClassName}${topClassName}${leftClassName}`);
    }
  }
  // -------------------- fade in / fade out --------------------
  _onDragStart() {
    this._isDragging = true;
    this._reveal();
  }
  _onDragEnd() {
    this._isDragging = false;
    this._hide();
  }
  _onMouseLeave(e) {
    this._mouseIsOver = false;
    this._hide();
  }
  _onMouseOver(e) {
    this._mouseIsOver = true;
    this._reveal();
  }
  _reveal() {
    this._verticalScrollbar.beginReveal();
    this._horizontalScrollbar.beginReveal();
    this._scheduleHide();
  }
  _hide() {
    if (!this._mouseIsOver && !this._isDragging) {
      this._verticalScrollbar.beginHide();
      this._horizontalScrollbar.beginHide();
    }
  }
  _scheduleHide() {
    if (!this._mouseIsOver && !this._isDragging) {
      this._hideTimeout.cancelAndSet(() => this._hide(), HIDE_TIMEOUT);
    }
  }
}
class ScrollableElement extends AbstractScrollableElement {
  constructor(element, options) {
    options = options || {};
    options.mouseWheelSmoothScroll = false;
    const scrollable = new Scrollable({
      forceIntegerValues: true,
      smoothScrollDuration: 0,
      scheduleAtNextAnimationFrame: (callback) => scheduleAtNextAnimationFrame(callback)
    });
    super(element, options, scrollable);
    this._register(scrollable);
  }
  setScrollPosition(update) {
    this._scrollable.setScrollPositionNow(update);
  }
}
class SmoothScrollableElement extends AbstractScrollableElement {
  constructor(element, options, scrollable) {
    super(element, options, scrollable);
  }
  setScrollPosition(update) {
    if (update.reuseAnimation) {
      this._scrollable.setScrollPositionSmooth(update, update.reuseAnimation);
    } else {
      this._scrollable.setScrollPositionNow(update);
    }
  }
  getScrollPosition() {
    return this._scrollable.getCurrentScrollPosition();
  }
}
class DomScrollableElement extends AbstractScrollableElement {
  constructor(element, options) {
    options = options || {};
    options.mouseWheelSmoothScroll = false;
    const scrollable = new Scrollable({
      forceIntegerValues: false,
      smoothScrollDuration: 0,
      scheduleAtNextAnimationFrame: (callback) => scheduleAtNextAnimationFrame(callback)
    });
    super(element, options, scrollable);
    this._register(scrollable);
    this._element = element;
    this.onScroll((e) => {
      if (e.scrollTopChanged) {
        this._element.scrollTop = e.scrollTop;
      }
      if (e.scrollLeftChanged) {
        this._element.scrollLeft = e.scrollLeft;
      }
    });
    this.scanDomNode();
  }
  setScrollPosition(update) {
    this._scrollable.setScrollPositionNow(update);
  }
  getScrollPosition() {
    return this._scrollable.getCurrentScrollPosition();
  }
  scanDomNode() {
    this.setScrollDimensions({
      width: this._element.clientWidth,
      scrollWidth: this._element.scrollWidth,
      height: this._element.clientHeight,
      scrollHeight: this._element.scrollHeight
    });
    this.setScrollPosition({
      scrollLeft: this._element.scrollLeft,
      scrollTop: this._element.scrollTop
    });
  }
}
function resolveOptions$1(opts) {
  const result2 = {
    lazyRender: typeof opts.lazyRender !== "undefined" ? opts.lazyRender : false,
    className: typeof opts.className !== "undefined" ? opts.className : "",
    useShadows: typeof opts.useShadows !== "undefined" ? opts.useShadows : true,
    handleMouseWheel: typeof opts.handleMouseWheel !== "undefined" ? opts.handleMouseWheel : true,
    flipAxes: typeof opts.flipAxes !== "undefined" ? opts.flipAxes : false,
    consumeMouseWheelIfScrollbarIsNeeded: typeof opts.consumeMouseWheelIfScrollbarIsNeeded !== "undefined" ? opts.consumeMouseWheelIfScrollbarIsNeeded : false,
    alwaysConsumeMouseWheel: typeof opts.alwaysConsumeMouseWheel !== "undefined" ? opts.alwaysConsumeMouseWheel : false,
    scrollYToX: typeof opts.scrollYToX !== "undefined" ? opts.scrollYToX : false,
    mouseWheelScrollSensitivity: typeof opts.mouseWheelScrollSensitivity !== "undefined" ? opts.mouseWheelScrollSensitivity : 1,
    fastScrollSensitivity: typeof opts.fastScrollSensitivity !== "undefined" ? opts.fastScrollSensitivity : 5,
    scrollPredominantAxis: typeof opts.scrollPredominantAxis !== "undefined" ? opts.scrollPredominantAxis : true,
    mouseWheelSmoothScroll: typeof opts.mouseWheelSmoothScroll !== "undefined" ? opts.mouseWheelSmoothScroll : true,
    arrowSize: typeof opts.arrowSize !== "undefined" ? opts.arrowSize : 11,
    listenOnDomNode: typeof opts.listenOnDomNode !== "undefined" ? opts.listenOnDomNode : null,
    horizontal: typeof opts.horizontal !== "undefined" ? opts.horizontal : 1,
    horizontalScrollbarSize: typeof opts.horizontalScrollbarSize !== "undefined" ? opts.horizontalScrollbarSize : 10,
    horizontalSliderSize: typeof opts.horizontalSliderSize !== "undefined" ? opts.horizontalSliderSize : 0,
    horizontalHasArrows: typeof opts.horizontalHasArrows !== "undefined" ? opts.horizontalHasArrows : false,
    vertical: typeof opts.vertical !== "undefined" ? opts.vertical : 1,
    verticalScrollbarSize: typeof opts.verticalScrollbarSize !== "undefined" ? opts.verticalScrollbarSize : 10,
    verticalHasArrows: typeof opts.verticalHasArrows !== "undefined" ? opts.verticalHasArrows : false,
    verticalSliderSize: typeof opts.verticalSliderSize !== "undefined" ? opts.verticalSliderSize : 0,
    scrollByPage: typeof opts.scrollByPage !== "undefined" ? opts.scrollByPage : false
  };
  result2.horizontalSliderSize = typeof opts.horizontalSliderSize !== "undefined" ? opts.horizontalSliderSize : result2.horizontalScrollbarSize;
  result2.verticalSliderSize = typeof opts.verticalSliderSize !== "undefined" ? opts.verticalSliderSize : result2.verticalScrollbarSize;
  if (isMacintosh) {
    result2.className += " mac";
  }
  return result2;
}
class MouseHandler extends ViewEventHandler {
  constructor(context, viewController, viewHelper) {
    super();
    this._mouseLeaveMonitor = null;
    this._context = context;
    this.viewController = viewController;
    this.viewHelper = viewHelper;
    this.mouseTargetFactory = new MouseTargetFactory(this._context, viewHelper);
    this._mouseDownOperation = this._register(new MouseDownOperation(this._context, this.viewController, this.viewHelper, this.mouseTargetFactory, (e, testEventTarget) => this._createMouseTarget(e, testEventTarget), (e) => this._getMouseColumn(e)));
    this.lastMouseLeaveTime = -1;
    this._height = this._context.configuration.options.get(
      142
      /* EditorOption.layoutInfo */
    ).height;
    const mouseEvents = new EditorMouseEventFactory(this.viewHelper.viewDomNode);
    this._register(mouseEvents.onContextMenu(this.viewHelper.viewDomNode, (e) => this._onContextMenu(e, true)));
    this._register(mouseEvents.onMouseMove(this.viewHelper.viewDomNode, (e) => {
      this._onMouseMove(e);
      if (!this._mouseLeaveMonitor) {
        this._mouseLeaveMonitor = addDisposableListener(document, "mousemove", (e2) => {
          if (!this.viewHelper.viewDomNode.contains(e2.target)) {
            this._onMouseLeave(new EditorMouseEvent(e2, false, this.viewHelper.viewDomNode));
          }
        });
      }
    }));
    this._register(mouseEvents.onMouseUp(this.viewHelper.viewDomNode, (e) => this._onMouseUp(e)));
    this._register(mouseEvents.onMouseLeave(this.viewHelper.viewDomNode, (e) => this._onMouseLeave(e)));
    let capturePointerId = 0;
    this._register(mouseEvents.onPointerDown(this.viewHelper.viewDomNode, (e, pointerId) => {
      capturePointerId = pointerId;
    }));
    this._register(addDisposableListener(this.viewHelper.viewDomNode, EventType$1.POINTER_UP, (e) => {
      this._mouseDownOperation.onPointerUp();
    }));
    this._register(mouseEvents.onMouseDown(this.viewHelper.viewDomNode, (e) => this._onMouseDown(e, capturePointerId)));
    this._setupMouseWheelZoomListener();
    this._context.addEventHandler(this);
  }
  _setupMouseWheelZoomListener() {
    const classifier = MouseWheelClassifier.INSTANCE;
    let prevMouseWheelTime = 0;
    let gestureStartZoomLevel = EditorZoom.getZoomLevel();
    let gestureHasZoomModifiers = false;
    let gestureAccumulatedDelta = 0;
    const onMouseWheel = (browserEvent) => {
      this.viewController.emitMouseWheel(browserEvent);
      if (!this._context.configuration.options.get(
        74
        /* EditorOption.mouseWheelZoom */
      )) {
        return;
      }
      const e = new StandardWheelEvent(browserEvent);
      classifier.acceptStandardWheelEvent(e);
      if (classifier.isPhysicalMouseWheel()) {
        if (hasMouseWheelZoomModifiers(browserEvent)) {
          const zoomLevel = EditorZoom.getZoomLevel();
          const delta = e.deltaY > 0 ? 1 : -1;
          EditorZoom.setZoomLevel(zoomLevel + delta);
          e.preventDefault();
          e.stopPropagation();
        }
      } else {
        if (Date.now() - prevMouseWheelTime > 50) {
          gestureStartZoomLevel = EditorZoom.getZoomLevel();
          gestureHasZoomModifiers = hasMouseWheelZoomModifiers(browserEvent);
          gestureAccumulatedDelta = 0;
        }
        prevMouseWheelTime = Date.now();
        gestureAccumulatedDelta += e.deltaY;
        if (gestureHasZoomModifiers) {
          EditorZoom.setZoomLevel(gestureStartZoomLevel + gestureAccumulatedDelta / 5);
          e.preventDefault();
          e.stopPropagation();
        }
      }
    };
    this._register(addDisposableListener(this.viewHelper.viewDomNode, EventType$1.MOUSE_WHEEL, onMouseWheel, { capture: true, passive: false }));
    function hasMouseWheelZoomModifiers(browserEvent) {
      return isMacintosh ? (browserEvent.metaKey || browserEvent.ctrlKey) && !browserEvent.shiftKey && !browserEvent.altKey : browserEvent.ctrlKey && !browserEvent.metaKey && !browserEvent.shiftKey && !browserEvent.altKey;
    }
  }
  dispose() {
    this._context.removeEventHandler(this);
    if (this._mouseLeaveMonitor) {
      this._mouseLeaveMonitor.dispose();
      this._mouseLeaveMonitor = null;
    }
    super.dispose();
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    if (e.hasChanged(
      142
      /* EditorOption.layoutInfo */
    )) {
      const height = this._context.configuration.options.get(
        142
        /* EditorOption.layoutInfo */
      ).height;
      if (this._height !== height) {
        this._height = height;
        this._mouseDownOperation.onHeightChanged();
      }
    }
    return false;
  }
  onCursorStateChanged(e) {
    this._mouseDownOperation.onCursorStateChanged(e);
    return false;
  }
  onFocusChanged(e) {
    return false;
  }
  // --- end event handlers
  getTargetAtClientPoint(clientX, clientY) {
    const clientPos = new ClientCoordinates(clientX, clientY);
    const pos = clientPos.toPageCoordinates();
    const editorPos = createEditorPagePosition(this.viewHelper.viewDomNode);
    if (pos.y < editorPos.y || pos.y > editorPos.y + editorPos.height || pos.x < editorPos.x || pos.x > editorPos.x + editorPos.width) {
      return null;
    }
    const relativePos = createCoordinatesRelativeToEditor(this.viewHelper.viewDomNode, editorPos, pos);
    return this.mouseTargetFactory.createMouseTarget(this.viewHelper.getLastRenderData(), editorPos, pos, relativePos, null);
  }
  _createMouseTarget(e, testEventTarget) {
    let target = e.target;
    if (!this.viewHelper.viewDomNode.contains(target)) {
      const shadowRoot = getShadowRoot(this.viewHelper.viewDomNode);
      if (shadowRoot) {
        target = shadowRoot.elementsFromPoint(e.posx, e.posy).find((el) => this.viewHelper.viewDomNode.contains(el));
      }
    }
    return this.mouseTargetFactory.createMouseTarget(this.viewHelper.getLastRenderData(), e.editorPos, e.pos, e.relativePos, testEventTarget ? target : null);
  }
  _getMouseColumn(e) {
    return this.mouseTargetFactory.getMouseColumn(e.relativePos);
  }
  _onContextMenu(e, testEventTarget) {
    this.viewController.emitContextMenu({
      event: e,
      target: this._createMouseTarget(e, testEventTarget)
    });
  }
  _onMouseMove(e) {
    const targetIsWidget = this.mouseTargetFactory.mouseTargetIsWidget(e);
    if (!targetIsWidget) {
      e.preventDefault();
    }
    if (this._mouseDownOperation.isActive()) {
      return;
    }
    const actualMouseMoveTime = e.timestamp;
    if (actualMouseMoveTime < this.lastMouseLeaveTime) {
      return;
    }
    this.viewController.emitMouseMove({
      event: e,
      target: this._createMouseTarget(e, true)
    });
  }
  _onMouseLeave(e) {
    if (this._mouseLeaveMonitor) {
      this._mouseLeaveMonitor.dispose();
      this._mouseLeaveMonitor = null;
    }
    this.lastMouseLeaveTime = (/* @__PURE__ */ new Date()).getTime();
    this.viewController.emitMouseLeave({
      event: e,
      target: null
    });
  }
  _onMouseUp(e) {
    this.viewController.emitMouseUp({
      event: e,
      target: this._createMouseTarget(e, true)
    });
  }
  _onMouseDown(e, pointerId) {
    const t = this._createMouseTarget(e, true);
    const targetIsContent = t.type === 6 || t.type === 7;
    const targetIsGutter = t.type === 2 || t.type === 3 || t.type === 4;
    const targetIsLineNumbers = t.type === 3;
    const selectOnLineNumbers = this._context.configuration.options.get(
      107
      /* EditorOption.selectOnLineNumbers */
    );
    const targetIsViewZone = t.type === 8 || t.type === 5;
    const targetIsWidget = t.type === 9;
    let shouldHandle = e.leftButton || e.middleButton;
    if (isMacintosh && e.leftButton && e.ctrlKey) {
      shouldHandle = false;
    }
    const focus = () => {
      e.preventDefault();
      this.viewHelper.focusTextArea();
    };
    if (shouldHandle && (targetIsContent || targetIsLineNumbers && selectOnLineNumbers)) {
      focus();
      this._mouseDownOperation.start(t.type, e, pointerId);
    } else if (targetIsGutter) {
      e.preventDefault();
    } else if (targetIsViewZone) {
      const viewZoneData = t.detail;
      if (shouldHandle && this.viewHelper.shouldSuppressMouseDownOnViewZone(viewZoneData.viewZoneId)) {
        focus();
        this._mouseDownOperation.start(t.type, e, pointerId);
        e.preventDefault();
      }
    } else if (targetIsWidget && this.viewHelper.shouldSuppressMouseDownOnWidget(t.detail)) {
      focus();
      e.preventDefault();
    }
    this.viewController.emitMouseDown({
      event: e,
      target: t
    });
  }
}
class MouseDownOperation extends Disposable {
  constructor(_context, _viewController, _viewHelper, _mouseTargetFactory, createMouseTarget, getMouseColumn) {
    super();
    this._context = _context;
    this._viewController = _viewController;
    this._viewHelper = _viewHelper;
    this._mouseTargetFactory = _mouseTargetFactory;
    this._createMouseTarget = createMouseTarget;
    this._getMouseColumn = getMouseColumn;
    this._mouseMoveMonitor = this._register(new GlobalEditorPointerMoveMonitor(this._viewHelper.viewDomNode));
    this._topBottomDragScrolling = this._register(new TopBottomDragScrolling(this._context, this._viewHelper, this._mouseTargetFactory, (position, inSelectionMode, revealType) => this._dispatchMouse(position, inSelectionMode, revealType)));
    this._mouseState = new MouseDownState();
    this._currentSelection = new Selection$1(1, 1, 1, 1);
    this._isActive = false;
    this._lastMouseEvent = null;
  }
  dispose() {
    super.dispose();
  }
  isActive() {
    return this._isActive;
  }
  _onMouseDownThenMove(e) {
    this._lastMouseEvent = e;
    this._mouseState.setModifiers(e);
    const position = this._findMousePosition(e, false);
    if (!position) {
      return;
    }
    if (this._mouseState.isDragAndDrop) {
      this._viewController.emitMouseDrag({
        event: e,
        target: position
      });
    } else {
      if (position.type === 13 && (position.outsidePosition === "above" || position.outsidePosition === "below")) {
        this._topBottomDragScrolling.start(position, e);
      } else {
        this._topBottomDragScrolling.stop();
        this._dispatchMouse(
          position,
          true,
          1
          /* NavigationCommandRevealType.Minimal */
        );
      }
    }
  }
  start(targetType, e, pointerId) {
    this._lastMouseEvent = e;
    this._mouseState.setStartedOnLineNumbers(
      targetType === 3
      /* MouseTargetType.GUTTER_LINE_NUMBERS */
    );
    this._mouseState.setStartButtons(e);
    this._mouseState.setModifiers(e);
    const position = this._findMousePosition(e, true);
    if (!position || !position.position) {
      return;
    }
    this._mouseState.trySetCount(e.detail, position.position);
    e.detail = this._mouseState.count;
    const options = this._context.configuration.options;
    if (!options.get(
      89
      /* EditorOption.readOnly */
    ) && options.get(
      34
      /* EditorOption.dragAndDrop */
    ) && !options.get(
      21
      /* EditorOption.columnSelection */
    ) && !this._mouseState.altKey && e.detail < 2 && !this._isActive && !this._currentSelection.isEmpty() && position.type === 6 && position.position && this._currentSelection.containsPosition(position.position)) {
      this._mouseState.isDragAndDrop = true;
      this._isActive = true;
      this._mouseMoveMonitor.startMonitoring(this._viewHelper.viewLinesDomNode, pointerId, e.buttons, (e2) => this._onMouseDownThenMove(e2), (browserEvent) => {
        const position2 = this._findMousePosition(this._lastMouseEvent, false);
        if (browserEvent && browserEvent instanceof KeyboardEvent) {
          this._viewController.emitMouseDropCanceled();
        } else {
          this._viewController.emitMouseDrop({
            event: this._lastMouseEvent,
            target: position2 ? this._createMouseTarget(this._lastMouseEvent, true) : null
            // Ignoring because position is unknown, e.g., Content View Zone
          });
        }
        this._stop();
      });
      return;
    }
    this._mouseState.isDragAndDrop = false;
    this._dispatchMouse(
      position,
      e.shiftKey,
      1
      /* NavigationCommandRevealType.Minimal */
    );
    if (!this._isActive) {
      this._isActive = true;
      this._mouseMoveMonitor.startMonitoring(this._viewHelper.viewLinesDomNode, pointerId, e.buttons, (e2) => this._onMouseDownThenMove(e2), () => this._stop());
    }
  }
  _stop() {
    this._isActive = false;
    this._topBottomDragScrolling.stop();
  }
  onHeightChanged() {
    this._mouseMoveMonitor.stopMonitoring();
  }
  onPointerUp() {
    this._mouseMoveMonitor.stopMonitoring();
  }
  onCursorStateChanged(e) {
    this._currentSelection = e.selections[0];
  }
  _getPositionOutsideEditor(e) {
    const editorContent = e.editorPos;
    const model = this._context.viewModel;
    const viewLayout = this._context.viewLayout;
    const mouseColumn = this._getMouseColumn(e);
    if (e.posy < editorContent.y) {
      const outsideDistance = editorContent.y - e.posy;
      const verticalOffset = Math.max(viewLayout.getCurrentScrollTop() - outsideDistance, 0);
      const viewZoneData = HitTestContext.getZoneAtCoord(this._context, verticalOffset);
      if (viewZoneData) {
        const newPosition = this._helpPositionJumpOverViewZone(viewZoneData);
        if (newPosition) {
          return MouseTarget.createOutsideEditor(mouseColumn, newPosition, "above", outsideDistance);
        }
      }
      const aboveLineNumber = viewLayout.getLineNumberAtVerticalOffset(verticalOffset);
      return MouseTarget.createOutsideEditor(mouseColumn, new Position$2(aboveLineNumber, 1), "above", outsideDistance);
    }
    if (e.posy > editorContent.y + editorContent.height) {
      const outsideDistance = e.posy - editorContent.y - editorContent.height;
      const verticalOffset = viewLayout.getCurrentScrollTop() + e.relativePos.y;
      const viewZoneData = HitTestContext.getZoneAtCoord(this._context, verticalOffset);
      if (viewZoneData) {
        const newPosition = this._helpPositionJumpOverViewZone(viewZoneData);
        if (newPosition) {
          return MouseTarget.createOutsideEditor(mouseColumn, newPosition, "below", outsideDistance);
        }
      }
      const belowLineNumber = viewLayout.getLineNumberAtVerticalOffset(verticalOffset);
      return MouseTarget.createOutsideEditor(mouseColumn, new Position$2(belowLineNumber, model.getLineMaxColumn(belowLineNumber)), "below", outsideDistance);
    }
    const possibleLineNumber = viewLayout.getLineNumberAtVerticalOffset(viewLayout.getCurrentScrollTop() + e.relativePos.y);
    if (e.posx < editorContent.x) {
      const outsideDistance = editorContent.x - e.posx;
      return MouseTarget.createOutsideEditor(mouseColumn, new Position$2(possibleLineNumber, 1), "left", outsideDistance);
    }
    if (e.posx > editorContent.x + editorContent.width) {
      const outsideDistance = e.posx - editorContent.x - editorContent.width;
      return MouseTarget.createOutsideEditor(mouseColumn, new Position$2(possibleLineNumber, model.getLineMaxColumn(possibleLineNumber)), "right", outsideDistance);
    }
    return null;
  }
  _findMousePosition(e, testEventTarget) {
    const positionOutsideEditor = this._getPositionOutsideEditor(e);
    if (positionOutsideEditor) {
      return positionOutsideEditor;
    }
    const t = this._createMouseTarget(e, testEventTarget);
    const hintedPosition = t.position;
    if (!hintedPosition) {
      return null;
    }
    if (t.type === 8 || t.type === 5) {
      const newPosition = this._helpPositionJumpOverViewZone(t.detail);
      if (newPosition) {
        return MouseTarget.createViewZone(t.type, t.element, t.mouseColumn, newPosition, t.detail);
      }
    }
    return t;
  }
  _helpPositionJumpOverViewZone(viewZoneData) {
    const selectionStart = new Position$2(this._currentSelection.selectionStartLineNumber, this._currentSelection.selectionStartColumn);
    const positionBefore = viewZoneData.positionBefore;
    const positionAfter = viewZoneData.positionAfter;
    if (positionBefore && positionAfter) {
      if (positionBefore.isBefore(selectionStart)) {
        return positionBefore;
      } else {
        return positionAfter;
      }
    }
    return null;
  }
  _dispatchMouse(position, inSelectionMode, revealType) {
    if (!position.position) {
      return;
    }
    this._viewController.dispatchMouse({
      position: position.position,
      mouseColumn: position.mouseColumn,
      startedOnLineNumbers: this._mouseState.startedOnLineNumbers,
      revealType,
      inSelectionMode,
      mouseDownCount: this._mouseState.count,
      altKey: this._mouseState.altKey,
      ctrlKey: this._mouseState.ctrlKey,
      metaKey: this._mouseState.metaKey,
      shiftKey: this._mouseState.shiftKey,
      leftButton: this._mouseState.leftButton,
      middleButton: this._mouseState.middleButton,
      onInjectedText: position.type === 6 && position.detail.injectedText !== null
    });
  }
}
class TopBottomDragScrolling extends Disposable {
  constructor(_context, _viewHelper, _mouseTargetFactory, _dispatchMouse) {
    super();
    this._context = _context;
    this._viewHelper = _viewHelper;
    this._mouseTargetFactory = _mouseTargetFactory;
    this._dispatchMouse = _dispatchMouse;
    this._operation = null;
  }
  dispose() {
    super.dispose();
    this.stop();
  }
  start(position, mouseEvent) {
    if (this._operation) {
      this._operation.setPosition(position, mouseEvent);
    } else {
      this._operation = new TopBottomDragScrollingOperation(this._context, this._viewHelper, this._mouseTargetFactory, this._dispatchMouse, position, mouseEvent);
    }
  }
  stop() {
    if (this._operation) {
      this._operation.dispose();
      this._operation = null;
    }
  }
}
class TopBottomDragScrollingOperation extends Disposable {
  constructor(_context, _viewHelper, _mouseTargetFactory, _dispatchMouse, position, mouseEvent) {
    super();
    this._context = _context;
    this._viewHelper = _viewHelper;
    this._mouseTargetFactory = _mouseTargetFactory;
    this._dispatchMouse = _dispatchMouse;
    this._position = position;
    this._mouseEvent = mouseEvent;
    this._lastTime = Date.now();
    this._animationFrameDisposable = scheduleAtNextAnimationFrame(() => this._execute());
  }
  dispose() {
    this._animationFrameDisposable.dispose();
  }
  setPosition(position, mouseEvent) {
    this._position = position;
    this._mouseEvent = mouseEvent;
  }
  /**
   * update internal state and return elapsed ms since last time
   */
  _tick() {
    const now = Date.now();
    const elapsed = now - this._lastTime;
    this._lastTime = now;
    return elapsed;
  }
  /**
   * get the number of lines per second to auto-scroll
   */
  _getScrollSpeed() {
    const lineHeight = this._context.configuration.options.get(
      65
      /* EditorOption.lineHeight */
    );
    const viewportInLines = this._context.configuration.options.get(
      142
      /* EditorOption.layoutInfo */
    ).height / lineHeight;
    const outsideDistanceInLines = this._position.outsideDistance / lineHeight;
    if (outsideDistanceInLines <= 1.5) {
      return Math.max(30, viewportInLines * (1 + outsideDistanceInLines));
    }
    if (outsideDistanceInLines <= 3) {
      return Math.max(60, viewportInLines * (2 + outsideDistanceInLines));
    }
    return Math.max(200, viewportInLines * (7 + outsideDistanceInLines));
  }
  _execute() {
    const lineHeight = this._context.configuration.options.get(
      65
      /* EditorOption.lineHeight */
    );
    const scrollSpeedInLines = this._getScrollSpeed();
    const elapsed = this._tick();
    const scrollInPixels = scrollSpeedInLines * (elapsed / 1e3) * lineHeight;
    const scrollValue = this._position.outsidePosition === "above" ? -scrollInPixels : scrollInPixels;
    this._context.viewModel.viewLayout.deltaScrollNow(0, scrollValue);
    this._viewHelper.renderNow();
    const viewportData = this._context.viewLayout.getLinesViewportData();
    const edgeLineNumber = this._position.outsidePosition === "above" ? viewportData.startLineNumber : viewportData.endLineNumber;
    let mouseTarget;
    {
      const editorPos = createEditorPagePosition(this._viewHelper.viewDomNode);
      const horizontalScrollbarHeight = this._context.configuration.options.get(
        142
        /* EditorOption.layoutInfo */
      ).horizontalScrollbarHeight;
      const pos = new PageCoordinates(this._mouseEvent.pos.x, editorPos.y + editorPos.height - horizontalScrollbarHeight - 0.1);
      const relativePos = createCoordinatesRelativeToEditor(this._viewHelper.viewDomNode, editorPos, pos);
      mouseTarget = this._mouseTargetFactory.createMouseTarget(this._viewHelper.getLastRenderData(), editorPos, pos, relativePos, null);
    }
    if (!mouseTarget.position || mouseTarget.position.lineNumber !== edgeLineNumber) {
      if (this._position.outsidePosition === "above") {
        mouseTarget = MouseTarget.createOutsideEditor(this._position.mouseColumn, new Position$2(edgeLineNumber, 1), "above", this._position.outsideDistance);
      } else {
        mouseTarget = MouseTarget.createOutsideEditor(this._position.mouseColumn, new Position$2(edgeLineNumber, this._context.viewModel.getLineMaxColumn(edgeLineNumber)), "below", this._position.outsideDistance);
      }
    }
    this._dispatchMouse(
      mouseTarget,
      true,
      2
      /* NavigationCommandRevealType.None */
    );
    this._animationFrameDisposable = scheduleAtNextAnimationFrame(() => this._execute());
  }
}
class MouseDownState {
  get altKey() {
    return this._altKey;
  }
  get ctrlKey() {
    return this._ctrlKey;
  }
  get metaKey() {
    return this._metaKey;
  }
  get shiftKey() {
    return this._shiftKey;
  }
  get leftButton() {
    return this._leftButton;
  }
  get middleButton() {
    return this._middleButton;
  }
  get startedOnLineNumbers() {
    return this._startedOnLineNumbers;
  }
  constructor() {
    this._altKey = false;
    this._ctrlKey = false;
    this._metaKey = false;
    this._shiftKey = false;
    this._leftButton = false;
    this._middleButton = false;
    this._startedOnLineNumbers = false;
    this._lastMouseDownPosition = null;
    this._lastMouseDownPositionEqualCount = 0;
    this._lastMouseDownCount = 0;
    this._lastSetMouseDownCountTime = 0;
    this.isDragAndDrop = false;
  }
  get count() {
    return this._lastMouseDownCount;
  }
  setModifiers(source) {
    this._altKey = source.altKey;
    this._ctrlKey = source.ctrlKey;
    this._metaKey = source.metaKey;
    this._shiftKey = source.shiftKey;
  }
  setStartButtons(source) {
    this._leftButton = source.leftButton;
    this._middleButton = source.middleButton;
  }
  setStartedOnLineNumbers(startedOnLineNumbers) {
    this._startedOnLineNumbers = startedOnLineNumbers;
  }
  trySetCount(setMouseDownCount, newMouseDownPosition) {
    const currentTime = (/* @__PURE__ */ new Date()).getTime();
    if (currentTime - this._lastSetMouseDownCountTime > MouseDownState.CLEAR_MOUSE_DOWN_COUNT_TIME) {
      setMouseDownCount = 1;
    }
    this._lastSetMouseDownCountTime = currentTime;
    if (setMouseDownCount > this._lastMouseDownCount + 1) {
      setMouseDownCount = this._lastMouseDownCount + 1;
    }
    if (this._lastMouseDownPosition && this._lastMouseDownPosition.equals(newMouseDownPosition)) {
      this._lastMouseDownPositionEqualCount++;
    } else {
      this._lastMouseDownPositionEqualCount = 1;
    }
    this._lastMouseDownPosition = newMouseDownPosition;
    this._lastMouseDownCount = Math.min(setMouseDownCount, this._lastMouseDownPositionEqualCount);
  }
}
MouseDownState.CLEAR_MOUSE_DOWN_COUNT_TIME = 400;
class DomEmitter {
  get event() {
    return this.emitter.event;
  }
  constructor(element, type, useCapture) {
    const fn = (e) => this.emitter.fire(e);
    this.emitter = new Emitter$1({
      onWillAddFirstListener: () => element.addEventListener(type, fn, useCapture),
      onDidRemoveLastListener: () => element.removeEventListener(type, fn, useCapture)
    });
  }
  dispose() {
    this.emitter.dispose();
  }
}
var inputLatency;
(function(inputLatency2) {
  const totalKeydownTime = { total: 0, min: Number.MAX_VALUE, max: 0 };
  const totalInputTime = Object.assign({}, totalKeydownTime);
  const totalRenderTime = Object.assign({}, totalKeydownTime);
  const totalInputLatencyTime = Object.assign({}, totalKeydownTime);
  let measurementsCount = 0;
  const state = {
    keydown: 0,
    input: 0,
    render: 0
  };
  function onKeyDown() {
    recordIfFinished();
    performance.mark("inputlatency/start");
    performance.mark("keydown/start");
    state.keydown = 1;
    queueMicrotask(markKeyDownEnd);
  }
  inputLatency2.onKeyDown = onKeyDown;
  function markKeyDownEnd() {
    if (state.keydown === 1) {
      performance.mark("keydown/end");
      state.keydown = 2;
    }
  }
  function onBeforeInput() {
    performance.mark("input/start");
    state.input = 1;
    scheduleRecordIfFinishedTask();
  }
  inputLatency2.onBeforeInput = onBeforeInput;
  function onInput() {
    if (state.input === 0) {
      onBeforeInput();
    }
    queueMicrotask(markInputEnd);
  }
  inputLatency2.onInput = onInput;
  function markInputEnd() {
    if (state.input === 1) {
      performance.mark("input/end");
      state.input = 2;
    }
  }
  function onKeyUp() {
    recordIfFinished();
  }
  inputLatency2.onKeyUp = onKeyUp;
  function onSelectionChange() {
    recordIfFinished();
  }
  inputLatency2.onSelectionChange = onSelectionChange;
  function onRenderStart() {
    if (state.keydown === 2 && state.input === 2 && state.render === 0) {
      performance.mark("render/start");
      state.render = 1;
      queueMicrotask(markRenderEnd);
      scheduleRecordIfFinishedTask();
    }
  }
  inputLatency2.onRenderStart = onRenderStart;
  function markRenderEnd() {
    if (state.render === 1) {
      performance.mark("render/end");
      state.render = 2;
    }
  }
  function scheduleRecordIfFinishedTask() {
    setTimeout(recordIfFinished);
  }
  function recordIfFinished() {
    if (state.keydown === 2 && state.input === 2 && state.render === 2) {
      performance.mark("inputlatency/end");
      performance.measure("keydown", "keydown/start", "keydown/end");
      performance.measure("input", "input/start", "input/end");
      performance.measure("render", "render/start", "render/end");
      performance.measure("inputlatency", "inputlatency/start", "inputlatency/end");
      addMeasure("keydown", totalKeydownTime);
      addMeasure("input", totalInputTime);
      addMeasure("render", totalRenderTime);
      addMeasure("inputlatency", totalInputLatencyTime);
      measurementsCount++;
      reset2();
    }
  }
  function addMeasure(entryName, cumulativeMeasurement) {
    const duration = performance.getEntriesByName(entryName)[0].duration;
    cumulativeMeasurement.total += duration;
    cumulativeMeasurement.min = Math.min(cumulativeMeasurement.min, duration);
    cumulativeMeasurement.max = Math.max(cumulativeMeasurement.max, duration);
  }
  function reset2() {
    performance.clearMarks("keydown/start");
    performance.clearMarks("keydown/end");
    performance.clearMarks("input/start");
    performance.clearMarks("input/end");
    performance.clearMarks("render/start");
    performance.clearMarks("render/end");
    performance.clearMarks("inputlatency/start");
    performance.clearMarks("inputlatency/end");
    performance.clearMeasures("keydown");
    performance.clearMeasures("input");
    performance.clearMeasures("render");
    performance.clearMeasures("inputlatency");
    state.keydown = 0;
    state.input = 0;
    state.render = 0;
  }
  function getAndClearMeasurements() {
    if (measurementsCount === 0) {
      return void 0;
    }
    const result2 = {
      keydown: cumulativeToFinalMeasurement(totalKeydownTime),
      input: cumulativeToFinalMeasurement(totalInputTime),
      render: cumulativeToFinalMeasurement(totalRenderTime),
      total: cumulativeToFinalMeasurement(totalInputLatencyTime),
      sampleCount: measurementsCount
    };
    clearCumulativeMeasurement(totalKeydownTime);
    clearCumulativeMeasurement(totalInputTime);
    clearCumulativeMeasurement(totalRenderTime);
    clearCumulativeMeasurement(totalInputLatencyTime);
    measurementsCount = 0;
    return result2;
  }
  inputLatency2.getAndClearMeasurements = getAndClearMeasurements;
  function cumulativeToFinalMeasurement(cumulative) {
    return {
      average: cumulative.total / measurementsCount,
      max: cumulative.max,
      min: cumulative.min
    };
  }
  function clearCumulativeMeasurement(cumulative) {
    cumulative.total = 0;
    cumulative.min = Number.MAX_VALUE;
    cumulative.max = 0;
  }
})(inputLatency || (inputLatency = {}));
class TextAreaState {
  constructor(value, selectionStart, selectionEnd, selection, newlineCountBeforeSelection) {
    this.value = value;
    this.selectionStart = selectionStart;
    this.selectionEnd = selectionEnd;
    this.selection = selection;
    this.newlineCountBeforeSelection = newlineCountBeforeSelection;
  }
  toString() {
    return `[ <${this.value}>, selectionStart: ${this.selectionStart}, selectionEnd: ${this.selectionEnd}]`;
  }
  static readFromTextArea(textArea, previousState) {
    const value = textArea.getValue();
    const selectionStart = textArea.getSelectionStart();
    const selectionEnd = textArea.getSelectionEnd();
    let newlineCountBeforeSelection = void 0;
    if (previousState) {
      const valueBeforeSelectionStart = value.substring(0, selectionStart);
      const previousValueBeforeSelectionStart = previousState.value.substring(0, previousState.selectionStart);
      if (valueBeforeSelectionStart === previousValueBeforeSelectionStart) {
        newlineCountBeforeSelection = previousState.newlineCountBeforeSelection;
      }
    }
    return new TextAreaState(value, selectionStart, selectionEnd, null, newlineCountBeforeSelection);
  }
  collapseSelection() {
    if (this.selectionStart === this.value.length) {
      return this;
    }
    return new TextAreaState(this.value, this.value.length, this.value.length, null, void 0);
  }
  writeToTextArea(reason, textArea, select) {
    textArea.setValue(reason, this.value);
    if (select) {
      textArea.setSelectionRange(reason, this.selectionStart, this.selectionEnd);
    }
  }
  deduceEditorPosition(offset) {
    var _a2, _b2, _c2, _d2, _e2, _f2, _g2, _h2;
    if (offset <= this.selectionStart) {
      const str3 = this.value.substring(offset, this.selectionStart);
      return this._finishDeduceEditorPosition((_b2 = (_a2 = this.selection) === null || _a2 === void 0 ? void 0 : _a2.getStartPosition()) !== null && _b2 !== void 0 ? _b2 : null, str3, -1);
    }
    if (offset >= this.selectionEnd) {
      const str3 = this.value.substring(this.selectionEnd, offset);
      return this._finishDeduceEditorPosition((_d2 = (_c2 = this.selection) === null || _c2 === void 0 ? void 0 : _c2.getEndPosition()) !== null && _d2 !== void 0 ? _d2 : null, str3, 1);
    }
    const str1 = this.value.substring(this.selectionStart, offset);
    if (str1.indexOf(String.fromCharCode(8230)) === -1) {
      return this._finishDeduceEditorPosition((_f2 = (_e2 = this.selection) === null || _e2 === void 0 ? void 0 : _e2.getStartPosition()) !== null && _f2 !== void 0 ? _f2 : null, str1, 1);
    }
    const str2 = this.value.substring(offset, this.selectionEnd);
    return this._finishDeduceEditorPosition((_h2 = (_g2 = this.selection) === null || _g2 === void 0 ? void 0 : _g2.getEndPosition()) !== null && _h2 !== void 0 ? _h2 : null, str2, -1);
  }
  _finishDeduceEditorPosition(anchor, deltaText, signum) {
    let lineFeedCnt = 0;
    let lastLineFeedIndex = -1;
    while ((lastLineFeedIndex = deltaText.indexOf("\n", lastLineFeedIndex + 1)) !== -1) {
      lineFeedCnt++;
    }
    return [anchor, signum * deltaText.length, lineFeedCnt];
  }
  static deduceInput(previousState, currentState, couldBeEmojiInput) {
    if (!previousState) {
      return {
        text: "",
        replacePrevCharCnt: 0,
        replaceNextCharCnt: 0,
        positionDelta: 0
      };
    }
    const prefixLength = Math.min(commonPrefixLength(previousState.value, currentState.value), previousState.selectionStart, currentState.selectionStart);
    const suffixLength = Math.min(commonSuffixLength(previousState.value, currentState.value), previousState.value.length - previousState.selectionEnd, currentState.value.length - currentState.selectionEnd);
    previousState.value.substring(prefixLength, previousState.value.length - suffixLength);
    const currentValue = currentState.value.substring(prefixLength, currentState.value.length - suffixLength);
    const previousSelectionStart = previousState.selectionStart - prefixLength;
    const previousSelectionEnd = previousState.selectionEnd - prefixLength;
    const currentSelectionStart = currentState.selectionStart - prefixLength;
    const currentSelectionEnd = currentState.selectionEnd - prefixLength;
    if (currentSelectionStart === currentSelectionEnd) {
      const replacePreviousCharacters2 = previousState.selectionStart - prefixLength;
      return {
        text: currentValue,
        replacePrevCharCnt: replacePreviousCharacters2,
        replaceNextCharCnt: 0,
        positionDelta: 0
      };
    }
    const replacePreviousCharacters = previousSelectionEnd - previousSelectionStart;
    return {
      text: currentValue,
      replacePrevCharCnt: replacePreviousCharacters,
      replaceNextCharCnt: 0,
      positionDelta: 0
    };
  }
  static deduceAndroidCompositionInput(previousState, currentState) {
    if (!previousState) {
      return {
        text: "",
        replacePrevCharCnt: 0,
        replaceNextCharCnt: 0,
        positionDelta: 0
      };
    }
    if (previousState.value === currentState.value) {
      return {
        text: "",
        replacePrevCharCnt: 0,
        replaceNextCharCnt: 0,
        positionDelta: currentState.selectionEnd - previousState.selectionEnd
      };
    }
    const prefixLength = Math.min(commonPrefixLength(previousState.value, currentState.value), previousState.selectionEnd);
    const suffixLength = Math.min(commonSuffixLength(previousState.value, currentState.value), previousState.value.length - previousState.selectionEnd);
    const previousValue = previousState.value.substring(prefixLength, previousState.value.length - suffixLength);
    const currentValue = currentState.value.substring(prefixLength, currentState.value.length - suffixLength);
    previousState.selectionStart - prefixLength;
    const previousSelectionEnd = previousState.selectionEnd - prefixLength;
    currentState.selectionStart - prefixLength;
    const currentSelectionEnd = currentState.selectionEnd - prefixLength;
    return {
      text: currentValue,
      replacePrevCharCnt: previousSelectionEnd,
      replaceNextCharCnt: previousValue.length - previousSelectionEnd,
      positionDelta: currentSelectionEnd - currentValue.length
    };
  }
}
TextAreaState.EMPTY = new TextAreaState("", 0, 0, null, void 0);
class PagedScreenReaderStrategy {
  static _getPageOfLine(lineNumber, linesPerPage) {
    return Math.floor((lineNumber - 1) / linesPerPage);
  }
  static _getRangeForPage(page, linesPerPage) {
    const offset = page * linesPerPage;
    const startLineNumber = offset + 1;
    const endLineNumber = offset + linesPerPage;
    return new Range$2(startLineNumber, 1, endLineNumber + 1, 1);
  }
  static fromEditorSelection(model, selection, linesPerPage, trimLongText) {
    const LIMIT_CHARS = 500;
    const selectionStartPage = PagedScreenReaderStrategy._getPageOfLine(selection.startLineNumber, linesPerPage);
    const selectionStartPageRange = PagedScreenReaderStrategy._getRangeForPage(selectionStartPage, linesPerPage);
    const selectionEndPage = PagedScreenReaderStrategy._getPageOfLine(selection.endLineNumber, linesPerPage);
    const selectionEndPageRange = PagedScreenReaderStrategy._getRangeForPage(selectionEndPage, linesPerPage);
    let pretextRange = selectionStartPageRange.intersectRanges(new Range$2(1, 1, selection.startLineNumber, selection.startColumn));
    if (trimLongText && model.getValueLengthInRange(
      pretextRange,
      1
      /* EndOfLinePreference.LF */
    ) > LIMIT_CHARS) {
      const pretextStart = model.modifyPosition(pretextRange.getEndPosition(), -LIMIT_CHARS);
      pretextRange = Range$2.fromPositions(pretextStart, pretextRange.getEndPosition());
    }
    const pretext = model.getValueInRange(
      pretextRange,
      1
      /* EndOfLinePreference.LF */
    );
    const lastLine = model.getLineCount();
    const lastLineMaxColumn = model.getLineMaxColumn(lastLine);
    let posttextRange = selectionEndPageRange.intersectRanges(new Range$2(selection.endLineNumber, selection.endColumn, lastLine, lastLineMaxColumn));
    if (trimLongText && model.getValueLengthInRange(
      posttextRange,
      1
      /* EndOfLinePreference.LF */
    ) > LIMIT_CHARS) {
      const posttextEnd = model.modifyPosition(posttextRange.getStartPosition(), LIMIT_CHARS);
      posttextRange = Range$2.fromPositions(posttextRange.getStartPosition(), posttextEnd);
    }
    const posttext = model.getValueInRange(
      posttextRange,
      1
      /* EndOfLinePreference.LF */
    );
    let text2;
    if (selectionStartPage === selectionEndPage || selectionStartPage + 1 === selectionEndPage) {
      text2 = model.getValueInRange(
        selection,
        1
        /* EndOfLinePreference.LF */
      );
    } else {
      const selectionRange1 = selectionStartPageRange.intersectRanges(selection);
      const selectionRange2 = selectionEndPageRange.intersectRanges(selection);
      text2 = model.getValueInRange(
        selectionRange1,
        1
        /* EndOfLinePreference.LF */
      ) + String.fromCharCode(8230) + model.getValueInRange(
        selectionRange2,
        1
        /* EndOfLinePreference.LF */
      );
    }
    if (trimLongText && text2.length > 2 * LIMIT_CHARS) {
      text2 = text2.substring(0, LIMIT_CHARS) + String.fromCharCode(8230) + text2.substring(text2.length - LIMIT_CHARS, text2.length);
    }
    return new TextAreaState(pretext + text2 + posttext, pretext.length, pretext.length + text2.length, selection, pretextRange.endLineNumber - pretextRange.startLineNumber);
  }
}
var TextAreaSyntethicEvents;
(function(TextAreaSyntethicEvents2) {
  TextAreaSyntethicEvents2.Tap = "-monaco-textarea-synthetic-tap";
})(TextAreaSyntethicEvents || (TextAreaSyntethicEvents = {}));
const CopyOptions = {
  forceCopyWithSyntaxHighlighting: false
};
class InMemoryClipboardMetadataManager {
  constructor() {
    this._lastState = null;
  }
  set(lastCopiedValue, data) {
    this._lastState = { lastCopiedValue, data };
  }
  get(pastedText) {
    if (this._lastState && this._lastState.lastCopiedValue === pastedText) {
      return this._lastState.data;
    }
    this._lastState = null;
    return null;
  }
}
InMemoryClipboardMetadataManager.INSTANCE = new InMemoryClipboardMetadataManager();
class CompositionContext {
  constructor() {
    this._lastTypeTextLength = 0;
  }
  handleCompositionUpdate(text2) {
    text2 = text2 || "";
    const typeInput = {
      text: text2,
      replacePrevCharCnt: this._lastTypeTextLength,
      replaceNextCharCnt: 0,
      positionDelta: 0
    };
    this._lastTypeTextLength = text2.length;
    return typeInput;
  }
}
class TextAreaInput extends Disposable {
  get textAreaState() {
    return this._textAreaState;
  }
  constructor(_host, _textArea, _OS, _browser) {
    super();
    this._host = _host;
    this._textArea = _textArea;
    this._OS = _OS;
    this._browser = _browser;
    this._onFocus = this._register(new Emitter$1());
    this.onFocus = this._onFocus.event;
    this._onBlur = this._register(new Emitter$1());
    this.onBlur = this._onBlur.event;
    this._onKeyDown = this._register(new Emitter$1());
    this.onKeyDown = this._onKeyDown.event;
    this._onKeyUp = this._register(new Emitter$1());
    this.onKeyUp = this._onKeyUp.event;
    this._onCut = this._register(new Emitter$1());
    this.onCut = this._onCut.event;
    this._onPaste = this._register(new Emitter$1());
    this.onPaste = this._onPaste.event;
    this._onType = this._register(new Emitter$1());
    this.onType = this._onType.event;
    this._onCompositionStart = this._register(new Emitter$1());
    this.onCompositionStart = this._onCompositionStart.event;
    this._onCompositionUpdate = this._register(new Emitter$1());
    this.onCompositionUpdate = this._onCompositionUpdate.event;
    this._onCompositionEnd = this._register(new Emitter$1());
    this.onCompositionEnd = this._onCompositionEnd.event;
    this._onSelectionChangeRequest = this._register(new Emitter$1());
    this.onSelectionChangeRequest = this._onSelectionChangeRequest.event;
    this._asyncTriggerCut = this._register(new RunOnceScheduler(() => this._onCut.fire(), 0));
    this._asyncFocusGainWriteScreenReaderContent = this._register(new RunOnceScheduler(() => this.writeScreenReaderContent("asyncFocusGain"), 0));
    this._textAreaState = TextAreaState.EMPTY;
    this._selectionChangeListener = null;
    this.writeScreenReaderContent("ctor");
    this._hasFocus = false;
    this._currentComposition = null;
    let lastKeyDown = null;
    this._register(this._textArea.onKeyDown((_e2) => {
      const e = new StandardKeyboardEvent(_e2);
      if (e.keyCode === 114 || this._currentComposition && e.keyCode === 1) {
        e.stopPropagation();
      }
      if (e.equals(
        9
        /* KeyCode.Escape */
      )) {
        e.preventDefault();
      }
      lastKeyDown = e;
      this._onKeyDown.fire(e);
    }));
    this._register(this._textArea.onKeyUp((_e2) => {
      const e = new StandardKeyboardEvent(_e2);
      this._onKeyUp.fire(e);
    }));
    this._register(this._textArea.onCompositionStart((e) => {
      const currentComposition = new CompositionContext();
      if (this._currentComposition) {
        this._currentComposition = currentComposition;
        return;
      }
      this._currentComposition = currentComposition;
      if (this._OS === 2 && lastKeyDown && lastKeyDown.equals(
        114
        /* KeyCode.KEY_IN_COMPOSITION */
      ) && this._textAreaState.selectionStart === this._textAreaState.selectionEnd && this._textAreaState.selectionStart > 0 && this._textAreaState.value.substr(this._textAreaState.selectionStart - 1, 1) === e.data && (lastKeyDown.code === "ArrowRight" || lastKeyDown.code === "ArrowLeft")) {
        currentComposition.handleCompositionUpdate("x");
        this._onCompositionStart.fire({ data: e.data });
        return;
      }
      if (this._browser.isAndroid) {
        this._onCompositionStart.fire({ data: e.data });
        return;
      }
      this._onCompositionStart.fire({ data: e.data });
    }));
    this._register(this._textArea.onCompositionUpdate((e) => {
      const currentComposition = this._currentComposition;
      if (!currentComposition) {
        return;
      }
      if (this._browser.isAndroid) {
        const newState = TextAreaState.readFromTextArea(this._textArea, this._textAreaState);
        const typeInput2 = TextAreaState.deduceAndroidCompositionInput(this._textAreaState, newState);
        this._textAreaState = newState;
        this._onType.fire(typeInput2);
        this._onCompositionUpdate.fire(e);
        return;
      }
      const typeInput = currentComposition.handleCompositionUpdate(e.data);
      this._textAreaState = TextAreaState.readFromTextArea(this._textArea, this._textAreaState);
      this._onType.fire(typeInput);
      this._onCompositionUpdate.fire(e);
    }));
    this._register(this._textArea.onCompositionEnd((e) => {
      const currentComposition = this._currentComposition;
      if (!currentComposition) {
        return;
      }
      this._currentComposition = null;
      if (this._browser.isAndroid) {
        const newState = TextAreaState.readFromTextArea(this._textArea, this._textAreaState);
        const typeInput2 = TextAreaState.deduceAndroidCompositionInput(this._textAreaState, newState);
        this._textAreaState = newState;
        this._onType.fire(typeInput2);
        this._onCompositionEnd.fire();
        return;
      }
      const typeInput = currentComposition.handleCompositionUpdate(e.data);
      this._textAreaState = TextAreaState.readFromTextArea(this._textArea, this._textAreaState);
      this._onType.fire(typeInput);
      this._onCompositionEnd.fire();
    }));
    this._register(this._textArea.onInput((e) => {
      this._textArea.setIgnoreSelectionChangeTime("received input event");
      if (this._currentComposition) {
        return;
      }
      const newState = TextAreaState.readFromTextArea(this._textArea, this._textAreaState);
      const typeInput = TextAreaState.deduceInput(
        this._textAreaState,
        newState,
        /*couldBeEmojiInput*/
        this._OS === 2
        /* OperatingSystem.Macintosh */
      );
      if (typeInput.replacePrevCharCnt === 0 && typeInput.text.length === 1) {
        if (isHighSurrogate(typeInput.text.charCodeAt(0)) || typeInput.text.charCodeAt(0) === 127) {
          return;
        }
      }
      this._textAreaState = newState;
      if (typeInput.text !== "" || typeInput.replacePrevCharCnt !== 0 || typeInput.replaceNextCharCnt !== 0 || typeInput.positionDelta !== 0) {
        this._onType.fire(typeInput);
      }
    }));
    this._register(this._textArea.onCut((e) => {
      this._textArea.setIgnoreSelectionChangeTime("received cut event");
      this._ensureClipboardGetsEditorSelection(e);
      this._asyncTriggerCut.schedule();
    }));
    this._register(this._textArea.onCopy((e) => {
      this._ensureClipboardGetsEditorSelection(e);
    }));
    this._register(this._textArea.onPaste((e) => {
      this._textArea.setIgnoreSelectionChangeTime("received paste event");
      e.preventDefault();
      if (!e.clipboardData) {
        return;
      }
      let [text2, metadata] = ClipboardEventUtils.getTextData(e.clipboardData);
      if (!text2) {
        return;
      }
      metadata = metadata || InMemoryClipboardMetadataManager.INSTANCE.get(text2);
      this._onPaste.fire({
        text: text2,
        metadata
      });
    }));
    this._register(this._textArea.onFocus(() => {
      const hadFocus = this._hasFocus;
      this._setHasFocus(true);
      if (this._browser.isSafari && !hadFocus && this._hasFocus) {
        this._asyncFocusGainWriteScreenReaderContent.schedule();
      }
    }));
    this._register(this._textArea.onBlur(() => {
      if (this._currentComposition) {
        this._currentComposition = null;
        this.writeScreenReaderContent("blurWithoutCompositionEnd");
        this._onCompositionEnd.fire();
      }
      this._setHasFocus(false);
    }));
    this._register(this._textArea.onSyntheticTap(() => {
      if (this._browser.isAndroid && this._currentComposition) {
        this._currentComposition = null;
        this.writeScreenReaderContent("tapWithoutCompositionEnd");
        this._onCompositionEnd.fire();
      }
    }));
  }
  _installSelectionChangeListener() {
    let previousSelectionChangeEventTime = 0;
    return addDisposableListener(document, "selectionchange", (e) => {
      inputLatency.onSelectionChange();
      if (!this._hasFocus) {
        return;
      }
      if (this._currentComposition) {
        return;
      }
      if (!this._browser.isChrome) {
        return;
      }
      const now = Date.now();
      const delta1 = now - previousSelectionChangeEventTime;
      previousSelectionChangeEventTime = now;
      if (delta1 < 5) {
        return;
      }
      const delta2 = now - this._textArea.getIgnoreSelectionChangeTime();
      this._textArea.resetSelectionChangeTime();
      if (delta2 < 100) {
        return;
      }
      if (!this._textAreaState.selection) {
        return;
      }
      const newValue = this._textArea.getValue();
      if (this._textAreaState.value !== newValue) {
        return;
      }
      const newSelectionStart = this._textArea.getSelectionStart();
      const newSelectionEnd = this._textArea.getSelectionEnd();
      if (this._textAreaState.selectionStart === newSelectionStart && this._textAreaState.selectionEnd === newSelectionEnd) {
        return;
      }
      const _newSelectionStartPosition = this._textAreaState.deduceEditorPosition(newSelectionStart);
      const newSelectionStartPosition = this._host.deduceModelPosition(_newSelectionStartPosition[0], _newSelectionStartPosition[1], _newSelectionStartPosition[2]);
      const _newSelectionEndPosition = this._textAreaState.deduceEditorPosition(newSelectionEnd);
      const newSelectionEndPosition = this._host.deduceModelPosition(_newSelectionEndPosition[0], _newSelectionEndPosition[1], _newSelectionEndPosition[2]);
      const newSelection = new Selection$1(newSelectionStartPosition.lineNumber, newSelectionStartPosition.column, newSelectionEndPosition.lineNumber, newSelectionEndPosition.column);
      this._onSelectionChangeRequest.fire(newSelection);
    });
  }
  dispose() {
    super.dispose();
    if (this._selectionChangeListener) {
      this._selectionChangeListener.dispose();
      this._selectionChangeListener = null;
    }
  }
  focusTextArea() {
    this._setHasFocus(true);
    this.refreshFocusState();
  }
  isFocused() {
    return this._hasFocus;
  }
  refreshFocusState() {
    this._setHasFocus(this._textArea.hasFocus());
  }
  _setHasFocus(newHasFocus) {
    if (this._hasFocus === newHasFocus) {
      return;
    }
    this._hasFocus = newHasFocus;
    if (this._selectionChangeListener) {
      this._selectionChangeListener.dispose();
      this._selectionChangeListener = null;
    }
    if (this._hasFocus) {
      this._selectionChangeListener = this._installSelectionChangeListener();
    }
    if (this._hasFocus) {
      this.writeScreenReaderContent("focusgain");
    }
    if (this._hasFocus) {
      this._onFocus.fire();
    } else {
      this._onBlur.fire();
    }
  }
  _setAndWriteTextAreaState(reason, textAreaState) {
    if (!this._hasFocus) {
      textAreaState = textAreaState.collapseSelection();
    }
    textAreaState.writeToTextArea(reason, this._textArea, this._hasFocus);
    this._textAreaState = textAreaState;
  }
  writeScreenReaderContent(reason) {
    if (this._currentComposition) {
      return;
    }
    this._setAndWriteTextAreaState(reason, this._host.getScreenReaderContent());
  }
  _ensureClipboardGetsEditorSelection(e) {
    const dataToCopy = this._host.getDataToCopy();
    const storedMetadata = {
      version: 1,
      isFromEmptySelection: dataToCopy.isFromEmptySelection,
      multicursorText: dataToCopy.multicursorText,
      mode: dataToCopy.mode
    };
    InMemoryClipboardMetadataManager.INSTANCE.set(
      // When writing "LINE\r\n" to the clipboard and then pasting,
      // Firefox pastes "LINE\n", so let's work around this quirk
      this._browser.isFirefox ? dataToCopy.text.replace(/\r\n/g, "\n") : dataToCopy.text,
      storedMetadata
    );
    e.preventDefault();
    if (e.clipboardData) {
      ClipboardEventUtils.setTextData(e.clipboardData, dataToCopy.text, dataToCopy.html, storedMetadata);
    }
  }
}
const ClipboardEventUtils = {
  getTextData(clipboardData) {
    const text2 = clipboardData.getData(Mimes.text);
    let metadata = null;
    const rawmetadata = clipboardData.getData("vscode-editor-data");
    if (typeof rawmetadata === "string") {
      try {
        metadata = JSON.parse(rawmetadata);
        if (metadata.version !== 1) {
          metadata = null;
        }
      } catch (err) {
      }
    }
    if (text2.length === 0 && metadata === null && clipboardData.files.length > 0) {
      const files = Array.prototype.slice.call(clipboardData.files, 0);
      return [files.map((file) => file.name).join("\n"), null];
    }
    return [text2, metadata];
  },
  setTextData(clipboardData, text2, html2, metadata) {
    clipboardData.setData(Mimes.text, text2);
    if (typeof html2 === "string") {
      clipboardData.setData("text/html", html2);
    }
    clipboardData.setData("vscode-editor-data", JSON.stringify(metadata));
  }
};
class TextAreaWrapper extends Disposable {
  constructor(_actual) {
    super();
    this._actual = _actual;
    this.onKeyDown = this._register(new DomEmitter(this._actual, "keydown")).event;
    this.onKeyUp = this._register(new DomEmitter(this._actual, "keyup")).event;
    this.onCompositionStart = this._register(new DomEmitter(this._actual, "compositionstart")).event;
    this.onCompositionUpdate = this._register(new DomEmitter(this._actual, "compositionupdate")).event;
    this.onCompositionEnd = this._register(new DomEmitter(this._actual, "compositionend")).event;
    this.onBeforeInput = this._register(new DomEmitter(this._actual, "beforeinput")).event;
    this.onInput = this._register(new DomEmitter(this._actual, "input")).event;
    this.onCut = this._register(new DomEmitter(this._actual, "cut")).event;
    this.onCopy = this._register(new DomEmitter(this._actual, "copy")).event;
    this.onPaste = this._register(new DomEmitter(this._actual, "paste")).event;
    this.onFocus = this._register(new DomEmitter(this._actual, "focus")).event;
    this.onBlur = this._register(new DomEmitter(this._actual, "blur")).event;
    this._onSyntheticTap = this._register(new Emitter$1());
    this.onSyntheticTap = this._onSyntheticTap.event;
    this._ignoreSelectionChangeTime = 0;
    this._register(this.onKeyDown(() => inputLatency.onKeyDown()));
    this._register(this.onBeforeInput(() => inputLatency.onBeforeInput()));
    this._register(this.onInput(() => inputLatency.onInput()));
    this._register(this.onKeyUp(() => inputLatency.onKeyUp()));
    this._register(addDisposableListener(this._actual, TextAreaSyntethicEvents.Tap, () => this._onSyntheticTap.fire()));
  }
  hasFocus() {
    const shadowRoot = getShadowRoot(this._actual);
    if (shadowRoot) {
      return shadowRoot.activeElement === this._actual;
    } else if (isInDOM(this._actual)) {
      return document.activeElement === this._actual;
    } else {
      return false;
    }
  }
  setIgnoreSelectionChangeTime(reason) {
    this._ignoreSelectionChangeTime = Date.now();
  }
  getIgnoreSelectionChangeTime() {
    return this._ignoreSelectionChangeTime;
  }
  resetSelectionChangeTime() {
    this._ignoreSelectionChangeTime = 0;
  }
  getValue() {
    return this._actual.value;
  }
  setValue(reason, value) {
    const textArea = this._actual;
    if (textArea.value === value) {
      return;
    }
    this.setIgnoreSelectionChangeTime("setValue");
    textArea.value = value;
  }
  getSelectionStart() {
    return this._actual.selectionDirection === "backward" ? this._actual.selectionEnd : this._actual.selectionStart;
  }
  getSelectionEnd() {
    return this._actual.selectionDirection === "backward" ? this._actual.selectionStart : this._actual.selectionEnd;
  }
  setSelectionRange(reason, selectionStart, selectionEnd) {
    const textArea = this._actual;
    let activeElement = null;
    const shadowRoot = getShadowRoot(textArea);
    if (shadowRoot) {
      activeElement = shadowRoot.activeElement;
    } else {
      activeElement = document.activeElement;
    }
    const currentIsFocused = activeElement === textArea;
    const currentSelectionStart = textArea.selectionStart;
    const currentSelectionEnd = textArea.selectionEnd;
    if (currentIsFocused && currentSelectionStart === selectionStart && currentSelectionEnd === selectionEnd) {
      if (isFirefox$1 && window.parent !== window) {
        textArea.focus();
      }
      return;
    }
    if (currentIsFocused) {
      this.setIgnoreSelectionChangeTime("setSelectionRange");
      textArea.setSelectionRange(selectionStart, selectionEnd);
      if (isFirefox$1 && window.parent !== window) {
        textArea.focus();
      }
      return;
    }
    try {
      const scrollState = saveParentsScrollTop(textArea);
      this.setIgnoreSelectionChangeTime("setSelectionRange");
      textArea.focus();
      textArea.setSelectionRange(selectionStart, selectionEnd);
      restoreParentsScrollTop(textArea, scrollState);
    } catch (e) {
    }
  }
}
class PointerEventHandler extends MouseHandler {
  constructor(context, viewController, viewHelper) {
    super(context, viewController, viewHelper);
    this._register(Gesture.addTarget(this.viewHelper.linesContentDomNode));
    this._register(addDisposableListener(this.viewHelper.linesContentDomNode, EventType.Tap, (e) => this.onTap(e)));
    this._register(addDisposableListener(this.viewHelper.linesContentDomNode, EventType.Change, (e) => this.onChange(e)));
    this._register(addDisposableListener(this.viewHelper.linesContentDomNode, EventType.Contextmenu, (e) => this._onContextMenu(new EditorMouseEvent(e, false, this.viewHelper.viewDomNode), false)));
    this._lastPointerType = "mouse";
    this._register(addDisposableListener(this.viewHelper.linesContentDomNode, "pointerdown", (e) => {
      const pointerType = e.pointerType;
      if (pointerType === "mouse") {
        this._lastPointerType = "mouse";
        return;
      } else if (pointerType === "touch") {
        this._lastPointerType = "touch";
      } else {
        this._lastPointerType = "pen";
      }
    }));
    const pointerEvents = new EditorPointerEventFactory(this.viewHelper.viewDomNode);
    this._register(pointerEvents.onPointerMove(this.viewHelper.viewDomNode, (e) => this._onMouseMove(e)));
    this._register(pointerEvents.onPointerUp(this.viewHelper.viewDomNode, (e) => this._onMouseUp(e)));
    this._register(pointerEvents.onPointerLeave(this.viewHelper.viewDomNode, (e) => this._onMouseLeave(e)));
    this._register(pointerEvents.onPointerDown(this.viewHelper.viewDomNode, (e, pointerId) => this._onMouseDown(e, pointerId)));
  }
  onTap(event) {
    if (!event.initialTarget || !this.viewHelper.linesContentDomNode.contains(event.initialTarget)) {
      return;
    }
    event.preventDefault();
    this.viewHelper.focusTextArea();
    const target = this._createMouseTarget(new EditorMouseEvent(event, false, this.viewHelper.viewDomNode), false);
    if (target.position) {
      this.viewController.dispatchMouse({
        position: target.position,
        mouseColumn: target.position.column,
        startedOnLineNumbers: false,
        revealType: 1,
        mouseDownCount: event.tapCount,
        inSelectionMode: false,
        altKey: false,
        ctrlKey: false,
        metaKey: false,
        shiftKey: false,
        leftButton: false,
        middleButton: false,
        onInjectedText: target.type === 6 && target.detail.injectedText !== null
      });
    }
  }
  onChange(e) {
    if (this._lastPointerType === "touch") {
      this._context.viewModel.viewLayout.deltaScrollNow(-e.translationX, -e.translationY);
    }
  }
  _onMouseDown(e, pointerId) {
    if (e.browserEvent.pointerType === "touch") {
      return;
    }
    super._onMouseDown(e, pointerId);
  }
}
class TouchHandler extends MouseHandler {
  constructor(context, viewController, viewHelper) {
    super(context, viewController, viewHelper);
    this._register(Gesture.addTarget(this.viewHelper.linesContentDomNode));
    this._register(addDisposableListener(this.viewHelper.linesContentDomNode, EventType.Tap, (e) => this.onTap(e)));
    this._register(addDisposableListener(this.viewHelper.linesContentDomNode, EventType.Change, (e) => this.onChange(e)));
    this._register(addDisposableListener(this.viewHelper.linesContentDomNode, EventType.Contextmenu, (e) => this._onContextMenu(new EditorMouseEvent(e, false, this.viewHelper.viewDomNode), false)));
  }
  onTap(event) {
    event.preventDefault();
    this.viewHelper.focusTextArea();
    const target = this._createMouseTarget(new EditorMouseEvent(event, false, this.viewHelper.viewDomNode), false);
    if (target.position) {
      const event2 = document.createEvent("CustomEvent");
      event2.initEvent(TextAreaSyntethicEvents.Tap, false, true);
      this.viewHelper.dispatchTextAreaEvent(event2);
      this.viewController.moveTo(
        target.position,
        1
        /* NavigationCommandRevealType.Minimal */
      );
    }
  }
  onChange(e) {
    this._context.viewModel.viewLayout.deltaScrollNow(-e.translationX, -e.translationY);
  }
}
class PointerHandler extends Disposable {
  constructor(context, viewController, viewHelper) {
    super();
    if (isIOS && BrowserFeatures.pointerEvents) {
      this.handler = this._register(new PointerEventHandler(context, viewController, viewHelper));
    } else if (window.TouchEvent) {
      this.handler = this._register(new TouchHandler(context, viewController, viewHelper));
    } else {
      this.handler = this._register(new MouseHandler(context, viewController, viewHelper));
    }
  }
  getTargetAtClientPoint(clientX, clientY) {
    return this.handler.getTargetAtClientPoint(clientX, clientY);
  }
}
const textAreaHandler = "";
const lineNumbers = "";
class DynamicViewOverlay extends ViewEventHandler {
}
const IThemeService = createDecorator("themeService");
function themeColorFromId(id3) {
  return { id: id3 };
}
function getThemeTypeSelector(type) {
  switch (type) {
    case ColorScheme.DARK:
      return "vs-dark";
    case ColorScheme.HIGH_CONTRAST_DARK:
      return "hc-black";
    case ColorScheme.HIGH_CONTRAST_LIGHT:
      return "hc-light";
    default:
      return "vs";
  }
}
const Extensions$3 = {
  ThemingContribution: "base.contributions.theming"
};
class ThemingRegistry {
  constructor() {
    this.themingParticipants = [];
    this.themingParticipants = [];
    this.onThemingParticipantAddedEmitter = new Emitter$1();
  }
  onColorThemeChange(participant) {
    this.themingParticipants.push(participant);
    this.onThemingParticipantAddedEmitter.fire(participant);
    return toDisposable(() => {
      const idx = this.themingParticipants.indexOf(participant);
      this.themingParticipants.splice(idx, 1);
    });
  }
  getThemingParticipants() {
    return this.themingParticipants;
  }
}
const themingRegistry$1 = new ThemingRegistry();
Registry.add(Extensions$3.ThemingContribution, themingRegistry$1);
function registerThemingParticipant(participant) {
  return themingRegistry$1.onColorThemeChange(participant);
}
class Themable extends Disposable {
  constructor(themeService) {
    super();
    this.themeService = themeService;
    this.theme = themeService.getColorTheme();
    this._register(this.themeService.onDidColorThemeChange((theme) => this.onThemeChange(theme)));
  }
  onThemeChange(theme) {
    this.theme = theme;
    this.updateStyles();
  }
  updateStyles() {
  }
}
const editorLineHighlight = registerColor("editor.lineHighlightBackground", { dark: null, light: null, hcDark: null, hcLight: null }, localize("lineHighlight", "Background color for the highlight of line at the cursor position."));
const editorLineHighlightBorder = registerColor("editor.lineHighlightBorder", { dark: "#282828", light: "#eeeeee", hcDark: "#f38518", hcLight: contrastBorder }, localize("lineHighlightBorderBox", "Background color for the border around the line at the cursor position."));
registerColor("editor.rangeHighlightBackground", { dark: "#ffffff0b", light: "#fdff0033", hcDark: null, hcLight: null }, localize("rangeHighlight", "Background color of highlighted ranges, like by quick open and find features. The color must not be opaque so as not to hide underlying decorations."), true);
registerColor("editor.rangeHighlightBorder", { dark: null, light: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize("rangeHighlightBorder", "Background color of the border around highlighted ranges."), true);
registerColor("editor.symbolHighlightBackground", { dark: editorFindMatchHighlight, light: editorFindMatchHighlight, hcDark: null, hcLight: null }, localize("symbolHighlight", "Background color of highlighted symbol, like for go to definition or go next/previous symbol. The color must not be opaque so as not to hide underlying decorations."), true);
registerColor("editor.symbolHighlightBorder", { dark: null, light: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize("symbolHighlightBorder", "Background color of the border around highlighted symbols."), true);
const editorCursorForeground = registerColor("editorCursor.foreground", { dark: "#AEAFAD", light: Color.black, hcDark: Color.white, hcLight: "#0F4A85" }, localize("caret", "Color of the editor cursor."));
const editorCursorBackground = registerColor("editorCursor.background", null, localize("editorCursorBackground", "The background color of the editor cursor. Allows customizing the color of a character overlapped by a block cursor."));
const editorWhitespaces = registerColor("editorWhitespace.foreground", { dark: "#e3e4e229", light: "#33333333", hcDark: "#e3e4e229", hcLight: "#CCCCCC" }, localize("editorWhitespaces", "Color of whitespace characters in the editor."));
const editorLineNumbers = registerColor("editorLineNumber.foreground", { dark: "#858585", light: "#237893", hcDark: Color.white, hcLight: "#292929" }, localize("editorLineNumbers", "Color of editor line numbers."));
const deprecatedEditorIndentGuides = registerColor("editorIndentGuide.background", { dark: editorWhitespaces, light: editorWhitespaces, hcDark: editorWhitespaces, hcLight: editorWhitespaces }, localize("editorIndentGuides", "Color of the editor indentation guides."), false, localize("deprecatedEditorIndentGuides", "'editorIndentGuide.background' is deprecated. Use 'editorIndentGuide.background1' instead."));
const deprecatedEditorActiveIndentGuides = registerColor("editorIndentGuide.activeBackground", { dark: editorWhitespaces, light: editorWhitespaces, hcDark: editorWhitespaces, hcLight: editorWhitespaces }, localize("editorActiveIndentGuide", "Color of the active editor indentation guides."), false, localize("deprecatedEditorActiveIndentGuide", "'editorIndentGuide.activeBackground' is deprecated. Use 'editorIndentGuide.activeBackground1' instead."));
const editorIndentGuide1 = registerColor("editorIndentGuide.background1", { dark: deprecatedEditorIndentGuides, light: deprecatedEditorIndentGuides, hcDark: deprecatedEditorIndentGuides, hcLight: deprecatedEditorIndentGuides }, localize("editorIndentGuides1", "Color of the editor indentation guides (1)."));
const editorIndentGuide2 = registerColor("editorIndentGuide.background2", { dark: "#00000000", light: "#00000000", hcDark: "#00000000", hcLight: "#00000000" }, localize("editorIndentGuides2", "Color of the editor indentation guides (2)."));
const editorIndentGuide3 = registerColor("editorIndentGuide.background3", { dark: "#00000000", light: "#00000000", hcDark: "#00000000", hcLight: "#00000000" }, localize("editorIndentGuides3", "Color of the editor indentation guides (3)."));
const editorIndentGuide4 = registerColor("editorIndentGuide.background4", { dark: "#00000000", light: "#00000000", hcDark: "#00000000", hcLight: "#00000000" }, localize("editorIndentGuides4", "Color of the editor indentation guides (4)."));
const editorIndentGuide5 = registerColor("editorIndentGuide.background5", { dark: "#00000000", light: "#00000000", hcDark: "#00000000", hcLight: "#00000000" }, localize("editorIndentGuides5", "Color of the editor indentation guides (5)."));
const editorIndentGuide6 = registerColor("editorIndentGuide.background6", { dark: "#00000000", light: "#00000000", hcDark: "#00000000", hcLight: "#00000000" }, localize("editorIndentGuides6", "Color of the editor indentation guides (6)."));
const editorActiveIndentGuide1 = registerColor("editorIndentGuide.activeBackground1", { dark: deprecatedEditorActiveIndentGuides, light: deprecatedEditorActiveIndentGuides, hcDark: deprecatedEditorActiveIndentGuides, hcLight: deprecatedEditorActiveIndentGuides }, localize("editorActiveIndentGuide1", "Color of the active editor indentation guides (1)."));
const editorActiveIndentGuide2 = registerColor("editorIndentGuide.activeBackground2", { dark: "#00000000", light: "#00000000", hcDark: "#00000000", hcLight: "#00000000" }, localize("editorActiveIndentGuide2", "Color of the active editor indentation guides (2)."));
const editorActiveIndentGuide3 = registerColor("editorIndentGuide.activeBackground3", { dark: "#00000000", light: "#00000000", hcDark: "#00000000", hcLight: "#00000000" }, localize("editorActiveIndentGuide3", "Color of the active editor indentation guides (3)."));
const editorActiveIndentGuide4 = registerColor("editorIndentGuide.activeBackground4", { dark: "#00000000", light: "#00000000", hcDark: "#00000000", hcLight: "#00000000" }, localize("editorActiveIndentGuide4", "Color of the active editor indentation guides (4)."));
const editorActiveIndentGuide5 = registerColor("editorIndentGuide.activeBackground5", { dark: "#00000000", light: "#00000000", hcDark: "#00000000", hcLight: "#00000000" }, localize("editorActiveIndentGuide5", "Color of the active editor indentation guides (5)."));
const editorActiveIndentGuide6 = registerColor("editorIndentGuide.activeBackground6", { dark: "#00000000", light: "#00000000", hcDark: "#00000000", hcLight: "#00000000" }, localize("editorActiveIndentGuide6", "Color of the active editor indentation guides (6)."));
const deprecatedEditorActiveLineNumber = registerColor("editorActiveLineNumber.foreground", { dark: "#c6c6c6", light: "#0B216F", hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize("editorActiveLineNumber", "Color of editor active line number"), false, localize("deprecatedEditorActiveLineNumber", "Id is deprecated. Use 'editorLineNumber.activeForeground' instead."));
registerColor("editorLineNumber.activeForeground", { dark: deprecatedEditorActiveLineNumber, light: deprecatedEditorActiveLineNumber, hcDark: deprecatedEditorActiveLineNumber, hcLight: deprecatedEditorActiveLineNumber }, localize("editorActiveLineNumber", "Color of editor active line number"));
const editorDimmedLineNumber = registerColor("editorLineNumber.dimmedForeground", { dark: null, light: null, hcDark: null, hcLight: null }, localize("editorDimmedLineNumber", "Color of the final editor line when editor.renderFinalNewline is set to dimmed."));
registerColor("editorRuler.foreground", { dark: "#5A5A5A", light: Color.lightgrey, hcDark: Color.white, hcLight: "#292929" }, localize("editorRuler", "Color of the editor rulers."));
registerColor("editorCodeLens.foreground", { dark: "#999999", light: "#919191", hcDark: "#999999", hcLight: "#292929" }, localize("editorCodeLensForeground", "Foreground color of editor CodeLens"));
registerColor("editorBracketMatch.background", { dark: "#0064001a", light: "#0064001a", hcDark: "#0064001a", hcLight: "#0000" }, localize("editorBracketMatchBackground", "Background color behind matching brackets"));
registerColor("editorBracketMatch.border", { dark: "#888", light: "#B9B9B9", hcDark: contrastBorder, hcLight: contrastBorder }, localize("editorBracketMatchBorder", "Color for matching brackets boxes"));
const editorOverviewRulerBorder = registerColor("editorOverviewRuler.border", { dark: "#7f7f7f4d", light: "#7f7f7f4d", hcDark: "#7f7f7f4d", hcLight: "#666666" }, localize("editorOverviewRulerBorder", "Color of the overview ruler border."));
const editorOverviewRulerBackground = registerColor("editorOverviewRuler.background", null, localize("editorOverviewRulerBackground", "Background color of the editor overview ruler."));
registerColor("editorGutter.background", { dark: editorBackground, light: editorBackground, hcDark: editorBackground, hcLight: editorBackground }, localize("editorGutter", "Background color of the editor gutter. The gutter contains the glyph margins and the line numbers."));
registerColor("editorUnnecessaryCode.border", { dark: null, light: null, hcDark: Color.fromHex("#fff").transparent(0.8), hcLight: contrastBorder }, localize("unnecessaryCodeBorder", "Border color of unnecessary (unused) source code in the editor."));
const editorUnnecessaryCodeOpacity = registerColor("editorUnnecessaryCode.opacity", { dark: Color.fromHex("#000a"), light: Color.fromHex("#0007"), hcDark: null, hcLight: null }, localize("unnecessaryCodeOpacity", `Opacity of unnecessary (unused) source code in the editor. For example, "#000000c0" will render the code with 75% opacity. For high contrast themes, use the  'editorUnnecessaryCode.border' theme color to underline unnecessary code instead of fading it out.`));
registerColor("editorGhostText.border", { dark: null, light: null, hcDark: Color.fromHex("#fff").transparent(0.8), hcLight: Color.fromHex("#292929").transparent(0.8) }, localize("editorGhostTextBorder", "Border color of ghost text in the editor."));
registerColor("editorGhostText.foreground", { dark: Color.fromHex("#ffffff56"), light: Color.fromHex("#0007"), hcDark: null, hcLight: null }, localize("editorGhostTextForeground", "Foreground color of the ghost text in the editor."));
registerColor("editorGhostText.background", { dark: null, light: null, hcDark: null, hcLight: null }, localize("editorGhostTextBackground", "Background color of the ghost text in the editor."));
const rulerRangeDefault = new Color(new RGBA(0, 122, 204, 0.6));
const overviewRulerRangeHighlight = registerColor("editorOverviewRuler.rangeHighlightForeground", { dark: rulerRangeDefault, light: rulerRangeDefault, hcDark: rulerRangeDefault, hcLight: rulerRangeDefault }, localize("overviewRulerRangeHighlight", "Overview ruler marker color for range highlights. The color must not be opaque so as not to hide underlying decorations."), true);
const overviewRulerError = registerColor("editorOverviewRuler.errorForeground", { dark: new Color(new RGBA(255, 18, 18, 0.7)), light: new Color(new RGBA(255, 18, 18, 0.7)), hcDark: new Color(new RGBA(255, 50, 50, 1)), hcLight: "#B5200D" }, localize("overviewRuleError", "Overview ruler marker color for errors."));
const overviewRulerWarning = registerColor("editorOverviewRuler.warningForeground", { dark: editorWarningForeground, light: editorWarningForeground, hcDark: editorWarningBorder, hcLight: editorWarningBorder }, localize("overviewRuleWarning", "Overview ruler marker color for warnings."));
const overviewRulerInfo = registerColor("editorOverviewRuler.infoForeground", { dark: editorInfoForeground, light: editorInfoForeground, hcDark: editorInfoBorder, hcLight: editorInfoBorder }, localize("overviewRuleInfo", "Overview ruler marker color for infos."));
const editorBracketHighlightingForeground1 = registerColor("editorBracketHighlight.foreground1", { dark: "#FFD700", light: "#0431FAFF", hcDark: "#FFD700", hcLight: "#0431FAFF" }, localize("editorBracketHighlightForeground1", "Foreground color of brackets (1). Requires enabling bracket pair colorization."));
const editorBracketHighlightingForeground2 = registerColor("editorBracketHighlight.foreground2", { dark: "#DA70D6", light: "#319331FF", hcDark: "#DA70D6", hcLight: "#319331FF" }, localize("editorBracketHighlightForeground2", "Foreground color of brackets (2). Requires enabling bracket pair colorization."));
const editorBracketHighlightingForeground3 = registerColor("editorBracketHighlight.foreground3", { dark: "#179FFF", light: "#7B3814FF", hcDark: "#87CEFA", hcLight: "#7B3814FF" }, localize("editorBracketHighlightForeground3", "Foreground color of brackets (3). Requires enabling bracket pair colorization."));
const editorBracketHighlightingForeground4 = registerColor("editorBracketHighlight.foreground4", { dark: "#00000000", light: "#00000000", hcDark: "#00000000", hcLight: "#00000000" }, localize("editorBracketHighlightForeground4", "Foreground color of brackets (4). Requires enabling bracket pair colorization."));
const editorBracketHighlightingForeground5 = registerColor("editorBracketHighlight.foreground5", { dark: "#00000000", light: "#00000000", hcDark: "#00000000", hcLight: "#00000000" }, localize("editorBracketHighlightForeground5", "Foreground color of brackets (5). Requires enabling bracket pair colorization."));
const editorBracketHighlightingForeground6 = registerColor("editorBracketHighlight.foreground6", { dark: "#00000000", light: "#00000000", hcDark: "#00000000", hcLight: "#00000000" }, localize("editorBracketHighlightForeground6", "Foreground color of brackets (6). Requires enabling bracket pair colorization."));
const editorBracketHighlightingUnexpectedBracketForeground = registerColor("editorBracketHighlight.unexpectedBracket.foreground", { dark: new Color(new RGBA(255, 18, 18, 0.8)), light: new Color(new RGBA(255, 18, 18, 0.8)), hcDark: new Color(new RGBA(255, 50, 50, 1)), hcLight: "" }, localize("editorBracketHighlightUnexpectedBracketForeground", "Foreground color of unexpected brackets."));
const editorBracketPairGuideBackground1 = registerColor("editorBracketPairGuide.background1", { dark: "#00000000", light: "#00000000", hcDark: "#00000000", hcLight: "#00000000" }, localize("editorBracketPairGuide.background1", "Background color of inactive bracket pair guides (1). Requires enabling bracket pair guides."));
const editorBracketPairGuideBackground2 = registerColor("editorBracketPairGuide.background2", { dark: "#00000000", light: "#00000000", hcDark: "#00000000", hcLight: "#00000000" }, localize("editorBracketPairGuide.background2", "Background color of inactive bracket pair guides (2). Requires enabling bracket pair guides."));
const editorBracketPairGuideBackground3 = registerColor("editorBracketPairGuide.background3", { dark: "#00000000", light: "#00000000", hcDark: "#00000000", hcLight: "#00000000" }, localize("editorBracketPairGuide.background3", "Background color of inactive bracket pair guides (3). Requires enabling bracket pair guides."));
const editorBracketPairGuideBackground4 = registerColor("editorBracketPairGuide.background4", { dark: "#00000000", light: "#00000000", hcDark: "#00000000", hcLight: "#00000000" }, localize("editorBracketPairGuide.background4", "Background color of inactive bracket pair guides (4). Requires enabling bracket pair guides."));
const editorBracketPairGuideBackground5 = registerColor("editorBracketPairGuide.background5", { dark: "#00000000", light: "#00000000", hcDark: "#00000000", hcLight: "#00000000" }, localize("editorBracketPairGuide.background5", "Background color of inactive bracket pair guides (5). Requires enabling bracket pair guides."));
const editorBracketPairGuideBackground6 = registerColor("editorBracketPairGuide.background6", { dark: "#00000000", light: "#00000000", hcDark: "#00000000", hcLight: "#00000000" }, localize("editorBracketPairGuide.background6", "Background color of inactive bracket pair guides (6). Requires enabling bracket pair guides."));
const editorBracketPairGuideActiveBackground1 = registerColor("editorBracketPairGuide.activeBackground1", { dark: "#00000000", light: "#00000000", hcDark: "#00000000", hcLight: "#00000000" }, localize("editorBracketPairGuide.activeBackground1", "Background color of active bracket pair guides (1). Requires enabling bracket pair guides."));
const editorBracketPairGuideActiveBackground2 = registerColor("editorBracketPairGuide.activeBackground2", { dark: "#00000000", light: "#00000000", hcDark: "#00000000", hcLight: "#00000000" }, localize("editorBracketPairGuide.activeBackground2", "Background color of active bracket pair guides (2). Requires enabling bracket pair guides."));
const editorBracketPairGuideActiveBackground3 = registerColor("editorBracketPairGuide.activeBackground3", { dark: "#00000000", light: "#00000000", hcDark: "#00000000", hcLight: "#00000000" }, localize("editorBracketPairGuide.activeBackground3", "Background color of active bracket pair guides (3). Requires enabling bracket pair guides."));
const editorBracketPairGuideActiveBackground4 = registerColor("editorBracketPairGuide.activeBackground4", { dark: "#00000000", light: "#00000000", hcDark: "#00000000", hcLight: "#00000000" }, localize("editorBracketPairGuide.activeBackground4", "Background color of active bracket pair guides (4). Requires enabling bracket pair guides."));
const editorBracketPairGuideActiveBackground5 = registerColor("editorBracketPairGuide.activeBackground5", { dark: "#00000000", light: "#00000000", hcDark: "#00000000", hcLight: "#00000000" }, localize("editorBracketPairGuide.activeBackground5", "Background color of active bracket pair guides (5). Requires enabling bracket pair guides."));
const editorBracketPairGuideActiveBackground6 = registerColor("editorBracketPairGuide.activeBackground6", { dark: "#00000000", light: "#00000000", hcDark: "#00000000", hcLight: "#00000000" }, localize("editorBracketPairGuide.activeBackground6", "Background color of active bracket pair guides (6). Requires enabling bracket pair guides."));
registerColor("editorUnicodeHighlight.border", { dark: "#BD9B03", light: "#CEA33D", hcDark: "#ff0000", hcLight: "#CEA33D" }, localize("editorUnicodeHighlight.border", "Border color used to highlight unicode characters."));
registerColor("editorUnicodeHighlight.background", { dark: "#bd9b0326", light: "#cea33d14", hcDark: "#00000000", hcLight: "#cea33d14" }, localize("editorUnicodeHighlight.background", "Background color used to highlight unicode characters."));
registerThemingParticipant((theme, collector) => {
  const background = theme.getColor(editorBackground);
  const lineHighlight = theme.getColor(editorLineHighlight);
  const imeBackground = lineHighlight && !lineHighlight.isTransparent() ? lineHighlight : background;
  if (imeBackground) {
    collector.addRule(`.monaco-editor .inputarea.ime-input { background-color: ${imeBackground}; }`);
  }
});
class LineNumbersOverlay extends DynamicViewOverlay {
  constructor(context) {
    super();
    this._context = context;
    this._readConfig();
    this._lastCursorModelPosition = new Position$2(1, 1);
    this._renderResult = null;
    this._activeLineNumber = 1;
    this._context.addEventHandler(this);
  }
  _readConfig() {
    const options = this._context.configuration.options;
    this._lineHeight = options.get(
      65
      /* EditorOption.lineHeight */
    );
    const lineNumbers2 = options.get(
      66
      /* EditorOption.lineNumbers */
    );
    this._renderLineNumbers = lineNumbers2.renderType;
    this._renderCustomLineNumbers = lineNumbers2.renderFn;
    this._renderFinalNewline = options.get(
      93
      /* EditorOption.renderFinalNewline */
    );
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    this._lineNumbersLeft = layoutInfo.lineNumbersLeft;
    this._lineNumbersWidth = layoutInfo.lineNumbersWidth;
  }
  dispose() {
    this._context.removeEventHandler(this);
    this._renderResult = null;
    super.dispose();
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    this._readConfig();
    return true;
  }
  onCursorStateChanged(e) {
    const primaryViewPosition = e.selections[0].getPosition();
    this._lastCursorModelPosition = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(primaryViewPosition);
    let shouldRender = false;
    if (this._activeLineNumber !== primaryViewPosition.lineNumber) {
      this._activeLineNumber = primaryViewPosition.lineNumber;
      shouldRender = true;
    }
    if (this._renderLineNumbers === 2 || this._renderLineNumbers === 3) {
      shouldRender = true;
    }
    return shouldRender;
  }
  onFlushed(e) {
    return true;
  }
  onLinesChanged(e) {
    return true;
  }
  onLinesDeleted(e) {
    return true;
  }
  onLinesInserted(e) {
    return true;
  }
  onScrollChanged(e) {
    return e.scrollTopChanged;
  }
  onZonesChanged(e) {
    return true;
  }
  // --- end event handlers
  _getLineRenderLineNumber(viewLineNumber) {
    const modelPosition = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new Position$2(viewLineNumber, 1));
    if (modelPosition.column !== 1) {
      return "";
    }
    const modelLineNumber = modelPosition.lineNumber;
    if (this._renderCustomLineNumbers) {
      return this._renderCustomLineNumbers(modelLineNumber);
    }
    if (this._renderLineNumbers === 2) {
      const diff = Math.abs(this._lastCursorModelPosition.lineNumber - modelLineNumber);
      if (diff === 0) {
        return '<span class="relative-current-line-number">' + modelLineNumber + "</span>";
      }
      return String(diff);
    }
    if (this._renderLineNumbers === 3) {
      if (this._lastCursorModelPosition.lineNumber === modelLineNumber) {
        return String(modelLineNumber);
      }
      if (modelLineNumber % 10 === 0) {
        return String(modelLineNumber);
      }
      return "";
    }
    return String(modelLineNumber);
  }
  prepareRender(ctx) {
    if (this._renderLineNumbers === 0) {
      this._renderResult = null;
      return;
    }
    const lineHeightClassName = isLinux ? this._lineHeight % 2 === 0 ? " lh-even" : " lh-odd" : "";
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    const lineCount = this._context.viewModel.getLineCount();
    const output = [];
    for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
      const lineIndex = lineNumber - visibleStartLineNumber;
      const renderLineNumber = this._getLineRenderLineNumber(lineNumber);
      if (!renderLineNumber) {
        output[lineIndex] = "";
        continue;
      }
      let extraClassName = "";
      if (lineNumber === lineCount && this._context.viewModel.getLineLength(lineNumber) === 0) {
        if (this._renderFinalNewline === "off") {
          output[lineIndex] = "";
          continue;
        }
        if (this._renderFinalNewline === "dimmed") {
          extraClassName = " dimmed-line-number";
        }
      }
      if (lineNumber === this._activeLineNumber) {
        extraClassName = " active-line-number";
      }
      output[lineIndex] = `<div class="${LineNumbersOverlay.CLASS_NAME}${lineHeightClassName}${extraClassName}" style="left:${this._lineNumbersLeft}px;width:${this._lineNumbersWidth}px;">${renderLineNumber}</div>`;
    }
    this._renderResult = output;
  }
  render(startLineNumber, lineNumber) {
    if (!this._renderResult) {
      return "";
    }
    const lineIndex = lineNumber - startLineNumber;
    if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
      return "";
    }
    return this._renderResult[lineIndex];
  }
}
LineNumbersOverlay.CLASS_NAME = "line-numbers";
registerThemingParticipant((theme, collector) => {
  const editorLineNumbersColor = theme.getColor(editorLineNumbers);
  const editorDimmedLineNumberColor = theme.getColor(editorDimmedLineNumber);
  if (editorDimmedLineNumberColor) {
    collector.addRule(`.monaco-editor .line-numbers.dimmed-line-number { color: ${editorDimmedLineNumberColor}; }`);
  } else if (editorLineNumbersColor) {
    collector.addRule(`.monaco-editor .line-numbers.dimmed-line-number { color: ${editorLineNumbersColor.transparent(0.4)}; }`);
  }
});
const margin = "";
class Margin extends ViewPart {
  constructor(context) {
    super(context);
    const options = this._context.configuration.options;
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    this._canUseLayerHinting = !options.get(
      31
      /* EditorOption.disableLayerHinting */
    );
    this._contentLeft = layoutInfo.contentLeft;
    this._glyphMarginLeft = layoutInfo.glyphMarginLeft;
    this._glyphMarginWidth = layoutInfo.glyphMarginWidth;
    this._domNode = createFastDomNode(document.createElement("div"));
    this._domNode.setClassName(Margin.OUTER_CLASS_NAME);
    this._domNode.setPosition("absolute");
    this._domNode.setAttribute("role", "presentation");
    this._domNode.setAttribute("aria-hidden", "true");
    this._glyphMarginBackgroundDomNode = createFastDomNode(document.createElement("div"));
    this._glyphMarginBackgroundDomNode.setClassName(Margin.CLASS_NAME);
    this._domNode.appendChild(this._glyphMarginBackgroundDomNode);
  }
  dispose() {
    super.dispose();
  }
  getDomNode() {
    return this._domNode;
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    const options = this._context.configuration.options;
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    this._canUseLayerHinting = !options.get(
      31
      /* EditorOption.disableLayerHinting */
    );
    this._contentLeft = layoutInfo.contentLeft;
    this._glyphMarginLeft = layoutInfo.glyphMarginLeft;
    this._glyphMarginWidth = layoutInfo.glyphMarginWidth;
    return true;
  }
  onScrollChanged(e) {
    return super.onScrollChanged(e) || e.scrollTopChanged;
  }
  // --- end event handlers
  prepareRender(ctx) {
  }
  render(ctx) {
    this._domNode.setLayerHinting(this._canUseLayerHinting);
    this._domNode.setContain("strict");
    const adjustedScrollTop = ctx.scrollTop - ctx.bigNumbersDelta;
    this._domNode.setTop(-adjustedScrollTop);
    const height = Math.min(ctx.scrollHeight, 1e6);
    this._domNode.setHeight(height);
    this._domNode.setWidth(this._contentLeft);
    this._glyphMarginBackgroundDomNode.setLeft(this._glyphMarginLeft);
    this._glyphMarginBackgroundDomNode.setWidth(this._glyphMarginWidth);
    this._glyphMarginBackgroundDomNode.setHeight(height);
  }
}
Margin.CLASS_NAME = "glyph-margin";
Margin.OUTER_CLASS_NAME = "margin";
const mouseCursor = "";
const MOUSE_CURSOR_TEXT_CSS_CLASS_NAME = `monaco-mouse-cursor-text`;
var __awaiter$1y = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
let TokenizationRegistry$1 = class TokenizationRegistry {
  constructor() {
    this._tokenizationSupports = /* @__PURE__ */ new Map();
    this._factories = /* @__PURE__ */ new Map();
    this._onDidChange = new Emitter$1();
    this.onDidChange = this._onDidChange.event;
    this._colorMap = null;
  }
  handleChange(languageIds) {
    this._onDidChange.fire({
      changedLanguages: languageIds,
      changedColorMap: false
    });
  }
  register(languageId, support) {
    this._tokenizationSupports.set(languageId, support);
    this.handleChange([languageId]);
    return toDisposable(() => {
      if (this._tokenizationSupports.get(languageId) !== support) {
        return;
      }
      this._tokenizationSupports.delete(languageId);
      this.handleChange([languageId]);
    });
  }
  get(languageId) {
    return this._tokenizationSupports.get(languageId) || null;
  }
  registerFactory(languageId, factory) {
    var _a2;
    (_a2 = this._factories.get(languageId)) === null || _a2 === void 0 ? void 0 : _a2.dispose();
    const myData = new TokenizationSupportFactoryData(this, languageId, factory);
    this._factories.set(languageId, myData);
    return toDisposable(() => {
      const v = this._factories.get(languageId);
      if (!v || v !== myData) {
        return;
      }
      this._factories.delete(languageId);
      v.dispose();
    });
  }
  getOrCreate(languageId) {
    return __awaiter$1y(this, void 0, void 0, function* () {
      const tokenizationSupport = this.get(languageId);
      if (tokenizationSupport) {
        return tokenizationSupport;
      }
      const factory = this._factories.get(languageId);
      if (!factory || factory.isResolved) {
        return null;
      }
      yield factory.resolve();
      return this.get(languageId);
    });
  }
  isResolved(languageId) {
    const tokenizationSupport = this.get(languageId);
    if (tokenizationSupport) {
      return true;
    }
    const factory = this._factories.get(languageId);
    if (!factory || factory.isResolved) {
      return true;
    }
    return false;
  }
  setColorMap(colorMap) {
    this._colorMap = colorMap;
    this._onDidChange.fire({
      changedLanguages: Array.from(this._tokenizationSupports.keys()),
      changedColorMap: true
    });
  }
  getColorMap() {
    return this._colorMap;
  }
  getDefaultBackground() {
    if (this._colorMap && this._colorMap.length > 2) {
      return this._colorMap[
        2
        /* ColorId.DefaultBackground */
      ];
    }
    return null;
  }
};
class TokenizationSupportFactoryData extends Disposable {
  get isResolved() {
    return this._isResolved;
  }
  constructor(_registry2, _languageId, _factory) {
    super();
    this._registry = _registry2;
    this._languageId = _languageId;
    this._factory = _factory;
    this._isDisposed = false;
    this._resolvePromise = null;
    this._isResolved = false;
  }
  dispose() {
    this._isDisposed = true;
    super.dispose();
  }
  resolve() {
    return __awaiter$1y(this, void 0, void 0, function* () {
      if (!this._resolvePromise) {
        this._resolvePromise = this._create();
      }
      return this._resolvePromise;
    });
  }
  _create() {
    return __awaiter$1y(this, void 0, void 0, function* () {
      const value = yield this._factory.tokenizationSupport;
      this._isResolved = true;
      if (value && !this._isDisposed) {
        this._register(this._registry.register(this._languageId, value));
      }
    });
  }
}
let Token$3 = class Token {
  constructor(offset, type, language2) {
    this.offset = offset;
    this.type = type;
    this.language = language2;
    this._tokenBrand = void 0;
  }
  toString() {
    return "(" + this.offset + ", " + this.type + ")";
  }
};
class TokenizationResult {
  constructor(tokens, endState) {
    this.tokens = tokens;
    this.endState = endState;
    this._tokenizationResultBrand = void 0;
  }
}
class EncodedTokenizationResult {
  constructor(tokens, endState) {
    this.tokens = tokens;
    this.endState = endState;
    this._encodedTokenizationResultBrand = void 0;
  }
}
var CompletionItemKinds;
(function(CompletionItemKinds2) {
  const byKind = /* @__PURE__ */ new Map();
  byKind.set(0, Codicon.symbolMethod);
  byKind.set(1, Codicon.symbolFunction);
  byKind.set(2, Codicon.symbolConstructor);
  byKind.set(3, Codicon.symbolField);
  byKind.set(4, Codicon.symbolVariable);
  byKind.set(5, Codicon.symbolClass);
  byKind.set(6, Codicon.symbolStruct);
  byKind.set(7, Codicon.symbolInterface);
  byKind.set(8, Codicon.symbolModule);
  byKind.set(9, Codicon.symbolProperty);
  byKind.set(10, Codicon.symbolEvent);
  byKind.set(11, Codicon.symbolOperator);
  byKind.set(12, Codicon.symbolUnit);
  byKind.set(13, Codicon.symbolValue);
  byKind.set(15, Codicon.symbolEnum);
  byKind.set(14, Codicon.symbolConstant);
  byKind.set(15, Codicon.symbolEnum);
  byKind.set(16, Codicon.symbolEnumMember);
  byKind.set(17, Codicon.symbolKeyword);
  byKind.set(27, Codicon.symbolSnippet);
  byKind.set(18, Codicon.symbolText);
  byKind.set(19, Codicon.symbolColor);
  byKind.set(20, Codicon.symbolFile);
  byKind.set(21, Codicon.symbolReference);
  byKind.set(22, Codicon.symbolCustomColor);
  byKind.set(23, Codicon.symbolFolder);
  byKind.set(24, Codicon.symbolTypeParameter);
  byKind.set(25, Codicon.account);
  byKind.set(26, Codicon.issues);
  function toIcon(kind) {
    let codicon2 = byKind.get(kind);
    if (!codicon2) {
      console.info("No codicon found for CompletionItemKind " + kind);
      codicon2 = Codicon.symbolProperty;
    }
    return codicon2;
  }
  CompletionItemKinds2.toIcon = toIcon;
  const data = /* @__PURE__ */ new Map();
  data.set(
    "method",
    0
    /* CompletionItemKind.Method */
  );
  data.set(
    "function",
    1
    /* CompletionItemKind.Function */
  );
  data.set(
    "constructor",
    2
    /* CompletionItemKind.Constructor */
  );
  data.set(
    "field",
    3
    /* CompletionItemKind.Field */
  );
  data.set(
    "variable",
    4
    /* CompletionItemKind.Variable */
  );
  data.set(
    "class",
    5
    /* CompletionItemKind.Class */
  );
  data.set(
    "struct",
    6
    /* CompletionItemKind.Struct */
  );
  data.set(
    "interface",
    7
    /* CompletionItemKind.Interface */
  );
  data.set(
    "module",
    8
    /* CompletionItemKind.Module */
  );
  data.set(
    "property",
    9
    /* CompletionItemKind.Property */
  );
  data.set(
    "event",
    10
    /* CompletionItemKind.Event */
  );
  data.set(
    "operator",
    11
    /* CompletionItemKind.Operator */
  );
  data.set(
    "unit",
    12
    /* CompletionItemKind.Unit */
  );
  data.set(
    "value",
    13
    /* CompletionItemKind.Value */
  );
  data.set(
    "constant",
    14
    /* CompletionItemKind.Constant */
  );
  data.set(
    "enum",
    15
    /* CompletionItemKind.Enum */
  );
  data.set(
    "enum-member",
    16
    /* CompletionItemKind.EnumMember */
  );
  data.set(
    "enumMember",
    16
    /* CompletionItemKind.EnumMember */
  );
  data.set(
    "keyword",
    17
    /* CompletionItemKind.Keyword */
  );
  data.set(
    "snippet",
    27
    /* CompletionItemKind.Snippet */
  );
  data.set(
    "text",
    18
    /* CompletionItemKind.Text */
  );
  data.set(
    "color",
    19
    /* CompletionItemKind.Color */
  );
  data.set(
    "file",
    20
    /* CompletionItemKind.File */
  );
  data.set(
    "reference",
    21
    /* CompletionItemKind.Reference */
  );
  data.set(
    "customcolor",
    22
    /* CompletionItemKind.Customcolor */
  );
  data.set(
    "folder",
    23
    /* CompletionItemKind.Folder */
  );
  data.set(
    "type-parameter",
    24
    /* CompletionItemKind.TypeParameter */
  );
  data.set(
    "typeParameter",
    24
    /* CompletionItemKind.TypeParameter */
  );
  data.set(
    "account",
    25
    /* CompletionItemKind.User */
  );
  data.set(
    "issue",
    26
    /* CompletionItemKind.Issue */
  );
  function fromString2(value, strict) {
    let res = data.get(value);
    if (typeof res === "undefined" && !strict) {
      res = 9;
    }
    return res;
  }
  CompletionItemKinds2.fromString = fromString2;
})(CompletionItemKinds || (CompletionItemKinds = {}));
var InlineCompletionTriggerKind$1;
(function(InlineCompletionTriggerKind2) {
  InlineCompletionTriggerKind2[InlineCompletionTriggerKind2["Automatic"] = 0] = "Automatic";
  InlineCompletionTriggerKind2[InlineCompletionTriggerKind2["Explicit"] = 1] = "Explicit";
})(InlineCompletionTriggerKind$1 || (InlineCompletionTriggerKind$1 = {}));
class SelectedSuggestionInfo {
  constructor(range2, text2, completionKind, isSnippetText) {
    this.range = range2;
    this.text = text2;
    this.completionKind = completionKind;
    this.isSnippetText = isSnippetText;
  }
  equals(other) {
    return Range$2.lift(this.range).equalsRange(other.range) && this.text === other.text && this.completionKind === other.completionKind && this.isSnippetText === other.isSnippetText;
  }
}
var SignatureHelpTriggerKind$1;
(function(SignatureHelpTriggerKind2) {
  SignatureHelpTriggerKind2[SignatureHelpTriggerKind2["Invoke"] = 1] = "Invoke";
  SignatureHelpTriggerKind2[SignatureHelpTriggerKind2["TriggerCharacter"] = 2] = "TriggerCharacter";
  SignatureHelpTriggerKind2[SignatureHelpTriggerKind2["ContentChange"] = 3] = "ContentChange";
})(SignatureHelpTriggerKind$1 || (SignatureHelpTriggerKind$1 = {}));
var DocumentHighlightKind$1;
(function(DocumentHighlightKind2) {
  DocumentHighlightKind2[DocumentHighlightKind2["Text"] = 0] = "Text";
  DocumentHighlightKind2[DocumentHighlightKind2["Read"] = 1] = "Read";
  DocumentHighlightKind2[DocumentHighlightKind2["Write"] = 2] = "Write";
})(DocumentHighlightKind$1 || (DocumentHighlightKind$1 = {}));
function isLocationLink(thing) {
  return thing && URI.isUri(thing.uri) && Range$2.isIRange(thing.range) && (Range$2.isIRange(thing.originSelectionRange) || Range$2.isIRange(thing.targetSelectionRange));
}
const symbolKindNames = {
  [
    17
    /* SymbolKind.Array */
  ]: localize("Array", "array"),
  [
    16
    /* SymbolKind.Boolean */
  ]: localize("Boolean", "boolean"),
  [
    4
    /* SymbolKind.Class */
  ]: localize("Class", "class"),
  [
    13
    /* SymbolKind.Constant */
  ]: localize("Constant", "constant"),
  [
    8
    /* SymbolKind.Constructor */
  ]: localize("Constructor", "constructor"),
  [
    9
    /* SymbolKind.Enum */
  ]: localize("Enum", "enumeration"),
  [
    21
    /* SymbolKind.EnumMember */
  ]: localize("EnumMember", "enumeration member"),
  [
    23
    /* SymbolKind.Event */
  ]: localize("Event", "event"),
  [
    7
    /* SymbolKind.Field */
  ]: localize("Field", "field"),
  [
    0
    /* SymbolKind.File */
  ]: localize("File", "file"),
  [
    11
    /* SymbolKind.Function */
  ]: localize("Function", "function"),
  [
    10
    /* SymbolKind.Interface */
  ]: localize("Interface", "interface"),
  [
    19
    /* SymbolKind.Key */
  ]: localize("Key", "key"),
  [
    5
    /* SymbolKind.Method */
  ]: localize("Method", "method"),
  [
    1
    /* SymbolKind.Module */
  ]: localize("Module", "module"),
  [
    2
    /* SymbolKind.Namespace */
  ]: localize("Namespace", "namespace"),
  [
    20
    /* SymbolKind.Null */
  ]: localize("Null", "null"),
  [
    15
    /* SymbolKind.Number */
  ]: localize("Number", "number"),
  [
    18
    /* SymbolKind.Object */
  ]: localize("Object", "object"),
  [
    24
    /* SymbolKind.Operator */
  ]: localize("Operator", "operator"),
  [
    3
    /* SymbolKind.Package */
  ]: localize("Package", "package"),
  [
    6
    /* SymbolKind.Property */
  ]: localize("Property", "property"),
  [
    14
    /* SymbolKind.String */
  ]: localize("String", "string"),
  [
    22
    /* SymbolKind.Struct */
  ]: localize("Struct", "struct"),
  [
    25
    /* SymbolKind.TypeParameter */
  ]: localize("TypeParameter", "type parameter"),
  [
    12
    /* SymbolKind.Variable */
  ]: localize("Variable", "variable")
};
function getAriaLabelForSymbol(symbolName, kind) {
  return localize("symbolAriaLabel", "{0} ({1})", symbolName, symbolKindNames[kind]);
}
var SymbolKinds;
(function(SymbolKinds2) {
  const byKind = /* @__PURE__ */ new Map();
  byKind.set(0, Codicon.symbolFile);
  byKind.set(1, Codicon.symbolModule);
  byKind.set(2, Codicon.symbolNamespace);
  byKind.set(3, Codicon.symbolPackage);
  byKind.set(4, Codicon.symbolClass);
  byKind.set(5, Codicon.symbolMethod);
  byKind.set(6, Codicon.symbolProperty);
  byKind.set(7, Codicon.symbolField);
  byKind.set(8, Codicon.symbolConstructor);
  byKind.set(9, Codicon.symbolEnum);
  byKind.set(10, Codicon.symbolInterface);
  byKind.set(11, Codicon.symbolFunction);
  byKind.set(12, Codicon.symbolVariable);
  byKind.set(13, Codicon.symbolConstant);
  byKind.set(14, Codicon.symbolString);
  byKind.set(15, Codicon.symbolNumber);
  byKind.set(16, Codicon.symbolBoolean);
  byKind.set(17, Codicon.symbolArray);
  byKind.set(18, Codicon.symbolObject);
  byKind.set(19, Codicon.symbolKey);
  byKind.set(20, Codicon.symbolNull);
  byKind.set(21, Codicon.symbolEnumMember);
  byKind.set(22, Codicon.symbolStruct);
  byKind.set(23, Codicon.symbolEvent);
  byKind.set(24, Codicon.symbolOperator);
  byKind.set(25, Codicon.symbolTypeParameter);
  function toIcon(kind) {
    let icon = byKind.get(kind);
    if (!icon) {
      console.info("No codicon found for SymbolKind " + kind);
      icon = Codicon.symbolProperty;
    }
    return icon;
  }
  SymbolKinds2.toIcon = toIcon;
})(SymbolKinds || (SymbolKinds = {}));
class FoldingRangeKind {
  /**
   * Returns a {@link FoldingRangeKind} for the given value.
   *
   * @param value of the kind.
   */
  static fromValue(value) {
    switch (value) {
      case "comment":
        return FoldingRangeKind.Comment;
      case "imports":
        return FoldingRangeKind.Imports;
      case "region":
        return FoldingRangeKind.Region;
    }
    return new FoldingRangeKind(value);
  }
  /**
   * Creates a new {@link FoldingRangeKind}.
   *
   * @param value of the kind.
   */
  constructor(value) {
    this.value = value;
  }
}
FoldingRangeKind.Comment = new FoldingRangeKind("comment");
FoldingRangeKind.Imports = new FoldingRangeKind("imports");
FoldingRangeKind.Region = new FoldingRangeKind("region");
var Command2;
(function(Command3) {
  function is(obj) {
    if (!obj || typeof obj !== "object") {
      return false;
    }
    return typeof obj.id === "string" && typeof obj.title === "string";
  }
  Command3.is = is;
})(Command2 || (Command2 = {}));
var InlayHintKind$1;
(function(InlayHintKind2) {
  InlayHintKind2[InlayHintKind2["Type"] = 1] = "Type";
  InlayHintKind2[InlayHintKind2["Parameter"] = 2] = "Parameter";
})(InlayHintKind$1 || (InlayHintKind$1 = {}));
class LazyTokenizationSupport {
  constructor(createSupport) {
    this.createSupport = createSupport;
    this._tokenizationSupport = null;
  }
  dispose() {
    if (this._tokenizationSupport) {
      this._tokenizationSupport.then((support) => {
        if (support) {
          support.dispose();
        }
      });
    }
  }
  get tokenizationSupport() {
    if (!this._tokenizationSupport) {
      this._tokenizationSupport = this.createSupport();
    }
    return this._tokenizationSupport;
  }
}
const TokenizationRegistry2 = new TokenizationRegistry$1();
class IMEImpl {
  constructor() {
    this._onDidChange = new Emitter$1();
    this.onDidChange = this._onDidChange.event;
    this._enabled = true;
  }
  get enabled() {
    return this._enabled;
  }
  /**
   * Enable IME
   */
  enable() {
    this._enabled = true;
    this._onDidChange.fire();
  }
  /**
   * Disable IME
   */
  disable() {
    this._enabled = false;
    this._onDidChange.fire();
  }
}
const IME = new IMEImpl();
const IKeybindingService = createDecorator("keybindingService");
var __decorate$25 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1$ = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
class VisibleTextAreaData {
  constructor(_context, modelLineNumber, distanceToModelLineStart, widthOfHiddenLineTextBefore, distanceToModelLineEnd) {
    this._context = _context;
    this.modelLineNumber = modelLineNumber;
    this.distanceToModelLineStart = distanceToModelLineStart;
    this.widthOfHiddenLineTextBefore = widthOfHiddenLineTextBefore;
    this.distanceToModelLineEnd = distanceToModelLineEnd;
    this._visibleTextAreaBrand = void 0;
    this.startPosition = null;
    this.endPosition = null;
    this.visibleTextareaStart = null;
    this.visibleTextareaEnd = null;
    this._previousPresentation = null;
  }
  prepareRender(visibleRangeProvider) {
    const startModelPosition = new Position$2(this.modelLineNumber, this.distanceToModelLineStart + 1);
    const endModelPosition = new Position$2(this.modelLineNumber, this._context.viewModel.model.getLineMaxColumn(this.modelLineNumber) - this.distanceToModelLineEnd);
    this.startPosition = this._context.viewModel.coordinatesConverter.convertModelPositionToViewPosition(startModelPosition);
    this.endPosition = this._context.viewModel.coordinatesConverter.convertModelPositionToViewPosition(endModelPosition);
    if (this.startPosition.lineNumber === this.endPosition.lineNumber) {
      this.visibleTextareaStart = visibleRangeProvider.visibleRangeForPosition(this.startPosition);
      this.visibleTextareaEnd = visibleRangeProvider.visibleRangeForPosition(this.endPosition);
    } else {
      this.visibleTextareaStart = null;
      this.visibleTextareaEnd = null;
    }
  }
  definePresentation(tokenPresentation) {
    if (!this._previousPresentation) {
      if (tokenPresentation) {
        this._previousPresentation = tokenPresentation;
      } else {
        this._previousPresentation = {
          foreground: 1,
          italic: false,
          bold: false,
          underline: false,
          strikethrough: false
        };
      }
    }
    return this._previousPresentation;
  }
}
const canUseZeroSizeTextarea = isFirefox$1;
let TextAreaHandler = class TextAreaHandler2 extends ViewPart {
  constructor(context, viewController, visibleRangeProvider, _keybindingService) {
    super(context);
    this._keybindingService = _keybindingService;
    this._primaryCursorPosition = new Position$2(1, 1);
    this._primaryCursorVisibleRange = null;
    this._viewController = viewController;
    this._visibleRangeProvider = visibleRangeProvider;
    this._scrollLeft = 0;
    this._scrollTop = 0;
    const options = this._context.configuration.options;
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    this._setAccessibilityOptions(options);
    this._contentLeft = layoutInfo.contentLeft;
    this._contentWidth = layoutInfo.contentWidth;
    this._contentHeight = layoutInfo.height;
    this._fontInfo = options.get(
      49
      /* EditorOption.fontInfo */
    );
    this._lineHeight = options.get(
      65
      /* EditorOption.lineHeight */
    );
    this._emptySelectionClipboard = options.get(
      36
      /* EditorOption.emptySelectionClipboard */
    );
    this._copyWithSyntaxHighlighting = options.get(
      24
      /* EditorOption.copyWithSyntaxHighlighting */
    );
    this._visibleTextArea = null;
    this._selections = [new Selection$1(1, 1, 1, 1)];
    this._modelSelections = [new Selection$1(1, 1, 1, 1)];
    this._lastRenderPosition = null;
    this.textArea = createFastDomNode(document.createElement("textarea"));
    PartFingerprints.write(
      this.textArea,
      6
      /* PartFingerprint.TextArea */
    );
    this.textArea.setClassName(`inputarea ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`);
    this.textArea.setAttribute("wrap", this._textAreaWrapping && !this._visibleTextArea ? "on" : "off");
    const { tabSize } = this._context.viewModel.model.getOptions();
    this.textArea.domNode.style.tabSize = `${tabSize * this._fontInfo.spaceWidth}px`;
    this.textArea.setAttribute("autocorrect", "off");
    this.textArea.setAttribute("autocapitalize", "off");
    this.textArea.setAttribute("autocomplete", "off");
    this.textArea.setAttribute("spellcheck", "false");
    this.textArea.setAttribute("aria-label", this._getAriaLabel(options));
    this.textArea.setAttribute("aria-required", options.get(
      5
      /* EditorOption.ariaRequired */
    ) ? "true" : "false");
    this.textArea.setAttribute("tabindex", String(options.get(
      122
      /* EditorOption.tabIndex */
    )));
    this.textArea.setAttribute("role", "textbox");
    this.textArea.setAttribute("aria-roledescription", localize("editor", "editor"));
    this.textArea.setAttribute("aria-multiline", "true");
    this.textArea.setAttribute("aria-haspopup", "false");
    this.textArea.setAttribute("aria-autocomplete", "both");
    this._ensureReadOnlyAttribute();
    this.textAreaCover = createFastDomNode(document.createElement("div"));
    this.textAreaCover.setPosition("absolute");
    const simpleModel = {
      getLineCount: () => {
        return this._context.viewModel.getLineCount();
      },
      getLineMaxColumn: (lineNumber) => {
        return this._context.viewModel.getLineMaxColumn(lineNumber);
      },
      getValueInRange: (range2, eol) => {
        return this._context.viewModel.getValueInRange(range2, eol);
      },
      getValueLengthInRange: (range2, eol) => {
        return this._context.viewModel.getValueLengthInRange(range2, eol);
      },
      modifyPosition: (position, offset) => {
        return this._context.viewModel.modifyPosition(position, offset);
      }
    };
    const textAreaInputHost = {
      getDataToCopy: () => {
        const rawTextToCopy = this._context.viewModel.getPlainTextToCopy(this._modelSelections, this._emptySelectionClipboard, isWindows);
        const newLineCharacter = this._context.viewModel.model.getEOL();
        const isFromEmptySelection = this._emptySelectionClipboard && this._modelSelections.length === 1 && this._modelSelections[0].isEmpty();
        const multicursorText = Array.isArray(rawTextToCopy) ? rawTextToCopy : null;
        const text2 = Array.isArray(rawTextToCopy) ? rawTextToCopy.join(newLineCharacter) : rawTextToCopy;
        let html2 = void 0;
        let mode = null;
        if (CopyOptions.forceCopyWithSyntaxHighlighting || this._copyWithSyntaxHighlighting && text2.length < 65536) {
          const richText = this._context.viewModel.getRichTextToCopy(this._modelSelections, this._emptySelectionClipboard);
          if (richText) {
            html2 = richText.html;
            mode = richText.mode;
          }
        }
        return {
          isFromEmptySelection,
          multicursorText,
          text: text2,
          html: html2,
          mode
        };
      },
      getScreenReaderContent: () => {
        if (this._accessibilitySupport === 1) {
          const selection = this._selections[0];
          if (isMacintosh && selection.isEmpty()) {
            const position = selection.getStartPosition();
            let textBefore = this._getWordBeforePosition(position);
            if (textBefore.length === 0) {
              textBefore = this._getCharacterBeforePosition(position);
            }
            if (textBefore.length > 0) {
              return new TextAreaState(textBefore, textBefore.length, textBefore.length, Range$2.fromPositions(position), 0);
            }
          }
          const LIMIT_CHARS = 500;
          if (isMacintosh && !selection.isEmpty() && simpleModel.getValueLengthInRange(
            selection,
            0
            /* EndOfLinePreference.TextDefined */
          ) < LIMIT_CHARS) {
            const text2 = simpleModel.getValueInRange(
              selection,
              0
              /* EndOfLinePreference.TextDefined */
            );
            return new TextAreaState(text2, 0, text2.length, selection, 0);
          }
          if (isSafari$1 && !selection.isEmpty()) {
            const placeholderText = "vscode-placeholder";
            return new TextAreaState(placeholderText, 0, placeholderText.length, null, void 0);
          }
          return TextAreaState.EMPTY;
        }
        if (isAndroid) {
          const selection = this._selections[0];
          if (selection.isEmpty()) {
            const position = selection.getStartPosition();
            const [wordAtPosition, positionOffsetInWord] = this._getAndroidWordAtPosition(position);
            if (wordAtPosition.length > 0) {
              return new TextAreaState(wordAtPosition, positionOffsetInWord, positionOffsetInWord, Range$2.fromPositions(position), 0);
            }
          }
          return TextAreaState.EMPTY;
        }
        return PagedScreenReaderStrategy.fromEditorSelection(
          simpleModel,
          this._selections[0],
          this._accessibilityPageSize,
          this._accessibilitySupport === 0
          /* AccessibilitySupport.Unknown */
        );
      },
      deduceModelPosition: (viewAnchorPosition, deltaOffset, lineFeedCnt) => {
        return this._context.viewModel.deduceModelPositionRelativeToViewPosition(viewAnchorPosition, deltaOffset, lineFeedCnt);
      }
    };
    const textAreaWrapper = this._register(new TextAreaWrapper(this.textArea.domNode));
    this._textAreaInput = this._register(new TextAreaInput(textAreaInputHost, textAreaWrapper, OS, {
      isAndroid,
      isChrome: isChrome$1,
      isFirefox: isFirefox$1,
      isSafari: isSafari$1
    }));
    this._register(this._textAreaInput.onKeyDown((e) => {
      this._viewController.emitKeyDown(e);
    }));
    this._register(this._textAreaInput.onKeyUp((e) => {
      this._viewController.emitKeyUp(e);
    }));
    this._register(this._textAreaInput.onPaste((e) => {
      let pasteOnNewLine = false;
      let multicursorText = null;
      let mode = null;
      if (e.metadata) {
        pasteOnNewLine = this._emptySelectionClipboard && !!e.metadata.isFromEmptySelection;
        multicursorText = typeof e.metadata.multicursorText !== "undefined" ? e.metadata.multicursorText : null;
        mode = e.metadata.mode;
      }
      this._viewController.paste(e.text, pasteOnNewLine, multicursorText, mode);
    }));
    this._register(this._textAreaInput.onCut(() => {
      this._viewController.cut();
    }));
    this._register(this._textAreaInput.onType((e) => {
      if (e.replacePrevCharCnt || e.replaceNextCharCnt || e.positionDelta) {
        this._viewController.compositionType(e.text, e.replacePrevCharCnt, e.replaceNextCharCnt, e.positionDelta);
      } else {
        this._viewController.type(e.text);
      }
    }));
    this._register(this._textAreaInput.onSelectionChangeRequest((modelSelection) => {
      this._viewController.setSelection(modelSelection);
    }));
    this._register(this._textAreaInput.onCompositionStart((e) => {
      const ta = this.textArea.domNode;
      const modelSelection = this._modelSelections[0];
      const { distanceToModelLineStart, widthOfHiddenTextBefore } = (() => {
        const textBeforeSelection = ta.value.substring(0, Math.min(ta.selectionStart, ta.selectionEnd));
        const lineFeedOffset1 = textBeforeSelection.lastIndexOf("\n");
        const lineTextBeforeSelection = textBeforeSelection.substring(lineFeedOffset1 + 1);
        const tabOffset1 = lineTextBeforeSelection.lastIndexOf("	");
        const desiredVisibleBeforeCharCount = lineTextBeforeSelection.length - tabOffset1 - 1;
        const startModelPosition = modelSelection.getStartPosition();
        const visibleBeforeCharCount = Math.min(startModelPosition.column - 1, desiredVisibleBeforeCharCount);
        const distanceToModelLineStart2 = startModelPosition.column - 1 - visibleBeforeCharCount;
        const hiddenLineTextBefore = lineTextBeforeSelection.substring(0, lineTextBeforeSelection.length - visibleBeforeCharCount);
        const { tabSize: tabSize2 } = this._context.viewModel.model.getOptions();
        const widthOfHiddenTextBefore2 = measureText(hiddenLineTextBefore, this._fontInfo, tabSize2);
        return { distanceToModelLineStart: distanceToModelLineStart2, widthOfHiddenTextBefore: widthOfHiddenTextBefore2 };
      })();
      const { distanceToModelLineEnd } = (() => {
        const textAfterSelection = ta.value.substring(Math.max(ta.selectionStart, ta.selectionEnd));
        const lineFeedOffset2 = textAfterSelection.indexOf("\n");
        const lineTextAfterSelection = lineFeedOffset2 === -1 ? textAfterSelection : textAfterSelection.substring(0, lineFeedOffset2);
        const tabOffset2 = lineTextAfterSelection.indexOf("	");
        const desiredVisibleAfterCharCount = tabOffset2 === -1 ? lineTextAfterSelection.length : lineTextAfterSelection.length - tabOffset2 - 1;
        const endModelPosition = modelSelection.getEndPosition();
        const visibleAfterCharCount = Math.min(this._context.viewModel.model.getLineMaxColumn(endModelPosition.lineNumber) - endModelPosition.column, desiredVisibleAfterCharCount);
        const distanceToModelLineEnd2 = this._context.viewModel.model.getLineMaxColumn(endModelPosition.lineNumber) - endModelPosition.column - visibleAfterCharCount;
        return { distanceToModelLineEnd: distanceToModelLineEnd2 };
      })();
      this._context.viewModel.revealRange(
        "keyboard",
        true,
        Range$2.fromPositions(this._selections[0].getStartPosition()),
        0,
        1
        /* ScrollType.Immediate */
      );
      this._visibleTextArea = new VisibleTextAreaData(this._context, modelSelection.startLineNumber, distanceToModelLineStart, widthOfHiddenTextBefore, distanceToModelLineEnd);
      this.textArea.setAttribute("wrap", this._textAreaWrapping && !this._visibleTextArea ? "on" : "off");
      this._visibleTextArea.prepareRender(this._visibleRangeProvider);
      this._render();
      this.textArea.setClassName(`inputarea ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME} ime-input`);
      this._viewController.compositionStart();
      this._context.viewModel.onCompositionStart();
    }));
    this._register(this._textAreaInput.onCompositionUpdate((e) => {
      if (!this._visibleTextArea) {
        return;
      }
      this._visibleTextArea.prepareRender(this._visibleRangeProvider);
      this._render();
    }));
    this._register(this._textAreaInput.onCompositionEnd(() => {
      this._visibleTextArea = null;
      this.textArea.setAttribute("wrap", this._textAreaWrapping && !this._visibleTextArea ? "on" : "off");
      this._render();
      this.textArea.setClassName(`inputarea ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`);
      this._viewController.compositionEnd();
      this._context.viewModel.onCompositionEnd();
    }));
    this._register(this._textAreaInput.onFocus(() => {
      this._context.viewModel.setHasFocus(true);
    }));
    this._register(this._textAreaInput.onBlur(() => {
      this._context.viewModel.setHasFocus(false);
    }));
    this._register(IME.onDidChange(() => {
      this._ensureReadOnlyAttribute();
    }));
  }
  writeScreenReaderContent(reason) {
    this._textAreaInput.writeScreenReaderContent(reason);
  }
  dispose() {
    super.dispose();
  }
  _getAndroidWordAtPosition(position) {
    const ANDROID_WORD_SEPARATORS = '`~!@#$%^&*()-=+[{]}\\|;:",.<>/?';
    const lineContent = this._context.viewModel.getLineContent(position.lineNumber);
    const wordSeparators2 = getMapForWordSeparators(ANDROID_WORD_SEPARATORS);
    let goingLeft = true;
    let startColumn = position.column;
    let goingRight = true;
    let endColumn = position.column;
    let distance = 0;
    while (distance < 50 && (goingLeft || goingRight)) {
      if (goingLeft && startColumn <= 1) {
        goingLeft = false;
      }
      if (goingLeft) {
        const charCode = lineContent.charCodeAt(startColumn - 2);
        const charClass = wordSeparators2.get(charCode);
        if (charClass !== 0) {
          goingLeft = false;
        } else {
          startColumn--;
        }
      }
      if (goingRight && endColumn > lineContent.length) {
        goingRight = false;
      }
      if (goingRight) {
        const charCode = lineContent.charCodeAt(endColumn - 1);
        const charClass = wordSeparators2.get(charCode);
        if (charClass !== 0) {
          goingRight = false;
        } else {
          endColumn++;
        }
      }
      distance++;
    }
    return [lineContent.substring(startColumn - 1, endColumn - 1), position.column - startColumn];
  }
  _getWordBeforePosition(position) {
    const lineContent = this._context.viewModel.getLineContent(position.lineNumber);
    const wordSeparators2 = getMapForWordSeparators(this._context.configuration.options.get(
      128
      /* EditorOption.wordSeparators */
    ));
    let column = position.column;
    let distance = 0;
    while (column > 1) {
      const charCode = lineContent.charCodeAt(column - 2);
      const charClass = wordSeparators2.get(charCode);
      if (charClass !== 0 || distance > 50) {
        return lineContent.substring(column - 1, position.column - 1);
      }
      distance++;
      column--;
    }
    return lineContent.substring(0, position.column - 1);
  }
  _getCharacterBeforePosition(position) {
    if (position.column > 1) {
      const lineContent = this._context.viewModel.getLineContent(position.lineNumber);
      const charBefore = lineContent.charAt(position.column - 2);
      if (!isHighSurrogate(charBefore.charCodeAt(0))) {
        return charBefore;
      }
    }
    return "";
  }
  _getAriaLabel(options) {
    var _a2, _b2, _c2;
    const accessibilitySupport = options.get(
      2
      /* EditorOption.accessibilitySupport */
    );
    if (accessibilitySupport === 1) {
      const toggleKeybindingLabel = (_a2 = this._keybindingService.lookupKeybinding("editor.action.toggleScreenReaderAccessibilityMode")) === null || _a2 === void 0 ? void 0 : _a2.getAriaLabel();
      const runCommandKeybindingLabel = (_b2 = this._keybindingService.lookupKeybinding("workbench.action.showCommands")) === null || _b2 === void 0 ? void 0 : _b2.getAriaLabel();
      const keybindingEditorKeybindingLabel = (_c2 = this._keybindingService.lookupKeybinding("workbench.action.openGlobalKeybindings")) === null || _c2 === void 0 ? void 0 : _c2.getAriaLabel();
      const editorNotAccessibleMessage = localize("accessibilityModeOff", "The editor is not accessible at this time.");
      if (toggleKeybindingLabel) {
        return localize("accessibilityOffAriaLabel", "{0} To enable screen reader optimized mode, use {1}", editorNotAccessibleMessage, toggleKeybindingLabel);
      } else if (runCommandKeybindingLabel) {
        return localize("accessibilityOffAriaLabelNoKb", "{0} To enable screen reader optimized mode, open the quick pick with {1} and run the command Toggle Screen Reader Accessibility Mode, which is currently not triggerable via keyboard.", editorNotAccessibleMessage, runCommandKeybindingLabel);
      } else if (keybindingEditorKeybindingLabel) {
        return localize("accessibilityOffAriaLabelNoKbs", "{0} Please assign a keybinding for the command Toggle Screen Reader Accessibility Mode by accessing the keybindings editor with {1} and run it.", editorNotAccessibleMessage, keybindingEditorKeybindingLabel);
      } else {
        return editorNotAccessibleMessage;
      }
    }
    return options.get(
      4
      /* EditorOption.ariaLabel */
    );
  }
  _setAccessibilityOptions(options) {
    this._accessibilitySupport = options.get(
      2
      /* EditorOption.accessibilitySupport */
    );
    const accessibilityPageSize = options.get(
      3
      /* EditorOption.accessibilityPageSize */
    );
    if (this._accessibilitySupport === 2 && accessibilityPageSize === EditorOptions.accessibilityPageSize.defaultValue) {
      this._accessibilityPageSize = 500;
    } else {
      this._accessibilityPageSize = accessibilityPageSize;
    }
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    const wrappingColumn = layoutInfo.wrappingColumn;
    if (wrappingColumn !== -1 && this._accessibilitySupport !== 1) {
      const fontInfo = options.get(
        49
        /* EditorOption.fontInfo */
      );
      this._textAreaWrapping = true;
      this._textAreaWidth = Math.round(wrappingColumn * fontInfo.typicalHalfwidthCharacterWidth);
    } else {
      this._textAreaWrapping = false;
      this._textAreaWidth = canUseZeroSizeTextarea ? 0 : 1;
    }
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    const options = this._context.configuration.options;
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    this._setAccessibilityOptions(options);
    this._contentLeft = layoutInfo.contentLeft;
    this._contentWidth = layoutInfo.contentWidth;
    this._contentHeight = layoutInfo.height;
    this._fontInfo = options.get(
      49
      /* EditorOption.fontInfo */
    );
    this._lineHeight = options.get(
      65
      /* EditorOption.lineHeight */
    );
    this._emptySelectionClipboard = options.get(
      36
      /* EditorOption.emptySelectionClipboard */
    );
    this._copyWithSyntaxHighlighting = options.get(
      24
      /* EditorOption.copyWithSyntaxHighlighting */
    );
    this.textArea.setAttribute("wrap", this._textAreaWrapping && !this._visibleTextArea ? "on" : "off");
    const { tabSize } = this._context.viewModel.model.getOptions();
    this.textArea.domNode.style.tabSize = `${tabSize * this._fontInfo.spaceWidth}px`;
    this.textArea.setAttribute("aria-label", this._getAriaLabel(options));
    this.textArea.setAttribute("aria-required", options.get(
      5
      /* EditorOption.ariaRequired */
    ) ? "true" : "false");
    this.textArea.setAttribute("tabindex", String(options.get(
      122
      /* EditorOption.tabIndex */
    )));
    if (e.hasChanged(
      33
      /* EditorOption.domReadOnly */
    ) || e.hasChanged(
      89
      /* EditorOption.readOnly */
    )) {
      this._ensureReadOnlyAttribute();
    }
    if (e.hasChanged(
      2
      /* EditorOption.accessibilitySupport */
    )) {
      this._textAreaInput.writeScreenReaderContent("strategy changed");
    }
    return true;
  }
  onCursorStateChanged(e) {
    this._selections = e.selections.slice(0);
    this._modelSelections = e.modelSelections.slice(0);
    this._textAreaInput.writeScreenReaderContent("selection changed");
    return true;
  }
  onDecorationsChanged(e) {
    return true;
  }
  onFlushed(e) {
    return true;
  }
  onLinesChanged(e) {
    return true;
  }
  onLinesDeleted(e) {
    return true;
  }
  onLinesInserted(e) {
    return true;
  }
  onScrollChanged(e) {
    this._scrollLeft = e.scrollLeft;
    this._scrollTop = e.scrollTop;
    return true;
  }
  onZonesChanged(e) {
    return true;
  }
  // --- end event handlers
  // --- begin view API
  isFocused() {
    return this._textAreaInput.isFocused();
  }
  focusTextArea() {
    this._textAreaInput.focusTextArea();
  }
  getLastRenderData() {
    return this._lastRenderPosition;
  }
  setAriaOptions(options) {
    if (options.activeDescendant) {
      this.textArea.setAttribute("aria-haspopup", "true");
      this.textArea.setAttribute("aria-autocomplete", "list");
      this.textArea.setAttribute("aria-activedescendant", options.activeDescendant);
    } else {
      this.textArea.setAttribute("aria-haspopup", "false");
      this.textArea.setAttribute("aria-autocomplete", "both");
      this.textArea.removeAttribute("aria-activedescendant");
    }
    if (options.role) {
      this.textArea.setAttribute("role", options.role);
    }
  }
  // --- end view API
  _ensureReadOnlyAttribute() {
    const options = this._context.configuration.options;
    const useReadOnly = !IME.enabled || options.get(
      33
      /* EditorOption.domReadOnly */
    ) && options.get(
      89
      /* EditorOption.readOnly */
    );
    if (useReadOnly) {
      this.textArea.setAttribute("readonly", "true");
    } else {
      this.textArea.removeAttribute("readonly");
    }
  }
  prepareRender(ctx) {
    var _a2;
    this._primaryCursorPosition = new Position$2(this._selections[0].positionLineNumber, this._selections[0].positionColumn);
    this._primaryCursorVisibleRange = ctx.visibleRangeForPosition(this._primaryCursorPosition);
    (_a2 = this._visibleTextArea) === null || _a2 === void 0 ? void 0 : _a2.prepareRender(ctx);
  }
  render(ctx) {
    this._textAreaInput.writeScreenReaderContent("render");
    this._render();
  }
  _render() {
    var _a2;
    if (this._visibleTextArea) {
      const visibleStart = this._visibleTextArea.visibleTextareaStart;
      const visibleEnd = this._visibleTextArea.visibleTextareaEnd;
      const startPosition = this._visibleTextArea.startPosition;
      const endPosition = this._visibleTextArea.endPosition;
      if (startPosition && endPosition && visibleStart && visibleEnd && visibleEnd.left >= this._scrollLeft && visibleStart.left <= this._scrollLeft + this._contentWidth) {
        const top2 = this._context.viewLayout.getVerticalOffsetForLineNumber(this._primaryCursorPosition.lineNumber) - this._scrollTop;
        const lineCount = this._newlinecount(this.textArea.domNode.value.substr(0, this.textArea.domNode.selectionStart));
        let scrollLeft = this._visibleTextArea.widthOfHiddenLineTextBefore;
        let left2 = this._contentLeft + visibleStart.left - this._scrollLeft;
        let width = visibleEnd.left - visibleStart.left + 1;
        if (left2 < this._contentLeft) {
          const delta = this._contentLeft - left2;
          left2 += delta;
          scrollLeft += delta;
          width -= delta;
        }
        if (width > this._contentWidth) {
          width = this._contentWidth;
        }
        const viewLineData = this._context.viewModel.getViewLineData(startPosition.lineNumber);
        const startTokenIndex = viewLineData.tokens.findTokenIndexAtOffset(startPosition.column - 1);
        const endTokenIndex = viewLineData.tokens.findTokenIndexAtOffset(endPosition.column - 1);
        const textareaSpansSingleToken = startTokenIndex === endTokenIndex;
        const presentation = this._visibleTextArea.definePresentation(textareaSpansSingleToken ? viewLineData.tokens.getPresentation(startTokenIndex) : null);
        this.textArea.domNode.scrollTop = lineCount * this._lineHeight;
        this.textArea.domNode.scrollLeft = scrollLeft;
        this._doRender({
          lastRenderPosition: null,
          top: top2,
          left: left2,
          width,
          height: this._lineHeight,
          useCover: false,
          color: (TokenizationRegistry2.getColorMap() || [])[presentation.foreground],
          italic: presentation.italic,
          bold: presentation.bold,
          underline: presentation.underline,
          strikethrough: presentation.strikethrough
        });
      }
      return;
    }
    if (!this._primaryCursorVisibleRange) {
      this._renderAtTopLeft();
      return;
    }
    const left = this._contentLeft + this._primaryCursorVisibleRange.left - this._scrollLeft;
    if (left < this._contentLeft || left > this._contentLeft + this._contentWidth) {
      this._renderAtTopLeft();
      return;
    }
    const top = this._context.viewLayout.getVerticalOffsetForLineNumber(this._selections[0].positionLineNumber) - this._scrollTop;
    if (top < 0 || top > this._contentHeight) {
      this._renderAtTopLeft();
      return;
    }
    if (isMacintosh) {
      this._doRender({
        lastRenderPosition: this._primaryCursorPosition,
        top,
        left: this._textAreaWrapping ? this._contentLeft : left,
        width: this._textAreaWidth,
        height: this._lineHeight,
        useCover: false
      });
      this.textArea.domNode.scrollLeft = this._primaryCursorVisibleRange.left;
      const lineCount = (_a2 = this._textAreaInput.textAreaState.newlineCountBeforeSelection) !== null && _a2 !== void 0 ? _a2 : this._newlinecount(this.textArea.domNode.value.substr(0, this.textArea.domNode.selectionStart));
      this.textArea.domNode.scrollTop = lineCount * this._lineHeight;
      return;
    }
    this._doRender({
      lastRenderPosition: this._primaryCursorPosition,
      top,
      left: this._textAreaWrapping ? this._contentLeft : left,
      width: this._textAreaWidth,
      height: canUseZeroSizeTextarea ? 0 : 1,
      useCover: false
    });
  }
  _newlinecount(text2) {
    let result2 = 0;
    let startIndex = -1;
    do {
      startIndex = text2.indexOf("\n", startIndex + 1);
      if (startIndex === -1) {
        break;
      }
      result2++;
    } while (true);
    return result2;
  }
  _renderAtTopLeft() {
    this._doRender({
      lastRenderPosition: null,
      top: 0,
      left: 0,
      width: this._textAreaWidth,
      height: canUseZeroSizeTextarea ? 0 : 1,
      useCover: true
    });
  }
  _doRender(renderData) {
    this._lastRenderPosition = renderData.lastRenderPosition;
    const ta = this.textArea;
    const tac = this.textAreaCover;
    applyFontInfo(ta, this._fontInfo);
    ta.setTop(renderData.top);
    ta.setLeft(renderData.left);
    ta.setWidth(renderData.width);
    ta.setHeight(renderData.height);
    ta.setColor(renderData.color ? Color.Format.CSS.formatHex(renderData.color) : "");
    ta.setFontStyle(renderData.italic ? "italic" : "");
    if (renderData.bold) {
      ta.setFontWeight("bold");
    }
    ta.setTextDecoration(`${renderData.underline ? " underline" : ""}${renderData.strikethrough ? " line-through" : ""}`);
    tac.setTop(renderData.useCover ? renderData.top : 0);
    tac.setLeft(renderData.useCover ? renderData.left : 0);
    tac.setWidth(renderData.useCover ? renderData.width : 0);
    tac.setHeight(renderData.useCover ? renderData.height : 0);
    const options = this._context.configuration.options;
    if (options.get(
      56
      /* EditorOption.glyphMargin */
    )) {
      tac.setClassName("monaco-editor-background textAreaCover " + Margin.OUTER_CLASS_NAME);
    } else {
      if (options.get(
        66
        /* EditorOption.lineNumbers */
      ).renderType !== 0) {
        tac.setClassName("monaco-editor-background textAreaCover " + LineNumbersOverlay.CLASS_NAME);
      } else {
        tac.setClassName("monaco-editor-background textAreaCover");
      }
    }
  }
};
TextAreaHandler = __decorate$25([
  __param$1$(3, IKeybindingService)
], TextAreaHandler);
function measureText(text2, fontInfo, tabSize) {
  if (text2.length === 0) {
    return 0;
  }
  const container2 = document.createElement("div");
  container2.style.position = "absolute";
  container2.style.top = "-50000px";
  container2.style.width = "50000px";
  const regularDomNode = document.createElement("span");
  applyFontInfo(regularDomNode, fontInfo);
  regularDomNode.style.whiteSpace = "pre";
  regularDomNode.style.tabSize = `${tabSize * fontInfo.spaceWidth}px`;
  regularDomNode.append(text2);
  container2.appendChild(regularDomNode);
  document.body.appendChild(container2);
  const res = regularDomNode.offsetWidth;
  document.body.removeChild(container2);
  return res;
}
class ViewController {
  constructor(configuration, viewModel, userInputEvents, commandDelegate) {
    this.configuration = configuration;
    this.viewModel = viewModel;
    this.userInputEvents = userInputEvents;
    this.commandDelegate = commandDelegate;
  }
  paste(text2, pasteOnNewLine, multicursorText, mode) {
    this.commandDelegate.paste(text2, pasteOnNewLine, multicursorText, mode);
  }
  type(text2) {
    this.commandDelegate.type(text2);
  }
  compositionType(text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta) {
    this.commandDelegate.compositionType(text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta);
  }
  compositionStart() {
    this.commandDelegate.startComposition();
  }
  compositionEnd() {
    this.commandDelegate.endComposition();
  }
  cut() {
    this.commandDelegate.cut();
  }
  setSelection(modelSelection) {
    CoreNavigationCommands.SetSelection.runCoreEditorCommand(this.viewModel, {
      source: "keyboard",
      selection: modelSelection
    });
  }
  _validateViewColumn(viewPosition) {
    const minColumn = this.viewModel.getLineMinColumn(viewPosition.lineNumber);
    if (viewPosition.column < minColumn) {
      return new Position$2(viewPosition.lineNumber, minColumn);
    }
    return viewPosition;
  }
  _hasMulticursorModifier(data) {
    switch (this.configuration.options.get(
      76
      /* EditorOption.multiCursorModifier */
    )) {
      case "altKey":
        return data.altKey;
      case "ctrlKey":
        return data.ctrlKey;
      case "metaKey":
        return data.metaKey;
      default:
        return false;
    }
  }
  _hasNonMulticursorModifier(data) {
    switch (this.configuration.options.get(
      76
      /* EditorOption.multiCursorModifier */
    )) {
      case "altKey":
        return data.ctrlKey || data.metaKey;
      case "ctrlKey":
        return data.altKey || data.metaKey;
      case "metaKey":
        return data.ctrlKey || data.altKey;
      default:
        return false;
    }
  }
  dispatchMouse(data) {
    const options = this.configuration.options;
    const selectionClipboardIsOn = isLinux && options.get(
      105
      /* EditorOption.selectionClipboard */
    );
    const columnSelection = options.get(
      21
      /* EditorOption.columnSelection */
    );
    if (data.middleButton && !selectionClipboardIsOn) {
      this._columnSelect(data.position, data.mouseColumn, data.inSelectionMode);
    } else if (data.startedOnLineNumbers) {
      if (this._hasMulticursorModifier(data)) {
        if (data.inSelectionMode) {
          this._lastCursorLineSelect(data.position, data.revealType);
        } else {
          this._createCursor(data.position, true);
        }
      } else {
        if (data.inSelectionMode) {
          this._lineSelectDrag(data.position, data.revealType);
        } else {
          this._lineSelect(data.position, data.revealType);
        }
      }
    } else if (data.mouseDownCount >= 4) {
      this._selectAll();
    } else if (data.mouseDownCount === 3) {
      if (this._hasMulticursorModifier(data)) {
        if (data.inSelectionMode) {
          this._lastCursorLineSelectDrag(data.position, data.revealType);
        } else {
          this._lastCursorLineSelect(data.position, data.revealType);
        }
      } else {
        if (data.inSelectionMode) {
          this._lineSelectDrag(data.position, data.revealType);
        } else {
          this._lineSelect(data.position, data.revealType);
        }
      }
    } else if (data.mouseDownCount === 2) {
      if (!data.onInjectedText) {
        if (this._hasMulticursorModifier(data)) {
          this._lastCursorWordSelect(data.position, data.revealType);
        } else {
          if (data.inSelectionMode) {
            this._wordSelectDrag(data.position, data.revealType);
          } else {
            this._wordSelect(data.position, data.revealType);
          }
        }
      }
    } else {
      if (this._hasMulticursorModifier(data)) {
        if (!this._hasNonMulticursorModifier(data)) {
          if (data.shiftKey) {
            this._columnSelect(data.position, data.mouseColumn, true);
          } else {
            if (data.inSelectionMode) {
              this._lastCursorMoveToSelect(data.position, data.revealType);
            } else {
              this._createCursor(data.position, false);
            }
          }
        }
      } else {
        if (data.inSelectionMode) {
          if (data.altKey) {
            this._columnSelect(data.position, data.mouseColumn, true);
          } else {
            if (columnSelection) {
              this._columnSelect(data.position, data.mouseColumn, true);
            } else {
              this._moveToSelect(data.position, data.revealType);
            }
          }
        } else {
          this.moveTo(data.position, data.revealType);
        }
      }
    }
  }
  _usualArgs(viewPosition, revealType) {
    viewPosition = this._validateViewColumn(viewPosition);
    return {
      source: "mouse",
      position: this._convertViewToModelPosition(viewPosition),
      viewPosition,
      revealType
    };
  }
  moveTo(viewPosition, revealType) {
    CoreNavigationCommands.MoveTo.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
  }
  _moveToSelect(viewPosition, revealType) {
    CoreNavigationCommands.MoveToSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
  }
  _columnSelect(viewPosition, mouseColumn, doColumnSelect) {
    viewPosition = this._validateViewColumn(viewPosition);
    CoreNavigationCommands.ColumnSelect.runCoreEditorCommand(this.viewModel, {
      source: "mouse",
      position: this._convertViewToModelPosition(viewPosition),
      viewPosition,
      mouseColumn,
      doColumnSelect
    });
  }
  _createCursor(viewPosition, wholeLine) {
    viewPosition = this._validateViewColumn(viewPosition);
    CoreNavigationCommands.CreateCursor.runCoreEditorCommand(this.viewModel, {
      source: "mouse",
      position: this._convertViewToModelPosition(viewPosition),
      viewPosition,
      wholeLine
    });
  }
  _lastCursorMoveToSelect(viewPosition, revealType) {
    CoreNavigationCommands.LastCursorMoveToSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
  }
  _wordSelect(viewPosition, revealType) {
    CoreNavigationCommands.WordSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
  }
  _wordSelectDrag(viewPosition, revealType) {
    CoreNavigationCommands.WordSelectDrag.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
  }
  _lastCursorWordSelect(viewPosition, revealType) {
    CoreNavigationCommands.LastCursorWordSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
  }
  _lineSelect(viewPosition, revealType) {
    CoreNavigationCommands.LineSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
  }
  _lineSelectDrag(viewPosition, revealType) {
    CoreNavigationCommands.LineSelectDrag.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
  }
  _lastCursorLineSelect(viewPosition, revealType) {
    CoreNavigationCommands.LastCursorLineSelect.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
  }
  _lastCursorLineSelectDrag(viewPosition, revealType) {
    CoreNavigationCommands.LastCursorLineSelectDrag.runCoreEditorCommand(this.viewModel, this._usualArgs(viewPosition, revealType));
  }
  _selectAll() {
    CoreNavigationCommands.SelectAll.runCoreEditorCommand(this.viewModel, { source: "mouse" });
  }
  // ----------------------
  _convertViewToModelPosition(viewPosition) {
    return this.viewModel.coordinatesConverter.convertViewPositionToModelPosition(viewPosition);
  }
  emitKeyDown(e) {
    this.userInputEvents.emitKeyDown(e);
  }
  emitKeyUp(e) {
    this.userInputEvents.emitKeyUp(e);
  }
  emitContextMenu(e) {
    this.userInputEvents.emitContextMenu(e);
  }
  emitMouseMove(e) {
    this.userInputEvents.emitMouseMove(e);
  }
  emitMouseLeave(e) {
    this.userInputEvents.emitMouseLeave(e);
  }
  emitMouseUp(e) {
    this.userInputEvents.emitMouseUp(e);
  }
  emitMouseDown(e) {
    this.userInputEvents.emitMouseDown(e);
  }
  emitMouseDrag(e) {
    this.userInputEvents.emitMouseDrag(e);
  }
  emitMouseDrop(e) {
    this.userInputEvents.emitMouseDrop(e);
  }
  emitMouseDropCanceled() {
    this.userInputEvents.emitMouseDropCanceled();
  }
  emitMouseWheel(e) {
    this.userInputEvents.emitMouseWheel(e);
  }
}
class ViewUserInputEvents {
  constructor(coordinatesConverter) {
    this.onKeyDown = null;
    this.onKeyUp = null;
    this.onContextMenu = null;
    this.onMouseMove = null;
    this.onMouseLeave = null;
    this.onMouseDown = null;
    this.onMouseUp = null;
    this.onMouseDrag = null;
    this.onMouseDrop = null;
    this.onMouseDropCanceled = null;
    this.onMouseWheel = null;
    this._coordinatesConverter = coordinatesConverter;
  }
  emitKeyDown(e) {
    var _a2;
    (_a2 = this.onKeyDown) === null || _a2 === void 0 ? void 0 : _a2.call(this, e);
  }
  emitKeyUp(e) {
    var _a2;
    (_a2 = this.onKeyUp) === null || _a2 === void 0 ? void 0 : _a2.call(this, e);
  }
  emitContextMenu(e) {
    var _a2;
    (_a2 = this.onContextMenu) === null || _a2 === void 0 ? void 0 : _a2.call(this, this._convertViewToModelMouseEvent(e));
  }
  emitMouseMove(e) {
    var _a2;
    (_a2 = this.onMouseMove) === null || _a2 === void 0 ? void 0 : _a2.call(this, this._convertViewToModelMouseEvent(e));
  }
  emitMouseLeave(e) {
    var _a2;
    (_a2 = this.onMouseLeave) === null || _a2 === void 0 ? void 0 : _a2.call(this, this._convertViewToModelMouseEvent(e));
  }
  emitMouseDown(e) {
    var _a2;
    (_a2 = this.onMouseDown) === null || _a2 === void 0 ? void 0 : _a2.call(this, this._convertViewToModelMouseEvent(e));
  }
  emitMouseUp(e) {
    var _a2;
    (_a2 = this.onMouseUp) === null || _a2 === void 0 ? void 0 : _a2.call(this, this._convertViewToModelMouseEvent(e));
  }
  emitMouseDrag(e) {
    var _a2;
    (_a2 = this.onMouseDrag) === null || _a2 === void 0 ? void 0 : _a2.call(this, this._convertViewToModelMouseEvent(e));
  }
  emitMouseDrop(e) {
    var _a2;
    (_a2 = this.onMouseDrop) === null || _a2 === void 0 ? void 0 : _a2.call(this, this._convertViewToModelMouseEvent(e));
  }
  emitMouseDropCanceled() {
    var _a2;
    (_a2 = this.onMouseDropCanceled) === null || _a2 === void 0 ? void 0 : _a2.call(this);
  }
  emitMouseWheel(e) {
    var _a2;
    (_a2 = this.onMouseWheel) === null || _a2 === void 0 ? void 0 : _a2.call(this, e);
  }
  _convertViewToModelMouseEvent(e) {
    if (e.target) {
      return {
        event: e.event,
        target: this._convertViewToModelMouseTarget(e.target)
      };
    }
    return e;
  }
  _convertViewToModelMouseTarget(target) {
    return ViewUserInputEvents.convertViewToModelMouseTarget(target, this._coordinatesConverter);
  }
  static convertViewToModelMouseTarget(target, coordinatesConverter) {
    const result2 = Object.assign({}, target);
    if (result2.position) {
      result2.position = coordinatesConverter.convertViewPositionToModelPosition(result2.position);
    }
    if (result2.range) {
      result2.range = coordinatesConverter.convertViewRangeToModelRange(result2.range);
    }
    if (result2.type === 5 || result2.type === 8) {
      result2.detail = this.convertViewToModelViewZoneData(result2.detail, coordinatesConverter);
    }
    return result2;
  }
  static convertViewToModelViewZoneData(data, coordinatesConverter) {
    return {
      viewZoneId: data.viewZoneId,
      positionBefore: data.positionBefore ? coordinatesConverter.convertViewPositionToModelPosition(data.positionBefore) : data.positionBefore,
      positionAfter: data.positionAfter ? coordinatesConverter.convertViewPositionToModelPosition(data.positionAfter) : data.positionAfter,
      position: coordinatesConverter.convertViewPositionToModelPosition(data.position),
      afterLineNumber: coordinatesConverter.convertViewPositionToModelPosition(new Position$2(data.afterLineNumber, 1)).lineNumber
    };
  }
}
function createTrustedTypesPolicy(policyName, policyOptions) {
  var _a2;
  const monacoEnvironment2 = globalThis.MonacoEnvironment;
  if (monacoEnvironment2 === null || monacoEnvironment2 === void 0 ? void 0 : monacoEnvironment2.createTrustedTypesPolicy) {
    try {
      return monacoEnvironment2.createTrustedTypesPolicy(policyName, policyOptions);
    } catch (err) {
      onUnexpectedError(err);
      return void 0;
    }
  }
  try {
    return (_a2 = window.trustedTypes) === null || _a2 === void 0 ? void 0 : _a2.createPolicy(policyName, policyOptions);
  } catch (err) {
    onUnexpectedError(err);
    return void 0;
  }
}
class RenderedLinesCollection {
  constructor(createLine) {
    this._createLine = createLine;
    this._set(1, []);
  }
  flush() {
    this._set(1, []);
  }
  _set(rendLineNumberStart, lines) {
    this._lines = lines;
    this._rendLineNumberStart = rendLineNumberStart;
  }
  _get() {
    return {
      rendLineNumberStart: this._rendLineNumberStart,
      lines: this._lines
    };
  }
  /**
   * @returns Inclusive line number that is inside this collection
   */
  getStartLineNumber() {
    return this._rendLineNumberStart;
  }
  /**
   * @returns Inclusive line number that is inside this collection
   */
  getEndLineNumber() {
    return this._rendLineNumberStart + this._lines.length - 1;
  }
  getCount() {
    return this._lines.length;
  }
  getLine(lineNumber) {
    const lineIndex = lineNumber - this._rendLineNumberStart;
    if (lineIndex < 0 || lineIndex >= this._lines.length) {
      throw new BugIndicatingError("Illegal value for lineNumber");
    }
    return this._lines[lineIndex];
  }
  /**
   * @returns Lines that were removed from this collection
   */
  onLinesDeleted(deleteFromLineNumber, deleteToLineNumber) {
    if (this.getCount() === 0) {
      return null;
    }
    const startLineNumber = this.getStartLineNumber();
    const endLineNumber = this.getEndLineNumber();
    if (deleteToLineNumber < startLineNumber) {
      const deleteCnt = deleteToLineNumber - deleteFromLineNumber + 1;
      this._rendLineNumberStart -= deleteCnt;
      return null;
    }
    if (deleteFromLineNumber > endLineNumber) {
      return null;
    }
    let deleteStartIndex = 0;
    let deleteCount = 0;
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      const lineIndex = lineNumber - this._rendLineNumberStart;
      if (deleteFromLineNumber <= lineNumber && lineNumber <= deleteToLineNumber) {
        if (deleteCount === 0) {
          deleteStartIndex = lineIndex;
          deleteCount = 1;
        } else {
          deleteCount++;
        }
      }
    }
    if (deleteFromLineNumber < startLineNumber) {
      let deleteAboveCount = 0;
      if (deleteToLineNumber < startLineNumber) {
        deleteAboveCount = deleteToLineNumber - deleteFromLineNumber + 1;
      } else {
        deleteAboveCount = startLineNumber - deleteFromLineNumber;
      }
      this._rendLineNumberStart -= deleteAboveCount;
    }
    const deleted = this._lines.splice(deleteStartIndex, deleteCount);
    return deleted;
  }
  onLinesChanged(changeFromLineNumber, changeCount) {
    const changeToLineNumber = changeFromLineNumber + changeCount - 1;
    if (this.getCount() === 0) {
      return false;
    }
    const startLineNumber = this.getStartLineNumber();
    const endLineNumber = this.getEndLineNumber();
    let someoneNotified = false;
    for (let changedLineNumber = changeFromLineNumber; changedLineNumber <= changeToLineNumber; changedLineNumber++) {
      if (changedLineNumber >= startLineNumber && changedLineNumber <= endLineNumber) {
        this._lines[changedLineNumber - this._rendLineNumberStart].onContentChanged();
        someoneNotified = true;
      }
    }
    return someoneNotified;
  }
  onLinesInserted(insertFromLineNumber, insertToLineNumber) {
    if (this.getCount() === 0) {
      return null;
    }
    const insertCnt = insertToLineNumber - insertFromLineNumber + 1;
    const startLineNumber = this.getStartLineNumber();
    const endLineNumber = this.getEndLineNumber();
    if (insertFromLineNumber <= startLineNumber) {
      this._rendLineNumberStart += insertCnt;
      return null;
    }
    if (insertFromLineNumber > endLineNumber) {
      return null;
    }
    if (insertCnt + insertFromLineNumber > endLineNumber) {
      const deleted = this._lines.splice(insertFromLineNumber - this._rendLineNumberStart, endLineNumber - insertFromLineNumber + 1);
      return deleted;
    }
    const newLines = [];
    for (let i = 0; i < insertCnt; i++) {
      newLines[i] = this._createLine();
    }
    const insertIndex = insertFromLineNumber - this._rendLineNumberStart;
    const beforeLines = this._lines.slice(0, insertIndex);
    const afterLines = this._lines.slice(insertIndex, this._lines.length - insertCnt);
    const deletedLines = this._lines.slice(this._lines.length - insertCnt, this._lines.length);
    this._lines = beforeLines.concat(newLines).concat(afterLines);
    return deletedLines;
  }
  onTokensChanged(ranges) {
    if (this.getCount() === 0) {
      return false;
    }
    const startLineNumber = this.getStartLineNumber();
    const endLineNumber = this.getEndLineNumber();
    let notifiedSomeone = false;
    for (let i = 0, len = ranges.length; i < len; i++) {
      const rng = ranges[i];
      if (rng.toLineNumber < startLineNumber || rng.fromLineNumber > endLineNumber) {
        continue;
      }
      const from2 = Math.max(startLineNumber, rng.fromLineNumber);
      const to = Math.min(endLineNumber, rng.toLineNumber);
      for (let lineNumber = from2; lineNumber <= to; lineNumber++) {
        const lineIndex = lineNumber - this._rendLineNumberStart;
        this._lines[lineIndex].onTokensChanged();
        notifiedSomeone = true;
      }
    }
    return notifiedSomeone;
  }
}
class VisibleLinesCollection {
  constructor(host) {
    this._host = host;
    this.domNode = this._createDomNode();
    this._linesCollection = new RenderedLinesCollection(() => this._host.createVisibleLine());
  }
  _createDomNode() {
    const domNode = createFastDomNode(document.createElement("div"));
    domNode.setClassName("view-layer");
    domNode.setPosition("absolute");
    domNode.domNode.setAttribute("role", "presentation");
    domNode.domNode.setAttribute("aria-hidden", "true");
    return domNode;
  }
  // ---- begin view event handlers
  onConfigurationChanged(e) {
    if (e.hasChanged(
      142
      /* EditorOption.layoutInfo */
    )) {
      return true;
    }
    return false;
  }
  onFlushed(e) {
    this._linesCollection.flush();
    return true;
  }
  onLinesChanged(e) {
    return this._linesCollection.onLinesChanged(e.fromLineNumber, e.count);
  }
  onLinesDeleted(e) {
    const deleted = this._linesCollection.onLinesDeleted(e.fromLineNumber, e.toLineNumber);
    if (deleted) {
      for (let i = 0, len = deleted.length; i < len; i++) {
        const lineDomNode = deleted[i].getDomNode();
        if (lineDomNode) {
          this.domNode.domNode.removeChild(lineDomNode);
        }
      }
    }
    return true;
  }
  onLinesInserted(e) {
    const deleted = this._linesCollection.onLinesInserted(e.fromLineNumber, e.toLineNumber);
    if (deleted) {
      for (let i = 0, len = deleted.length; i < len; i++) {
        const lineDomNode = deleted[i].getDomNode();
        if (lineDomNode) {
          this.domNode.domNode.removeChild(lineDomNode);
        }
      }
    }
    return true;
  }
  onScrollChanged(e) {
    return e.scrollTopChanged;
  }
  onTokensChanged(e) {
    return this._linesCollection.onTokensChanged(e.ranges);
  }
  onZonesChanged(e) {
    return true;
  }
  // ---- end view event handlers
  getStartLineNumber() {
    return this._linesCollection.getStartLineNumber();
  }
  getEndLineNumber() {
    return this._linesCollection.getEndLineNumber();
  }
  getVisibleLine(lineNumber) {
    return this._linesCollection.getLine(lineNumber);
  }
  renderLines(viewportData) {
    const inp = this._linesCollection._get();
    const renderer2 = new ViewLayerRenderer(this.domNode.domNode, this._host, viewportData);
    const ctx = {
      rendLineNumberStart: inp.rendLineNumberStart,
      lines: inp.lines,
      linesLength: inp.lines.length
    };
    const resCtx = renderer2.render(ctx, viewportData.startLineNumber, viewportData.endLineNumber, viewportData.relativeVerticalOffset);
    this._linesCollection._set(resCtx.rendLineNumberStart, resCtx.lines);
  }
}
class ViewLayerRenderer {
  constructor(domNode, host, viewportData) {
    this.domNode = domNode;
    this.host = host;
    this.viewportData = viewportData;
  }
  render(inContext, startLineNumber, stopLineNumber, deltaTop) {
    const ctx = {
      rendLineNumberStart: inContext.rendLineNumberStart,
      lines: inContext.lines.slice(0),
      linesLength: inContext.linesLength
    };
    if (ctx.rendLineNumberStart + ctx.linesLength - 1 < startLineNumber || stopLineNumber < ctx.rendLineNumberStart) {
      ctx.rendLineNumberStart = startLineNumber;
      ctx.linesLength = stopLineNumber - startLineNumber + 1;
      ctx.lines = [];
      for (let x = startLineNumber; x <= stopLineNumber; x++) {
        ctx.lines[x - startLineNumber] = this.host.createVisibleLine();
      }
      this._finishRendering(ctx, true, deltaTop);
      return ctx;
    }
    this._renderUntouchedLines(ctx, Math.max(startLineNumber - ctx.rendLineNumberStart, 0), Math.min(stopLineNumber - ctx.rendLineNumberStart, ctx.linesLength - 1), deltaTop, startLineNumber);
    if (ctx.rendLineNumberStart > startLineNumber) {
      const fromLineNumber = startLineNumber;
      const toLineNumber = Math.min(stopLineNumber, ctx.rendLineNumberStart - 1);
      if (fromLineNumber <= toLineNumber) {
        this._insertLinesBefore(ctx, fromLineNumber, toLineNumber, deltaTop, startLineNumber);
        ctx.linesLength += toLineNumber - fromLineNumber + 1;
      }
    } else if (ctx.rendLineNumberStart < startLineNumber) {
      const removeCnt = Math.min(ctx.linesLength, startLineNumber - ctx.rendLineNumberStart);
      if (removeCnt > 0) {
        this._removeLinesBefore(ctx, removeCnt);
        ctx.linesLength -= removeCnt;
      }
    }
    ctx.rendLineNumberStart = startLineNumber;
    if (ctx.rendLineNumberStart + ctx.linesLength - 1 < stopLineNumber) {
      const fromLineNumber = ctx.rendLineNumberStart + ctx.linesLength;
      const toLineNumber = stopLineNumber;
      if (fromLineNumber <= toLineNumber) {
        this._insertLinesAfter(ctx, fromLineNumber, toLineNumber, deltaTop, startLineNumber);
        ctx.linesLength += toLineNumber - fromLineNumber + 1;
      }
    } else if (ctx.rendLineNumberStart + ctx.linesLength - 1 > stopLineNumber) {
      const fromLineNumber = Math.max(0, stopLineNumber - ctx.rendLineNumberStart + 1);
      const toLineNumber = ctx.linesLength - 1;
      const removeCnt = toLineNumber - fromLineNumber + 1;
      if (removeCnt > 0) {
        this._removeLinesAfter(ctx, removeCnt);
        ctx.linesLength -= removeCnt;
      }
    }
    this._finishRendering(ctx, false, deltaTop);
    return ctx;
  }
  _renderUntouchedLines(ctx, startIndex, endIndex, deltaTop, deltaLN) {
    const rendLineNumberStart = ctx.rendLineNumberStart;
    const lines = ctx.lines;
    for (let i = startIndex; i <= endIndex; i++) {
      const lineNumber = rendLineNumberStart + i;
      lines[i].layoutLine(lineNumber, deltaTop[lineNumber - deltaLN]);
    }
  }
  _insertLinesBefore(ctx, fromLineNumber, toLineNumber, deltaTop, deltaLN) {
    const newLines = [];
    let newLinesLen = 0;
    for (let lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {
      newLines[newLinesLen++] = this.host.createVisibleLine();
    }
    ctx.lines = newLines.concat(ctx.lines);
  }
  _removeLinesBefore(ctx, removeCount) {
    for (let i = 0; i < removeCount; i++) {
      const lineDomNode = ctx.lines[i].getDomNode();
      if (lineDomNode) {
        this.domNode.removeChild(lineDomNode);
      }
    }
    ctx.lines.splice(0, removeCount);
  }
  _insertLinesAfter(ctx, fromLineNumber, toLineNumber, deltaTop, deltaLN) {
    const newLines = [];
    let newLinesLen = 0;
    for (let lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {
      newLines[newLinesLen++] = this.host.createVisibleLine();
    }
    ctx.lines = ctx.lines.concat(newLines);
  }
  _removeLinesAfter(ctx, removeCount) {
    const removeIndex = ctx.linesLength - removeCount;
    for (let i = 0; i < removeCount; i++) {
      const lineDomNode = ctx.lines[removeIndex + i].getDomNode();
      if (lineDomNode) {
        this.domNode.removeChild(lineDomNode);
      }
    }
    ctx.lines.splice(removeIndex, removeCount);
  }
  _finishRenderingNewLines(ctx, domNodeIsEmpty, newLinesHTML, wasNew) {
    if (ViewLayerRenderer._ttPolicy) {
      newLinesHTML = ViewLayerRenderer._ttPolicy.createHTML(newLinesHTML);
    }
    const lastChild = this.domNode.lastChild;
    if (domNodeIsEmpty || !lastChild) {
      this.domNode.innerHTML = newLinesHTML;
    } else {
      lastChild.insertAdjacentHTML("afterend", newLinesHTML);
    }
    let currChild = this.domNode.lastChild;
    for (let i = ctx.linesLength - 1; i >= 0; i--) {
      const line = ctx.lines[i];
      if (wasNew[i]) {
        line.setDomNode(currChild);
        currChild = currChild.previousSibling;
      }
    }
  }
  _finishRenderingInvalidLines(ctx, invalidLinesHTML, wasInvalid) {
    const hugeDomNode = document.createElement("div");
    if (ViewLayerRenderer._ttPolicy) {
      invalidLinesHTML = ViewLayerRenderer._ttPolicy.createHTML(invalidLinesHTML);
    }
    hugeDomNode.innerHTML = invalidLinesHTML;
    for (let i = 0; i < ctx.linesLength; i++) {
      const line = ctx.lines[i];
      if (wasInvalid[i]) {
        const source = hugeDomNode.firstChild;
        const lineDomNode = line.getDomNode();
        lineDomNode.parentNode.replaceChild(source, lineDomNode);
        line.setDomNode(source);
      }
    }
  }
  _finishRendering(ctx, domNodeIsEmpty, deltaTop) {
    const sb = ViewLayerRenderer._sb;
    const linesLength = ctx.linesLength;
    const lines = ctx.lines;
    const rendLineNumberStart = ctx.rendLineNumberStart;
    const wasNew = [];
    {
      sb.reset();
      let hadNewLine = false;
      for (let i = 0; i < linesLength; i++) {
        const line = lines[i];
        wasNew[i] = false;
        const lineDomNode = line.getDomNode();
        if (lineDomNode) {
          continue;
        }
        const renderResult = line.renderLine(i + rendLineNumberStart, deltaTop[i], this.viewportData, sb);
        if (!renderResult) {
          continue;
        }
        wasNew[i] = true;
        hadNewLine = true;
      }
      if (hadNewLine) {
        this._finishRenderingNewLines(ctx, domNodeIsEmpty, sb.build(), wasNew);
      }
    }
    {
      sb.reset();
      let hadInvalidLine = false;
      const wasInvalid = [];
      for (let i = 0; i < linesLength; i++) {
        const line = lines[i];
        wasInvalid[i] = false;
        if (wasNew[i]) {
          continue;
        }
        const renderResult = line.renderLine(i + rendLineNumberStart, deltaTop[i], this.viewportData, sb);
        if (!renderResult) {
          continue;
        }
        wasInvalid[i] = true;
        hadInvalidLine = true;
      }
      if (hadInvalidLine) {
        this._finishRenderingInvalidLines(ctx, sb.build(), wasInvalid);
      }
    }
  }
}
ViewLayerRenderer._ttPolicy = createTrustedTypesPolicy("editorViewLayer", { createHTML: (value) => value });
ViewLayerRenderer._sb = new StringBuilder(1e5);
class ViewOverlays extends ViewPart {
  constructor(context) {
    super(context);
    this._visibleLines = new VisibleLinesCollection(this);
    this.domNode = this._visibleLines.domNode;
    const options = this._context.configuration.options;
    const fontInfo = options.get(
      49
      /* EditorOption.fontInfo */
    );
    applyFontInfo(this.domNode, fontInfo);
    this._dynamicOverlays = [];
    this._isFocused = false;
    this.domNode.setClassName("view-overlays");
  }
  shouldRender() {
    if (super.shouldRender()) {
      return true;
    }
    for (let i = 0, len = this._dynamicOverlays.length; i < len; i++) {
      const dynamicOverlay = this._dynamicOverlays[i];
      if (dynamicOverlay.shouldRender()) {
        return true;
      }
    }
    return false;
  }
  dispose() {
    super.dispose();
    for (let i = 0, len = this._dynamicOverlays.length; i < len; i++) {
      const dynamicOverlay = this._dynamicOverlays[i];
      dynamicOverlay.dispose();
    }
    this._dynamicOverlays = [];
  }
  getDomNode() {
    return this.domNode;
  }
  // ---- begin IVisibleLinesHost
  createVisibleLine() {
    return new ViewOverlayLine(this._context.configuration, this._dynamicOverlays);
  }
  // ---- end IVisibleLinesHost
  addDynamicOverlay(overlay) {
    this._dynamicOverlays.push(overlay);
  }
  // ----- event handlers
  onConfigurationChanged(e) {
    this._visibleLines.onConfigurationChanged(e);
    const startLineNumber = this._visibleLines.getStartLineNumber();
    const endLineNumber = this._visibleLines.getEndLineNumber();
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      const line = this._visibleLines.getVisibleLine(lineNumber);
      line.onConfigurationChanged(e);
    }
    const options = this._context.configuration.options;
    const fontInfo = options.get(
      49
      /* EditorOption.fontInfo */
    );
    applyFontInfo(this.domNode, fontInfo);
    return true;
  }
  onFlushed(e) {
    return this._visibleLines.onFlushed(e);
  }
  onFocusChanged(e) {
    this._isFocused = e.isFocused;
    return true;
  }
  onLinesChanged(e) {
    return this._visibleLines.onLinesChanged(e);
  }
  onLinesDeleted(e) {
    return this._visibleLines.onLinesDeleted(e);
  }
  onLinesInserted(e) {
    return this._visibleLines.onLinesInserted(e);
  }
  onScrollChanged(e) {
    return this._visibleLines.onScrollChanged(e) || true;
  }
  onTokensChanged(e) {
    return this._visibleLines.onTokensChanged(e);
  }
  onZonesChanged(e) {
    return this._visibleLines.onZonesChanged(e);
  }
  // ----- end event handlers
  prepareRender(ctx) {
    const toRender = this._dynamicOverlays.filter((overlay) => overlay.shouldRender());
    for (let i = 0, len = toRender.length; i < len; i++) {
      const dynamicOverlay = toRender[i];
      dynamicOverlay.prepareRender(ctx);
      dynamicOverlay.onDidRender();
    }
  }
  render(ctx) {
    this._viewOverlaysRender(ctx);
    this.domNode.toggleClassName("focused", this._isFocused);
  }
  _viewOverlaysRender(ctx) {
    this._visibleLines.renderLines(ctx.viewportData);
  }
}
class ViewOverlayLine {
  constructor(configuration, dynamicOverlays) {
    this._configuration = configuration;
    this._lineHeight = this._configuration.options.get(
      65
      /* EditorOption.lineHeight */
    );
    this._dynamicOverlays = dynamicOverlays;
    this._domNode = null;
    this._renderedContent = null;
  }
  getDomNode() {
    if (!this._domNode) {
      return null;
    }
    return this._domNode.domNode;
  }
  setDomNode(domNode) {
    this._domNode = createFastDomNode(domNode);
  }
  onContentChanged() {
  }
  onTokensChanged() {
  }
  onConfigurationChanged(e) {
    this._lineHeight = this._configuration.options.get(
      65
      /* EditorOption.lineHeight */
    );
  }
  renderLine(lineNumber, deltaTop, viewportData, sb) {
    let result2 = "";
    for (let i = 0, len = this._dynamicOverlays.length; i < len; i++) {
      const dynamicOverlay = this._dynamicOverlays[i];
      result2 += dynamicOverlay.render(viewportData.startLineNumber, lineNumber);
    }
    if (this._renderedContent === result2) {
      return false;
    }
    this._renderedContent = result2;
    sb.appendString('<div style="position:absolute;top:');
    sb.appendString(String(deltaTop));
    sb.appendString("px;width:100%;height:");
    sb.appendString(String(this._lineHeight));
    sb.appendString('px;">');
    sb.appendString(result2);
    sb.appendString("</div>");
    return true;
  }
  layoutLine(lineNumber, deltaTop) {
    if (this._domNode) {
      this._domNode.setTop(deltaTop);
      this._domNode.setHeight(this._lineHeight);
    }
  }
}
class ContentViewOverlays extends ViewOverlays {
  constructor(context) {
    super(context);
    const options = this._context.configuration.options;
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    this._contentWidth = layoutInfo.contentWidth;
    this.domNode.setHeight(0);
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    const options = this._context.configuration.options;
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    this._contentWidth = layoutInfo.contentWidth;
    return super.onConfigurationChanged(e) || true;
  }
  onScrollChanged(e) {
    return super.onScrollChanged(e) || e.scrollWidthChanged;
  }
  // --- end event handlers
  _viewOverlaysRender(ctx) {
    super._viewOverlaysRender(ctx);
    this.domNode.setWidth(Math.max(ctx.scrollWidth, this._contentWidth));
  }
}
class MarginViewOverlays extends ViewOverlays {
  constructor(context) {
    super(context);
    const options = this._context.configuration.options;
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    this._contentLeft = layoutInfo.contentLeft;
    this.domNode.setClassName("margin-view-overlays");
    this.domNode.setWidth(1);
    applyFontInfo(this.domNode, options.get(
      49
      /* EditorOption.fontInfo */
    ));
  }
  onConfigurationChanged(e) {
    const options = this._context.configuration.options;
    applyFontInfo(this.domNode, options.get(
      49
      /* EditorOption.fontInfo */
    ));
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    this._contentLeft = layoutInfo.contentLeft;
    return super.onConfigurationChanged(e) || true;
  }
  onScrollChanged(e) {
    return super.onScrollChanged(e) || e.scrollHeightChanged;
  }
  _viewOverlaysRender(ctx) {
    super._viewOverlaysRender(ctx);
    const height = Math.min(ctx.scrollHeight, 1e6);
    this.domNode.setHeight(height);
    this.domNode.setWidth(this._contentLeft);
  }
}
class ViewContentWidgets extends ViewPart {
  constructor(context, viewDomNode) {
    super(context);
    this._viewDomNode = viewDomNode;
    this._widgets = {};
    this.domNode = createFastDomNode(document.createElement("div"));
    PartFingerprints.write(
      this.domNode,
      1
      /* PartFingerprint.ContentWidgets */
    );
    this.domNode.setClassName("contentWidgets");
    this.domNode.setPosition("absolute");
    this.domNode.setTop(0);
    this.overflowingContentWidgetsDomNode = createFastDomNode(document.createElement("div"));
    PartFingerprints.write(
      this.overflowingContentWidgetsDomNode,
      2
      /* PartFingerprint.OverflowingContentWidgets */
    );
    this.overflowingContentWidgetsDomNode.setClassName("overflowingContentWidgets");
  }
  dispose() {
    super.dispose();
    this._widgets = {};
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    const keys = Object.keys(this._widgets);
    for (const widgetId of keys) {
      this._widgets[widgetId].onConfigurationChanged(e);
    }
    return true;
  }
  onDecorationsChanged(e) {
    return true;
  }
  onFlushed(e) {
    return true;
  }
  onLineMappingChanged(e) {
    this._updateAnchorsViewPositions();
    return true;
  }
  onLinesChanged(e) {
    this._updateAnchorsViewPositions();
    return true;
  }
  onLinesDeleted(e) {
    this._updateAnchorsViewPositions();
    return true;
  }
  onLinesInserted(e) {
    this._updateAnchorsViewPositions();
    return true;
  }
  onScrollChanged(e) {
    return true;
  }
  onZonesChanged(e) {
    return true;
  }
  // ---- end view event handlers
  _updateAnchorsViewPositions() {
    const keys = Object.keys(this._widgets);
    for (const widgetId of keys) {
      this._widgets[widgetId].updateAnchorViewPosition();
    }
  }
  addWidget(_widget) {
    const myWidget = new Widget2(this._context, this._viewDomNode, _widget);
    this._widgets[myWidget.id] = myWidget;
    if (myWidget.allowEditorOverflow) {
      this.overflowingContentWidgetsDomNode.appendChild(myWidget.domNode);
    } else {
      this.domNode.appendChild(myWidget.domNode);
    }
    this.setShouldRender();
  }
  setWidgetPosition(widget, primaryAnchor, secondaryAnchor, preference, affinity) {
    const myWidget = this._widgets[widget.getId()];
    myWidget.setPosition(primaryAnchor, secondaryAnchor, preference, affinity);
    this.setShouldRender();
  }
  removeWidget(widget) {
    const widgetId = widget.getId();
    if (this._widgets.hasOwnProperty(widgetId)) {
      const myWidget = this._widgets[widgetId];
      delete this._widgets[widgetId];
      const domNode = myWidget.domNode.domNode;
      domNode.parentNode.removeChild(domNode);
      domNode.removeAttribute("monaco-visible-content-widget");
      this.setShouldRender();
    }
  }
  shouldSuppressMouseDownOnWidget(widgetId) {
    if (this._widgets.hasOwnProperty(widgetId)) {
      return this._widgets[widgetId].suppressMouseDown;
    }
    return false;
  }
  onBeforeRender(viewportData) {
    const keys = Object.keys(this._widgets);
    for (const widgetId of keys) {
      this._widgets[widgetId].onBeforeRender(viewportData);
    }
  }
  prepareRender(ctx) {
    const keys = Object.keys(this._widgets);
    for (const widgetId of keys) {
      this._widgets[widgetId].prepareRender(ctx);
    }
  }
  render(ctx) {
    const keys = Object.keys(this._widgets);
    for (const widgetId of keys) {
      this._widgets[widgetId].render(ctx);
    }
  }
}
class Widget2 {
  constructor(context, viewDomNode, actual) {
    this._primaryAnchor = new PositionPair(null, null);
    this._secondaryAnchor = new PositionPair(null, null);
    this._context = context;
    this._viewDomNode = viewDomNode;
    this._actual = actual;
    this.domNode = createFastDomNode(this._actual.getDomNode());
    this.id = this._actual.getId();
    this.allowEditorOverflow = this._actual.allowEditorOverflow || false;
    this.suppressMouseDown = this._actual.suppressMouseDown || false;
    const options = this._context.configuration.options;
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    this._fixedOverflowWidgets = options.get(
      41
      /* EditorOption.fixedOverflowWidgets */
    );
    this._contentWidth = layoutInfo.contentWidth;
    this._contentLeft = layoutInfo.contentLeft;
    this._lineHeight = options.get(
      65
      /* EditorOption.lineHeight */
    );
    this._affinity = null;
    this._preference = [];
    this._cachedDomNodeOffsetWidth = -1;
    this._cachedDomNodeOffsetHeight = -1;
    this._maxWidth = this._getMaxWidth();
    this._isVisible = false;
    this._renderData = null;
    this.domNode.setPosition(this._fixedOverflowWidgets && this.allowEditorOverflow ? "fixed" : "absolute");
    this.domNode.setDisplay("none");
    this.domNode.setVisibility("hidden");
    this.domNode.setAttribute("widgetId", this.id);
    this.domNode.setMaxWidth(this._maxWidth);
  }
  onConfigurationChanged(e) {
    const options = this._context.configuration.options;
    this._lineHeight = options.get(
      65
      /* EditorOption.lineHeight */
    );
    if (e.hasChanged(
      142
      /* EditorOption.layoutInfo */
    )) {
      const layoutInfo = options.get(
        142
        /* EditorOption.layoutInfo */
      );
      this._contentLeft = layoutInfo.contentLeft;
      this._contentWidth = layoutInfo.contentWidth;
      this._maxWidth = this._getMaxWidth();
    }
  }
  updateAnchorViewPosition() {
    this._setPosition(this._affinity, this._primaryAnchor.modelPosition, this._secondaryAnchor.modelPosition);
  }
  _setPosition(affinity, primaryAnchor, secondaryAnchor) {
    this._affinity = affinity;
    this._primaryAnchor = getValidPositionPair(primaryAnchor, this._context.viewModel, this._affinity);
    this._secondaryAnchor = getValidPositionPair(secondaryAnchor, this._context.viewModel, this._affinity);
    function getValidPositionPair(position, viewModel, affinity2) {
      if (!position) {
        return new PositionPair(null, null);
      }
      const validModelPosition = viewModel.model.validatePosition(position);
      if (viewModel.coordinatesConverter.modelPositionIsVisible(validModelPosition)) {
        const viewPosition = viewModel.coordinatesConverter.convertModelPositionToViewPosition(validModelPosition, affinity2 !== null && affinity2 !== void 0 ? affinity2 : void 0);
        return new PositionPair(position, viewPosition);
      }
      return new PositionPair(position, null);
    }
  }
  _getMaxWidth() {
    return this.allowEditorOverflow ? window.innerWidth || document.documentElement.offsetWidth || document.body.offsetWidth : this._contentWidth;
  }
  setPosition(primaryAnchor, secondaryAnchor, preference, affinity) {
    this._setPosition(affinity, primaryAnchor, secondaryAnchor);
    this._preference = preference;
    if (this._primaryAnchor.viewPosition && this._preference && this._preference.length > 0) {
      this.domNode.setDisplay("block");
    } else {
      this.domNode.setDisplay("none");
    }
    this._cachedDomNodeOffsetWidth = -1;
    this._cachedDomNodeOffsetHeight = -1;
  }
  _layoutBoxInViewport(anchor, width, height, ctx) {
    const aboveLineTop = anchor.top;
    const heightAvailableAboveLine = aboveLineTop;
    const underLineTop = anchor.top + anchor.height;
    const heightAvailableUnderLine = ctx.viewportHeight - underLineTop;
    const aboveTop = aboveLineTop - height;
    const fitsAbove = heightAvailableAboveLine >= height;
    const belowTop = underLineTop;
    const fitsBelow = heightAvailableUnderLine >= height;
    let left = anchor.left;
    if (left + width > ctx.scrollLeft + ctx.viewportWidth) {
      left = ctx.scrollLeft + ctx.viewportWidth - width;
    }
    if (left < ctx.scrollLeft) {
      left = ctx.scrollLeft;
    }
    return { fitsAbove, aboveTop, fitsBelow, belowTop, left };
  }
  _layoutHorizontalSegmentInPage(windowSize, domNodePosition, left, width) {
    const LEFT_PADDING = 15;
    const RIGHT_PADDING = 15;
    const MIN_LIMIT = Math.max(LEFT_PADDING, domNodePosition.left - width);
    const MAX_LIMIT = Math.min(domNodePosition.left + domNodePosition.width + width, windowSize.width - RIGHT_PADDING);
    let absoluteLeft = domNodePosition.left + left - window.scrollX;
    if (absoluteLeft + width > MAX_LIMIT) {
      const delta = absoluteLeft - (MAX_LIMIT - width);
      absoluteLeft -= delta;
      left -= delta;
    }
    if (absoluteLeft < MIN_LIMIT) {
      const delta = absoluteLeft - MIN_LIMIT;
      absoluteLeft -= delta;
      left -= delta;
    }
    return [left, absoluteLeft];
  }
  _layoutBoxInPage(anchor, width, height, ctx) {
    const aboveTop = anchor.top - height;
    const belowTop = anchor.top + anchor.height;
    const domNodePosition = getDomNodePagePosition(this._viewDomNode.domNode);
    const absoluteAboveTop = domNodePosition.top + aboveTop - window.scrollY;
    const absoluteBelowTop = domNodePosition.top + belowTop - window.scrollY;
    const windowSize = getClientArea(document.body);
    const [left, absoluteAboveLeft] = this._layoutHorizontalSegmentInPage(windowSize, domNodePosition, anchor.left - ctx.scrollLeft + this._contentLeft, width);
    const TOP_PADDING = 22;
    const BOTTOM_PADDING = 22;
    const fitsAbove = absoluteAboveTop >= TOP_PADDING;
    const fitsBelow = absoluteBelowTop + height <= windowSize.height - BOTTOM_PADDING;
    if (this._fixedOverflowWidgets) {
      return {
        fitsAbove,
        aboveTop: Math.max(absoluteAboveTop, TOP_PADDING),
        fitsBelow,
        belowTop: absoluteBelowTop,
        left: absoluteAboveLeft
      };
    }
    return { fitsAbove, aboveTop, fitsBelow, belowTop, left };
  }
  _prepareRenderWidgetAtExactPositionOverflowing(topLeft) {
    return new Coordinate(topLeft.top, topLeft.left + this._contentLeft);
  }
  /**
   * Compute the coordinates above and below the primary and secondary anchors.
   * The content widget *must* touch the primary anchor.
   * The content widget should touch if possible the secondary anchor.
   */
  _getAnchorsCoordinates(ctx) {
    var _a2, _b2;
    const primary = getCoordinates(this._primaryAnchor.viewPosition, this._affinity, this._lineHeight);
    const secondaryViewPosition = ((_a2 = this._secondaryAnchor.viewPosition) === null || _a2 === void 0 ? void 0 : _a2.lineNumber) === ((_b2 = this._primaryAnchor.viewPosition) === null || _b2 === void 0 ? void 0 : _b2.lineNumber) ? this._secondaryAnchor.viewPosition : null;
    const secondary = getCoordinates(secondaryViewPosition, this._affinity, this._lineHeight);
    return { primary, secondary };
    function getCoordinates(position, affinity, lineHeight) {
      if (!position) {
        return null;
      }
      const horizontalPosition = ctx.visibleRangeForPosition(position);
      if (!horizontalPosition) {
        return null;
      }
      const left = position.column === 1 && affinity === 3 ? 0 : horizontalPosition.left;
      const top = ctx.getVerticalOffsetForLineNumber(position.lineNumber) - ctx.scrollTop;
      return new AnchorCoordinate(top, left, lineHeight);
    }
  }
  _reduceAnchorCoordinates(primary, secondary, width) {
    if (!secondary) {
      return primary;
    }
    const fontInfo = this._context.configuration.options.get(
      49
      /* EditorOption.fontInfo */
    );
    let left = secondary.left;
    if (left < primary.left) {
      left = Math.max(left, primary.left - width + fontInfo.typicalFullwidthCharacterWidth);
    } else {
      left = Math.min(left, primary.left + width - fontInfo.typicalFullwidthCharacterWidth);
    }
    return new AnchorCoordinate(primary.top, left, primary.height);
  }
  _prepareRenderWidget(ctx) {
    if (!this._preference || this._preference.length === 0) {
      return null;
    }
    const { primary, secondary } = this._getAnchorsCoordinates(ctx);
    if (!primary) {
      return null;
    }
    if (this._cachedDomNodeOffsetWidth === -1 || this._cachedDomNodeOffsetHeight === -1) {
      let preferredDimensions = null;
      if (typeof this._actual.beforeRender === "function") {
        preferredDimensions = safeInvoke(this._actual.beforeRender, this._actual);
      }
      if (preferredDimensions) {
        this._cachedDomNodeOffsetWidth = preferredDimensions.width;
        this._cachedDomNodeOffsetHeight = preferredDimensions.height;
      } else {
        const domNode = this.domNode.domNode;
        const clientRect = domNode.getBoundingClientRect();
        this._cachedDomNodeOffsetWidth = Math.round(clientRect.width);
        this._cachedDomNodeOffsetHeight = Math.round(clientRect.height);
      }
    }
    const anchor = this._reduceAnchorCoordinates(primary, secondary, this._cachedDomNodeOffsetWidth);
    let placement;
    if (this.allowEditorOverflow) {
      placement = this._layoutBoxInPage(anchor, this._cachedDomNodeOffsetWidth, this._cachedDomNodeOffsetHeight, ctx);
    } else {
      placement = this._layoutBoxInViewport(anchor, this._cachedDomNodeOffsetWidth, this._cachedDomNodeOffsetHeight, ctx);
    }
    for (let pass = 1; pass <= 2; pass++) {
      for (const pref of this._preference) {
        if (pref === 1) {
          if (!placement) {
            return null;
          }
          if (pass === 2 || placement.fitsAbove) {
            return {
              coordinate: new Coordinate(placement.aboveTop, placement.left),
              position: 1
              /* ContentWidgetPositionPreference.ABOVE */
            };
          }
        } else if (pref === 2) {
          if (!placement) {
            return null;
          }
          if (pass === 2 || placement.fitsBelow) {
            return {
              coordinate: new Coordinate(placement.belowTop, placement.left),
              position: 2
              /* ContentWidgetPositionPreference.BELOW */
            };
          }
        } else {
          if (this.allowEditorOverflow) {
            return {
              coordinate: this._prepareRenderWidgetAtExactPositionOverflowing(new Coordinate(anchor.top, anchor.left)),
              position: 0
              /* ContentWidgetPositionPreference.EXACT */
            };
          } else {
            return {
              coordinate: new Coordinate(anchor.top, anchor.left),
              position: 0
              /* ContentWidgetPositionPreference.EXACT */
            };
          }
        }
      }
    }
    return null;
  }
  /**
   * On this first pass, we ensure that the content widget (if it is in the viewport) has the max width set correctly.
   */
  onBeforeRender(viewportData) {
    if (!this._primaryAnchor.viewPosition || !this._preference) {
      return;
    }
    if (this._primaryAnchor.viewPosition.lineNumber < viewportData.startLineNumber || this._primaryAnchor.viewPosition.lineNumber > viewportData.endLineNumber) {
      return;
    }
    this.domNode.setMaxWidth(this._maxWidth);
  }
  prepareRender(ctx) {
    this._renderData = this._prepareRenderWidget(ctx);
  }
  render(ctx) {
    if (!this._renderData) {
      if (this._isVisible) {
        this.domNode.removeAttribute("monaco-visible-content-widget");
        this._isVisible = false;
        this.domNode.setVisibility("hidden");
      }
      if (typeof this._actual.afterRender === "function") {
        safeInvoke(this._actual.afterRender, this._actual, null);
      }
      return;
    }
    if (this.allowEditorOverflow) {
      this.domNode.setTop(this._renderData.coordinate.top);
      this.domNode.setLeft(this._renderData.coordinate.left);
    } else {
      this.domNode.setTop(this._renderData.coordinate.top + ctx.scrollTop - ctx.bigNumbersDelta);
      this.domNode.setLeft(this._renderData.coordinate.left);
    }
    if (!this._isVisible) {
      this.domNode.setVisibility("inherit");
      this.domNode.setAttribute("monaco-visible-content-widget", "true");
      this._isVisible = true;
    }
    if (typeof this._actual.afterRender === "function") {
      safeInvoke(this._actual.afterRender, this._actual, this._renderData.position);
    }
  }
}
class PositionPair {
  constructor(modelPosition, viewPosition) {
    this.modelPosition = modelPosition;
    this.viewPosition = viewPosition;
  }
}
class Coordinate {
  constructor(top, left) {
    this.top = top;
    this.left = left;
    this._coordinateBrand = void 0;
  }
}
class AnchorCoordinate {
  constructor(top, left, height) {
    this.top = top;
    this.left = left;
    this.height = height;
    this._anchorCoordinateBrand = void 0;
  }
}
function safeInvoke(fn, thisArg, ...args) {
  try {
    return fn.call(thisArg, ...args);
  } catch (_a2) {
    return null;
  }
}
const currentLineHighlight = "";
class AbstractLineHighlightOverlay extends DynamicViewOverlay {
  constructor(context) {
    super();
    this._context = context;
    const options = this._context.configuration.options;
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    this._lineHeight = options.get(
      65
      /* EditorOption.lineHeight */
    );
    this._renderLineHighlight = options.get(
      94
      /* EditorOption.renderLineHighlight */
    );
    this._renderLineHighlightOnlyWhenFocus = options.get(
      95
      /* EditorOption.renderLineHighlightOnlyWhenFocus */
    );
    this._contentLeft = layoutInfo.contentLeft;
    this._contentWidth = layoutInfo.contentWidth;
    this._selectionIsEmpty = true;
    this._focused = false;
    this._cursorLineNumbers = [1];
    this._selections = [new Selection$1(1, 1, 1, 1)];
    this._renderData = null;
    this._context.addEventHandler(this);
  }
  dispose() {
    this._context.removeEventHandler(this);
    super.dispose();
  }
  _readFromSelections() {
    let hasChanged2 = false;
    const cursorsLineNumbers = this._selections.map((s) => s.positionLineNumber);
    cursorsLineNumbers.sort((a, b) => a - b);
    if (!equals$3(this._cursorLineNumbers, cursorsLineNumbers)) {
      this._cursorLineNumbers = cursorsLineNumbers;
      hasChanged2 = true;
    }
    const selectionIsEmpty = this._selections.every((s) => s.isEmpty());
    if (this._selectionIsEmpty !== selectionIsEmpty) {
      this._selectionIsEmpty = selectionIsEmpty;
      hasChanged2 = true;
    }
    return hasChanged2;
  }
  // --- begin event handlers
  onThemeChanged(e) {
    return this._readFromSelections();
  }
  onConfigurationChanged(e) {
    const options = this._context.configuration.options;
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    this._lineHeight = options.get(
      65
      /* EditorOption.lineHeight */
    );
    this._renderLineHighlight = options.get(
      94
      /* EditorOption.renderLineHighlight */
    );
    this._renderLineHighlightOnlyWhenFocus = options.get(
      95
      /* EditorOption.renderLineHighlightOnlyWhenFocus */
    );
    this._contentLeft = layoutInfo.contentLeft;
    this._contentWidth = layoutInfo.contentWidth;
    return true;
  }
  onCursorStateChanged(e) {
    this._selections = e.selections;
    return this._readFromSelections();
  }
  onFlushed(e) {
    return true;
  }
  onLinesDeleted(e) {
    return true;
  }
  onLinesInserted(e) {
    return true;
  }
  onScrollChanged(e) {
    return e.scrollWidthChanged || e.scrollTopChanged;
  }
  onZonesChanged(e) {
    return true;
  }
  onFocusChanged(e) {
    if (!this._renderLineHighlightOnlyWhenFocus) {
      return false;
    }
    this._focused = e.isFocused;
    return true;
  }
  // --- end event handlers
  prepareRender(ctx) {
    if (!this._shouldRenderThis()) {
      this._renderData = null;
      return;
    }
    const renderedLine = this._renderOne(ctx);
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    const len = this._cursorLineNumbers.length;
    let index = 0;
    const renderData = [];
    for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
      const lineIndex = lineNumber - visibleStartLineNumber;
      while (index < len && this._cursorLineNumbers[index] < lineNumber) {
        index++;
      }
      if (index < len && this._cursorLineNumbers[index] === lineNumber) {
        renderData[lineIndex] = renderedLine;
      } else {
        renderData[lineIndex] = "";
      }
    }
    this._renderData = renderData;
  }
  render(startLineNumber, lineNumber) {
    if (!this._renderData) {
      return "";
    }
    const lineIndex = lineNumber - startLineNumber;
    if (lineIndex >= this._renderData.length) {
      return "";
    }
    return this._renderData[lineIndex];
  }
  _shouldRenderInMargin() {
    return (this._renderLineHighlight === "gutter" || this._renderLineHighlight === "all") && (!this._renderLineHighlightOnlyWhenFocus || this._focused);
  }
  _shouldRenderInContent() {
    return (this._renderLineHighlight === "line" || this._renderLineHighlight === "all") && this._selectionIsEmpty && (!this._renderLineHighlightOnlyWhenFocus || this._focused);
  }
}
class CurrentLineHighlightOverlay extends AbstractLineHighlightOverlay {
  _renderOne(ctx) {
    const className3 = "current-line" + (this._shouldRenderOther() ? " current-line-both" : "");
    return `<div class="${className3}" style="width:${Math.max(ctx.scrollWidth, this._contentWidth)}px; height:${this._lineHeight}px;"></div>`;
  }
  _shouldRenderThis() {
    return this._shouldRenderInContent();
  }
  _shouldRenderOther() {
    return this._shouldRenderInMargin();
  }
}
class CurrentLineMarginHighlightOverlay extends AbstractLineHighlightOverlay {
  _renderOne(ctx) {
    const className3 = "current-line" + (this._shouldRenderInMargin() ? " current-line-margin" : "") + (this._shouldRenderOther() ? " current-line-margin-both" : "");
    return `<div class="${className3}" style="width:${this._contentLeft}px; height:${this._lineHeight}px;"></div>`;
  }
  _shouldRenderThis() {
    return true;
  }
  _shouldRenderOther() {
    return this._shouldRenderInContent();
  }
}
registerThemingParticipant((theme, collector) => {
  const lineHighlight = theme.getColor(editorLineHighlight);
  if (lineHighlight) {
    collector.addRule(`.monaco-editor .view-overlays .current-line { background-color: ${lineHighlight}; }`);
    collector.addRule(`.monaco-editor .margin-view-overlays .current-line-margin { background-color: ${lineHighlight}; border: none; }`);
  }
  if (!lineHighlight || lineHighlight.isTransparent() || theme.defines(editorLineHighlightBorder)) {
    const lineHighlightBorder = theme.getColor(editorLineHighlightBorder);
    if (lineHighlightBorder) {
      collector.addRule(`.monaco-editor .view-overlays .current-line { border: 2px solid ${lineHighlightBorder}; }`);
      collector.addRule(`.monaco-editor .margin-view-overlays .current-line-margin { border: 2px solid ${lineHighlightBorder}; }`);
      if (isHighContrast(theme.type)) {
        collector.addRule(`.monaco-editor .view-overlays .current-line { border-width: 1px; }`);
        collector.addRule(`.monaco-editor .margin-view-overlays .current-line-margin { border-width: 1px; }`);
      }
    }
  }
});
const decorations = "";
class DecorationsOverlay extends DynamicViewOverlay {
  constructor(context) {
    super();
    this._context = context;
    const options = this._context.configuration.options;
    this._lineHeight = options.get(
      65
      /* EditorOption.lineHeight */
    );
    this._typicalHalfwidthCharacterWidth = options.get(
      49
      /* EditorOption.fontInfo */
    ).typicalHalfwidthCharacterWidth;
    this._renderResult = null;
    this._context.addEventHandler(this);
  }
  dispose() {
    this._context.removeEventHandler(this);
    this._renderResult = null;
    super.dispose();
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    const options = this._context.configuration.options;
    this._lineHeight = options.get(
      65
      /* EditorOption.lineHeight */
    );
    this._typicalHalfwidthCharacterWidth = options.get(
      49
      /* EditorOption.fontInfo */
    ).typicalHalfwidthCharacterWidth;
    return true;
  }
  onDecorationsChanged(e) {
    return true;
  }
  onFlushed(e) {
    return true;
  }
  onLinesChanged(e) {
    return true;
  }
  onLinesDeleted(e) {
    return true;
  }
  onLinesInserted(e) {
    return true;
  }
  onScrollChanged(e) {
    return e.scrollTopChanged || e.scrollWidthChanged;
  }
  onZonesChanged(e) {
    return true;
  }
  // --- end event handlers
  prepareRender(ctx) {
    const _decorations = ctx.getDecorationsInViewport();
    let decorations2 = [];
    let decorationsLen = 0;
    for (let i = 0, len = _decorations.length; i < len; i++) {
      const d = _decorations[i];
      if (d.options.className) {
        decorations2[decorationsLen++] = d;
      }
    }
    decorations2 = decorations2.sort((a, b) => {
      if (a.options.zIndex < b.options.zIndex) {
        return -1;
      }
      if (a.options.zIndex > b.options.zIndex) {
        return 1;
      }
      const aClassName = a.options.className;
      const bClassName = b.options.className;
      if (aClassName < bClassName) {
        return -1;
      }
      if (aClassName > bClassName) {
        return 1;
      }
      return Range$2.compareRangesUsingStarts(a.range, b.range);
    });
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    const output = [];
    for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
      const lineIndex = lineNumber - visibleStartLineNumber;
      output[lineIndex] = "";
    }
    this._renderWholeLineDecorations(ctx, decorations2, output);
    this._renderNormalDecorations(ctx, decorations2, output);
    this._renderResult = output;
  }
  _renderWholeLineDecorations(ctx, decorations2, output) {
    const lineHeight = String(this._lineHeight);
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    for (let i = 0, lenI = decorations2.length; i < lenI; i++) {
      const d = decorations2[i];
      if (!d.options.isWholeLine) {
        continue;
      }
      const decorationOutput = '<div class="cdr ' + d.options.className + '" style="left:0;width:100%;height:' + lineHeight + 'px;"></div>';
      const startLineNumber = Math.max(d.range.startLineNumber, visibleStartLineNumber);
      const endLineNumber = Math.min(d.range.endLineNumber, visibleEndLineNumber);
      for (let j = startLineNumber; j <= endLineNumber; j++) {
        const lineIndex = j - visibleStartLineNumber;
        output[lineIndex] += decorationOutput;
      }
    }
  }
  _renderNormalDecorations(ctx, decorations2, output) {
    var _a2;
    const lineHeight = String(this._lineHeight);
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    let prevClassName = null;
    let prevShowIfCollapsed = false;
    let prevRange = null;
    let prevShouldFillLineOnLineBreak = false;
    for (let i = 0, lenI = decorations2.length; i < lenI; i++) {
      const d = decorations2[i];
      if (d.options.isWholeLine) {
        continue;
      }
      const className3 = d.options.className;
      const showIfCollapsed = Boolean(d.options.showIfCollapsed);
      let range2 = d.range;
      if (showIfCollapsed && range2.endColumn === 1 && range2.endLineNumber !== range2.startLineNumber) {
        range2 = new Range$2(range2.startLineNumber, range2.startColumn, range2.endLineNumber - 1, this._context.viewModel.getLineMaxColumn(range2.endLineNumber - 1));
      }
      if (prevClassName === className3 && prevShowIfCollapsed === showIfCollapsed && Range$2.areIntersectingOrTouching(prevRange, range2)) {
        prevRange = Range$2.plusRange(prevRange, range2);
        continue;
      }
      if (prevClassName !== null) {
        this._renderNormalDecoration(ctx, prevRange, prevClassName, prevShouldFillLineOnLineBreak, prevShowIfCollapsed, lineHeight, visibleStartLineNumber, output);
      }
      prevClassName = className3;
      prevShowIfCollapsed = showIfCollapsed;
      prevRange = range2;
      prevShouldFillLineOnLineBreak = (_a2 = d.options.shouldFillLineOnLineBreak) !== null && _a2 !== void 0 ? _a2 : false;
    }
    if (prevClassName !== null) {
      this._renderNormalDecoration(ctx, prevRange, prevClassName, prevShouldFillLineOnLineBreak, prevShowIfCollapsed, lineHeight, visibleStartLineNumber, output);
    }
  }
  _renderNormalDecoration(ctx, range2, className3, shouldFillLineOnLineBreak, showIfCollapsed, lineHeight, visibleStartLineNumber, output) {
    const linesVisibleRanges = ctx.linesVisibleRangesForRange(
      range2,
      /*TODO@Alex*/
      className3 === "findMatch"
    );
    if (!linesVisibleRanges) {
      return;
    }
    for (let j = 0, lenJ = linesVisibleRanges.length; j < lenJ; j++) {
      const lineVisibleRanges = linesVisibleRanges[j];
      if (lineVisibleRanges.outsideRenderedLine) {
        continue;
      }
      const lineIndex = lineVisibleRanges.lineNumber - visibleStartLineNumber;
      if (showIfCollapsed && lineVisibleRanges.ranges.length === 1) {
        const singleVisibleRange = lineVisibleRanges.ranges[0];
        if (singleVisibleRange.width < this._typicalHalfwidthCharacterWidth) {
          const center = Math.round(singleVisibleRange.left + singleVisibleRange.width / 2);
          const left = Math.max(0, Math.round(center - this._typicalHalfwidthCharacterWidth / 2));
          lineVisibleRanges.ranges[0] = new HorizontalRange(left, this._typicalHalfwidthCharacterWidth);
        }
      }
      for (let k = 0, lenK = lineVisibleRanges.ranges.length; k < lenK; k++) {
        const expandToLeft = shouldFillLineOnLineBreak && lineVisibleRanges.continuesOnNextLine && lenK === 1;
        const visibleRange = lineVisibleRanges.ranges[k];
        const decorationOutput = '<div class="cdr ' + className3 + '" style="left:' + String(visibleRange.left) + (expandToLeft ? "px;width:100%;height:" : "px;width:" + String(visibleRange.width) + "px;height:") + lineHeight + 'px;"></div>';
        output[lineIndex] += decorationOutput;
      }
    }
  }
  render(startLineNumber, lineNumber) {
    if (!this._renderResult) {
      return "";
    }
    const lineIndex = lineNumber - startLineNumber;
    if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
      return "";
    }
    return this._renderResult[lineIndex];
  }
}
class EditorScrollbar2 extends ViewPart {
  constructor(context, linesContent, viewDomNode, overflowGuardDomNode) {
    super(context);
    const options = this._context.configuration.options;
    const scrollbar = options.get(
      101
      /* EditorOption.scrollbar */
    );
    const mouseWheelScrollSensitivity = options.get(
      73
      /* EditorOption.mouseWheelScrollSensitivity */
    );
    const fastScrollSensitivity = options.get(
      39
      /* EditorOption.fastScrollSensitivity */
    );
    const scrollPredominantAxis = options.get(
      104
      /* EditorOption.scrollPredominantAxis */
    );
    const scrollbarOptions = {
      listenOnDomNode: viewDomNode.domNode,
      className: "editor-scrollable " + getThemeTypeSelector(context.theme.type),
      useShadows: false,
      lazyRender: true,
      vertical: scrollbar.vertical,
      horizontal: scrollbar.horizontal,
      verticalHasArrows: scrollbar.verticalHasArrows,
      horizontalHasArrows: scrollbar.horizontalHasArrows,
      verticalScrollbarSize: scrollbar.verticalScrollbarSize,
      verticalSliderSize: scrollbar.verticalSliderSize,
      horizontalScrollbarSize: scrollbar.horizontalScrollbarSize,
      horizontalSliderSize: scrollbar.horizontalSliderSize,
      handleMouseWheel: scrollbar.handleMouseWheel,
      alwaysConsumeMouseWheel: scrollbar.alwaysConsumeMouseWheel,
      arrowSize: scrollbar.arrowSize,
      mouseWheelScrollSensitivity,
      fastScrollSensitivity,
      scrollPredominantAxis,
      scrollByPage: scrollbar.scrollByPage
    };
    this.scrollbar = this._register(new SmoothScrollableElement(linesContent.domNode, scrollbarOptions, this._context.viewLayout.getScrollable()));
    PartFingerprints.write(
      this.scrollbar.getDomNode(),
      5
      /* PartFingerprint.ScrollableElement */
    );
    this.scrollbarDomNode = createFastDomNode(this.scrollbar.getDomNode());
    this.scrollbarDomNode.setPosition("absolute");
    this._setLayout();
    const onBrowserDesperateReveal = (domNode, lookAtScrollTop, lookAtScrollLeft) => {
      const newScrollPosition = {};
      if (lookAtScrollTop) {
        const deltaTop = domNode.scrollTop;
        if (deltaTop) {
          newScrollPosition.scrollTop = this._context.viewLayout.getCurrentScrollTop() + deltaTop;
          domNode.scrollTop = 0;
        }
      }
      if (lookAtScrollLeft) {
        const deltaLeft = domNode.scrollLeft;
        if (deltaLeft) {
          newScrollPosition.scrollLeft = this._context.viewLayout.getCurrentScrollLeft() + deltaLeft;
          domNode.scrollLeft = 0;
        }
      }
      this._context.viewModel.viewLayout.setScrollPosition(
        newScrollPosition,
        1
        /* ScrollType.Immediate */
      );
    };
    this._register(addDisposableListener(viewDomNode.domNode, "scroll", (e) => onBrowserDesperateReveal(viewDomNode.domNode, true, true)));
    this._register(addDisposableListener(linesContent.domNode, "scroll", (e) => onBrowserDesperateReveal(linesContent.domNode, true, false)));
    this._register(addDisposableListener(overflowGuardDomNode.domNode, "scroll", (e) => onBrowserDesperateReveal(overflowGuardDomNode.domNode, true, false)));
    this._register(addDisposableListener(this.scrollbarDomNode.domNode, "scroll", (e) => onBrowserDesperateReveal(this.scrollbarDomNode.domNode, true, false)));
  }
  dispose() {
    super.dispose();
  }
  _setLayout() {
    const options = this._context.configuration.options;
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    this.scrollbarDomNode.setLeft(layoutInfo.contentLeft);
    const minimap2 = options.get(
      71
      /* EditorOption.minimap */
    );
    const side = minimap2.side;
    if (side === "right") {
      this.scrollbarDomNode.setWidth(layoutInfo.contentWidth + layoutInfo.minimap.minimapWidth);
    } else {
      this.scrollbarDomNode.setWidth(layoutInfo.contentWidth);
    }
    this.scrollbarDomNode.setHeight(layoutInfo.height);
  }
  getOverviewRulerLayoutInfo() {
    return this.scrollbar.getOverviewRulerLayoutInfo();
  }
  getDomNode() {
    return this.scrollbarDomNode;
  }
  delegateVerticalScrollbarPointerDown(browserEvent) {
    this.scrollbar.delegateVerticalScrollbarPointerDown(browserEvent);
  }
  delegateScrollFromMouseWheelEvent(browserEvent) {
    this.scrollbar.delegateScrollFromMouseWheelEvent(browserEvent);
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    if (e.hasChanged(
      101
      /* EditorOption.scrollbar */
    ) || e.hasChanged(
      73
      /* EditorOption.mouseWheelScrollSensitivity */
    ) || e.hasChanged(
      39
      /* EditorOption.fastScrollSensitivity */
    )) {
      const options = this._context.configuration.options;
      const scrollbar = options.get(
        101
        /* EditorOption.scrollbar */
      );
      const mouseWheelScrollSensitivity = options.get(
        73
        /* EditorOption.mouseWheelScrollSensitivity */
      );
      const fastScrollSensitivity = options.get(
        39
        /* EditorOption.fastScrollSensitivity */
      );
      const scrollPredominantAxis = options.get(
        104
        /* EditorOption.scrollPredominantAxis */
      );
      const newOpts = {
        vertical: scrollbar.vertical,
        horizontal: scrollbar.horizontal,
        verticalScrollbarSize: scrollbar.verticalScrollbarSize,
        horizontalScrollbarSize: scrollbar.horizontalScrollbarSize,
        scrollByPage: scrollbar.scrollByPage,
        handleMouseWheel: scrollbar.handleMouseWheel,
        mouseWheelScrollSensitivity,
        fastScrollSensitivity,
        scrollPredominantAxis
      };
      this.scrollbar.updateOptions(newOpts);
    }
    if (e.hasChanged(
      142
      /* EditorOption.layoutInfo */
    )) {
      this._setLayout();
    }
    return true;
  }
  onScrollChanged(e) {
    return true;
  }
  onThemeChanged(e) {
    this.scrollbar.updateClassName("editor-scrollable " + getThemeTypeSelector(this._context.theme.type));
    return true;
  }
  // --- end event handlers
  prepareRender(ctx) {
  }
  render(ctx) {
    this.scrollbar.renderNow();
  }
}
const indentGuides = "";
class TextModelPart extends Disposable {
  constructor() {
    super(...arguments);
    this._isDisposed = false;
  }
  dispose() {
    super.dispose();
    this._isDisposed = true;
  }
  assertNotDisposed() {
    if (this._isDisposed) {
      throw new Error("TextModelPart is disposed!");
    }
  }
}
function computeIndentLevel(line, tabSize) {
  let indent = 0;
  let i = 0;
  const len = line.length;
  while (i < len) {
    const chCode = line.charCodeAt(i);
    if (chCode === 32) {
      indent++;
    } else if (chCode === 9) {
      indent = indent - indent % tabSize + tabSize;
    } else {
      break;
    }
    i++;
  }
  if (i === len) {
    return -1;
  }
  return indent;
}
var HorizontalGuidesState;
(function(HorizontalGuidesState2) {
  HorizontalGuidesState2[HorizontalGuidesState2["Disabled"] = 0] = "Disabled";
  HorizontalGuidesState2[HorizontalGuidesState2["EnabledForActive"] = 1] = "EnabledForActive";
  HorizontalGuidesState2[HorizontalGuidesState2["Enabled"] = 2] = "Enabled";
})(HorizontalGuidesState || (HorizontalGuidesState = {}));
class IndentGuide {
  constructor(visibleColumn, column, className3, horizontalLine, forWrappedLinesAfterColumn, forWrappedLinesBeforeOrAtColumn) {
    this.visibleColumn = visibleColumn;
    this.column = column;
    this.className = className3;
    this.horizontalLine = horizontalLine;
    this.forWrappedLinesAfterColumn = forWrappedLinesAfterColumn;
    this.forWrappedLinesBeforeOrAtColumn = forWrappedLinesBeforeOrAtColumn;
    if (visibleColumn !== -1 === (column !== -1)) {
      throw new Error();
    }
  }
}
class IndentGuideHorizontalLine {
  constructor(top, endColumn) {
    this.top = top;
    this.endColumn = endColumn;
  }
}
class GuidesTextModelPart extends TextModelPart {
  constructor(textModel, languageConfigurationService) {
    super();
    this.textModel = textModel;
    this.languageConfigurationService = languageConfigurationService;
  }
  getLanguageConfiguration(languageId) {
    return this.languageConfigurationService.getLanguageConfiguration(languageId);
  }
  _computeIndentLevel(lineIndex) {
    return computeIndentLevel(this.textModel.getLineContent(lineIndex + 1), this.textModel.getOptions().tabSize);
  }
  getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber) {
    this.assertNotDisposed();
    const lineCount = this.textModel.getLineCount();
    if (lineNumber < 1 || lineNumber > lineCount) {
      throw new BugIndicatingError("Illegal value for lineNumber");
    }
    const foldingRules = this.getLanguageConfiguration(this.textModel.getLanguageId()).foldingRules;
    const offSide = Boolean(foldingRules && foldingRules.offSide);
    let up_aboveContentLineIndex = -2;
    let up_aboveContentLineIndent = -1;
    let up_belowContentLineIndex = -2;
    let up_belowContentLineIndent = -1;
    const up_resolveIndents = (lineNumber2) => {
      if (up_aboveContentLineIndex !== -1 && (up_aboveContentLineIndex === -2 || up_aboveContentLineIndex > lineNumber2 - 1)) {
        up_aboveContentLineIndex = -1;
        up_aboveContentLineIndent = -1;
        for (let lineIndex = lineNumber2 - 2; lineIndex >= 0; lineIndex--) {
          const indent2 = this._computeIndentLevel(lineIndex);
          if (indent2 >= 0) {
            up_aboveContentLineIndex = lineIndex;
            up_aboveContentLineIndent = indent2;
            break;
          }
        }
      }
      if (up_belowContentLineIndex === -2) {
        up_belowContentLineIndex = -1;
        up_belowContentLineIndent = -1;
        for (let lineIndex = lineNumber2; lineIndex < lineCount; lineIndex++) {
          const indent2 = this._computeIndentLevel(lineIndex);
          if (indent2 >= 0) {
            up_belowContentLineIndex = lineIndex;
            up_belowContentLineIndent = indent2;
            break;
          }
        }
      }
    };
    let down_aboveContentLineIndex = -2;
    let down_aboveContentLineIndent = -1;
    let down_belowContentLineIndex = -2;
    let down_belowContentLineIndent = -1;
    const down_resolveIndents = (lineNumber2) => {
      if (down_aboveContentLineIndex === -2) {
        down_aboveContentLineIndex = -1;
        down_aboveContentLineIndent = -1;
        for (let lineIndex = lineNumber2 - 2; lineIndex >= 0; lineIndex--) {
          const indent2 = this._computeIndentLevel(lineIndex);
          if (indent2 >= 0) {
            down_aboveContentLineIndex = lineIndex;
            down_aboveContentLineIndent = indent2;
            break;
          }
        }
      }
      if (down_belowContentLineIndex !== -1 && (down_belowContentLineIndex === -2 || down_belowContentLineIndex < lineNumber2 - 1)) {
        down_belowContentLineIndex = -1;
        down_belowContentLineIndent = -1;
        for (let lineIndex = lineNumber2; lineIndex < lineCount; lineIndex++) {
          const indent2 = this._computeIndentLevel(lineIndex);
          if (indent2 >= 0) {
            down_belowContentLineIndex = lineIndex;
            down_belowContentLineIndent = indent2;
            break;
          }
        }
      }
    };
    let startLineNumber = 0;
    let goUp = true;
    let endLineNumber = 0;
    let goDown = true;
    let indent = 0;
    let initialIndent = 0;
    for (let distance = 0; goUp || goDown; distance++) {
      const upLineNumber = lineNumber - distance;
      const downLineNumber = lineNumber + distance;
      if (distance > 1 && (upLineNumber < 1 || upLineNumber < minLineNumber)) {
        goUp = false;
      }
      if (distance > 1 && (downLineNumber > lineCount || downLineNumber > maxLineNumber)) {
        goDown = false;
      }
      if (distance > 5e4) {
        goUp = false;
        goDown = false;
      }
      let upLineIndentLevel = -1;
      if (goUp && upLineNumber >= 1) {
        const currentIndent = this._computeIndentLevel(upLineNumber - 1);
        if (currentIndent >= 0) {
          up_belowContentLineIndex = upLineNumber - 1;
          up_belowContentLineIndent = currentIndent;
          upLineIndentLevel = Math.ceil(currentIndent / this.textModel.getOptions().indentSize);
        } else {
          up_resolveIndents(upLineNumber);
          upLineIndentLevel = this._getIndentLevelForWhitespaceLine(offSide, up_aboveContentLineIndent, up_belowContentLineIndent);
        }
      }
      let downLineIndentLevel = -1;
      if (goDown && downLineNumber <= lineCount) {
        const currentIndent = this._computeIndentLevel(downLineNumber - 1);
        if (currentIndent >= 0) {
          down_aboveContentLineIndex = downLineNumber - 1;
          down_aboveContentLineIndent = currentIndent;
          downLineIndentLevel = Math.ceil(currentIndent / this.textModel.getOptions().indentSize);
        } else {
          down_resolveIndents(downLineNumber);
          downLineIndentLevel = this._getIndentLevelForWhitespaceLine(offSide, down_aboveContentLineIndent, down_belowContentLineIndent);
        }
      }
      if (distance === 0) {
        initialIndent = upLineIndentLevel;
        continue;
      }
      if (distance === 1) {
        if (downLineNumber <= lineCount && downLineIndentLevel >= 0 && initialIndent + 1 === downLineIndentLevel) {
          goUp = false;
          startLineNumber = downLineNumber;
          endLineNumber = downLineNumber;
          indent = downLineIndentLevel;
          continue;
        }
        if (upLineNumber >= 1 && upLineIndentLevel >= 0 && upLineIndentLevel - 1 === initialIndent) {
          goDown = false;
          startLineNumber = upLineNumber;
          endLineNumber = upLineNumber;
          indent = upLineIndentLevel;
          continue;
        }
        startLineNumber = lineNumber;
        endLineNumber = lineNumber;
        indent = initialIndent;
        if (indent === 0) {
          return { startLineNumber, endLineNumber, indent };
        }
      }
      if (goUp) {
        if (upLineIndentLevel >= indent) {
          startLineNumber = upLineNumber;
        } else {
          goUp = false;
        }
      }
      if (goDown) {
        if (downLineIndentLevel >= indent) {
          endLineNumber = downLineNumber;
        } else {
          goDown = false;
        }
      }
    }
    return { startLineNumber, endLineNumber, indent };
  }
  getLinesBracketGuides(startLineNumber, endLineNumber, activePosition, options) {
    var _a2;
    const result2 = [];
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      result2.push([]);
    }
    const includeSingleLinePairs = true;
    const bracketPairs = this.textModel.bracketPairs.getBracketPairsInRangeWithMinIndentation(new Range$2(startLineNumber, 1, endLineNumber, this.textModel.getLineMaxColumn(endLineNumber))).toArray();
    let activeBracketPairRange = void 0;
    if (activePosition && bracketPairs.length > 0) {
      const bracketsContainingActivePosition = (startLineNumber <= activePosition.lineNumber && activePosition.lineNumber <= endLineNumber ? bracketPairs : this.textModel.bracketPairs.getBracketPairsInRange(Range$2.fromPositions(activePosition)).toArray()).filter((bp) => Range$2.strictContainsPosition(bp.range, activePosition));
      activeBracketPairRange = (_a2 = findLast(bracketsContainingActivePosition, (i) => includeSingleLinePairs)) === null || _a2 === void 0 ? void 0 : _a2.range;
    }
    const independentColorPoolPerBracketType = this.textModel.getOptions().bracketPairColorizationOptions.independentColorPoolPerBracketType;
    const colorProvider = new BracketPairGuidesClassNames();
    for (const pair of bracketPairs) {
      if (!pair.closingBracketRange) {
        continue;
      }
      const isActive = activeBracketPairRange && pair.range.equalsRange(activeBracketPairRange);
      if (!isActive && !options.includeInactive) {
        continue;
      }
      const className3 = colorProvider.getInlineClassName(pair.nestingLevel, pair.nestingLevelOfEqualBracketType, independentColorPoolPerBracketType) + (options.highlightActive && isActive ? " " + colorProvider.activeClassName : "");
      const start = pair.openingBracketRange.getStartPosition();
      const end = pair.closingBracketRange.getStartPosition();
      const horizontalGuides = options.horizontalGuides === HorizontalGuidesState.Enabled || options.horizontalGuides === HorizontalGuidesState.EnabledForActive && isActive;
      if (pair.range.startLineNumber === pair.range.endLineNumber) {
        if (horizontalGuides) {
          result2[pair.range.startLineNumber - startLineNumber].push(new IndentGuide(-1, pair.openingBracketRange.getEndPosition().column, className3, new IndentGuideHorizontalLine(false, end.column), -1, -1));
        }
        continue;
      }
      const endVisibleColumn = this.getVisibleColumnFromPosition(end);
      const startVisibleColumn = this.getVisibleColumnFromPosition(pair.openingBracketRange.getStartPosition());
      const guideVisibleColumn = Math.min(startVisibleColumn, endVisibleColumn, pair.minVisibleColumnIndentation + 1);
      let renderHorizontalEndLineAtTheBottom = false;
      const firstNonWsIndex = firstNonWhitespaceIndex(this.textModel.getLineContent(pair.closingBracketRange.startLineNumber));
      const hasTextBeforeClosingBracket = firstNonWsIndex < pair.closingBracketRange.startColumn - 1;
      if (hasTextBeforeClosingBracket) {
        renderHorizontalEndLineAtTheBottom = true;
      }
      const visibleGuideStartLineNumber = Math.max(start.lineNumber, startLineNumber);
      const visibleGuideEndLineNumber = Math.min(end.lineNumber, endLineNumber);
      const offset = renderHorizontalEndLineAtTheBottom ? 1 : 0;
      for (let l = visibleGuideStartLineNumber; l < visibleGuideEndLineNumber + offset; l++) {
        result2[l - startLineNumber].push(new IndentGuide(guideVisibleColumn, -1, className3, null, l === start.lineNumber ? start.column : -1, l === end.lineNumber ? end.column : -1));
      }
      if (horizontalGuides) {
        if (start.lineNumber >= startLineNumber && startVisibleColumn > guideVisibleColumn) {
          result2[start.lineNumber - startLineNumber].push(new IndentGuide(guideVisibleColumn, -1, className3, new IndentGuideHorizontalLine(false, start.column), -1, -1));
        }
        if (end.lineNumber <= endLineNumber && endVisibleColumn > guideVisibleColumn) {
          result2[end.lineNumber - startLineNumber].push(new IndentGuide(guideVisibleColumn, -1, className3, new IndentGuideHorizontalLine(!renderHorizontalEndLineAtTheBottom, end.column), -1, -1));
        }
      }
    }
    for (const guides of result2) {
      guides.sort((a, b) => a.visibleColumn - b.visibleColumn);
    }
    return result2;
  }
  getVisibleColumnFromPosition(position) {
    return CursorColumns.visibleColumnFromColumn(this.textModel.getLineContent(position.lineNumber), position.column, this.textModel.getOptions().tabSize) + 1;
  }
  getLinesIndentGuides(startLineNumber, endLineNumber) {
    this.assertNotDisposed();
    const lineCount = this.textModel.getLineCount();
    if (startLineNumber < 1 || startLineNumber > lineCount) {
      throw new Error("Illegal value for startLineNumber");
    }
    if (endLineNumber < 1 || endLineNumber > lineCount) {
      throw new Error("Illegal value for endLineNumber");
    }
    const options = this.textModel.getOptions();
    const foldingRules = this.getLanguageConfiguration(this.textModel.getLanguageId()).foldingRules;
    const offSide = Boolean(foldingRules && foldingRules.offSide);
    const result2 = new Array(endLineNumber - startLineNumber + 1);
    let aboveContentLineIndex = -2;
    let aboveContentLineIndent = -1;
    let belowContentLineIndex = -2;
    let belowContentLineIndent = -1;
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      const resultIndex = lineNumber - startLineNumber;
      const currentIndent = this._computeIndentLevel(lineNumber - 1);
      if (currentIndent >= 0) {
        aboveContentLineIndex = lineNumber - 1;
        aboveContentLineIndent = currentIndent;
        result2[resultIndex] = Math.ceil(currentIndent / options.indentSize);
        continue;
      }
      if (aboveContentLineIndex === -2) {
        aboveContentLineIndex = -1;
        aboveContentLineIndent = -1;
        for (let lineIndex = lineNumber - 2; lineIndex >= 0; lineIndex--) {
          const indent = this._computeIndentLevel(lineIndex);
          if (indent >= 0) {
            aboveContentLineIndex = lineIndex;
            aboveContentLineIndent = indent;
            break;
          }
        }
      }
      if (belowContentLineIndex !== -1 && (belowContentLineIndex === -2 || belowContentLineIndex < lineNumber - 1)) {
        belowContentLineIndex = -1;
        belowContentLineIndent = -1;
        for (let lineIndex = lineNumber; lineIndex < lineCount; lineIndex++) {
          const indent = this._computeIndentLevel(lineIndex);
          if (indent >= 0) {
            belowContentLineIndex = lineIndex;
            belowContentLineIndent = indent;
            break;
          }
        }
      }
      result2[resultIndex] = this._getIndentLevelForWhitespaceLine(offSide, aboveContentLineIndent, belowContentLineIndent);
    }
    return result2;
  }
  _getIndentLevelForWhitespaceLine(offSide, aboveContentLineIndent, belowContentLineIndent) {
    const options = this.textModel.getOptions();
    if (aboveContentLineIndent === -1 || belowContentLineIndent === -1) {
      return 0;
    } else if (aboveContentLineIndent < belowContentLineIndent) {
      return 1 + Math.floor(aboveContentLineIndent / options.indentSize);
    } else if (aboveContentLineIndent === belowContentLineIndent) {
      return Math.ceil(belowContentLineIndent / options.indentSize);
    } else {
      if (offSide) {
        return Math.ceil(belowContentLineIndent / options.indentSize);
      } else {
        return 1 + Math.floor(belowContentLineIndent / options.indentSize);
      }
    }
  }
}
class BracketPairGuidesClassNames {
  constructor() {
    this.activeClassName = "indent-active";
  }
  getInlineClassName(nestingLevel, nestingLevelOfEqualBracketType, independentColorPoolPerBracketType) {
    return this.getInlineClassNameOfLevel(independentColorPoolPerBracketType ? nestingLevelOfEqualBracketType : nestingLevel);
  }
  getInlineClassNameOfLevel(level) {
    return `bracket-indent-guide lvl-${level % 30}`;
  }
}
class IndentGuidesOverlay extends DynamicViewOverlay {
  constructor(context) {
    super();
    this._context = context;
    this._primaryPosition = null;
    const options = this._context.configuration.options;
    const wrappingInfo = options.get(
      143
      /* EditorOption.wrappingInfo */
    );
    const fontInfo = options.get(
      49
      /* EditorOption.fontInfo */
    );
    this._lineHeight = options.get(
      65
      /* EditorOption.lineHeight */
    );
    this._spaceWidth = fontInfo.spaceWidth;
    this._maxIndentLeft = wrappingInfo.wrappingColumn === -1 ? -1 : wrappingInfo.wrappingColumn * fontInfo.typicalHalfwidthCharacterWidth;
    this._bracketPairGuideOptions = options.get(
      15
      /* EditorOption.guides */
    );
    this._renderResult = null;
    this._context.addEventHandler(this);
  }
  dispose() {
    this._context.removeEventHandler(this);
    this._renderResult = null;
    super.dispose();
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    const options = this._context.configuration.options;
    const wrappingInfo = options.get(
      143
      /* EditorOption.wrappingInfo */
    );
    const fontInfo = options.get(
      49
      /* EditorOption.fontInfo */
    );
    this._lineHeight = options.get(
      65
      /* EditorOption.lineHeight */
    );
    this._spaceWidth = fontInfo.spaceWidth;
    this._maxIndentLeft = wrappingInfo.wrappingColumn === -1 ? -1 : wrappingInfo.wrappingColumn * fontInfo.typicalHalfwidthCharacterWidth;
    this._bracketPairGuideOptions = options.get(
      15
      /* EditorOption.guides */
    );
    return true;
  }
  onCursorStateChanged(e) {
    var _a2;
    const selection = e.selections[0];
    const newPosition = selection.getPosition();
    if (!((_a2 = this._primaryPosition) === null || _a2 === void 0 ? void 0 : _a2.equals(newPosition))) {
      this._primaryPosition = newPosition;
      return true;
    }
    return false;
  }
  onDecorationsChanged(e) {
    return true;
  }
  onFlushed(e) {
    return true;
  }
  onLinesChanged(e) {
    return true;
  }
  onLinesDeleted(e) {
    return true;
  }
  onLinesInserted(e) {
    return true;
  }
  onScrollChanged(e) {
    return e.scrollTopChanged;
  }
  onZonesChanged(e) {
    return true;
  }
  onLanguageConfigurationChanged(e) {
    return true;
  }
  // --- end event handlers
  prepareRender(ctx) {
    var _a2, _b2, _c2, _d2;
    if (!this._bracketPairGuideOptions.indentation && this._bracketPairGuideOptions.bracketPairs === false) {
      this._renderResult = null;
      return;
    }
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    const scrollWidth = ctx.scrollWidth;
    const lineHeight = this._lineHeight;
    const activeCursorPosition = this._primaryPosition;
    const indents = this.getGuidesByLine(visibleStartLineNumber, Math.min(visibleEndLineNumber + 1, this._context.viewModel.getLineCount()), activeCursorPosition);
    const output = [];
    for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
      const lineIndex = lineNumber - visibleStartLineNumber;
      const indent = indents[lineIndex];
      let result2 = "";
      const leftOffset = (_b2 = (_a2 = ctx.visibleRangeForPosition(new Position$2(lineNumber, 1))) === null || _a2 === void 0 ? void 0 : _a2.left) !== null && _b2 !== void 0 ? _b2 : 0;
      for (const guide of indent) {
        const left = guide.column === -1 ? leftOffset + (guide.visibleColumn - 1) * this._spaceWidth : ctx.visibleRangeForPosition(new Position$2(lineNumber, guide.column)).left;
        if (left > scrollWidth || this._maxIndentLeft > 0 && left > this._maxIndentLeft) {
          break;
        }
        const className3 = guide.horizontalLine ? guide.horizontalLine.top ? "horizontal-top" : "horizontal-bottom" : "vertical";
        const width = guide.horizontalLine ? ((_d2 = (_c2 = ctx.visibleRangeForPosition(new Position$2(lineNumber, guide.horizontalLine.endColumn))) === null || _c2 === void 0 ? void 0 : _c2.left) !== null && _d2 !== void 0 ? _d2 : left + this._spaceWidth) - left : this._spaceWidth;
        result2 += `<div class="core-guide ${guide.className} ${className3}" style="left:${left}px;height:${lineHeight}px;width:${width}px"></div>`;
      }
      output[lineIndex] = result2;
    }
    this._renderResult = output;
  }
  getGuidesByLine(visibleStartLineNumber, visibleEndLineNumber, activeCursorPosition) {
    const bracketGuides = this._bracketPairGuideOptions.bracketPairs !== false ? this._context.viewModel.getBracketGuidesInRangeByLine(visibleStartLineNumber, visibleEndLineNumber, activeCursorPosition, {
      highlightActive: this._bracketPairGuideOptions.highlightActiveBracketPair,
      horizontalGuides: this._bracketPairGuideOptions.bracketPairsHorizontal === true ? HorizontalGuidesState.Enabled : this._bracketPairGuideOptions.bracketPairsHorizontal === "active" ? HorizontalGuidesState.EnabledForActive : HorizontalGuidesState.Disabled,
      includeInactive: this._bracketPairGuideOptions.bracketPairs === true
    }) : null;
    const indentGuides2 = this._bracketPairGuideOptions.indentation ? this._context.viewModel.getLinesIndentGuides(visibleStartLineNumber, visibleEndLineNumber) : null;
    let activeIndentStartLineNumber = 0;
    let activeIndentEndLineNumber = 0;
    let activeIndentLevel = 0;
    if (this._bracketPairGuideOptions.highlightActiveIndentation !== false && activeCursorPosition) {
      const activeIndentInfo = this._context.viewModel.getActiveIndentGuide(activeCursorPosition.lineNumber, visibleStartLineNumber, visibleEndLineNumber);
      activeIndentStartLineNumber = activeIndentInfo.startLineNumber;
      activeIndentEndLineNumber = activeIndentInfo.endLineNumber;
      activeIndentLevel = activeIndentInfo.indent;
    }
    const { indentSize } = this._context.viewModel.model.getOptions();
    const result2 = [];
    for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
      const lineGuides = new Array();
      result2.push(lineGuides);
      const bracketGuidesInLine = bracketGuides ? bracketGuides[lineNumber - visibleStartLineNumber] : [];
      const bracketGuidesInLineQueue = new ArrayQueue(bracketGuidesInLine);
      const indentGuidesInLine = indentGuides2 ? indentGuides2[lineNumber - visibleStartLineNumber] : 0;
      for (let indentLvl = 1; indentLvl <= indentGuidesInLine; indentLvl++) {
        const indentGuide = (indentLvl - 1) * indentSize + 1;
        const isActive = (
          // Disable active indent guide if there are bracket guides.
          (this._bracketPairGuideOptions.highlightActiveIndentation === "always" || bracketGuidesInLine.length === 0) && activeIndentStartLineNumber <= lineNumber && lineNumber <= activeIndentEndLineNumber && indentLvl === activeIndentLevel
        );
        lineGuides.push(...bracketGuidesInLineQueue.takeWhile((g) => g.visibleColumn < indentGuide) || []);
        const peeked = bracketGuidesInLineQueue.peek();
        if (!peeked || peeked.visibleColumn !== indentGuide || peeked.horizontalLine) {
          lineGuides.push(new IndentGuide(indentGuide, -1, `core-guide-indent lvl-${(indentLvl - 1) % 30}` + (isActive ? " indent-active" : ""), null, -1, -1));
        }
      }
      lineGuides.push(...bracketGuidesInLineQueue.takeWhile((g) => true) || []);
    }
    return result2;
  }
  render(startLineNumber, lineNumber) {
    if (!this._renderResult) {
      return "";
    }
    const lineIndex = lineNumber - startLineNumber;
    if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
      return "";
    }
    return this._renderResult[lineIndex];
  }
}
function transparentToUndefined(color) {
  if (color && color.isTransparent()) {
    return void 0;
  }
  return color;
}
registerThemingParticipant((theme, collector) => {
  const colors = [
    { bracketColor: editorBracketHighlightingForeground1, guideColor: editorBracketPairGuideBackground1, guideColorActive: editorBracketPairGuideActiveBackground1 },
    { bracketColor: editorBracketHighlightingForeground2, guideColor: editorBracketPairGuideBackground2, guideColorActive: editorBracketPairGuideActiveBackground2 },
    { bracketColor: editorBracketHighlightingForeground3, guideColor: editorBracketPairGuideBackground3, guideColorActive: editorBracketPairGuideActiveBackground3 },
    { bracketColor: editorBracketHighlightingForeground4, guideColor: editorBracketPairGuideBackground4, guideColorActive: editorBracketPairGuideActiveBackground4 },
    { bracketColor: editorBracketHighlightingForeground5, guideColor: editorBracketPairGuideBackground5, guideColorActive: editorBracketPairGuideActiveBackground5 },
    { bracketColor: editorBracketHighlightingForeground6, guideColor: editorBracketPairGuideBackground6, guideColorActive: editorBracketPairGuideActiveBackground6 }
  ];
  const colorProvider = new BracketPairGuidesClassNames();
  const indentColors = [
    { indentColor: editorIndentGuide1, indentColorActive: editorActiveIndentGuide1 },
    { indentColor: editorIndentGuide2, indentColorActive: editorActiveIndentGuide2 },
    { indentColor: editorIndentGuide3, indentColorActive: editorActiveIndentGuide3 },
    { indentColor: editorIndentGuide4, indentColorActive: editorActiveIndentGuide4 },
    { indentColor: editorIndentGuide5, indentColorActive: editorActiveIndentGuide5 },
    { indentColor: editorIndentGuide6, indentColorActive: editorActiveIndentGuide6 }
  ];
  const colorValues = colors.map((c) => {
    var _a2, _b2;
    const bracketColor = theme.getColor(c.bracketColor);
    const guideColor = theme.getColor(c.guideColor);
    const guideColorActive = theme.getColor(c.guideColorActive);
    const effectiveGuideColor = transparentToUndefined((_a2 = transparentToUndefined(guideColor)) !== null && _a2 !== void 0 ? _a2 : bracketColor === null || bracketColor === void 0 ? void 0 : bracketColor.transparent(0.3));
    const effectiveGuideColorActive = transparentToUndefined((_b2 = transparentToUndefined(guideColorActive)) !== null && _b2 !== void 0 ? _b2 : bracketColor);
    if (!effectiveGuideColor || !effectiveGuideColorActive) {
      return void 0;
    }
    return {
      guideColor: effectiveGuideColor,
      guideColorActive: effectiveGuideColorActive
    };
  }).filter(isDefined);
  const indentColorValues = indentColors.map((c) => {
    const indentColor = theme.getColor(c.indentColor);
    const indentColorActive = theme.getColor(c.indentColorActive);
    const effectiveIndentColor = transparentToUndefined(indentColor);
    const effectiveIndentColorActive = transparentToUndefined(indentColorActive);
    if (!effectiveIndentColor || !effectiveIndentColorActive) {
      return void 0;
    }
    return {
      indentColor: effectiveIndentColor,
      indentColorActive: effectiveIndentColorActive
    };
  }).filter(isDefined);
  if (colorValues.length > 0) {
    for (let level = 0; level < 30; level++) {
      const colors2 = colorValues[level % colorValues.length];
      collector.addRule(`.monaco-editor .${colorProvider.getInlineClassNameOfLevel(level).replace(/ /g, ".")} { --guide-color: ${colors2.guideColor}; --guide-color-active: ${colors2.guideColorActive}; }`);
    }
    collector.addRule(`.monaco-editor .vertical { box-shadow: 1px 0 0 0 var(--guide-color) inset; }`);
    collector.addRule(`.monaco-editor .horizontal-top { border-top: 1px solid var(--guide-color); }`);
    collector.addRule(`.monaco-editor .horizontal-bottom { border-bottom: 1px solid var(--guide-color); }`);
    collector.addRule(`.monaco-editor .vertical.${colorProvider.activeClassName} { box-shadow: 1px 0 0 0 var(--guide-color-active) inset; }`);
    collector.addRule(`.monaco-editor .horizontal-top.${colorProvider.activeClassName} { border-top: 1px solid var(--guide-color-active); }`);
    collector.addRule(`.monaco-editor .horizontal-bottom.${colorProvider.activeClassName} { border-bottom: 1px solid var(--guide-color-active); }`);
  }
  if (indentColorValues.length > 0) {
    for (let level = 0; level < 30; level++) {
      const colors2 = indentColorValues[level % indentColorValues.length];
      collector.addRule(`.monaco-editor .lines-content .core-guide-indent.lvl-${level} { --indent-color: ${colors2.indentColor}; --indent-color-active: ${colors2.indentColorActive}; }`);
    }
    collector.addRule(`.monaco-editor .lines-content .core-guide-indent { box-shadow: 1px 0 0 0 var(--indent-color) inset; }`);
    collector.addRule(`.monaco-editor .lines-content .core-guide-indent.indent-active { box-shadow: 1px 0 0 0 var(--indent-color-active) inset; }`);
  }
});
const viewLines = "";
class DomReadingContext {
  get didDomLayout() {
    return this._didDomLayout;
  }
  readClientRect() {
    if (!this._clientRectRead) {
      this._clientRectRead = true;
      const rect = this._domNode.getBoundingClientRect();
      this.markDidDomLayout();
      this._clientRectDeltaLeft = rect.left;
      this._clientRectScale = rect.width / this._domNode.offsetWidth;
    }
  }
  get clientRectDeltaLeft() {
    if (!this._clientRectRead) {
      this.readClientRect();
    }
    return this._clientRectDeltaLeft;
  }
  get clientRectScale() {
    if (!this._clientRectRead) {
      this.readClientRect();
    }
    return this._clientRectScale;
  }
  constructor(_domNode, endNode) {
    this._domNode = _domNode;
    this.endNode = endNode;
    this._didDomLayout = false;
    this._clientRectDeltaLeft = 0;
    this._clientRectScale = 1;
    this._clientRectRead = false;
  }
  markDidDomLayout() {
    this._didDomLayout = true;
  }
}
class LastRenderedData {
  constructor() {
    this._currentVisibleRange = new Range$2(1, 1, 1, 1);
  }
  getCurrentVisibleRange() {
    return this._currentVisibleRange;
  }
  setCurrentVisibleRange(currentVisibleRange) {
    this._currentVisibleRange = currentVisibleRange;
  }
}
class HorizontalRevealRangeRequest {
  constructor(minimalReveal, lineNumber, startColumn, endColumn, startScrollTop, stopScrollTop, scrollType) {
    this.minimalReveal = minimalReveal;
    this.lineNumber = lineNumber;
    this.startColumn = startColumn;
    this.endColumn = endColumn;
    this.startScrollTop = startScrollTop;
    this.stopScrollTop = stopScrollTop;
    this.scrollType = scrollType;
    this.type = "range";
    this.minLineNumber = lineNumber;
    this.maxLineNumber = lineNumber;
  }
}
class HorizontalRevealSelectionsRequest {
  constructor(minimalReveal, selections2, startScrollTop, stopScrollTop, scrollType) {
    this.minimalReveal = minimalReveal;
    this.selections = selections2;
    this.startScrollTop = startScrollTop;
    this.stopScrollTop = stopScrollTop;
    this.scrollType = scrollType;
    this.type = "selections";
    let minLineNumber = selections2[0].startLineNumber;
    let maxLineNumber = selections2[0].endLineNumber;
    for (let i = 1, len = selections2.length; i < len; i++) {
      const selection = selections2[i];
      minLineNumber = Math.min(minLineNumber, selection.startLineNumber);
      maxLineNumber = Math.max(maxLineNumber, selection.endLineNumber);
    }
    this.minLineNumber = minLineNumber;
    this.maxLineNumber = maxLineNumber;
  }
}
class ViewLines extends ViewPart {
  constructor(context, linesContent) {
    super(context);
    this._linesContent = linesContent;
    this._textRangeRestingSpot = document.createElement("div");
    this._visibleLines = new VisibleLinesCollection(this);
    this.domNode = this._visibleLines.domNode;
    const conf = this._context.configuration;
    const options = this._context.configuration.options;
    const fontInfo = options.get(
      49
      /* EditorOption.fontInfo */
    );
    const wrappingInfo = options.get(
      143
      /* EditorOption.wrappingInfo */
    );
    this._lineHeight = options.get(
      65
      /* EditorOption.lineHeight */
    );
    this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
    this._isViewportWrapping = wrappingInfo.isViewportWrapping;
    this._revealHorizontalRightPadding = options.get(
      98
      /* EditorOption.revealHorizontalRightPadding */
    );
    this._cursorSurroundingLines = options.get(
      28
      /* EditorOption.cursorSurroundingLines */
    );
    this._cursorSurroundingLinesStyle = options.get(
      29
      /* EditorOption.cursorSurroundingLinesStyle */
    );
    this._canUseLayerHinting = !options.get(
      31
      /* EditorOption.disableLayerHinting */
    );
    this._viewLineOptions = new ViewLineOptions(conf, this._context.theme.type);
    PartFingerprints.write(
      this.domNode,
      7
      /* PartFingerprint.ViewLines */
    );
    this.domNode.setClassName(`view-lines ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`);
    applyFontInfo(this.domNode, fontInfo);
    this._maxLineWidth = 0;
    this._asyncUpdateLineWidths = new RunOnceScheduler(() => {
      this._updateLineWidthsSlow();
    }, 200);
    this._asyncCheckMonospaceFontAssumptions = new RunOnceScheduler(() => {
      this._checkMonospaceFontAssumptions();
    }, 2e3);
    this._lastRenderedData = new LastRenderedData();
    this._horizontalRevealRequest = null;
    this._stickyScrollEnabled = options.get(
      113
      /* EditorOption.stickyScroll */
    ).enabled;
    this._maxNumberStickyLines = options.get(
      113
      /* EditorOption.stickyScroll */
    ).maxLineCount;
  }
  dispose() {
    this._asyncUpdateLineWidths.dispose();
    this._asyncCheckMonospaceFontAssumptions.dispose();
    super.dispose();
  }
  getDomNode() {
    return this.domNode;
  }
  // ---- begin IVisibleLinesHost
  createVisibleLine() {
    return new ViewLine(this._viewLineOptions);
  }
  // ---- end IVisibleLinesHost
  // ---- begin view event handlers
  onConfigurationChanged(e) {
    this._visibleLines.onConfigurationChanged(e);
    if (e.hasChanged(
      143
      /* EditorOption.wrappingInfo */
    )) {
      this._maxLineWidth = 0;
    }
    const options = this._context.configuration.options;
    const fontInfo = options.get(
      49
      /* EditorOption.fontInfo */
    );
    const wrappingInfo = options.get(
      143
      /* EditorOption.wrappingInfo */
    );
    this._lineHeight = options.get(
      65
      /* EditorOption.lineHeight */
    );
    this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
    this._isViewportWrapping = wrappingInfo.isViewportWrapping;
    this._revealHorizontalRightPadding = options.get(
      98
      /* EditorOption.revealHorizontalRightPadding */
    );
    this._cursorSurroundingLines = options.get(
      28
      /* EditorOption.cursorSurroundingLines */
    );
    this._cursorSurroundingLinesStyle = options.get(
      29
      /* EditorOption.cursorSurroundingLinesStyle */
    );
    this._canUseLayerHinting = !options.get(
      31
      /* EditorOption.disableLayerHinting */
    );
    this._stickyScrollEnabled = options.get(
      113
      /* EditorOption.stickyScroll */
    ).enabled;
    this._maxNumberStickyLines = options.get(
      113
      /* EditorOption.stickyScroll */
    ).maxLineCount;
    applyFontInfo(this.domNode, fontInfo);
    this._onOptionsMaybeChanged();
    if (e.hasChanged(
      142
      /* EditorOption.layoutInfo */
    )) {
      this._maxLineWidth = 0;
    }
    return true;
  }
  _onOptionsMaybeChanged() {
    const conf = this._context.configuration;
    const newViewLineOptions = new ViewLineOptions(conf, this._context.theme.type);
    if (!this._viewLineOptions.equals(newViewLineOptions)) {
      this._viewLineOptions = newViewLineOptions;
      const startLineNumber = this._visibleLines.getStartLineNumber();
      const endLineNumber = this._visibleLines.getEndLineNumber();
      for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
        const line = this._visibleLines.getVisibleLine(lineNumber);
        line.onOptionsChanged(this._viewLineOptions);
      }
      return true;
    }
    return false;
  }
  onCursorStateChanged(e) {
    const rendStartLineNumber = this._visibleLines.getStartLineNumber();
    const rendEndLineNumber = this._visibleLines.getEndLineNumber();
    let r = false;
    for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
      r = this._visibleLines.getVisibleLine(lineNumber).onSelectionChanged() || r;
    }
    return r;
  }
  onDecorationsChanged(e) {
    {
      const rendStartLineNumber = this._visibleLines.getStartLineNumber();
      const rendEndLineNumber = this._visibleLines.getEndLineNumber();
      for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
        this._visibleLines.getVisibleLine(lineNumber).onDecorationsChanged();
      }
    }
    return true;
  }
  onFlushed(e) {
    const shouldRender = this._visibleLines.onFlushed(e);
    this._maxLineWidth = 0;
    return shouldRender;
  }
  onLinesChanged(e) {
    return this._visibleLines.onLinesChanged(e);
  }
  onLinesDeleted(e) {
    return this._visibleLines.onLinesDeleted(e);
  }
  onLinesInserted(e) {
    return this._visibleLines.onLinesInserted(e);
  }
  onRevealRangeRequest(e) {
    const desiredScrollTop = this._computeScrollTopToRevealRange(this._context.viewLayout.getFutureViewport(), e.source, e.minimalReveal, e.range, e.selections, e.verticalType);
    if (desiredScrollTop === -1) {
      return false;
    }
    let newScrollPosition = this._context.viewLayout.validateScrollPosition({ scrollTop: desiredScrollTop });
    if (e.revealHorizontal) {
      if (e.range && e.range.startLineNumber !== e.range.endLineNumber) {
        newScrollPosition = {
          scrollTop: newScrollPosition.scrollTop,
          scrollLeft: 0
        };
      } else if (e.range) {
        this._horizontalRevealRequest = new HorizontalRevealRangeRequest(e.minimalReveal, e.range.startLineNumber, e.range.startColumn, e.range.endColumn, this._context.viewLayout.getCurrentScrollTop(), newScrollPosition.scrollTop, e.scrollType);
      } else if (e.selections && e.selections.length > 0) {
        this._horizontalRevealRequest = new HorizontalRevealSelectionsRequest(e.minimalReveal, e.selections, this._context.viewLayout.getCurrentScrollTop(), newScrollPosition.scrollTop, e.scrollType);
      }
    } else {
      this._horizontalRevealRequest = null;
    }
    const scrollTopDelta = Math.abs(this._context.viewLayout.getCurrentScrollTop() - newScrollPosition.scrollTop);
    const scrollType = scrollTopDelta <= this._lineHeight ? 1 : e.scrollType;
    this._context.viewModel.viewLayout.setScrollPosition(newScrollPosition, scrollType);
    return true;
  }
  onScrollChanged(e) {
    if (this._horizontalRevealRequest && e.scrollLeftChanged) {
      this._horizontalRevealRequest = null;
    }
    if (this._horizontalRevealRequest && e.scrollTopChanged) {
      const min = Math.min(this._horizontalRevealRequest.startScrollTop, this._horizontalRevealRequest.stopScrollTop);
      const max = Math.max(this._horizontalRevealRequest.startScrollTop, this._horizontalRevealRequest.stopScrollTop);
      if (e.scrollTop < min || e.scrollTop > max) {
        this._horizontalRevealRequest = null;
      }
    }
    this.domNode.setWidth(e.scrollWidth);
    return this._visibleLines.onScrollChanged(e) || true;
  }
  onTokensChanged(e) {
    return this._visibleLines.onTokensChanged(e);
  }
  onZonesChanged(e) {
    this._context.viewModel.viewLayout.setMaxLineWidth(this._maxLineWidth);
    return this._visibleLines.onZonesChanged(e);
  }
  onThemeChanged(e) {
    return this._onOptionsMaybeChanged();
  }
  // ---- end view event handlers
  // ----------- HELPERS FOR OTHERS
  getPositionFromDOMInfo(spanNode, offset) {
    const viewLineDomNode = this._getViewLineDomNode(spanNode);
    if (viewLineDomNode === null) {
      return null;
    }
    const lineNumber = this._getLineNumberFor(viewLineDomNode);
    if (lineNumber === -1) {
      return null;
    }
    if (lineNumber < 1 || lineNumber > this._context.viewModel.getLineCount()) {
      return null;
    }
    if (this._context.viewModel.getLineMaxColumn(lineNumber) === 1) {
      return new Position$2(lineNumber, 1);
    }
    const rendStartLineNumber = this._visibleLines.getStartLineNumber();
    const rendEndLineNumber = this._visibleLines.getEndLineNumber();
    if (lineNumber < rendStartLineNumber || lineNumber > rendEndLineNumber) {
      return null;
    }
    let column = this._visibleLines.getVisibleLine(lineNumber).getColumnOfNodeOffset(lineNumber, spanNode, offset);
    const minColumn = this._context.viewModel.getLineMinColumn(lineNumber);
    if (column < minColumn) {
      column = minColumn;
    }
    return new Position$2(lineNumber, column);
  }
  _getViewLineDomNode(node2) {
    while (node2 && node2.nodeType === 1) {
      if (node2.className === ViewLine.CLASS_NAME) {
        return node2;
      }
      node2 = node2.parentElement;
    }
    return null;
  }
  /**
   * @returns the line number of this view line dom node.
   */
  _getLineNumberFor(domNode) {
    const startLineNumber = this._visibleLines.getStartLineNumber();
    const endLineNumber = this._visibleLines.getEndLineNumber();
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      const line = this._visibleLines.getVisibleLine(lineNumber);
      if (domNode === line.getDomNode()) {
        return lineNumber;
      }
    }
    return -1;
  }
  getLineWidth(lineNumber) {
    const rendStartLineNumber = this._visibleLines.getStartLineNumber();
    const rendEndLineNumber = this._visibleLines.getEndLineNumber();
    if (lineNumber < rendStartLineNumber || lineNumber > rendEndLineNumber) {
      return -1;
    }
    const context = new DomReadingContext(this.domNode.domNode, this._textRangeRestingSpot);
    const result2 = this._visibleLines.getVisibleLine(lineNumber).getWidth(context);
    this._updateLineWidthsSlowIfDomDidLayout(context);
    return result2;
  }
  linesVisibleRangesForRange(_range, includeNewLines) {
    if (this.shouldRender()) {
      return null;
    }
    const originalEndLineNumber = _range.endLineNumber;
    const range2 = Range$2.intersectRanges(_range, this._lastRenderedData.getCurrentVisibleRange());
    if (!range2) {
      return null;
    }
    const visibleRanges = [];
    let visibleRangesLen = 0;
    const domReadingContext = new DomReadingContext(this.domNode.domNode, this._textRangeRestingSpot);
    let nextLineModelLineNumber = 0;
    if (includeNewLines) {
      nextLineModelLineNumber = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new Position$2(range2.startLineNumber, 1)).lineNumber;
    }
    const rendStartLineNumber = this._visibleLines.getStartLineNumber();
    const rendEndLineNumber = this._visibleLines.getEndLineNumber();
    for (let lineNumber = range2.startLineNumber; lineNumber <= range2.endLineNumber; lineNumber++) {
      if (lineNumber < rendStartLineNumber || lineNumber > rendEndLineNumber) {
        continue;
      }
      const startColumn = lineNumber === range2.startLineNumber ? range2.startColumn : 1;
      const continuesInNextLine = lineNumber !== range2.endLineNumber;
      const endColumn = continuesInNextLine ? this._context.viewModel.getLineMaxColumn(lineNumber) : range2.endColumn;
      const visibleRangesForLine = this._visibleLines.getVisibleLine(lineNumber).getVisibleRangesForRange(lineNumber, startColumn, endColumn, domReadingContext);
      if (!visibleRangesForLine) {
        continue;
      }
      if (includeNewLines && lineNumber < originalEndLineNumber) {
        const currentLineModelLineNumber = nextLineModelLineNumber;
        nextLineModelLineNumber = this._context.viewModel.coordinatesConverter.convertViewPositionToModelPosition(new Position$2(lineNumber + 1, 1)).lineNumber;
        if (currentLineModelLineNumber !== nextLineModelLineNumber) {
          visibleRangesForLine.ranges[visibleRangesForLine.ranges.length - 1].width += this._typicalHalfwidthCharacterWidth;
        }
      }
      visibleRanges[visibleRangesLen++] = new LineVisibleRanges(visibleRangesForLine.outsideRenderedLine, lineNumber, HorizontalRange.from(visibleRangesForLine.ranges), continuesInNextLine);
    }
    this._updateLineWidthsSlowIfDomDidLayout(domReadingContext);
    if (visibleRangesLen === 0) {
      return null;
    }
    return visibleRanges;
  }
  _visibleRangesForLineRange(lineNumber, startColumn, endColumn) {
    if (this.shouldRender()) {
      return null;
    }
    if (lineNumber < this._visibleLines.getStartLineNumber() || lineNumber > this._visibleLines.getEndLineNumber()) {
      return null;
    }
    const domReadingContext = new DomReadingContext(this.domNode.domNode, this._textRangeRestingSpot);
    const result2 = this._visibleLines.getVisibleLine(lineNumber).getVisibleRangesForRange(lineNumber, startColumn, endColumn, domReadingContext);
    this._updateLineWidthsSlowIfDomDidLayout(domReadingContext);
    return result2;
  }
  visibleRangeForPosition(position) {
    const visibleRanges = this._visibleRangesForLineRange(position.lineNumber, position.column, position.column);
    if (!visibleRanges) {
      return null;
    }
    return new HorizontalPosition(visibleRanges.outsideRenderedLine, visibleRanges.ranges[0].left);
  }
  /**
   * Updates the max line width if it is fast to compute.
   * Returns true if all lines were taken into account.
   * Returns false if some lines need to be reevaluated (in a slow fashion).
   */
  _updateLineWidthsFast() {
    return this._updateLineWidths(true);
  }
  _updateLineWidthsSlow() {
    this._updateLineWidths(false);
  }
  /**
   * Update the line widths using DOM layout information after someone else
   * has caused a synchronous layout.
   */
  _updateLineWidthsSlowIfDomDidLayout(domReadingContext) {
    if (!domReadingContext.didDomLayout) {
      return;
    }
    if (this._asyncUpdateLineWidths.isScheduled()) {
      return;
    }
    this._asyncUpdateLineWidths.cancel();
    this._updateLineWidthsSlow();
  }
  _updateLineWidths(fast) {
    const rendStartLineNumber = this._visibleLines.getStartLineNumber();
    const rendEndLineNumber = this._visibleLines.getEndLineNumber();
    let localMaxLineWidth = 1;
    let allWidthsComputed = true;
    for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
      const visibleLine = this._visibleLines.getVisibleLine(lineNumber);
      if (fast && !visibleLine.getWidthIsFast()) {
        allWidthsComputed = false;
        continue;
      }
      localMaxLineWidth = Math.max(localMaxLineWidth, visibleLine.getWidth(null));
    }
    if (allWidthsComputed && rendStartLineNumber === 1 && rendEndLineNumber === this._context.viewModel.getLineCount()) {
      this._maxLineWidth = 0;
    }
    this._ensureMaxLineWidth(localMaxLineWidth);
    return allWidthsComputed;
  }
  _checkMonospaceFontAssumptions() {
    let longestLineNumber = -1;
    let longestWidth = -1;
    const rendStartLineNumber = this._visibleLines.getStartLineNumber();
    const rendEndLineNumber = this._visibleLines.getEndLineNumber();
    for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
      const visibleLine = this._visibleLines.getVisibleLine(lineNumber);
      if (visibleLine.needsMonospaceFontCheck()) {
        const lineWidth = visibleLine.getWidth(null);
        if (lineWidth > longestWidth) {
          longestWidth = lineWidth;
          longestLineNumber = lineNumber;
        }
      }
    }
    if (longestLineNumber === -1) {
      return;
    }
    if (!this._visibleLines.getVisibleLine(longestLineNumber).monospaceAssumptionsAreValid()) {
      for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
        const visibleLine = this._visibleLines.getVisibleLine(lineNumber);
        visibleLine.onMonospaceAssumptionsInvalidated();
      }
    }
  }
  prepareRender() {
    throw new Error("Not supported");
  }
  render() {
    throw new Error("Not supported");
  }
  renderText(viewportData) {
    this._visibleLines.renderLines(viewportData);
    this._lastRenderedData.setCurrentVisibleRange(viewportData.visibleRange);
    this.domNode.setWidth(this._context.viewLayout.getScrollWidth());
    this.domNode.setHeight(Math.min(this._context.viewLayout.getScrollHeight(), 1e6));
    if (this._horizontalRevealRequest) {
      const horizontalRevealRequest = this._horizontalRevealRequest;
      if (viewportData.startLineNumber <= horizontalRevealRequest.minLineNumber && horizontalRevealRequest.maxLineNumber <= viewportData.endLineNumber) {
        this._horizontalRevealRequest = null;
        this.onDidRender();
        const newScrollLeft = this._computeScrollLeftToReveal(horizontalRevealRequest);
        if (newScrollLeft) {
          if (!this._isViewportWrapping) {
            this._ensureMaxLineWidth(newScrollLeft.maxHorizontalOffset);
          }
          this._context.viewModel.viewLayout.setScrollPosition({
            scrollLeft: newScrollLeft.scrollLeft
          }, horizontalRevealRequest.scrollType);
        }
      }
    }
    if (!this._updateLineWidthsFast()) {
      this._asyncUpdateLineWidths.schedule();
    } else {
      this._asyncUpdateLineWidths.cancel();
    }
    if (isLinux && !this._asyncCheckMonospaceFontAssumptions.isScheduled()) {
      const rendStartLineNumber = this._visibleLines.getStartLineNumber();
      const rendEndLineNumber = this._visibleLines.getEndLineNumber();
      for (let lineNumber = rendStartLineNumber; lineNumber <= rendEndLineNumber; lineNumber++) {
        const visibleLine = this._visibleLines.getVisibleLine(lineNumber);
        if (visibleLine.needsMonospaceFontCheck()) {
          this._asyncCheckMonospaceFontAssumptions.schedule();
          break;
        }
      }
    }
    this._linesContent.setLayerHinting(this._canUseLayerHinting);
    this._linesContent.setContain("strict");
    const adjustedScrollTop = this._context.viewLayout.getCurrentScrollTop() - viewportData.bigNumbersDelta;
    this._linesContent.setTop(-adjustedScrollTop);
    this._linesContent.setLeft(-this._context.viewLayout.getCurrentScrollLeft());
  }
  // --- width
  _ensureMaxLineWidth(lineWidth) {
    const iLineWidth = Math.ceil(lineWidth);
    if (this._maxLineWidth < iLineWidth) {
      this._maxLineWidth = iLineWidth;
      this._context.viewModel.viewLayout.setMaxLineWidth(this._maxLineWidth);
    }
  }
  _computeScrollTopToRevealRange(viewport, source, minimalReveal, range2, selections2, verticalType) {
    const viewportStartY = viewport.top;
    const viewportHeight = viewport.height;
    const viewportEndY = viewportStartY + viewportHeight;
    let boxIsSingleRange;
    let boxStartY;
    let boxEndY;
    if (selections2 && selections2.length > 0) {
      let minLineNumber = selections2[0].startLineNumber;
      let maxLineNumber = selections2[0].endLineNumber;
      for (let i = 1, len = selections2.length; i < len; i++) {
        const selection = selections2[i];
        minLineNumber = Math.min(minLineNumber, selection.startLineNumber);
        maxLineNumber = Math.max(maxLineNumber, selection.endLineNumber);
      }
      boxIsSingleRange = false;
      boxStartY = this._context.viewLayout.getVerticalOffsetForLineNumber(minLineNumber);
      boxEndY = this._context.viewLayout.getVerticalOffsetForLineNumber(maxLineNumber) + this._lineHeight;
    } else if (range2) {
      boxIsSingleRange = true;
      boxStartY = this._context.viewLayout.getVerticalOffsetForLineNumber(range2.startLineNumber);
      boxEndY = this._context.viewLayout.getVerticalOffsetForLineNumber(range2.endLineNumber) + this._lineHeight;
    } else {
      return -1;
    }
    const shouldIgnoreScrollOff = (source === "mouse" || minimalReveal) && this._cursorSurroundingLinesStyle === "default";
    let paddingTop = 0;
    let paddingBottom = 0;
    if (!shouldIgnoreScrollOff) {
      const context = Math.min(viewportHeight / this._lineHeight / 2, this._cursorSurroundingLines);
      if (this._stickyScrollEnabled) {
        paddingTop = Math.max(context, this._maxNumberStickyLines) * this._lineHeight;
      } else {
        paddingTop = context * this._lineHeight;
      }
      paddingBottom = Math.max(0, context - 1) * this._lineHeight;
    } else {
      if (!minimalReveal) {
        paddingTop = this._lineHeight;
      }
    }
    if (!minimalReveal) {
      if (verticalType === 0 || verticalType === 4) {
        paddingBottom += this._lineHeight;
      }
    }
    boxStartY -= paddingTop;
    boxEndY += paddingBottom;
    let newScrollTop;
    if (boxEndY - boxStartY > viewportHeight) {
      if (!boxIsSingleRange) {
        return -1;
      }
      newScrollTop = boxStartY;
    } else if (verticalType === 5 || verticalType === 6) {
      if (verticalType === 6 && viewportStartY <= boxStartY && boxEndY <= viewportEndY) {
        newScrollTop = viewportStartY;
      } else {
        const desiredGapAbove = Math.max(5 * this._lineHeight, viewportHeight * 0.2);
        const desiredScrollTop = boxStartY - desiredGapAbove;
        const minScrollTop = boxEndY - viewportHeight;
        newScrollTop = Math.max(minScrollTop, desiredScrollTop);
      }
    } else if (verticalType === 1 || verticalType === 2) {
      if (verticalType === 2 && viewportStartY <= boxStartY && boxEndY <= viewportEndY) {
        newScrollTop = viewportStartY;
      } else {
        const boxMiddleY = (boxStartY + boxEndY) / 2;
        newScrollTop = Math.max(0, boxMiddleY - viewportHeight / 2);
      }
    } else {
      newScrollTop = this._computeMinimumScrolling(
        viewportStartY,
        viewportEndY,
        boxStartY,
        boxEndY,
        verticalType === 3,
        verticalType === 4
        /* viewEvents.VerticalRevealType.Bottom */
      );
    }
    return newScrollTop;
  }
  _computeScrollLeftToReveal(horizontalRevealRequest) {
    const viewport = this._context.viewLayout.getCurrentViewport();
    const layoutInfo = this._context.configuration.options.get(
      142
      /* EditorOption.layoutInfo */
    );
    const viewportStartX = viewport.left;
    const viewportEndX = viewportStartX + viewport.width - layoutInfo.verticalScrollbarWidth;
    let boxStartX = 1073741824;
    let boxEndX = 0;
    if (horizontalRevealRequest.type === "range") {
      const visibleRanges = this._visibleRangesForLineRange(horizontalRevealRequest.lineNumber, horizontalRevealRequest.startColumn, horizontalRevealRequest.endColumn);
      if (!visibleRanges) {
        return null;
      }
      for (const visibleRange of visibleRanges.ranges) {
        boxStartX = Math.min(boxStartX, Math.round(visibleRange.left));
        boxEndX = Math.max(boxEndX, Math.round(visibleRange.left + visibleRange.width));
      }
    } else {
      for (const selection of horizontalRevealRequest.selections) {
        if (selection.startLineNumber !== selection.endLineNumber) {
          return null;
        }
        const visibleRanges = this._visibleRangesForLineRange(selection.startLineNumber, selection.startColumn, selection.endColumn);
        if (!visibleRanges) {
          return null;
        }
        for (const visibleRange of visibleRanges.ranges) {
          boxStartX = Math.min(boxStartX, Math.round(visibleRange.left));
          boxEndX = Math.max(boxEndX, Math.round(visibleRange.left + visibleRange.width));
        }
      }
    }
    if (!horizontalRevealRequest.minimalReveal) {
      boxStartX = Math.max(0, boxStartX - ViewLines.HORIZONTAL_EXTRA_PX);
      boxEndX += this._revealHorizontalRightPadding;
    }
    if (horizontalRevealRequest.type === "selections" && boxEndX - boxStartX > viewport.width) {
      return null;
    }
    const newScrollLeft = this._computeMinimumScrolling(viewportStartX, viewportEndX, boxStartX, boxEndX);
    return {
      scrollLeft: newScrollLeft,
      maxHorizontalOffset: boxEndX
    };
  }
  _computeMinimumScrolling(viewportStart, viewportEnd, boxStart, boxEnd, revealAtStart, revealAtEnd) {
    viewportStart = viewportStart | 0;
    viewportEnd = viewportEnd | 0;
    boxStart = boxStart | 0;
    boxEnd = boxEnd | 0;
    revealAtStart = !!revealAtStart;
    revealAtEnd = !!revealAtEnd;
    const viewportLength = viewportEnd - viewportStart;
    const boxLength = boxEnd - boxStart;
    if (boxLength < viewportLength) {
      if (revealAtStart) {
        return boxStart;
      }
      if (revealAtEnd) {
        return Math.max(0, boxEnd - viewportLength);
      }
      if (boxStart < viewportStart) {
        return boxStart;
      } else if (boxEnd > viewportEnd) {
        return Math.max(0, boxEnd - viewportLength);
      }
    } else {
      return boxStart;
    }
    return viewportStart;
  }
}
ViewLines.HORIZONTAL_EXTRA_PX = 30;
const linesDecorations = "";
const glyphMargin = "";
class DecorationToRender {
  constructor(startLineNumber, endLineNumber, className3, zIndex) {
    this._decorationToRenderBrand = void 0;
    this.startLineNumber = +startLineNumber;
    this.endLineNumber = +endLineNumber;
    this.className = String(className3);
    this.zIndex = zIndex !== null && zIndex !== void 0 ? zIndex : 0;
  }
}
class LineDecorationToRender {
  constructor(className3, zIndex) {
    this.className = className3;
    this.zIndex = zIndex;
  }
}
class VisibleLineDecorationsToRender {
  constructor() {
    this.decorations = [];
  }
  add(decoration2) {
    this.decorations.push(decoration2);
  }
  getDecorations() {
    return this.decorations;
  }
}
class DedupOverlay extends DynamicViewOverlay {
  /**
   * Returns an array with an element for each visible line number.
   */
  _render(visibleStartLineNumber, visibleEndLineNumber, decorations2) {
    const output = [];
    for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
      const lineIndex = lineNumber - visibleStartLineNumber;
      output[lineIndex] = new VisibleLineDecorationsToRender();
    }
    if (decorations2.length === 0) {
      return output;
    }
    decorations2.sort((a, b) => {
      if (a.className === b.className) {
        if (a.startLineNumber === b.startLineNumber) {
          return a.endLineNumber - b.endLineNumber;
        }
        return a.startLineNumber - b.startLineNumber;
      }
      return a.className < b.className ? -1 : 1;
    });
    let prevClassName = null;
    let prevEndLineIndex = 0;
    for (let i = 0, len = decorations2.length; i < len; i++) {
      const d = decorations2[i];
      const className3 = d.className;
      const zIndex = d.zIndex;
      let startLineIndex = Math.max(d.startLineNumber, visibleStartLineNumber) - visibleStartLineNumber;
      const endLineIndex = Math.min(d.endLineNumber, visibleEndLineNumber) - visibleStartLineNumber;
      if (prevClassName === className3) {
        startLineIndex = Math.max(prevEndLineIndex + 1, startLineIndex);
        prevEndLineIndex = Math.max(prevEndLineIndex, endLineIndex);
      } else {
        prevClassName = className3;
        prevEndLineIndex = endLineIndex;
      }
      for (let i2 = startLineIndex; i2 <= prevEndLineIndex; i2++) {
        output[i2].add(new LineDecorationToRender(className3, zIndex));
      }
    }
    return output;
  }
}
class GlyphMarginWidgets extends ViewPart {
  constructor(context) {
    super(context);
    this._widgets = {};
    this._context = context;
    const options = this._context.configuration.options;
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    this.domNode = createFastDomNode(document.createElement("div"));
    this.domNode.setClassName("glyph-margin-widgets");
    this.domNode.setPosition("absolute");
    this.domNode.setTop(0);
    this._lineHeight = options.get(
      65
      /* EditorOption.lineHeight */
    );
    this._glyphMargin = options.get(
      56
      /* EditorOption.glyphMargin */
    );
    this._glyphMarginLeft = layoutInfo.glyphMarginLeft;
    this._glyphMarginWidth = layoutInfo.glyphMarginWidth;
    this._glyphMarginDecorationLaneCount = layoutInfo.glyphMarginDecorationLaneCount;
    this._managedDomNodes = [];
    this._decorationGlyphsToRender = [];
  }
  dispose() {
    this._managedDomNodes = [];
    this._decorationGlyphsToRender = [];
    this._widgets = {};
    super.dispose();
  }
  getWidgets() {
    return Object.values(this._widgets);
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    const options = this._context.configuration.options;
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    this._lineHeight = options.get(
      65
      /* EditorOption.lineHeight */
    );
    this._glyphMargin = options.get(
      56
      /* EditorOption.glyphMargin */
    );
    this._glyphMarginLeft = layoutInfo.glyphMarginLeft;
    this._glyphMarginWidth = layoutInfo.glyphMarginWidth;
    this._glyphMarginDecorationLaneCount = layoutInfo.glyphMarginDecorationLaneCount;
    return true;
  }
  onDecorationsChanged(e) {
    return true;
  }
  onFlushed(e) {
    return true;
  }
  onLinesChanged(e) {
    return true;
  }
  onLinesDeleted(e) {
    return true;
  }
  onLinesInserted(e) {
    return true;
  }
  onScrollChanged(e) {
    return e.scrollTopChanged;
  }
  onZonesChanged(e) {
    return true;
  }
  // --- end event handlers
  // --- begin widget management
  addWidget(widget) {
    const domNode = createFastDomNode(widget.getDomNode());
    this._widgets[widget.getId()] = {
      widget,
      preference: widget.getPosition(),
      domNode,
      renderInfo: null
    };
    domNode.setPosition("absolute");
    domNode.setDisplay("none");
    domNode.setAttribute("widgetId", widget.getId());
    this.domNode.appendChild(domNode);
    this.setShouldRender();
  }
  setWidgetPosition(widget, preference) {
    const myWidget = this._widgets[widget.getId()];
    if (myWidget.preference.lane === preference.lane && myWidget.preference.zIndex === preference.zIndex && Range$2.equalsRange(myWidget.preference.range, preference.range)) {
      return false;
    }
    myWidget.preference = preference;
    this.setShouldRender();
    return true;
  }
  removeWidget(widget) {
    var _a2;
    const widgetId = widget.getId();
    if (this._widgets[widgetId]) {
      const widgetData = this._widgets[widgetId];
      const domNode = widgetData.domNode.domNode;
      delete this._widgets[widgetId];
      (_a2 = domNode.parentNode) === null || _a2 === void 0 ? void 0 : _a2.removeChild(domNode);
      this.setShouldRender();
    }
  }
  // --- end widget management
  _collectDecorationBasedGlyphRenderRequest(ctx, requests) {
    var _a2, _b2, _c2;
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    const decorations2 = ctx.getDecorationsInViewport();
    for (const d of decorations2) {
      const glyphMarginClassName = d.options.glyphMarginClassName;
      if (!glyphMarginClassName) {
        continue;
      }
      const startLineNumber = Math.max(d.range.startLineNumber, visibleStartLineNumber);
      const endLineNumber = Math.min(d.range.endLineNumber, visibleEndLineNumber);
      const lane = Math.min((_b2 = (_a2 = d.options.glyphMargin) === null || _a2 === void 0 ? void 0 : _a2.position) !== null && _b2 !== void 0 ? _b2 : 1, this._glyphMarginDecorationLaneCount);
      const zIndex = (_c2 = d.options.zIndex) !== null && _c2 !== void 0 ? _c2 : 0;
      for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
        requests.push(new DecorationBasedGlyphRenderRequest(lineNumber, lane, zIndex, glyphMarginClassName));
      }
    }
  }
  _collectWidgetBasedGlyphRenderRequest(ctx, requests) {
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    for (const widget of Object.values(this._widgets)) {
      const range2 = widget.preference.range;
      if (range2.endLineNumber < visibleStartLineNumber || range2.startLineNumber > visibleEndLineNumber) {
        continue;
      }
      const widgetLineNumber = Math.max(range2.startLineNumber, visibleStartLineNumber);
      const lane = Math.min(widget.preference.lane, this._glyphMarginDecorationLaneCount);
      requests.push(new WidgetBasedGlyphRenderRequest(widgetLineNumber, lane, widget.preference.zIndex, widget));
    }
  }
  _collectSortedGlyphRenderRequests(ctx) {
    const requests = [];
    this._collectDecorationBasedGlyphRenderRequest(ctx, requests);
    this._collectWidgetBasedGlyphRenderRequest(ctx, requests);
    requests.sort((a, b) => {
      if (a.lineNumber === b.lineNumber) {
        if (a.lane === b.lane) {
          if (a.zIndex === b.zIndex) {
            if (b.type === a.type) {
              if (a.type === 0 && b.type === 0) {
                return a.className < b.className ? -1 : 1;
              }
              return 0;
            }
            return b.type - a.type;
          }
          return b.zIndex - a.zIndex;
        }
        return a.lane - b.lane;
      }
      return a.lineNumber - b.lineNumber;
    });
    return requests;
  }
  /**
   * Will store render information in each widget's renderInfo and in `_decorationGlyphsToRender`.
   */
  prepareRender(ctx) {
    if (!this._glyphMargin) {
      this._decorationGlyphsToRender = [];
      return;
    }
    for (const widget of Object.values(this._widgets)) {
      widget.renderInfo = null;
    }
    const requests = new ArrayQueue(this._collectSortedGlyphRenderRequests(ctx));
    const decorationGlyphsToRender = [];
    while (requests.length > 0) {
      const first2 = requests.peek();
      if (!first2) {
        break;
      }
      const requestsAtLocation = requests.takeWhile((el) => el.lineNumber === first2.lineNumber && el.lane === first2.lane);
      if (!requestsAtLocation || requestsAtLocation.length === 0) {
        break;
      }
      const winner = requestsAtLocation[0];
      if (winner.type === 0) {
        const classNames = [];
        for (const request of requestsAtLocation) {
          if (request.zIndex !== winner.zIndex || request.type !== winner.type) {
            break;
          }
          if (classNames.length === 0 || classNames[classNames.length - 1] !== request.className) {
            classNames.push(request.className);
          }
        }
        decorationGlyphsToRender.push(winner.accept(classNames.join(" ")));
      } else {
        winner.widget.renderInfo = {
          lineNumber: winner.lineNumber,
          lane: winner.lane
        };
      }
    }
    this._decorationGlyphsToRender = decorationGlyphsToRender;
  }
  render(ctx) {
    if (!this._glyphMargin) {
      for (const widget of Object.values(this._widgets)) {
        widget.domNode.setDisplay("none");
      }
      while (this._managedDomNodes.length > 0) {
        const domNode = this._managedDomNodes.pop();
        domNode === null || domNode === void 0 ? void 0 : domNode.domNode.remove();
      }
      return;
    }
    const width = Math.round(this._glyphMarginWidth / this._glyphMarginDecorationLaneCount);
    for (const widget of Object.values(this._widgets)) {
      if (!widget.renderInfo) {
        widget.domNode.setDisplay("none");
      } else {
        const top = ctx.viewportData.relativeVerticalOffset[widget.renderInfo.lineNumber - ctx.viewportData.startLineNumber];
        const left = this._glyphMarginLeft + (widget.renderInfo.lane - 1) * this._lineHeight;
        widget.domNode.setDisplay("block");
        widget.domNode.setTop(top);
        widget.domNode.setLeft(left);
        widget.domNode.setWidth(width);
        widget.domNode.setHeight(this._lineHeight);
      }
    }
    for (let i = 0; i < this._decorationGlyphsToRender.length; i++) {
      const dec = this._decorationGlyphsToRender[i];
      const top = ctx.viewportData.relativeVerticalOffset[dec.lineNumber - ctx.viewportData.startLineNumber];
      const left = this._glyphMarginLeft + (dec.lane - 1) * this._lineHeight;
      let domNode;
      if (i < this._managedDomNodes.length) {
        domNode = this._managedDomNodes[i];
      } else {
        domNode = createFastDomNode(document.createElement("div"));
        this._managedDomNodes.push(domNode);
        this.domNode.appendChild(domNode);
      }
      domNode.setClassName(`cgmr codicon ` + dec.combinedClassName);
      domNode.setPosition(`absolute`);
      domNode.setTop(top);
      domNode.setLeft(left);
      domNode.setWidth(width);
      domNode.setHeight(this._lineHeight);
    }
    while (this._managedDomNodes.length > this._decorationGlyphsToRender.length) {
      const domNode = this._managedDomNodes.pop();
      domNode === null || domNode === void 0 ? void 0 : domNode.domNode.remove();
    }
  }
}
class DecorationBasedGlyphRenderRequest {
  constructor(lineNumber, lane, zIndex, className3) {
    this.lineNumber = lineNumber;
    this.lane = lane;
    this.zIndex = zIndex;
    this.className = className3;
    this.type = 0;
  }
  accept(combinedClassName) {
    return new DecorationBasedGlyph(this.lineNumber, this.lane, combinedClassName);
  }
}
class WidgetBasedGlyphRenderRequest {
  constructor(lineNumber, lane, zIndex, widget) {
    this.lineNumber = lineNumber;
    this.lane = lane;
    this.zIndex = zIndex;
    this.widget = widget;
    this.type = 1;
  }
}
class DecorationBasedGlyph {
  constructor(lineNumber, lane, combinedClassName) {
    this.lineNumber = lineNumber;
    this.lane = lane;
    this.combinedClassName = combinedClassName;
  }
}
class LinesDecorationsOverlay extends DedupOverlay {
  constructor(context) {
    super();
    this._context = context;
    const options = this._context.configuration.options;
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    this._decorationsLeft = layoutInfo.decorationsLeft;
    this._decorationsWidth = layoutInfo.decorationsWidth;
    this._renderResult = null;
    this._context.addEventHandler(this);
  }
  dispose() {
    this._context.removeEventHandler(this);
    this._renderResult = null;
    super.dispose();
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    const options = this._context.configuration.options;
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    this._decorationsLeft = layoutInfo.decorationsLeft;
    this._decorationsWidth = layoutInfo.decorationsWidth;
    return true;
  }
  onDecorationsChanged(e) {
    return true;
  }
  onFlushed(e) {
    return true;
  }
  onLinesChanged(e) {
    return true;
  }
  onLinesDeleted(e) {
    return true;
  }
  onLinesInserted(e) {
    return true;
  }
  onScrollChanged(e) {
    return e.scrollTopChanged;
  }
  onZonesChanged(e) {
    return true;
  }
  // --- end event handlers
  _getDecorations(ctx) {
    const decorations2 = ctx.getDecorationsInViewport();
    const r = [];
    let rLen = 0;
    for (let i = 0, len = decorations2.length; i < len; i++) {
      const d = decorations2[i];
      const linesDecorationsClassName = d.options.linesDecorationsClassName;
      const zIndex = d.options.zIndex;
      if (linesDecorationsClassName) {
        r[rLen++] = new DecorationToRender(d.range.startLineNumber, d.range.endLineNumber, linesDecorationsClassName, zIndex);
      }
      const firstLineDecorationClassName = d.options.firstLineDecorationClassName;
      if (firstLineDecorationClassName) {
        r[rLen++] = new DecorationToRender(d.range.startLineNumber, d.range.startLineNumber, firstLineDecorationClassName, zIndex);
      }
    }
    return r;
  }
  prepareRender(ctx) {
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    const toRender = this._render(visibleStartLineNumber, visibleEndLineNumber, this._getDecorations(ctx));
    const left = this._decorationsLeft.toString();
    const width = this._decorationsWidth.toString();
    const common = '" style="left:' + left + "px;width:" + width + 'px;"></div>';
    const output = [];
    for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
      const lineIndex = lineNumber - visibleStartLineNumber;
      const decorations2 = toRender[lineIndex].getDecorations();
      let lineOutput = "";
      for (const decoration2 of decorations2) {
        lineOutput += '<div class="cldr ' + decoration2.className + common;
      }
      output[lineIndex] = lineOutput;
    }
    this._renderResult = output;
  }
  render(startLineNumber, lineNumber) {
    if (!this._renderResult) {
      return "";
    }
    return this._renderResult[lineNumber - startLineNumber];
  }
}
const marginDecorations = "";
class MarginViewLineDecorationsOverlay extends DedupOverlay {
  constructor(context) {
    super();
    this._context = context;
    this._renderResult = null;
    this._context.addEventHandler(this);
  }
  dispose() {
    this._context.removeEventHandler(this);
    this._renderResult = null;
    super.dispose();
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    return true;
  }
  onDecorationsChanged(e) {
    return true;
  }
  onFlushed(e) {
    return true;
  }
  onLinesChanged(e) {
    return true;
  }
  onLinesDeleted(e) {
    return true;
  }
  onLinesInserted(e) {
    return true;
  }
  onScrollChanged(e) {
    return e.scrollTopChanged;
  }
  onZonesChanged(e) {
    return true;
  }
  // --- end event handlers
  _getDecorations(ctx) {
    const decorations2 = ctx.getDecorationsInViewport();
    const r = [];
    let rLen = 0;
    for (let i = 0, len = decorations2.length; i < len; i++) {
      const d = decorations2[i];
      const marginClassName = d.options.marginClassName;
      const zIndex = d.options.zIndex;
      if (marginClassName) {
        r[rLen++] = new DecorationToRender(d.range.startLineNumber, d.range.endLineNumber, marginClassName, zIndex);
      }
    }
    return r;
  }
  prepareRender(ctx) {
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    const toRender = this._render(visibleStartLineNumber, visibleEndLineNumber, this._getDecorations(ctx));
    const output = [];
    for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
      const lineIndex = lineNumber - visibleStartLineNumber;
      const decorations2 = toRender[lineIndex].getDecorations();
      let lineOutput = "";
      for (const decoration2 of decorations2) {
        lineOutput += '<div class="cmdr ' + decoration2.className + '" style=""></div>';
      }
      output[lineIndex] = lineOutput;
    }
    this._renderResult = output;
  }
  render(startLineNumber, lineNumber) {
    if (!this._renderResult) {
      return "";
    }
    return this._renderResult[lineNumber - startLineNumber];
  }
}
const minimap = "";
class RGBA8 {
  constructor(r, g, b, a) {
    this._rgba8Brand = void 0;
    this.r = RGBA8._clamp(r);
    this.g = RGBA8._clamp(g);
    this.b = RGBA8._clamp(b);
    this.a = RGBA8._clamp(a);
  }
  equals(other) {
    return this.r === other.r && this.g === other.g && this.b === other.b && this.a === other.a;
  }
  static _clamp(c) {
    if (c < 0) {
      return 0;
    }
    if (c > 255) {
      return 255;
    }
    return c | 0;
  }
}
RGBA8.Empty = new RGBA8(0, 0, 0, 0);
class MinimapTokensColorTracker extends Disposable {
  static getInstance() {
    if (!this._INSTANCE) {
      this._INSTANCE = markAsSingleton(new MinimapTokensColorTracker());
    }
    return this._INSTANCE;
  }
  constructor() {
    super();
    this._onDidChange = new Emitter$1();
    this.onDidChange = this._onDidChange.event;
    this._updateColorMap();
    this._register(TokenizationRegistry2.onDidChange((e) => {
      if (e.changedColorMap) {
        this._updateColorMap();
      }
    }));
  }
  _updateColorMap() {
    const colorMap = TokenizationRegistry2.getColorMap();
    if (!colorMap) {
      this._colors = [RGBA8.Empty];
      this._backgroundIsLight = true;
      return;
    }
    this._colors = [RGBA8.Empty];
    for (let colorId = 1; colorId < colorMap.length; colorId++) {
      const source = colorMap[colorId].rgba;
      this._colors[colorId] = new RGBA8(source.r, source.g, source.b, Math.round(source.a * 255));
    }
    const backgroundLuminosity = colorMap[
      2
      /* ColorId.DefaultBackground */
    ].getRelativeLuminance();
    this._backgroundIsLight = backgroundLuminosity >= 0.5;
    this._onDidChange.fire(void 0);
  }
  getColor(colorId) {
    if (colorId < 1 || colorId >= this._colors.length) {
      colorId = 2;
    }
    return this._colors[colorId];
  }
  backgroundIsLight() {
    return this._backgroundIsLight;
  }
}
MinimapTokensColorTracker._INSTANCE = null;
class Viewport {
  constructor(top, left, width, height) {
    this._viewportBrand = void 0;
    this.top = top | 0;
    this.left = left | 0;
    this.width = width | 0;
    this.height = height | 0;
  }
}
class MinimapLinesRenderingData {
  constructor(tabSize, data) {
    this.tabSize = tabSize;
    this.data = data;
  }
}
class ViewLineData {
  constructor(content, continuesWithWrappedLine, minColumn, maxColumn, startVisibleColumn, tokens, inlineDecorations) {
    this._viewLineDataBrand = void 0;
    this.content = content;
    this.continuesWithWrappedLine = continuesWithWrappedLine;
    this.minColumn = minColumn;
    this.maxColumn = maxColumn;
    this.startVisibleColumn = startVisibleColumn;
    this.tokens = tokens;
    this.inlineDecorations = inlineDecorations;
  }
}
class ViewLineRenderingData {
  constructor(minColumn, maxColumn, content, continuesWithWrappedLine, mightContainRTL, mightContainNonBasicASCII, tokens, inlineDecorations, tabSize, startVisibleColumn) {
    this.minColumn = minColumn;
    this.maxColumn = maxColumn;
    this.content = content;
    this.continuesWithWrappedLine = continuesWithWrappedLine;
    this.isBasicASCII = ViewLineRenderingData.isBasicASCII(content, mightContainNonBasicASCII);
    this.containsRTL = ViewLineRenderingData.containsRTL(content, this.isBasicASCII, mightContainRTL);
    this.tokens = tokens;
    this.inlineDecorations = inlineDecorations;
    this.tabSize = tabSize;
    this.startVisibleColumn = startVisibleColumn;
  }
  static isBasicASCII(lineContent, mightContainNonBasicASCII) {
    if (mightContainNonBasicASCII) {
      return isBasicASCII(lineContent);
    }
    return true;
  }
  static containsRTL(lineContent, isBasicASCII2, mightContainRTL) {
    if (!isBasicASCII2 && mightContainRTL) {
      return containsRTL(lineContent);
    }
    return false;
  }
}
class InlineDecoration {
  constructor(range2, inlineClassName, type) {
    this.range = range2;
    this.inlineClassName = inlineClassName;
    this.type = type;
  }
}
class SingleLineInlineDecoration {
  constructor(startOffset, endOffset, inlineClassName, inlineClassNameAffectsLetterSpacing) {
    this.startOffset = startOffset;
    this.endOffset = endOffset;
    this.inlineClassName = inlineClassName;
    this.inlineClassNameAffectsLetterSpacing = inlineClassNameAffectsLetterSpacing;
  }
  toInlineDecoration(lineNumber) {
    return new InlineDecoration(
      new Range$2(lineNumber, this.startOffset + 1, lineNumber, this.endOffset + 1),
      this.inlineClassName,
      this.inlineClassNameAffectsLetterSpacing ? 3 : 0
      /* InlineDecorationType.Regular */
    );
  }
}
class ViewModelDecoration {
  constructor(range2, options) {
    this._viewModelDecorationBrand = void 0;
    this.range = range2;
    this.options = options;
  }
}
class OverviewRulerDecorationsGroup {
  constructor(color, zIndex, data) {
    this.color = color;
    this.zIndex = zIndex;
    this.data = data;
  }
  static cmp(a, b) {
    if (a.zIndex === b.zIndex) {
      if (a.color < b.color) {
        return -1;
      }
      if (a.color > b.color) {
        return 1;
      }
      return 0;
    }
    return a.zIndex - b.zIndex;
  }
}
const allCharCodes = (() => {
  const v = [];
  for (let i = 32; i <= 126; i++) {
    v.push(i);
  }
  v.push(
    65533
    /* Constants.UNKNOWN_CODE */
  );
  return v;
})();
const getCharIndex = (chCode, fontScale) => {
  chCode -= 32;
  if (chCode < 0 || chCode > 96) {
    if (fontScale <= 2) {
      return (chCode + 96) % 96;
    }
    return 96 - 1;
  }
  return chCode;
};
class MinimapCharRenderer {
  constructor(charData, scale) {
    this.scale = scale;
    this._minimapCharRendererBrand = void 0;
    this.charDataNormal = MinimapCharRenderer.soften(charData, 12 / 15);
    this.charDataLight = MinimapCharRenderer.soften(charData, 50 / 60);
  }
  static soften(input2, ratio) {
    const result2 = new Uint8ClampedArray(input2.length);
    for (let i = 0, len = input2.length; i < len; i++) {
      result2[i] = toUint8(input2[i] * ratio);
    }
    return result2;
  }
  renderChar(target, dx, dy, chCode, color, foregroundAlpha, backgroundColor, backgroundAlpha, fontScale, useLighterFont, force1pxHeight) {
    const charWidth = 1 * this.scale;
    const charHeight = 2 * this.scale;
    const renderHeight = force1pxHeight ? 1 : charHeight;
    if (dx + charWidth > target.width || dy + renderHeight > target.height) {
      console.warn("bad render request outside image data");
      return;
    }
    const charData = useLighterFont ? this.charDataLight : this.charDataNormal;
    const charIndex = getCharIndex(chCode, fontScale);
    const destWidth = target.width * 4;
    const backgroundR = backgroundColor.r;
    const backgroundG = backgroundColor.g;
    const backgroundB = backgroundColor.b;
    const deltaR = color.r - backgroundR;
    const deltaG = color.g - backgroundG;
    const deltaB = color.b - backgroundB;
    const destAlpha = Math.max(foregroundAlpha, backgroundAlpha);
    const dest = target.data;
    let sourceOffset = charIndex * charWidth * charHeight;
    let row = dy * destWidth + dx * 4;
    for (let y = 0; y < renderHeight; y++) {
      let column = row;
      for (let x = 0; x < charWidth; x++) {
        const c = charData[sourceOffset++] / 255 * (foregroundAlpha / 255);
        dest[column++] = backgroundR + deltaR * c;
        dest[column++] = backgroundG + deltaG * c;
        dest[column++] = backgroundB + deltaB * c;
        dest[column++] = destAlpha;
      }
      row += destWidth;
    }
  }
  blockRenderChar(target, dx, dy, color, foregroundAlpha, backgroundColor, backgroundAlpha, force1pxHeight) {
    const charWidth = 1 * this.scale;
    const charHeight = 2 * this.scale;
    const renderHeight = force1pxHeight ? 1 : charHeight;
    if (dx + charWidth > target.width || dy + renderHeight > target.height) {
      console.warn("bad render request outside image data");
      return;
    }
    const destWidth = target.width * 4;
    const c = 0.5 * (foregroundAlpha / 255);
    const backgroundR = backgroundColor.r;
    const backgroundG = backgroundColor.g;
    const backgroundB = backgroundColor.b;
    const deltaR = color.r - backgroundR;
    const deltaG = color.g - backgroundG;
    const deltaB = color.b - backgroundB;
    const colorR = backgroundR + deltaR * c;
    const colorG = backgroundG + deltaG * c;
    const colorB = backgroundB + deltaB * c;
    const destAlpha = Math.max(foregroundAlpha, backgroundAlpha);
    const dest = target.data;
    let row = dy * destWidth + dx * 4;
    for (let y = 0; y < renderHeight; y++) {
      let column = row;
      for (let x = 0; x < charWidth; x++) {
        dest[column++] = colorR;
        dest[column++] = colorG;
        dest[column++] = colorB;
        dest[column++] = destAlpha;
      }
      row += destWidth;
    }
  }
}
const charTable = {
  "0": 0,
  "1": 1,
  "2": 2,
  "3": 3,
  "4": 4,
  "5": 5,
  "6": 6,
  "7": 7,
  "8": 8,
  "9": 9,
  A: 10,
  B: 11,
  C: 12,
  D: 13,
  E: 14,
  F: 15
};
const decodeData = (str2) => {
  const output = new Uint8ClampedArray(str2.length / 2);
  for (let i = 0; i < str2.length; i += 2) {
    output[i >> 1] = charTable[str2[i]] << 4 | charTable[str2[i + 1]] & 15;
  }
  return output;
};
const prebakedMiniMaps = {
  1: once$2(() => decodeData("0000511D6300CF609C709645A78432005642574171487021003C451900274D35D762755E8B629C5BA856AF57BA649530C167D1512A272A3F6038604460398526BCA2A968DB6F8957C768BE5FBE2FB467CF5D8D5B795DC7625B5DFF50DE64C466DB2FC47CD860A65E9A2EB96CB54CE06DA763AB2EA26860524D3763536601005116008177A8705E53AB738E6A982F88BAA35B5F5B626D9C636B449B737E5B7B678598869A662F6B5B8542706C704C80736A607578685B70594A49715A4522E792")),
  2: once$2(() => decodeData("000000000000000055394F383D2800008B8B1F210002000081B1CBCBCC820000847AAF6B9AAF2119BE08B8881AD60000A44FD07DCCF107015338130C00000000385972265F390B406E2437634B4B48031B12B8A0847000001E15B29A402F0000000000004B33460B00007A752C2A0000000000004D3900000084394B82013400ABA5CFC7AD9C0302A45A3E5A98AB000089A43382D97900008BA54AA087A70A0248A6A7AE6DBE0000BF6F94987EA40A01A06DCFA7A7A9030496C32F77891D0000A99FB1A0AFA80603B29AB9CA75930D010C0948354D3900000C0948354F37460D0028BE673D8400000000AF9D7B6E00002B007AA8933400007AA642675C2700007984CFB9C3985B768772A8A6B7B20000CAAECAAFC4B700009F94A6009F840009D09F9BA4CA9C0000CC8FC76DC87F0000C991C472A2000000A894A48CA7B501079BA2C9C69BA20000B19A5D3FA89000005CA6009DA2960901B0A7F0669FB200009D009E00B7890000DAD0F5D092820000D294D4C48BD10000B5A7A4A3B1A50402CAB6CBA6A2000000B5A7A4A3B1A8044FCDADD19D9CB00000B7778F7B8AAE0803C9AB5D3F5D3F00009EA09EA0BAB006039EA0989A8C7900009B9EF4D6B7C00000A9A7816CACA80000ABAC84705D3F000096DA635CDC8C00006F486F266F263D4784006124097B00374F6D2D6D2D6D4A3A95872322000000030000000000008D8939130000000000002E22A5C9CBC70600AB25C0B5C9B400061A2DB04CA67001082AA6BEBEBFC606002321DACBC19E03087AA08B6768380000282FBAC0B8CA7A88AD25BBA5A29900004C396C5894A6000040485A6E356E9442A32CD17EADA70000B4237923628600003E2DE9C1D7B500002F25BBA5A2990000231DB6AFB4A804023025C0B5CAB588062B2CBDBEC0C706882435A75CA20000002326BD6A82A908048B4B9A5A668000002423A09CB4BB060025259C9D8A7900001C1FCAB2C7C700002A2A9387ABA200002626A4A47D6E9D14333163A0C87500004B6F9C2D643A257049364936493647358A34438355497F1A0000A24C1D590000D38DFFBDD4CD3126"))
};
class MinimapCharRendererFactory {
  /**
   * Creates a new character renderer factory with the given scale.
   */
  static create(scale, fontFamily) {
    if (this.lastCreated && scale === this.lastCreated.scale && fontFamily === this.lastFontFamily) {
      return this.lastCreated;
    }
    let factory;
    if (prebakedMiniMaps[scale]) {
      factory = new MinimapCharRenderer(prebakedMiniMaps[scale](), scale);
    } else {
      factory = MinimapCharRendererFactory.createFromSampleData(MinimapCharRendererFactory.createSampleData(fontFamily).data, scale);
    }
    this.lastFontFamily = fontFamily;
    this.lastCreated = factory;
    return factory;
  }
  /**
   * Creates the font sample data, writing to a canvas.
   */
  static createSampleData(fontFamily) {
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    canvas.style.height = `${16}px`;
    canvas.height = 16;
    canvas.width = 96 * 10;
    canvas.style.width = 96 * 10 + "px";
    ctx.fillStyle = "#ffffff";
    ctx.font = `bold ${16}px ${fontFamily}`;
    ctx.textBaseline = "middle";
    let x = 0;
    for (const code of allCharCodes) {
      ctx.fillText(String.fromCharCode(code), x, 16 / 2);
      x += 10;
    }
    return ctx.getImageData(
      0,
      0,
      96 * 10,
      16
      /* Constants.SAMPLED_CHAR_HEIGHT */
    );
  }
  /**
   * Creates a character renderer from the canvas sample data.
   */
  static createFromSampleData(source, scale) {
    const expectedLength = 16 * 10 * 4 * 96;
    if (source.length !== expectedLength) {
      throw new Error("Unexpected source in MinimapCharRenderer");
    }
    const charData = MinimapCharRendererFactory._downsample(source, scale);
    return new MinimapCharRenderer(charData, scale);
  }
  static _downsampleChar(source, sourceOffset, dest, destOffset, scale) {
    const width = 1 * scale;
    const height = 2 * scale;
    let targetIndex = destOffset;
    let brightest = 0;
    for (let y = 0; y < height; y++) {
      const sourceY1 = y / height * 16;
      const sourceY2 = (y + 1) / height * 16;
      for (let x = 0; x < width; x++) {
        const sourceX1 = x / width * 10;
        const sourceX2 = (x + 1) / width * 10;
        let value = 0;
        let samples = 0;
        for (let sy = sourceY1; sy < sourceY2; sy++) {
          const sourceRow = sourceOffset + Math.floor(sy) * 3840;
          const yBalance = 1 - (sy - Math.floor(sy));
          for (let sx = sourceX1; sx < sourceX2; sx++) {
            const xBalance = 1 - (sx - Math.floor(sx));
            const sourceIndex = sourceRow + Math.floor(sx) * 4;
            const weight2 = xBalance * yBalance;
            samples += weight2;
            value += source[sourceIndex] * source[sourceIndex + 3] / 255 * weight2;
          }
        }
        const final = value / samples;
        brightest = Math.max(brightest, final);
        dest[targetIndex++] = toUint8(final);
      }
    }
    return brightest;
  }
  static _downsample(data, scale) {
    const pixelsPerCharacter = 2 * scale * 1 * scale;
    const resultLen = pixelsPerCharacter * 96;
    const result2 = new Uint8ClampedArray(resultLen);
    let resultOffset = 0;
    let sourceOffset = 0;
    let brightest = 0;
    for (let charIndex = 0; charIndex < 96; charIndex++) {
      brightest = Math.max(brightest, this._downsampleChar(data, sourceOffset, result2, resultOffset, scale));
      resultOffset += pixelsPerCharacter;
      sourceOffset += 10 * 4;
    }
    if (brightest > 0) {
      const adjust = 255 / brightest;
      for (let i = 0; i < resultLen; i++) {
        result2[i] *= adjust;
      }
    }
    return result2;
  }
}
var OverviewRulerLane$1;
(function(OverviewRulerLane2) {
  OverviewRulerLane2[OverviewRulerLane2["Left"] = 1] = "Left";
  OverviewRulerLane2[OverviewRulerLane2["Center"] = 2] = "Center";
  OverviewRulerLane2[OverviewRulerLane2["Right"] = 4] = "Right";
  OverviewRulerLane2[OverviewRulerLane2["Full"] = 7] = "Full";
})(OverviewRulerLane$1 || (OverviewRulerLane$1 = {}));
var GlyphMarginLane$1;
(function(GlyphMarginLane2) {
  GlyphMarginLane2[GlyphMarginLane2["Left"] = 1] = "Left";
  GlyphMarginLane2[GlyphMarginLane2["Right"] = 2] = "Right";
})(GlyphMarginLane$1 || (GlyphMarginLane$1 = {}));
var MinimapPosition$1;
(function(MinimapPosition2) {
  MinimapPosition2[MinimapPosition2["Inline"] = 1] = "Inline";
  MinimapPosition2[MinimapPosition2["Gutter"] = 2] = "Gutter";
})(MinimapPosition$1 || (MinimapPosition$1 = {}));
var InjectedTextCursorStops$1;
(function(InjectedTextCursorStops2) {
  InjectedTextCursorStops2[InjectedTextCursorStops2["Both"] = 0] = "Both";
  InjectedTextCursorStops2[InjectedTextCursorStops2["Right"] = 1] = "Right";
  InjectedTextCursorStops2[InjectedTextCursorStops2["Left"] = 2] = "Left";
  InjectedTextCursorStops2[InjectedTextCursorStops2["None"] = 3] = "None";
})(InjectedTextCursorStops$1 || (InjectedTextCursorStops$1 = {}));
class TextModelResolvedOptions {
  get originalIndentSize() {
    return this._indentSizeIsTabSize ? "tabSize" : this.indentSize;
  }
  /**
   * @internal
   */
  constructor(src) {
    this._textModelResolvedOptionsBrand = void 0;
    this.tabSize = Math.max(1, src.tabSize | 0);
    if (src.indentSize === "tabSize") {
      this.indentSize = this.tabSize;
      this._indentSizeIsTabSize = true;
    } else {
      this.indentSize = Math.max(1, src.indentSize | 0);
      this._indentSizeIsTabSize = false;
    }
    this.insertSpaces = Boolean(src.insertSpaces);
    this.defaultEOL = src.defaultEOL | 0;
    this.trimAutoWhitespace = Boolean(src.trimAutoWhitespace);
    this.bracketPairColorizationOptions = src.bracketPairColorizationOptions;
  }
  /**
   * @internal
   */
  equals(other) {
    return this.tabSize === other.tabSize && this._indentSizeIsTabSize === other._indentSizeIsTabSize && this.indentSize === other.indentSize && this.insertSpaces === other.insertSpaces && this.defaultEOL === other.defaultEOL && this.trimAutoWhitespace === other.trimAutoWhitespace && equals$2(this.bracketPairColorizationOptions, other.bracketPairColorizationOptions);
  }
  /**
   * @internal
   */
  createChangeEvent(newOpts) {
    return {
      tabSize: this.tabSize !== newOpts.tabSize,
      indentSize: this.indentSize !== newOpts.indentSize,
      insertSpaces: this.insertSpaces !== newOpts.insertSpaces,
      trimAutoWhitespace: this.trimAutoWhitespace !== newOpts.trimAutoWhitespace
    };
  }
}
class FindMatch {
  /**
   * @internal
   */
  constructor(range2, matches) {
    this._findMatchBrand = void 0;
    this.range = range2;
    this.matches = matches;
  }
}
function isITextSnapshot(obj) {
  return obj && typeof obj.read === "function";
}
class ValidAnnotatedEditOperation {
  constructor(identifier, range2, text2, forceMoveMarkers, isAutoWhitespaceEdit, _isTracked) {
    this.identifier = identifier;
    this.range = range2;
    this.text = text2;
    this.forceMoveMarkers = forceMoveMarkers;
    this.isAutoWhitespaceEdit = isAutoWhitespaceEdit;
    this._isTracked = _isTracked;
  }
}
class SearchData {
  constructor(regex, wordSeparators2, simpleSearch) {
    this.regex = regex;
    this.wordSeparators = wordSeparators2;
    this.simpleSearch = simpleSearch;
  }
}
class ApplyEditsResult {
  constructor(reverseEdits, changes, trimAutoWhitespaceLineNumbers) {
    this.reverseEdits = reverseEdits;
    this.changes = changes;
    this.trimAutoWhitespaceLineNumbers = trimAutoWhitespaceLineNumbers;
  }
}
function shouldSynchronizeModel(model) {
  return !model.isTooLargeForSyncing() && !model.isForSimpleWidget;
}
const POINTER_DRAG_RESET_DISTANCE = 140;
const GUTTER_DECORATION_WIDTH = 2;
class MinimapOptions {
  constructor(configuration, theme, tokensColorTracker) {
    const options = configuration.options;
    const pixelRatio = options.get(
      140
      /* EditorOption.pixelRatio */
    );
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    const minimapLayout = layoutInfo.minimap;
    const fontInfo = options.get(
      49
      /* EditorOption.fontInfo */
    );
    const minimapOpts = options.get(
      71
      /* EditorOption.minimap */
    );
    this.renderMinimap = minimapLayout.renderMinimap;
    this.size = minimapOpts.size;
    this.minimapHeightIsEditorHeight = minimapLayout.minimapHeightIsEditorHeight;
    this.scrollBeyondLastLine = options.get(
      103
      /* EditorOption.scrollBeyondLastLine */
    );
    this.paddingTop = options.get(
      82
      /* EditorOption.padding */
    ).top;
    this.paddingBottom = options.get(
      82
      /* EditorOption.padding */
    ).bottom;
    this.showSlider = minimapOpts.showSlider;
    this.autohide = minimapOpts.autohide;
    this.pixelRatio = pixelRatio;
    this.typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
    this.lineHeight = options.get(
      65
      /* EditorOption.lineHeight */
    );
    this.minimapLeft = minimapLayout.minimapLeft;
    this.minimapWidth = minimapLayout.minimapWidth;
    this.minimapHeight = layoutInfo.height;
    this.canvasInnerWidth = minimapLayout.minimapCanvasInnerWidth;
    this.canvasInnerHeight = minimapLayout.minimapCanvasInnerHeight;
    this.canvasOuterWidth = minimapLayout.minimapCanvasOuterWidth;
    this.canvasOuterHeight = minimapLayout.minimapCanvasOuterHeight;
    this.isSampling = minimapLayout.minimapIsSampling;
    this.editorHeight = layoutInfo.height;
    this.fontScale = minimapLayout.minimapScale;
    this.minimapLineHeight = minimapLayout.minimapLineHeight;
    this.minimapCharWidth = 1 * this.fontScale;
    this.charRenderer = once$2(() => MinimapCharRendererFactory.create(this.fontScale, fontInfo.fontFamily));
    this.defaultBackgroundColor = tokensColorTracker.getColor(
      2
      /* ColorId.DefaultBackground */
    );
    this.backgroundColor = MinimapOptions._getMinimapBackground(theme, this.defaultBackgroundColor);
    this.foregroundAlpha = MinimapOptions._getMinimapForegroundOpacity(theme);
  }
  static _getMinimapBackground(theme, defaultBackgroundColor) {
    const themeColor = theme.getColor(minimapBackground);
    if (themeColor) {
      return new RGBA8(themeColor.rgba.r, themeColor.rgba.g, themeColor.rgba.b, Math.round(255 * themeColor.rgba.a));
    }
    return defaultBackgroundColor;
  }
  static _getMinimapForegroundOpacity(theme) {
    const themeColor = theme.getColor(minimapForegroundOpacity);
    if (themeColor) {
      return RGBA8._clamp(Math.round(255 * themeColor.rgba.a));
    }
    return 255;
  }
  equals(other) {
    return this.renderMinimap === other.renderMinimap && this.size === other.size && this.minimapHeightIsEditorHeight === other.minimapHeightIsEditorHeight && this.scrollBeyondLastLine === other.scrollBeyondLastLine && this.paddingTop === other.paddingTop && this.paddingBottom === other.paddingBottom && this.showSlider === other.showSlider && this.autohide === other.autohide && this.pixelRatio === other.pixelRatio && this.typicalHalfwidthCharacterWidth === other.typicalHalfwidthCharacterWidth && this.lineHeight === other.lineHeight && this.minimapLeft === other.minimapLeft && this.minimapWidth === other.minimapWidth && this.minimapHeight === other.minimapHeight && this.canvasInnerWidth === other.canvasInnerWidth && this.canvasInnerHeight === other.canvasInnerHeight && this.canvasOuterWidth === other.canvasOuterWidth && this.canvasOuterHeight === other.canvasOuterHeight && this.isSampling === other.isSampling && this.editorHeight === other.editorHeight && this.fontScale === other.fontScale && this.minimapLineHeight === other.minimapLineHeight && this.minimapCharWidth === other.minimapCharWidth && this.defaultBackgroundColor && this.defaultBackgroundColor.equals(other.defaultBackgroundColor) && this.backgroundColor && this.backgroundColor.equals(other.backgroundColor) && this.foregroundAlpha === other.foregroundAlpha;
  }
}
class MinimapLayout {
  constructor(scrollTop, scrollHeight, sliderNeeded, _computedSliderRatio, sliderTop, sliderHeight, topPaddingLineCount, startLineNumber, endLineNumber) {
    this.scrollTop = scrollTop;
    this.scrollHeight = scrollHeight;
    this.sliderNeeded = sliderNeeded;
    this._computedSliderRatio = _computedSliderRatio;
    this.sliderTop = sliderTop;
    this.sliderHeight = sliderHeight;
    this.topPaddingLineCount = topPaddingLineCount;
    this.startLineNumber = startLineNumber;
    this.endLineNumber = endLineNumber;
  }
  /**
   * Compute a desired `scrollPosition` such that the slider moves by `delta`.
   */
  getDesiredScrollTopFromDelta(delta) {
    return Math.round(this.scrollTop + delta / this._computedSliderRatio);
  }
  getDesiredScrollTopFromTouchLocation(pageY) {
    return Math.round((pageY - this.sliderHeight / 2) / this._computedSliderRatio);
  }
  /**
   * Intersect a line range with `this.startLineNumber` and `this.endLineNumber`.
   */
  intersectWithViewport(range2) {
    const startLineNumber = Math.max(this.startLineNumber, range2.startLineNumber);
    const endLineNumber = Math.min(this.endLineNumber, range2.endLineNumber);
    if (startLineNumber > endLineNumber) {
      return null;
    }
    return [startLineNumber, endLineNumber];
  }
  /**
   * Get the inner minimap y coordinate for a line number.
   */
  getYForLineNumber(lineNumber, minimapLineHeight) {
    return +(lineNumber - this.startLineNumber + this.topPaddingLineCount) * minimapLineHeight;
  }
  static create(options, viewportStartLineNumber, viewportEndLineNumber, viewportStartLineNumberVerticalOffset, viewportHeight, viewportContainsWhitespaceGaps, lineCount, realLineCount, scrollTop, scrollHeight, previousLayout) {
    const pixelRatio = options.pixelRatio;
    const minimapLineHeight = options.minimapLineHeight;
    const minimapLinesFitting = Math.floor(options.canvasInnerHeight / minimapLineHeight);
    const lineHeight = options.lineHeight;
    if (options.minimapHeightIsEditorHeight) {
      let logicalScrollHeight = realLineCount * options.lineHeight + options.paddingTop + options.paddingBottom;
      if (options.scrollBeyondLastLine) {
        logicalScrollHeight += Math.max(0, viewportHeight - options.lineHeight - options.paddingBottom);
      }
      const sliderHeight2 = Math.max(1, Math.floor(viewportHeight * viewportHeight / logicalScrollHeight));
      const maxMinimapSliderTop2 = Math.max(0, options.minimapHeight - sliderHeight2);
      const computedSliderRatio2 = maxMinimapSliderTop2 / (scrollHeight - viewportHeight);
      const sliderTop2 = scrollTop * computedSliderRatio2;
      const sliderNeeded = maxMinimapSliderTop2 > 0;
      const maxLinesFitting = Math.floor(options.canvasInnerHeight / options.minimapLineHeight);
      const topPaddingLineCount = Math.floor(options.paddingTop / options.lineHeight);
      return new MinimapLayout(scrollTop, scrollHeight, sliderNeeded, computedSliderRatio2, sliderTop2, sliderHeight2, topPaddingLineCount, 1, Math.min(lineCount, maxLinesFitting));
    }
    let sliderHeight;
    if (viewportContainsWhitespaceGaps && viewportEndLineNumber !== lineCount) {
      const viewportLineCount = viewportEndLineNumber - viewportStartLineNumber + 1;
      sliderHeight = Math.floor(viewportLineCount * minimapLineHeight / pixelRatio);
    } else {
      const expectedViewportLineCount = viewportHeight / lineHeight;
      sliderHeight = Math.floor(expectedViewportLineCount * minimapLineHeight / pixelRatio);
    }
    const extraLinesAtTheTop = Math.floor(options.paddingTop / lineHeight);
    let extraLinesAtTheBottom = Math.floor(options.paddingBottom / lineHeight);
    if (options.scrollBeyondLastLine) {
      const expectedViewportLineCount = viewportHeight / lineHeight;
      extraLinesAtTheBottom = Math.max(extraLinesAtTheBottom, expectedViewportLineCount - 1);
    }
    let maxMinimapSliderTop;
    if (extraLinesAtTheBottom > 0) {
      const expectedViewportLineCount = viewportHeight / lineHeight;
      maxMinimapSliderTop = (extraLinesAtTheTop + lineCount + extraLinesAtTheBottom - expectedViewportLineCount - 1) * minimapLineHeight / pixelRatio;
    } else {
      maxMinimapSliderTop = Math.max(0, (extraLinesAtTheTop + lineCount) * minimapLineHeight / pixelRatio - sliderHeight);
    }
    maxMinimapSliderTop = Math.min(options.minimapHeight - sliderHeight, maxMinimapSliderTop);
    const computedSliderRatio = maxMinimapSliderTop / (scrollHeight - viewportHeight);
    const sliderTop = scrollTop * computedSliderRatio;
    if (minimapLinesFitting >= extraLinesAtTheTop + lineCount + extraLinesAtTheBottom) {
      const sliderNeeded = maxMinimapSliderTop > 0;
      return new MinimapLayout(scrollTop, scrollHeight, sliderNeeded, computedSliderRatio, sliderTop, sliderHeight, extraLinesAtTheTop, 1, lineCount);
    } else {
      let consideringStartLineNumber;
      if (viewportStartLineNumber > 1) {
        consideringStartLineNumber = viewportStartLineNumber + extraLinesAtTheTop;
      } else {
        consideringStartLineNumber = Math.max(1, scrollTop / lineHeight);
      }
      let topPaddingLineCount;
      let startLineNumber = Math.max(1, Math.floor(consideringStartLineNumber - sliderTop * pixelRatio / minimapLineHeight));
      if (startLineNumber < extraLinesAtTheTop) {
        topPaddingLineCount = extraLinesAtTheTop - startLineNumber + 1;
        startLineNumber = 1;
      } else {
        topPaddingLineCount = 0;
        startLineNumber = Math.max(1, startLineNumber - extraLinesAtTheTop);
      }
      if (previousLayout && previousLayout.scrollHeight === scrollHeight) {
        if (previousLayout.scrollTop > scrollTop) {
          startLineNumber = Math.min(startLineNumber, previousLayout.startLineNumber);
          topPaddingLineCount = Math.max(topPaddingLineCount, previousLayout.topPaddingLineCount);
        }
        if (previousLayout.scrollTop < scrollTop) {
          startLineNumber = Math.max(startLineNumber, previousLayout.startLineNumber);
          topPaddingLineCount = Math.min(topPaddingLineCount, previousLayout.topPaddingLineCount);
        }
      }
      const endLineNumber = Math.min(lineCount, startLineNumber - topPaddingLineCount + minimapLinesFitting - 1);
      const partialLine = (scrollTop - viewportStartLineNumberVerticalOffset) / lineHeight;
      let sliderTopAligned;
      if (scrollTop >= options.paddingTop) {
        sliderTopAligned = (viewportStartLineNumber - startLineNumber + topPaddingLineCount + partialLine) * minimapLineHeight / pixelRatio;
      } else {
        sliderTopAligned = scrollTop / options.paddingTop * (topPaddingLineCount + partialLine) * minimapLineHeight / pixelRatio;
      }
      return new MinimapLayout(scrollTop, scrollHeight, true, computedSliderRatio, sliderTopAligned, sliderHeight, topPaddingLineCount, startLineNumber, endLineNumber);
    }
  }
}
class MinimapLine {
  constructor(dy) {
    this.dy = dy;
  }
  onContentChanged() {
    this.dy = -1;
  }
  onTokensChanged() {
    this.dy = -1;
  }
}
MinimapLine.INVALID = new MinimapLine(-1);
class RenderData {
  constructor(renderedLayout, imageData, lines) {
    this.renderedLayout = renderedLayout;
    this._imageData = imageData;
    this._renderedLines = new RenderedLinesCollection(() => MinimapLine.INVALID);
    this._renderedLines._set(renderedLayout.startLineNumber, lines);
  }
  /**
   * Check if the current RenderData matches accurately the new desired layout and no painting is needed.
   */
  linesEquals(layout2) {
    if (!this.scrollEquals(layout2)) {
      return false;
    }
    const tmp = this._renderedLines._get();
    const lines = tmp.lines;
    for (let i = 0, len = lines.length; i < len; i++) {
      if (lines[i].dy === -1) {
        return false;
      }
    }
    return true;
  }
  /**
   * Check if the current RenderData matches the new layout's scroll position
   */
  scrollEquals(layout2) {
    return this.renderedLayout.startLineNumber === layout2.startLineNumber && this.renderedLayout.endLineNumber === layout2.endLineNumber;
  }
  _get() {
    const tmp = this._renderedLines._get();
    return {
      imageData: this._imageData,
      rendLineNumberStart: tmp.rendLineNumberStart,
      lines: tmp.lines
    };
  }
  onLinesChanged(changeFromLineNumber, changeCount) {
    return this._renderedLines.onLinesChanged(changeFromLineNumber, changeCount);
  }
  onLinesDeleted(deleteFromLineNumber, deleteToLineNumber) {
    this._renderedLines.onLinesDeleted(deleteFromLineNumber, deleteToLineNumber);
  }
  onLinesInserted(insertFromLineNumber, insertToLineNumber) {
    this._renderedLines.onLinesInserted(insertFromLineNumber, insertToLineNumber);
  }
  onTokensChanged(ranges) {
    return this._renderedLines.onTokensChanged(ranges);
  }
}
class MinimapBuffers {
  constructor(ctx, WIDTH, HEIGHT, background) {
    this._backgroundFillData = MinimapBuffers._createBackgroundFillData(WIDTH, HEIGHT, background);
    this._buffers = [
      ctx.createImageData(WIDTH, HEIGHT),
      ctx.createImageData(WIDTH, HEIGHT)
    ];
    this._lastUsedBuffer = 0;
  }
  getBuffer() {
    this._lastUsedBuffer = 1 - this._lastUsedBuffer;
    const result2 = this._buffers[this._lastUsedBuffer];
    result2.data.set(this._backgroundFillData);
    return result2;
  }
  static _createBackgroundFillData(WIDTH, HEIGHT, background) {
    const backgroundR = background.r;
    const backgroundG = background.g;
    const backgroundB = background.b;
    const backgroundA = background.a;
    const result2 = new Uint8ClampedArray(WIDTH * HEIGHT * 4);
    let offset = 0;
    for (let i = 0; i < HEIGHT; i++) {
      for (let j = 0; j < WIDTH; j++) {
        result2[offset] = backgroundR;
        result2[offset + 1] = backgroundG;
        result2[offset + 2] = backgroundB;
        result2[offset + 3] = backgroundA;
        offset += 4;
      }
    }
    return result2;
  }
}
class MinimapSamplingState {
  static compute(options, viewLineCount, oldSamplingState) {
    if (options.renderMinimap === 0 || !options.isSampling) {
      return [null, []];
    }
    const { minimapLineCount } = EditorLayoutInfoComputer.computeContainedMinimapLineCount({
      viewLineCount,
      scrollBeyondLastLine: options.scrollBeyondLastLine,
      paddingTop: options.paddingTop,
      paddingBottom: options.paddingBottom,
      height: options.editorHeight,
      lineHeight: options.lineHeight,
      pixelRatio: options.pixelRatio
    });
    const ratio = viewLineCount / minimapLineCount;
    const halfRatio = ratio / 2;
    if (!oldSamplingState || oldSamplingState.minimapLines.length === 0) {
      const result3 = [];
      result3[0] = 1;
      if (minimapLineCount > 1) {
        for (let i = 0, lastIndex2 = minimapLineCount - 1; i < lastIndex2; i++) {
          result3[i] = Math.round(i * ratio + halfRatio);
        }
        result3[minimapLineCount - 1] = viewLineCount;
      }
      return [new MinimapSamplingState(ratio, result3), []];
    }
    const oldMinimapLines = oldSamplingState.minimapLines;
    const oldLength = oldMinimapLines.length;
    const result2 = [];
    let oldIndex = 0;
    let oldDeltaLineCount = 0;
    let minViewLineNumber = 1;
    const MAX_EVENT_COUNT = 10;
    let events = [];
    let lastEvent = null;
    for (let i = 0; i < minimapLineCount; i++) {
      const fromViewLineNumber = Math.max(minViewLineNumber, Math.round(i * ratio));
      const toViewLineNumber = Math.max(fromViewLineNumber, Math.round((i + 1) * ratio));
      while (oldIndex < oldLength && oldMinimapLines[oldIndex] < fromViewLineNumber) {
        if (events.length < MAX_EVENT_COUNT) {
          const oldMinimapLineNumber = oldIndex + 1 + oldDeltaLineCount;
          if (lastEvent && lastEvent.type === "deleted" && lastEvent._oldIndex === oldIndex - 1) {
            lastEvent.deleteToLineNumber++;
          } else {
            lastEvent = { type: "deleted", _oldIndex: oldIndex, deleteFromLineNumber: oldMinimapLineNumber, deleteToLineNumber: oldMinimapLineNumber };
            events.push(lastEvent);
          }
          oldDeltaLineCount--;
        }
        oldIndex++;
      }
      let selectedViewLineNumber;
      if (oldIndex < oldLength && oldMinimapLines[oldIndex] <= toViewLineNumber) {
        selectedViewLineNumber = oldMinimapLines[oldIndex];
        oldIndex++;
      } else {
        if (i === 0) {
          selectedViewLineNumber = 1;
        } else if (i + 1 === minimapLineCount) {
          selectedViewLineNumber = viewLineCount;
        } else {
          selectedViewLineNumber = Math.round(i * ratio + halfRatio);
        }
        if (events.length < MAX_EVENT_COUNT) {
          const oldMinimapLineNumber = oldIndex + 1 + oldDeltaLineCount;
          if (lastEvent && lastEvent.type === "inserted" && lastEvent._i === i - 1) {
            lastEvent.insertToLineNumber++;
          } else {
            lastEvent = { type: "inserted", _i: i, insertFromLineNumber: oldMinimapLineNumber, insertToLineNumber: oldMinimapLineNumber };
            events.push(lastEvent);
          }
          oldDeltaLineCount++;
        }
      }
      result2[i] = selectedViewLineNumber;
      minViewLineNumber = selectedViewLineNumber;
    }
    if (events.length < MAX_EVENT_COUNT) {
      while (oldIndex < oldLength) {
        const oldMinimapLineNumber = oldIndex + 1 + oldDeltaLineCount;
        if (lastEvent && lastEvent.type === "deleted" && lastEvent._oldIndex === oldIndex - 1) {
          lastEvent.deleteToLineNumber++;
        } else {
          lastEvent = { type: "deleted", _oldIndex: oldIndex, deleteFromLineNumber: oldMinimapLineNumber, deleteToLineNumber: oldMinimapLineNumber };
          events.push(lastEvent);
        }
        oldDeltaLineCount--;
        oldIndex++;
      }
    } else {
      events = [{ type: "flush" }];
    }
    return [new MinimapSamplingState(ratio, result2), events];
  }
  constructor(samplingRatio, minimapLines) {
    this.samplingRatio = samplingRatio;
    this.minimapLines = minimapLines;
  }
  modelLineToMinimapLine(lineNumber) {
    return Math.min(this.minimapLines.length, Math.max(1, Math.round(lineNumber / this.samplingRatio)));
  }
  /**
   * Will return null if the model line ranges are not intersecting with a sampled model line.
   */
  modelLineRangeToMinimapLineRange(fromLineNumber, toLineNumber) {
    let fromLineIndex = this.modelLineToMinimapLine(fromLineNumber) - 1;
    while (fromLineIndex > 0 && this.minimapLines[fromLineIndex - 1] >= fromLineNumber) {
      fromLineIndex--;
    }
    let toLineIndex = this.modelLineToMinimapLine(toLineNumber) - 1;
    while (toLineIndex + 1 < this.minimapLines.length && this.minimapLines[toLineIndex + 1] <= toLineNumber) {
      toLineIndex++;
    }
    if (fromLineIndex === toLineIndex) {
      const sampledLineNumber = this.minimapLines[fromLineIndex];
      if (sampledLineNumber < fromLineNumber || sampledLineNumber > toLineNumber) {
        return null;
      }
    }
    return [fromLineIndex + 1, toLineIndex + 1];
  }
  /**
   * Will always return a range, even if it is not intersecting with a sampled model line.
   */
  decorationLineRangeToMinimapLineRange(startLineNumber, endLineNumber) {
    let minimapLineStart = this.modelLineToMinimapLine(startLineNumber);
    let minimapLineEnd = this.modelLineToMinimapLine(endLineNumber);
    if (startLineNumber !== endLineNumber && minimapLineEnd === minimapLineStart) {
      if (minimapLineEnd === this.minimapLines.length) {
        if (minimapLineStart > 1) {
          minimapLineStart--;
        }
      } else {
        minimapLineEnd++;
      }
    }
    return [minimapLineStart, minimapLineEnd];
  }
  onLinesDeleted(e) {
    const deletedLineCount = e.toLineNumber - e.fromLineNumber + 1;
    let changeStartIndex = this.minimapLines.length;
    let changeEndIndex = 0;
    for (let i = this.minimapLines.length - 1; i >= 0; i--) {
      if (this.minimapLines[i] < e.fromLineNumber) {
        break;
      }
      if (this.minimapLines[i] <= e.toLineNumber) {
        this.minimapLines[i] = Math.max(1, e.fromLineNumber - 1);
        changeStartIndex = Math.min(changeStartIndex, i);
        changeEndIndex = Math.max(changeEndIndex, i);
      } else {
        this.minimapLines[i] -= deletedLineCount;
      }
    }
    return [changeStartIndex, changeEndIndex];
  }
  onLinesInserted(e) {
    const insertedLineCount = e.toLineNumber - e.fromLineNumber + 1;
    for (let i = this.minimapLines.length - 1; i >= 0; i--) {
      if (this.minimapLines[i] < e.fromLineNumber) {
        break;
      }
      this.minimapLines[i] += insertedLineCount;
    }
  }
}
class Minimap extends ViewPart {
  constructor(context) {
    super(context);
    this.tokensColorTracker = MinimapTokensColorTracker.getInstance();
    this._selections = [];
    this._minimapSelections = null;
    this.options = new MinimapOptions(this._context.configuration, this._context.theme, this.tokensColorTracker);
    const [samplingState] = MinimapSamplingState.compute(this.options, this._context.viewModel.getLineCount(), null);
    this._samplingState = samplingState;
    this._shouldCheckSampling = false;
    this._actual = new InnerMinimap(context.theme, this);
  }
  dispose() {
    this._actual.dispose();
    super.dispose();
  }
  getDomNode() {
    return this._actual.getDomNode();
  }
  _onOptionsMaybeChanged() {
    const opts = new MinimapOptions(this._context.configuration, this._context.theme, this.tokensColorTracker);
    if (this.options.equals(opts)) {
      return false;
    }
    this.options = opts;
    this._recreateLineSampling();
    this._actual.onDidChangeOptions();
    return true;
  }
  // ---- begin view event handlers
  onConfigurationChanged(e) {
    return this._onOptionsMaybeChanged();
  }
  onCursorStateChanged(e) {
    this._selections = e.selections;
    this._minimapSelections = null;
    return this._actual.onSelectionChanged();
  }
  onDecorationsChanged(e) {
    if (e.affectsMinimap) {
      return this._actual.onDecorationsChanged();
    }
    return false;
  }
  onFlushed(e) {
    if (this._samplingState) {
      this._shouldCheckSampling = true;
    }
    return this._actual.onFlushed();
  }
  onLinesChanged(e) {
    if (this._samplingState) {
      const minimapLineRange = this._samplingState.modelLineRangeToMinimapLineRange(e.fromLineNumber, e.fromLineNumber + e.count - 1);
      if (minimapLineRange) {
        return this._actual.onLinesChanged(minimapLineRange[0], minimapLineRange[1] - minimapLineRange[0] + 1);
      } else {
        return false;
      }
    } else {
      return this._actual.onLinesChanged(e.fromLineNumber, e.count);
    }
  }
  onLinesDeleted(e) {
    if (this._samplingState) {
      const [changeStartIndex, changeEndIndex] = this._samplingState.onLinesDeleted(e);
      if (changeStartIndex <= changeEndIndex) {
        this._actual.onLinesChanged(changeStartIndex + 1, changeEndIndex - changeStartIndex + 1);
      }
      this._shouldCheckSampling = true;
      return true;
    } else {
      return this._actual.onLinesDeleted(e.fromLineNumber, e.toLineNumber);
    }
  }
  onLinesInserted(e) {
    if (this._samplingState) {
      this._samplingState.onLinesInserted(e);
      this._shouldCheckSampling = true;
      return true;
    } else {
      return this._actual.onLinesInserted(e.fromLineNumber, e.toLineNumber);
    }
  }
  onScrollChanged(e) {
    return this._actual.onScrollChanged();
  }
  onThemeChanged(e) {
    this._actual.onThemeChanged();
    this._onOptionsMaybeChanged();
    return true;
  }
  onTokensChanged(e) {
    if (this._samplingState) {
      const ranges = [];
      for (const range2 of e.ranges) {
        const minimapLineRange = this._samplingState.modelLineRangeToMinimapLineRange(range2.fromLineNumber, range2.toLineNumber);
        if (minimapLineRange) {
          ranges.push({ fromLineNumber: minimapLineRange[0], toLineNumber: minimapLineRange[1] });
        }
      }
      if (ranges.length) {
        return this._actual.onTokensChanged(ranges);
      } else {
        return false;
      }
    } else {
      return this._actual.onTokensChanged(e.ranges);
    }
  }
  onTokensColorsChanged(e) {
    this._onOptionsMaybeChanged();
    return this._actual.onTokensColorsChanged();
  }
  onZonesChanged(e) {
    return this._actual.onZonesChanged();
  }
  // --- end event handlers
  prepareRender(ctx) {
    if (this._shouldCheckSampling) {
      this._shouldCheckSampling = false;
      this._recreateLineSampling();
    }
  }
  render(ctx) {
    let viewportStartLineNumber = ctx.visibleRange.startLineNumber;
    let viewportEndLineNumber = ctx.visibleRange.endLineNumber;
    if (this._samplingState) {
      viewportStartLineNumber = this._samplingState.modelLineToMinimapLine(viewportStartLineNumber);
      viewportEndLineNumber = this._samplingState.modelLineToMinimapLine(viewportEndLineNumber);
    }
    const minimapCtx = {
      viewportContainsWhitespaceGaps: ctx.viewportData.whitespaceViewportData.length > 0,
      scrollWidth: ctx.scrollWidth,
      scrollHeight: ctx.scrollHeight,
      viewportStartLineNumber,
      viewportEndLineNumber,
      viewportStartLineNumberVerticalOffset: ctx.getVerticalOffsetForLineNumber(viewportStartLineNumber),
      scrollTop: ctx.scrollTop,
      scrollLeft: ctx.scrollLeft,
      viewportWidth: ctx.viewportWidth,
      viewportHeight: ctx.viewportHeight
    };
    this._actual.render(minimapCtx);
  }
  //#region IMinimapModel
  _recreateLineSampling() {
    this._minimapSelections = null;
    const wasSampling = Boolean(this._samplingState);
    const [samplingState, events] = MinimapSamplingState.compute(this.options, this._context.viewModel.getLineCount(), this._samplingState);
    this._samplingState = samplingState;
    if (wasSampling && this._samplingState) {
      for (const event of events) {
        switch (event.type) {
          case "deleted":
            this._actual.onLinesDeleted(event.deleteFromLineNumber, event.deleteToLineNumber);
            break;
          case "inserted":
            this._actual.onLinesInserted(event.insertFromLineNumber, event.insertToLineNumber);
            break;
          case "flush":
            this._actual.onFlushed();
            break;
        }
      }
    }
  }
  getLineCount() {
    if (this._samplingState) {
      return this._samplingState.minimapLines.length;
    }
    return this._context.viewModel.getLineCount();
  }
  getRealLineCount() {
    return this._context.viewModel.getLineCount();
  }
  getLineContent(lineNumber) {
    if (this._samplingState) {
      return this._context.viewModel.getLineContent(this._samplingState.minimapLines[lineNumber - 1]);
    }
    return this._context.viewModel.getLineContent(lineNumber);
  }
  getLineMaxColumn(lineNumber) {
    if (this._samplingState) {
      return this._context.viewModel.getLineMaxColumn(this._samplingState.minimapLines[lineNumber - 1]);
    }
    return this._context.viewModel.getLineMaxColumn(lineNumber);
  }
  getMinimapLinesRenderingData(startLineNumber, endLineNumber, needed) {
    if (this._samplingState) {
      const result2 = [];
      for (let lineIndex = 0, lineCount = endLineNumber - startLineNumber + 1; lineIndex < lineCount; lineIndex++) {
        if (needed[lineIndex]) {
          result2[lineIndex] = this._context.viewModel.getViewLineData(this._samplingState.minimapLines[startLineNumber + lineIndex - 1]);
        } else {
          result2[lineIndex] = null;
        }
      }
      return result2;
    }
    return this._context.viewModel.getMinimapLinesRenderingData(startLineNumber, endLineNumber, needed).data;
  }
  getSelections() {
    if (this._minimapSelections === null) {
      if (this._samplingState) {
        this._minimapSelections = [];
        for (const selection of this._selections) {
          const [minimapLineStart, minimapLineEnd] = this._samplingState.decorationLineRangeToMinimapLineRange(selection.startLineNumber, selection.endLineNumber);
          this._minimapSelections.push(new Selection$1(minimapLineStart, selection.startColumn, minimapLineEnd, selection.endColumn));
        }
      } else {
        this._minimapSelections = this._selections;
      }
    }
    return this._minimapSelections;
  }
  getMinimapDecorationsInViewport(startLineNumber, endLineNumber) {
    let visibleRange;
    if (this._samplingState) {
      const modelStartLineNumber = this._samplingState.minimapLines[startLineNumber - 1];
      const modelEndLineNumber = this._samplingState.minimapLines[endLineNumber - 1];
      visibleRange = new Range$2(modelStartLineNumber, 1, modelEndLineNumber, this._context.viewModel.getLineMaxColumn(modelEndLineNumber));
    } else {
      visibleRange = new Range$2(startLineNumber, 1, endLineNumber, this._context.viewModel.getLineMaxColumn(endLineNumber));
    }
    const decorations2 = this._context.viewModel.getMinimapDecorationsInRange(visibleRange);
    if (this._samplingState) {
      const result2 = [];
      for (const decoration2 of decorations2) {
        if (!decoration2.options.minimap) {
          continue;
        }
        const range2 = decoration2.range;
        const minimapStartLineNumber = this._samplingState.modelLineToMinimapLine(range2.startLineNumber);
        const minimapEndLineNumber = this._samplingState.modelLineToMinimapLine(range2.endLineNumber);
        result2.push(new ViewModelDecoration(new Range$2(minimapStartLineNumber, range2.startColumn, minimapEndLineNumber, range2.endColumn), decoration2.options));
      }
      return result2;
    }
    return decorations2;
  }
  getOptions() {
    return this._context.viewModel.model.getOptions();
  }
  revealLineNumber(lineNumber) {
    if (this._samplingState) {
      lineNumber = this._samplingState.minimapLines[lineNumber - 1];
    }
    this._context.viewModel.revealRange(
      "mouse",
      false,
      new Range$2(lineNumber, 1, lineNumber, 1),
      1,
      0
      /* ScrollType.Smooth */
    );
  }
  setScrollTop(scrollTop) {
    this._context.viewModel.viewLayout.setScrollPosition(
      {
        scrollTop
      },
      1
      /* ScrollType.Immediate */
    );
  }
}
class InnerMinimap extends Disposable {
  constructor(theme, model) {
    super();
    this._renderDecorations = false;
    this._gestureInProgress = false;
    this._theme = theme;
    this._model = model;
    this._lastRenderData = null;
    this._buffers = null;
    this._selectionColor = this._theme.getColor(minimapSelection);
    this._domNode = createFastDomNode(document.createElement("div"));
    PartFingerprints.write(
      this._domNode,
      8
      /* PartFingerprint.Minimap */
    );
    this._domNode.setClassName(this._getMinimapDomNodeClassName());
    this._domNode.setPosition("absolute");
    this._domNode.setAttribute("role", "presentation");
    this._domNode.setAttribute("aria-hidden", "true");
    this._shadow = createFastDomNode(document.createElement("div"));
    this._shadow.setClassName("minimap-shadow-hidden");
    this._domNode.appendChild(this._shadow);
    this._canvas = createFastDomNode(document.createElement("canvas"));
    this._canvas.setPosition("absolute");
    this._canvas.setLeft(0);
    this._domNode.appendChild(this._canvas);
    this._decorationsCanvas = createFastDomNode(document.createElement("canvas"));
    this._decorationsCanvas.setPosition("absolute");
    this._decorationsCanvas.setClassName("minimap-decorations-layer");
    this._decorationsCanvas.setLeft(0);
    this._domNode.appendChild(this._decorationsCanvas);
    this._slider = createFastDomNode(document.createElement("div"));
    this._slider.setPosition("absolute");
    this._slider.setClassName("minimap-slider");
    this._slider.setLayerHinting(true);
    this._slider.setContain("strict");
    this._domNode.appendChild(this._slider);
    this._sliderHorizontal = createFastDomNode(document.createElement("div"));
    this._sliderHorizontal.setPosition("absolute");
    this._sliderHorizontal.setClassName("minimap-slider-horizontal");
    this._slider.appendChild(this._sliderHorizontal);
    this._applyLayout();
    this._pointerDownListener = addStandardDisposableListener(this._domNode.domNode, EventType$1.POINTER_DOWN, (e) => {
      e.preventDefault();
      const renderMinimap = this._model.options.renderMinimap;
      if (renderMinimap === 0) {
        return;
      }
      if (!this._lastRenderData) {
        return;
      }
      if (this._model.options.size !== "proportional") {
        if (e.button === 0 && this._lastRenderData) {
          const position = getDomNodePagePosition(this._slider.domNode);
          const initialPosY = position.top + position.height / 2;
          this._startSliderDragging(e, initialPosY, this._lastRenderData.renderedLayout);
        }
        return;
      }
      const minimapLineHeight = this._model.options.minimapLineHeight;
      const internalOffsetY = this._model.options.canvasInnerHeight / this._model.options.canvasOuterHeight * e.offsetY;
      const lineIndex = Math.floor(internalOffsetY / minimapLineHeight);
      let lineNumber = lineIndex + this._lastRenderData.renderedLayout.startLineNumber - this._lastRenderData.renderedLayout.topPaddingLineCount;
      lineNumber = Math.min(lineNumber, this._model.getLineCount());
      this._model.revealLineNumber(lineNumber);
    });
    this._sliderPointerMoveMonitor = new GlobalPointerMoveMonitor();
    this._sliderPointerDownListener = addStandardDisposableListener(this._slider.domNode, EventType$1.POINTER_DOWN, (e) => {
      e.preventDefault();
      e.stopPropagation();
      if (e.button === 0 && this._lastRenderData) {
        this._startSliderDragging(e, e.pageY, this._lastRenderData.renderedLayout);
      }
    });
    this._gestureDisposable = Gesture.addTarget(this._domNode.domNode);
    this._sliderTouchStartListener = addDisposableListener(this._domNode.domNode, EventType.Start, (e) => {
      e.preventDefault();
      e.stopPropagation();
      if (this._lastRenderData) {
        this._slider.toggleClassName("active", true);
        this._gestureInProgress = true;
        this.scrollDueToTouchEvent(e);
      }
    }, { passive: false });
    this._sliderTouchMoveListener = addDisposableListener(this._domNode.domNode, EventType.Change, (e) => {
      e.preventDefault();
      e.stopPropagation();
      if (this._lastRenderData && this._gestureInProgress) {
        this.scrollDueToTouchEvent(e);
      }
    }, { passive: false });
    this._sliderTouchEndListener = addStandardDisposableListener(this._domNode.domNode, EventType.End, (e) => {
      e.preventDefault();
      e.stopPropagation();
      this._gestureInProgress = false;
      this._slider.toggleClassName("active", false);
    });
  }
  _startSliderDragging(e, initialPosY, initialSliderState) {
    if (!e.target || !(e.target instanceof Element)) {
      return;
    }
    const initialPosX = e.pageX;
    this._slider.toggleClassName("active", true);
    const handlePointerMove = (posy, posx) => {
      const minimapPosition = getDomNodePagePosition(this._domNode.domNode);
      const pointerOrthogonalDelta = Math.min(Math.abs(posx - initialPosX), Math.abs(posx - minimapPosition.left), Math.abs(posx - minimapPosition.left - minimapPosition.width));
      if (isWindows && pointerOrthogonalDelta > POINTER_DRAG_RESET_DISTANCE) {
        this._model.setScrollTop(initialSliderState.scrollTop);
        return;
      }
      const pointerDelta = posy - initialPosY;
      this._model.setScrollTop(initialSliderState.getDesiredScrollTopFromDelta(pointerDelta));
    };
    if (e.pageY !== initialPosY) {
      handlePointerMove(e.pageY, initialPosX);
    }
    this._sliderPointerMoveMonitor.startMonitoring(e.target, e.pointerId, e.buttons, (pointerMoveData) => handlePointerMove(pointerMoveData.pageY, pointerMoveData.pageX), () => {
      this._slider.toggleClassName("active", false);
    });
  }
  scrollDueToTouchEvent(touch) {
    const startY = this._domNode.domNode.getBoundingClientRect().top;
    const scrollTop = this._lastRenderData.renderedLayout.getDesiredScrollTopFromTouchLocation(touch.pageY - startY);
    this._model.setScrollTop(scrollTop);
  }
  dispose() {
    this._pointerDownListener.dispose();
    this._sliderPointerMoveMonitor.dispose();
    this._sliderPointerDownListener.dispose();
    this._gestureDisposable.dispose();
    this._sliderTouchStartListener.dispose();
    this._sliderTouchMoveListener.dispose();
    this._sliderTouchEndListener.dispose();
    super.dispose();
  }
  _getMinimapDomNodeClassName() {
    const class_ = ["minimap"];
    if (this._model.options.showSlider === "always") {
      class_.push("slider-always");
    } else {
      class_.push("slider-mouseover");
    }
    if (this._model.options.autohide) {
      class_.push("autohide");
    }
    return class_.join(" ");
  }
  getDomNode() {
    return this._domNode;
  }
  _applyLayout() {
    this._domNode.setLeft(this._model.options.minimapLeft);
    this._domNode.setWidth(this._model.options.minimapWidth);
    this._domNode.setHeight(this._model.options.minimapHeight);
    this._shadow.setHeight(this._model.options.minimapHeight);
    this._canvas.setWidth(this._model.options.canvasOuterWidth);
    this._canvas.setHeight(this._model.options.canvasOuterHeight);
    this._canvas.domNode.width = this._model.options.canvasInnerWidth;
    this._canvas.domNode.height = this._model.options.canvasInnerHeight;
    this._decorationsCanvas.setWidth(this._model.options.canvasOuterWidth);
    this._decorationsCanvas.setHeight(this._model.options.canvasOuterHeight);
    this._decorationsCanvas.domNode.width = this._model.options.canvasInnerWidth;
    this._decorationsCanvas.domNode.height = this._model.options.canvasInnerHeight;
    this._slider.setWidth(this._model.options.minimapWidth);
  }
  _getBuffer() {
    if (!this._buffers) {
      if (this._model.options.canvasInnerWidth > 0 && this._model.options.canvasInnerHeight > 0) {
        this._buffers = new MinimapBuffers(this._canvas.domNode.getContext("2d"), this._model.options.canvasInnerWidth, this._model.options.canvasInnerHeight, this._model.options.backgroundColor);
      }
    }
    return this._buffers ? this._buffers.getBuffer() : null;
  }
  // ---- begin view event handlers
  onDidChangeOptions() {
    this._lastRenderData = null;
    this._buffers = null;
    this._applyLayout();
    this._domNode.setClassName(this._getMinimapDomNodeClassName());
  }
  onSelectionChanged() {
    this._renderDecorations = true;
    return true;
  }
  onDecorationsChanged() {
    this._renderDecorations = true;
    return true;
  }
  onFlushed() {
    this._lastRenderData = null;
    return true;
  }
  onLinesChanged(changeFromLineNumber, changeCount) {
    if (this._lastRenderData) {
      return this._lastRenderData.onLinesChanged(changeFromLineNumber, changeCount);
    }
    return false;
  }
  onLinesDeleted(deleteFromLineNumber, deleteToLineNumber) {
    var _a2;
    (_a2 = this._lastRenderData) === null || _a2 === void 0 ? void 0 : _a2.onLinesDeleted(deleteFromLineNumber, deleteToLineNumber);
    return true;
  }
  onLinesInserted(insertFromLineNumber, insertToLineNumber) {
    var _a2;
    (_a2 = this._lastRenderData) === null || _a2 === void 0 ? void 0 : _a2.onLinesInserted(insertFromLineNumber, insertToLineNumber);
    return true;
  }
  onScrollChanged() {
    this._renderDecorations = true;
    return true;
  }
  onThemeChanged() {
    this._selectionColor = this._theme.getColor(minimapSelection);
    this._renderDecorations = true;
    return true;
  }
  onTokensChanged(ranges) {
    if (this._lastRenderData) {
      return this._lastRenderData.onTokensChanged(ranges);
    }
    return false;
  }
  onTokensColorsChanged() {
    this._lastRenderData = null;
    this._buffers = null;
    return true;
  }
  onZonesChanged() {
    this._lastRenderData = null;
    return true;
  }
  // --- end event handlers
  render(renderingCtx) {
    const renderMinimap = this._model.options.renderMinimap;
    if (renderMinimap === 0) {
      this._shadow.setClassName("minimap-shadow-hidden");
      this._sliderHorizontal.setWidth(0);
      this._sliderHorizontal.setHeight(0);
      return;
    }
    if (renderingCtx.scrollLeft + renderingCtx.viewportWidth >= renderingCtx.scrollWidth) {
      this._shadow.setClassName("minimap-shadow-hidden");
    } else {
      this._shadow.setClassName("minimap-shadow-visible");
    }
    const layout2 = MinimapLayout.create(this._model.options, renderingCtx.viewportStartLineNumber, renderingCtx.viewportEndLineNumber, renderingCtx.viewportStartLineNumberVerticalOffset, renderingCtx.viewportHeight, renderingCtx.viewportContainsWhitespaceGaps, this._model.getLineCount(), this._model.getRealLineCount(), renderingCtx.scrollTop, renderingCtx.scrollHeight, this._lastRenderData ? this._lastRenderData.renderedLayout : null);
    this._slider.setDisplay(layout2.sliderNeeded ? "block" : "none");
    this._slider.setTop(layout2.sliderTop);
    this._slider.setHeight(layout2.sliderHeight);
    this._sliderHorizontal.setLeft(0);
    this._sliderHorizontal.setWidth(this._model.options.minimapWidth);
    this._sliderHorizontal.setTop(0);
    this._sliderHorizontal.setHeight(layout2.sliderHeight);
    this.renderDecorations(layout2);
    this._lastRenderData = this.renderLines(layout2);
  }
  renderDecorations(layout2) {
    if (this._renderDecorations) {
      this._renderDecorations = false;
      const selections2 = this._model.getSelections();
      selections2.sort(Range$2.compareRangesUsingStarts);
      const decorations2 = this._model.getMinimapDecorationsInViewport(layout2.startLineNumber, layout2.endLineNumber);
      decorations2.sort((a, b) => (a.options.zIndex || 0) - (b.options.zIndex || 0));
      const { canvasInnerWidth, canvasInnerHeight } = this._model.options;
      const minimapLineHeight = this._model.options.minimapLineHeight;
      const minimapCharWidth = this._model.options.minimapCharWidth;
      const tabSize = this._model.getOptions().tabSize;
      const canvasContext = this._decorationsCanvas.domNode.getContext("2d");
      canvasContext.clearRect(0, 0, canvasInnerWidth, canvasInnerHeight);
      const highlightedLines = new ContiguousLineMap(layout2.startLineNumber, layout2.endLineNumber, false);
      this._renderSelectionLineHighlights(canvasContext, selections2, highlightedLines, layout2, minimapLineHeight);
      this._renderDecorationsLineHighlights(canvasContext, decorations2, highlightedLines, layout2, minimapLineHeight);
      const lineOffsetMap = new ContiguousLineMap(layout2.startLineNumber, layout2.endLineNumber, null);
      this._renderSelectionsHighlights(canvasContext, selections2, lineOffsetMap, layout2, minimapLineHeight, tabSize, minimapCharWidth, canvasInnerWidth);
      this._renderDecorationsHighlights(canvasContext, decorations2, lineOffsetMap, layout2, minimapLineHeight, tabSize, minimapCharWidth, canvasInnerWidth);
    }
  }
  _renderSelectionLineHighlights(canvasContext, selections2, highlightedLines, layout2, minimapLineHeight) {
    if (!this._selectionColor || this._selectionColor.isTransparent()) {
      return;
    }
    canvasContext.fillStyle = this._selectionColor.transparent(0.5).toString();
    let y1 = 0;
    let y2 = 0;
    for (const selection of selections2) {
      const intersection = layout2.intersectWithViewport(selection);
      if (!intersection) {
        continue;
      }
      const [startLineNumber, endLineNumber] = intersection;
      for (let line = startLineNumber; line <= endLineNumber; line++) {
        highlightedLines.set(line, true);
      }
      const yy1 = layout2.getYForLineNumber(startLineNumber, minimapLineHeight);
      const yy2 = layout2.getYForLineNumber(endLineNumber, minimapLineHeight);
      if (y2 >= yy1) {
        y2 = yy2;
      } else {
        if (y2 > y1) {
          canvasContext.fillRect(MINIMAP_GUTTER_WIDTH, y1, canvasContext.canvas.width, y2 - y1);
        }
        y1 = yy1;
        y2 = yy2;
      }
    }
    if (y2 > y1) {
      canvasContext.fillRect(MINIMAP_GUTTER_WIDTH, y1, canvasContext.canvas.width, y2 - y1);
    }
  }
  _renderDecorationsLineHighlights(canvasContext, decorations2, highlightedLines, layout2, minimapLineHeight) {
    const highlightColors = /* @__PURE__ */ new Map();
    for (let i = decorations2.length - 1; i >= 0; i--) {
      const decoration2 = decorations2[i];
      const minimapOptions = decoration2.options.minimap;
      if (!minimapOptions || minimapOptions.position !== MinimapPosition$1.Inline) {
        continue;
      }
      const intersection = layout2.intersectWithViewport(decoration2.range);
      if (!intersection) {
        continue;
      }
      const [startLineNumber, endLineNumber] = intersection;
      const decorationColor = minimapOptions.getColor(this._theme.value);
      if (!decorationColor || decorationColor.isTransparent()) {
        continue;
      }
      let highlightColor = highlightColors.get(decorationColor.toString());
      if (!highlightColor) {
        highlightColor = decorationColor.transparent(0.5).toString();
        highlightColors.set(decorationColor.toString(), highlightColor);
      }
      canvasContext.fillStyle = highlightColor;
      for (let line = startLineNumber; line <= endLineNumber; line++) {
        if (highlightedLines.has(line)) {
          continue;
        }
        highlightedLines.set(line, true);
        const y = layout2.getYForLineNumber(startLineNumber, minimapLineHeight);
        canvasContext.fillRect(MINIMAP_GUTTER_WIDTH, y, canvasContext.canvas.width, minimapLineHeight);
      }
    }
  }
  _renderSelectionsHighlights(canvasContext, selections2, lineOffsetMap, layout2, lineHeight, tabSize, characterWidth, canvasInnerWidth) {
    if (!this._selectionColor || this._selectionColor.isTransparent()) {
      return;
    }
    for (const selection of selections2) {
      const intersection = layout2.intersectWithViewport(selection);
      if (!intersection) {
        continue;
      }
      const [startLineNumber, endLineNumber] = intersection;
      for (let line = startLineNumber; line <= endLineNumber; line++) {
        this.renderDecorationOnLine(canvasContext, lineOffsetMap, selection, this._selectionColor, layout2, line, lineHeight, lineHeight, tabSize, characterWidth, canvasInnerWidth);
      }
    }
  }
  _renderDecorationsHighlights(canvasContext, decorations2, lineOffsetMap, layout2, minimapLineHeight, tabSize, characterWidth, canvasInnerWidth) {
    for (const decoration2 of decorations2) {
      const minimapOptions = decoration2.options.minimap;
      if (!minimapOptions) {
        continue;
      }
      const intersection = layout2.intersectWithViewport(decoration2.range);
      if (!intersection) {
        continue;
      }
      const [startLineNumber, endLineNumber] = intersection;
      const decorationColor = minimapOptions.getColor(this._theme.value);
      if (!decorationColor || decorationColor.isTransparent()) {
        continue;
      }
      for (let line = startLineNumber; line <= endLineNumber; line++) {
        switch (minimapOptions.position) {
          case MinimapPosition$1.Inline:
            this.renderDecorationOnLine(canvasContext, lineOffsetMap, decoration2.range, decorationColor, layout2, line, minimapLineHeight, minimapLineHeight, tabSize, characterWidth, canvasInnerWidth);
            continue;
          case MinimapPosition$1.Gutter: {
            const y = layout2.getYForLineNumber(line, minimapLineHeight);
            const x = 2;
            this.renderDecoration(canvasContext, decorationColor, x, y, GUTTER_DECORATION_WIDTH, minimapLineHeight);
            continue;
          }
        }
      }
    }
  }
  renderDecorationOnLine(canvasContext, lineOffsetMap, decorationRange, decorationColor, layout2, lineNumber, height, minimapLineHeight, tabSize, charWidth, canvasInnerWidth) {
    const y = layout2.getYForLineNumber(lineNumber, minimapLineHeight);
    if (y + height < 0 || y > this._model.options.canvasInnerHeight) {
      return;
    }
    const { startLineNumber, endLineNumber } = decorationRange;
    const startColumn = startLineNumber === lineNumber ? decorationRange.startColumn : 1;
    const endColumn = endLineNumber === lineNumber ? decorationRange.endColumn : this._model.getLineMaxColumn(lineNumber);
    const x1 = this.getXOffsetForPosition(lineOffsetMap, lineNumber, startColumn, tabSize, charWidth, canvasInnerWidth);
    const x2 = this.getXOffsetForPosition(lineOffsetMap, lineNumber, endColumn, tabSize, charWidth, canvasInnerWidth);
    this.renderDecoration(canvasContext, decorationColor, x1, y, x2 - x1, height);
  }
  getXOffsetForPosition(lineOffsetMap, lineNumber, column, tabSize, charWidth, canvasInnerWidth) {
    if (column === 1) {
      return MINIMAP_GUTTER_WIDTH;
    }
    const minimumXOffset = (column - 1) * charWidth;
    if (minimumXOffset >= canvasInnerWidth) {
      return canvasInnerWidth;
    }
    let lineIndexToXOffset = lineOffsetMap.get(lineNumber);
    if (!lineIndexToXOffset) {
      const lineData = this._model.getLineContent(lineNumber);
      lineIndexToXOffset = [MINIMAP_GUTTER_WIDTH];
      let prevx = MINIMAP_GUTTER_WIDTH;
      for (let i = 1; i < lineData.length + 1; i++) {
        const charCode = lineData.charCodeAt(i - 1);
        const dx = charCode === 9 ? tabSize * charWidth : isFullWidthCharacter(charCode) ? 2 * charWidth : charWidth;
        const x = prevx + dx;
        if (x >= canvasInnerWidth) {
          lineIndexToXOffset[i] = canvasInnerWidth;
          break;
        }
        lineIndexToXOffset[i] = x;
        prevx = x;
      }
      lineOffsetMap.set(lineNumber, lineIndexToXOffset);
    }
    if (column - 1 < lineIndexToXOffset.length) {
      return lineIndexToXOffset[column - 1];
    }
    return canvasInnerWidth;
  }
  renderDecoration(canvasContext, decorationColor, x, y, width, height) {
    canvasContext.fillStyle = decorationColor && decorationColor.toString() || "";
    canvasContext.fillRect(x, y, width, height);
  }
  renderLines(layout2) {
    const startLineNumber = layout2.startLineNumber;
    const endLineNumber = layout2.endLineNumber;
    const minimapLineHeight = this._model.options.minimapLineHeight;
    if (this._lastRenderData && this._lastRenderData.linesEquals(layout2)) {
      const _lastData = this._lastRenderData._get();
      return new RenderData(layout2, _lastData.imageData, _lastData.lines);
    }
    const imageData = this._getBuffer();
    if (!imageData) {
      return null;
    }
    const [_dirtyY1, _dirtyY2, needed] = InnerMinimap._renderUntouchedLines(imageData, layout2.topPaddingLineCount, startLineNumber, endLineNumber, minimapLineHeight, this._lastRenderData);
    const lineInfo = this._model.getMinimapLinesRenderingData(startLineNumber, endLineNumber, needed);
    const tabSize = this._model.getOptions().tabSize;
    const defaultBackground = this._model.options.defaultBackgroundColor;
    const background = this._model.options.backgroundColor;
    const foregroundAlpha = this._model.options.foregroundAlpha;
    const tokensColorTracker = this._model.tokensColorTracker;
    const useLighterFont = tokensColorTracker.backgroundIsLight();
    const renderMinimap = this._model.options.renderMinimap;
    const charRenderer = this._model.options.charRenderer();
    const fontScale = this._model.options.fontScale;
    const minimapCharWidth = this._model.options.minimapCharWidth;
    const baseCharHeight = renderMinimap === 1 ? 2 : 2 + 1;
    const renderMinimapLineHeight = baseCharHeight * fontScale;
    const innerLinePadding = minimapLineHeight > renderMinimapLineHeight ? Math.floor((minimapLineHeight - renderMinimapLineHeight) / 2) : 0;
    const backgroundA = background.a / 255;
    const renderBackground = new RGBA8(Math.round((background.r - defaultBackground.r) * backgroundA + defaultBackground.r), Math.round((background.g - defaultBackground.g) * backgroundA + defaultBackground.g), Math.round((background.b - defaultBackground.b) * backgroundA + defaultBackground.b), 255);
    let dy = layout2.topPaddingLineCount * minimapLineHeight;
    const renderedLines = [];
    for (let lineIndex = 0, lineCount = endLineNumber - startLineNumber + 1; lineIndex < lineCount; lineIndex++) {
      if (needed[lineIndex]) {
        InnerMinimap._renderLine(imageData, renderBackground, background.a, useLighterFont, renderMinimap, minimapCharWidth, tokensColorTracker, foregroundAlpha, charRenderer, dy, innerLinePadding, tabSize, lineInfo[lineIndex], fontScale, minimapLineHeight);
      }
      renderedLines[lineIndex] = new MinimapLine(dy);
      dy += minimapLineHeight;
    }
    const dirtyY1 = _dirtyY1 === -1 ? 0 : _dirtyY1;
    const dirtyY2 = _dirtyY2 === -1 ? imageData.height : _dirtyY2;
    const dirtyHeight = dirtyY2 - dirtyY1;
    const ctx = this._canvas.domNode.getContext("2d");
    ctx.putImageData(imageData, 0, 0, 0, dirtyY1, imageData.width, dirtyHeight);
    return new RenderData(layout2, imageData, renderedLines);
  }
  static _renderUntouchedLines(target, topPaddingLineCount, startLineNumber, endLineNumber, minimapLineHeight, lastRenderData) {
    const needed = [];
    if (!lastRenderData) {
      for (let i = 0, len = endLineNumber - startLineNumber + 1; i < len; i++) {
        needed[i] = true;
      }
      return [-1, -1, needed];
    }
    const _lastData = lastRenderData._get();
    const lastTargetData = _lastData.imageData.data;
    const lastStartLineNumber = _lastData.rendLineNumberStart;
    const lastLines = _lastData.lines;
    const lastLinesLength = lastLines.length;
    const WIDTH = target.width;
    const targetData = target.data;
    const maxDestPixel = (endLineNumber - startLineNumber + 1) * minimapLineHeight * WIDTH * 4;
    let dirtyPixel1 = -1;
    let dirtyPixel2 = -1;
    let copySourceStart = -1;
    let copySourceEnd = -1;
    let copyDestStart = -1;
    let copyDestEnd = -1;
    let dest_dy = topPaddingLineCount * minimapLineHeight;
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      const lineIndex = lineNumber - startLineNumber;
      const lastLineIndex = lineNumber - lastStartLineNumber;
      const source_dy = lastLineIndex >= 0 && lastLineIndex < lastLinesLength ? lastLines[lastLineIndex].dy : -1;
      if (source_dy === -1) {
        needed[lineIndex] = true;
        dest_dy += minimapLineHeight;
        continue;
      }
      const sourceStart = source_dy * WIDTH * 4;
      const sourceEnd = (source_dy + minimapLineHeight) * WIDTH * 4;
      const destStart = dest_dy * WIDTH * 4;
      const destEnd = (dest_dy + minimapLineHeight) * WIDTH * 4;
      if (copySourceEnd === sourceStart && copyDestEnd === destStart) {
        copySourceEnd = sourceEnd;
        copyDestEnd = destEnd;
      } else {
        if (copySourceStart !== -1) {
          targetData.set(lastTargetData.subarray(copySourceStart, copySourceEnd), copyDestStart);
          if (dirtyPixel1 === -1 && copySourceStart === 0 && copySourceStart === copyDestStart) {
            dirtyPixel1 = copySourceEnd;
          }
          if (dirtyPixel2 === -1 && copySourceEnd === maxDestPixel && copySourceStart === copyDestStart) {
            dirtyPixel2 = copySourceStart;
          }
        }
        copySourceStart = sourceStart;
        copySourceEnd = sourceEnd;
        copyDestStart = destStart;
        copyDestEnd = destEnd;
      }
      needed[lineIndex] = false;
      dest_dy += minimapLineHeight;
    }
    if (copySourceStart !== -1) {
      targetData.set(lastTargetData.subarray(copySourceStart, copySourceEnd), copyDestStart);
      if (dirtyPixel1 === -1 && copySourceStart === 0 && copySourceStart === copyDestStart) {
        dirtyPixel1 = copySourceEnd;
      }
      if (dirtyPixel2 === -1 && copySourceEnd === maxDestPixel && copySourceStart === copyDestStart) {
        dirtyPixel2 = copySourceStart;
      }
    }
    const dirtyY1 = dirtyPixel1 === -1 ? -1 : dirtyPixel1 / (WIDTH * 4);
    const dirtyY2 = dirtyPixel2 === -1 ? -1 : dirtyPixel2 / (WIDTH * 4);
    return [dirtyY1, dirtyY2, needed];
  }
  static _renderLine(target, backgroundColor, backgroundAlpha, useLighterFont, renderMinimap, charWidth, colorTracker, foregroundAlpha, minimapCharRenderer, dy, innerLinePadding, tabSize, lineData, fontScale, minimapLineHeight) {
    const content = lineData.content;
    const tokens = lineData.tokens;
    const maxDx = target.width - charWidth;
    const force1pxHeight = minimapLineHeight === 1;
    let dx = MINIMAP_GUTTER_WIDTH;
    let charIndex = 0;
    let tabsCharDelta = 0;
    for (let tokenIndex = 0, tokensLen = tokens.getCount(); tokenIndex < tokensLen; tokenIndex++) {
      const tokenEndIndex = tokens.getEndOffset(tokenIndex);
      const tokenColorId = tokens.getForeground(tokenIndex);
      const tokenColor = colorTracker.getColor(tokenColorId);
      for (; charIndex < tokenEndIndex; charIndex++) {
        if (dx > maxDx) {
          return;
        }
        const charCode = content.charCodeAt(charIndex);
        if (charCode === 9) {
          const insertSpacesCount = tabSize - (charIndex + tabsCharDelta) % tabSize;
          tabsCharDelta += insertSpacesCount - 1;
          dx += insertSpacesCount * charWidth;
        } else if (charCode === 32) {
          dx += charWidth;
        } else {
          const count = isFullWidthCharacter(charCode) ? 2 : 1;
          for (let i = 0; i < count; i++) {
            if (renderMinimap === 2) {
              minimapCharRenderer.blockRenderChar(target, dx, dy + innerLinePadding, tokenColor, foregroundAlpha, backgroundColor, backgroundAlpha, force1pxHeight);
            } else {
              minimapCharRenderer.renderChar(target, dx, dy + innerLinePadding, charCode, tokenColor, foregroundAlpha, backgroundColor, backgroundAlpha, fontScale, useLighterFont, force1pxHeight);
            }
            dx += charWidth;
            if (dx > maxDx) {
              return;
            }
          }
        }
      }
    }
  }
}
class ContiguousLineMap {
  constructor(startLineNumber, endLineNumber, defaultValue) {
    this._startLineNumber = startLineNumber;
    this._endLineNumber = endLineNumber;
    this._defaultValue = defaultValue;
    this._values = [];
    for (let i = 0, count = this._endLineNumber - this._startLineNumber + 1; i < count; i++) {
      this._values[i] = defaultValue;
    }
  }
  has(lineNumber) {
    return this.get(lineNumber) !== this._defaultValue;
  }
  set(lineNumber, value) {
    if (lineNumber < this._startLineNumber || lineNumber > this._endLineNumber) {
      return;
    }
    this._values[lineNumber - this._startLineNumber] = value;
  }
  get(lineNumber) {
    if (lineNumber < this._startLineNumber || lineNumber > this._endLineNumber) {
      return this._defaultValue;
    }
    return this._values[lineNumber - this._startLineNumber];
  }
}
const overlayWidgets = "";
class ViewOverlayWidgets extends ViewPart {
  constructor(context) {
    super(context);
    const options = this._context.configuration.options;
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    this._widgets = {};
    this._verticalScrollbarWidth = layoutInfo.verticalScrollbarWidth;
    this._minimapWidth = layoutInfo.minimap.minimapWidth;
    this._horizontalScrollbarHeight = layoutInfo.horizontalScrollbarHeight;
    this._editorHeight = layoutInfo.height;
    this._editorWidth = layoutInfo.width;
    this._domNode = createFastDomNode(document.createElement("div"));
    PartFingerprints.write(
      this._domNode,
      4
      /* PartFingerprint.OverlayWidgets */
    );
    this._domNode.setClassName("overlayWidgets");
  }
  dispose() {
    super.dispose();
    this._widgets = {};
  }
  getDomNode() {
    return this._domNode;
  }
  // ---- begin view event handlers
  onConfigurationChanged(e) {
    const options = this._context.configuration.options;
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    this._verticalScrollbarWidth = layoutInfo.verticalScrollbarWidth;
    this._minimapWidth = layoutInfo.minimap.minimapWidth;
    this._horizontalScrollbarHeight = layoutInfo.horizontalScrollbarHeight;
    this._editorHeight = layoutInfo.height;
    this._editorWidth = layoutInfo.width;
    return true;
  }
  // ---- end view event handlers
  addWidget(widget) {
    const domNode = createFastDomNode(widget.getDomNode());
    this._widgets[widget.getId()] = {
      widget,
      preference: null,
      domNode
    };
    domNode.setPosition("absolute");
    domNode.setAttribute("widgetId", widget.getId());
    this._domNode.appendChild(domNode);
    this.setShouldRender();
  }
  setWidgetPosition(widget, preference) {
    const widgetData = this._widgets[widget.getId()];
    if (widgetData.preference === preference) {
      return false;
    }
    widgetData.preference = preference;
    this.setShouldRender();
    return true;
  }
  removeWidget(widget) {
    const widgetId = widget.getId();
    if (this._widgets.hasOwnProperty(widgetId)) {
      const widgetData = this._widgets[widgetId];
      const domNode = widgetData.domNode.domNode;
      delete this._widgets[widgetId];
      domNode.parentNode.removeChild(domNode);
      this.setShouldRender();
    }
  }
  _renderWidget(widgetData) {
    const domNode = widgetData.domNode;
    if (widgetData.preference === null) {
      domNode.setTop("");
      return;
    }
    if (widgetData.preference === 0) {
      domNode.setTop(0);
      domNode.setRight(2 * this._verticalScrollbarWidth + this._minimapWidth);
    } else if (widgetData.preference === 1) {
      const widgetHeight = domNode.domNode.clientHeight;
      domNode.setTop(this._editorHeight - widgetHeight - 2 * this._horizontalScrollbarHeight);
      domNode.setRight(2 * this._verticalScrollbarWidth + this._minimapWidth);
    } else if (widgetData.preference === 2) {
      domNode.setTop(0);
      domNode.domNode.style.right = "50%";
    }
  }
  prepareRender(ctx) {
  }
  render(ctx) {
    this._domNode.setWidth(this._editorWidth);
    const keys = Object.keys(this._widgets);
    for (let i = 0, len = keys.length; i < len; i++) {
      const widgetId = keys[i];
      this._renderWidget(this._widgets[widgetId]);
    }
  }
}
class Settings {
  constructor(config2, theme) {
    const options = config2.options;
    this.lineHeight = options.get(
      65
      /* EditorOption.lineHeight */
    );
    this.pixelRatio = options.get(
      140
      /* EditorOption.pixelRatio */
    );
    this.overviewRulerLanes = options.get(
      81
      /* EditorOption.overviewRulerLanes */
    );
    this.renderBorder = options.get(
      80
      /* EditorOption.overviewRulerBorder */
    );
    const borderColor = theme.getColor(editorOverviewRulerBorder);
    this.borderColor = borderColor ? borderColor.toString() : null;
    this.hideCursor = options.get(
      58
      /* EditorOption.hideCursorInOverviewRuler */
    );
    const cursorColor = theme.getColor(editorCursorForeground);
    this.cursorColor = cursorColor ? cursorColor.transparent(0.7).toString() : null;
    this.themeType = theme.type;
    const minimapOpts = options.get(
      71
      /* EditorOption.minimap */
    );
    const minimapEnabled = minimapOpts.enabled;
    const minimapSide = minimapOpts.side;
    const themeColor = theme.getColor(editorOverviewRulerBackground);
    const defaultBackground = TokenizationRegistry2.getDefaultBackground();
    if (themeColor) {
      this.backgroundColor = themeColor;
    } else if (minimapEnabled && minimapSide === "right") {
      this.backgroundColor = defaultBackground;
    } else {
      this.backgroundColor = null;
    }
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    const position = layoutInfo.overviewRuler;
    this.top = position.top;
    this.right = position.right;
    this.domWidth = position.width;
    this.domHeight = position.height;
    if (this.overviewRulerLanes === 0) {
      this.canvasWidth = 0;
      this.canvasHeight = 0;
    } else {
      this.canvasWidth = this.domWidth * this.pixelRatio | 0;
      this.canvasHeight = this.domHeight * this.pixelRatio | 0;
    }
    const [x, w] = this._initLanes(1, this.canvasWidth, this.overviewRulerLanes);
    this.x = x;
    this.w = w;
  }
  _initLanes(canvasLeftOffset, canvasWidth, laneCount) {
    const remainingWidth = canvasWidth - canvasLeftOffset;
    if (laneCount >= 3) {
      const leftWidth = Math.floor(remainingWidth / 3);
      const rightWidth = Math.floor(remainingWidth / 3);
      const centerWidth = remainingWidth - leftWidth - rightWidth;
      const leftOffset = canvasLeftOffset;
      const centerOffset = leftOffset + leftWidth;
      const rightOffset = leftOffset + leftWidth + centerWidth;
      return [
        [
          0,
          leftOffset,
          centerOffset,
          leftOffset,
          rightOffset,
          leftOffset,
          centerOffset,
          leftOffset
          // Left | Center | Right
        ],
        [
          0,
          leftWidth,
          centerWidth,
          leftWidth + centerWidth,
          rightWidth,
          leftWidth + centerWidth + rightWidth,
          centerWidth + rightWidth,
          leftWidth + centerWidth + rightWidth
          // Left | Center | Right
        ]
      ];
    } else if (laneCount === 2) {
      const leftWidth = Math.floor(remainingWidth / 2);
      const rightWidth = remainingWidth - leftWidth;
      const leftOffset = canvasLeftOffset;
      const rightOffset = leftOffset + leftWidth;
      return [
        [
          0,
          leftOffset,
          leftOffset,
          leftOffset,
          rightOffset,
          leftOffset,
          leftOffset,
          leftOffset
          // Left | Center | Right
        ],
        [
          0,
          leftWidth,
          leftWidth,
          leftWidth,
          rightWidth,
          leftWidth + rightWidth,
          leftWidth + rightWidth,
          leftWidth + rightWidth
          // Left | Center | Right
        ]
      ];
    } else {
      const offset = canvasLeftOffset;
      const width = remainingWidth;
      return [
        [
          0,
          offset,
          offset,
          offset,
          offset,
          offset,
          offset,
          offset
          // Left | Center | Right
        ],
        [
          0,
          width,
          width,
          width,
          width,
          width,
          width,
          width
          // Left | Center | Right
        ]
      ];
    }
  }
  equals(other) {
    return this.lineHeight === other.lineHeight && this.pixelRatio === other.pixelRatio && this.overviewRulerLanes === other.overviewRulerLanes && this.renderBorder === other.renderBorder && this.borderColor === other.borderColor && this.hideCursor === other.hideCursor && this.cursorColor === other.cursorColor && this.themeType === other.themeType && Color.equals(this.backgroundColor, other.backgroundColor) && this.top === other.top && this.right === other.right && this.domWidth === other.domWidth && this.domHeight === other.domHeight && this.canvasWidth === other.canvasWidth && this.canvasHeight === other.canvasHeight;
  }
}
class DecorationsOverviewRuler extends ViewPart {
  constructor(context) {
    super(context);
    this._domNode = createFastDomNode(document.createElement("canvas"));
    this._domNode.setClassName("decorationsOverviewRuler");
    this._domNode.setPosition("absolute");
    this._domNode.setLayerHinting(true);
    this._domNode.setContain("strict");
    this._domNode.setAttribute("aria-hidden", "true");
    this._updateSettings(false);
    this._tokensColorTrackerListener = TokenizationRegistry2.onDidChange((e) => {
      if (e.changedColorMap) {
        this._updateSettings(true);
      }
    });
    this._cursorPositions = [];
  }
  dispose() {
    super.dispose();
    this._tokensColorTrackerListener.dispose();
  }
  _updateSettings(renderNow) {
    const newSettings = new Settings(this._context.configuration, this._context.theme);
    if (this._settings && this._settings.equals(newSettings)) {
      return false;
    }
    this._settings = newSettings;
    this._domNode.setTop(this._settings.top);
    this._domNode.setRight(this._settings.right);
    this._domNode.setWidth(this._settings.domWidth);
    this._domNode.setHeight(this._settings.domHeight);
    this._domNode.domNode.width = this._settings.canvasWidth;
    this._domNode.domNode.height = this._settings.canvasHeight;
    if (renderNow) {
      this._render();
    }
    return true;
  }
  // ---- begin view event handlers
  onConfigurationChanged(e) {
    return this._updateSettings(false);
  }
  onCursorStateChanged(e) {
    this._cursorPositions = [];
    for (let i = 0, len = e.selections.length; i < len; i++) {
      this._cursorPositions[i] = e.selections[i].getPosition();
    }
    this._cursorPositions.sort(Position$2.compare);
    return true;
  }
  onDecorationsChanged(e) {
    if (e.affectsOverviewRuler) {
      return true;
    }
    return false;
  }
  onFlushed(e) {
    return true;
  }
  onScrollChanged(e) {
    return e.scrollHeightChanged;
  }
  onZonesChanged(e) {
    return true;
  }
  onThemeChanged(e) {
    return this._updateSettings(false);
  }
  // ---- end view event handlers
  getDomNode() {
    return this._domNode.domNode;
  }
  prepareRender(ctx) {
  }
  render(editorCtx) {
    this._render();
  }
  _render() {
    const backgroundColor = this._settings.backgroundColor;
    if (this._settings.overviewRulerLanes === 0) {
      this._domNode.setBackgroundColor(backgroundColor ? Color.Format.CSS.formatHexA(backgroundColor) : "");
      this._domNode.setDisplay("none");
      return;
    }
    this._domNode.setDisplay("block");
    const canvasWidth = this._settings.canvasWidth;
    const canvasHeight = this._settings.canvasHeight;
    const lineHeight = this._settings.lineHeight;
    const viewLayout = this._context.viewLayout;
    const outerHeight = this._context.viewLayout.getScrollHeight();
    const heightRatio = canvasHeight / outerHeight;
    const decorations2 = this._context.viewModel.getAllOverviewRulerDecorations(this._context.theme);
    const minDecorationHeight = 6 * this._settings.pixelRatio | 0;
    const halfMinDecorationHeight = minDecorationHeight / 2 | 0;
    const canvasCtx = this._domNode.domNode.getContext("2d");
    if (backgroundColor) {
      if (backgroundColor.isOpaque()) {
        canvasCtx.fillStyle = Color.Format.CSS.formatHexA(backgroundColor);
        canvasCtx.fillRect(0, 0, canvasWidth, canvasHeight);
      } else {
        canvasCtx.clearRect(0, 0, canvasWidth, canvasHeight);
        canvasCtx.fillStyle = Color.Format.CSS.formatHexA(backgroundColor);
        canvasCtx.fillRect(0, 0, canvasWidth, canvasHeight);
      }
    } else {
      canvasCtx.clearRect(0, 0, canvasWidth, canvasHeight);
    }
    const x = this._settings.x;
    const w = this._settings.w;
    decorations2.sort(OverviewRulerDecorationsGroup.cmp);
    for (const decorationGroup of decorations2) {
      const color = decorationGroup.color;
      const decorationGroupData = decorationGroup.data;
      canvasCtx.fillStyle = color;
      let prevLane = 0;
      let prevY1 = 0;
      let prevY2 = 0;
      for (let i = 0, len = decorationGroupData.length / 3; i < len; i++) {
        const lane = decorationGroupData[3 * i];
        const startLineNumber = decorationGroupData[3 * i + 1];
        const endLineNumber = decorationGroupData[3 * i + 2];
        let y1 = viewLayout.getVerticalOffsetForLineNumber(startLineNumber) * heightRatio | 0;
        let y2 = (viewLayout.getVerticalOffsetForLineNumber(endLineNumber) + lineHeight) * heightRatio | 0;
        const height = y2 - y1;
        if (height < minDecorationHeight) {
          let yCenter = (y1 + y2) / 2 | 0;
          if (yCenter < halfMinDecorationHeight) {
            yCenter = halfMinDecorationHeight;
          } else if (yCenter + halfMinDecorationHeight > canvasHeight) {
            yCenter = canvasHeight - halfMinDecorationHeight;
          }
          y1 = yCenter - halfMinDecorationHeight;
          y2 = yCenter + halfMinDecorationHeight;
        }
        if (y1 > prevY2 + 1 || lane !== prevLane) {
          if (i !== 0) {
            canvasCtx.fillRect(x[prevLane], prevY1, w[prevLane], prevY2 - prevY1);
          }
          prevLane = lane;
          prevY1 = y1;
          prevY2 = y2;
        } else {
          if (y2 > prevY2) {
            prevY2 = y2;
          }
        }
      }
      canvasCtx.fillRect(x[prevLane], prevY1, w[prevLane], prevY2 - prevY1);
    }
    if (!this._settings.hideCursor && this._settings.cursorColor) {
      const cursorHeight = 2 * this._settings.pixelRatio | 0;
      const halfCursorHeight = cursorHeight / 2 | 0;
      const cursorX = this._settings.x[
        7
        /* OverviewRulerLane.Full */
      ];
      const cursorW = this._settings.w[
        7
        /* OverviewRulerLane.Full */
      ];
      canvasCtx.fillStyle = this._settings.cursorColor;
      let prevY1 = -100;
      let prevY2 = -100;
      for (let i = 0, len = this._cursorPositions.length; i < len; i++) {
        const cursor = this._cursorPositions[i];
        let yCenter = viewLayout.getVerticalOffsetForLineNumber(cursor.lineNumber) * heightRatio | 0;
        if (yCenter < halfCursorHeight) {
          yCenter = halfCursorHeight;
        } else if (yCenter + halfCursorHeight > canvasHeight) {
          yCenter = canvasHeight - halfCursorHeight;
        }
        const y1 = yCenter - halfCursorHeight;
        const y2 = y1 + cursorHeight;
        if (y1 > prevY2 + 1) {
          if (i !== 0) {
            canvasCtx.fillRect(cursorX, prevY1, cursorW, prevY2 - prevY1);
          }
          prevY1 = y1;
          prevY2 = y2;
        } else {
          if (y2 > prevY2) {
            prevY2 = y2;
          }
        }
      }
      canvasCtx.fillRect(cursorX, prevY1, cursorW, prevY2 - prevY1);
    }
    if (this._settings.renderBorder && this._settings.borderColor && this._settings.overviewRulerLanes > 0) {
      canvasCtx.beginPath();
      canvasCtx.lineWidth = 1;
      canvasCtx.strokeStyle = this._settings.borderColor;
      canvasCtx.moveTo(0, 0);
      canvasCtx.lineTo(0, canvasHeight);
      canvasCtx.stroke();
      canvasCtx.moveTo(0, 0);
      canvasCtx.lineTo(canvasWidth, 0);
      canvasCtx.stroke();
    }
  }
}
class ColorZone {
  constructor(from2, to, colorId) {
    this._colorZoneBrand = void 0;
    this.from = from2 | 0;
    this.to = to | 0;
    this.colorId = colorId | 0;
  }
  static compare(a, b) {
    if (a.colorId === b.colorId) {
      if (a.from === b.from) {
        return a.to - b.to;
      }
      return a.from - b.from;
    }
    return a.colorId - b.colorId;
  }
}
class OverviewRulerZone {
  constructor(startLineNumber, endLineNumber, heightInLines, color) {
    this._overviewRulerZoneBrand = void 0;
    this.startLineNumber = startLineNumber;
    this.endLineNumber = endLineNumber;
    this.heightInLines = heightInLines;
    this.color = color;
    this._colorZone = null;
  }
  static compare(a, b) {
    if (a.color === b.color) {
      if (a.startLineNumber === b.startLineNumber) {
        if (a.heightInLines === b.heightInLines) {
          return a.endLineNumber - b.endLineNumber;
        }
        return a.heightInLines - b.heightInLines;
      }
      return a.startLineNumber - b.startLineNumber;
    }
    return a.color < b.color ? -1 : 1;
  }
  setColorZone(colorZone) {
    this._colorZone = colorZone;
  }
  getColorZones() {
    return this._colorZone;
  }
}
class OverviewZoneManager {
  constructor(getVerticalOffsetForLine) {
    this._getVerticalOffsetForLine = getVerticalOffsetForLine;
    this._zones = [];
    this._colorZonesInvalid = false;
    this._lineHeight = 0;
    this._domWidth = 0;
    this._domHeight = 0;
    this._outerHeight = 0;
    this._pixelRatio = 1;
    this._lastAssignedId = 0;
    this._color2Id = /* @__PURE__ */ Object.create(null);
    this._id2Color = [];
  }
  getId2Color() {
    return this._id2Color;
  }
  setZones(newZones) {
    this._zones = newZones;
    this._zones.sort(OverviewRulerZone.compare);
  }
  setLineHeight(lineHeight) {
    if (this._lineHeight === lineHeight) {
      return false;
    }
    this._lineHeight = lineHeight;
    this._colorZonesInvalid = true;
    return true;
  }
  setPixelRatio(pixelRatio) {
    this._pixelRatio = pixelRatio;
    this._colorZonesInvalid = true;
  }
  getDOMWidth() {
    return this._domWidth;
  }
  getCanvasWidth() {
    return this._domWidth * this._pixelRatio;
  }
  setDOMWidth(width) {
    if (this._domWidth === width) {
      return false;
    }
    this._domWidth = width;
    this._colorZonesInvalid = true;
    return true;
  }
  getDOMHeight() {
    return this._domHeight;
  }
  getCanvasHeight() {
    return this._domHeight * this._pixelRatio;
  }
  setDOMHeight(height) {
    if (this._domHeight === height) {
      return false;
    }
    this._domHeight = height;
    this._colorZonesInvalid = true;
    return true;
  }
  getOuterHeight() {
    return this._outerHeight;
  }
  setOuterHeight(outerHeight) {
    if (this._outerHeight === outerHeight) {
      return false;
    }
    this._outerHeight = outerHeight;
    this._colorZonesInvalid = true;
    return true;
  }
  resolveColorZones() {
    const colorZonesInvalid = this._colorZonesInvalid;
    const lineHeight = Math.floor(this._lineHeight);
    const totalHeight = Math.floor(this.getCanvasHeight());
    const outerHeight = Math.floor(this._outerHeight);
    const heightRatio = totalHeight / outerHeight;
    const halfMinimumHeight = Math.floor(4 * this._pixelRatio / 2);
    const allColorZones = [];
    for (let i = 0, len = this._zones.length; i < len; i++) {
      const zone = this._zones[i];
      if (!colorZonesInvalid) {
        const colorZone2 = zone.getColorZones();
        if (colorZone2) {
          allColorZones.push(colorZone2);
          continue;
        }
      }
      const offset1 = this._getVerticalOffsetForLine(zone.startLineNumber);
      const offset2 = zone.heightInLines === 0 ? this._getVerticalOffsetForLine(zone.endLineNumber) + lineHeight : offset1 + zone.heightInLines * lineHeight;
      const y1 = Math.floor(heightRatio * offset1);
      const y2 = Math.floor(heightRatio * offset2);
      let ycenter = Math.floor((y1 + y2) / 2);
      let halfHeight = y2 - ycenter;
      if (halfHeight < halfMinimumHeight) {
        halfHeight = halfMinimumHeight;
      }
      if (ycenter - halfHeight < 0) {
        ycenter = halfHeight;
      }
      if (ycenter + halfHeight > totalHeight) {
        ycenter = totalHeight - halfHeight;
      }
      const color = zone.color;
      let colorId = this._color2Id[color];
      if (!colorId) {
        colorId = ++this._lastAssignedId;
        this._color2Id[color] = colorId;
        this._id2Color[colorId] = color;
      }
      const colorZone = new ColorZone(ycenter - halfHeight, ycenter + halfHeight, colorId);
      zone.setColorZone(colorZone);
      allColorZones.push(colorZone);
    }
    this._colorZonesInvalid = false;
    allColorZones.sort(ColorZone.compare);
    return allColorZones;
  }
}
class OverviewRuler extends ViewEventHandler {
  constructor(context, cssClassName) {
    super();
    this._context = context;
    const options = this._context.configuration.options;
    this._domNode = createFastDomNode(document.createElement("canvas"));
    this._domNode.setClassName(cssClassName);
    this._domNode.setPosition("absolute");
    this._domNode.setLayerHinting(true);
    this._domNode.setContain("strict");
    this._zoneManager = new OverviewZoneManager((lineNumber) => this._context.viewLayout.getVerticalOffsetForLineNumber(lineNumber));
    this._zoneManager.setDOMWidth(0);
    this._zoneManager.setDOMHeight(0);
    this._zoneManager.setOuterHeight(this._context.viewLayout.getScrollHeight());
    this._zoneManager.setLineHeight(options.get(
      65
      /* EditorOption.lineHeight */
    ));
    this._zoneManager.setPixelRatio(options.get(
      140
      /* EditorOption.pixelRatio */
    ));
    this._context.addEventHandler(this);
  }
  dispose() {
    this._context.removeEventHandler(this);
    super.dispose();
  }
  // ---- begin view event handlers
  onConfigurationChanged(e) {
    const options = this._context.configuration.options;
    if (e.hasChanged(
      65
      /* EditorOption.lineHeight */
    )) {
      this._zoneManager.setLineHeight(options.get(
        65
        /* EditorOption.lineHeight */
      ));
      this._render();
    }
    if (e.hasChanged(
      140
      /* EditorOption.pixelRatio */
    )) {
      this._zoneManager.setPixelRatio(options.get(
        140
        /* EditorOption.pixelRatio */
      ));
      this._domNode.setWidth(this._zoneManager.getDOMWidth());
      this._domNode.setHeight(this._zoneManager.getDOMHeight());
      this._domNode.domNode.width = this._zoneManager.getCanvasWidth();
      this._domNode.domNode.height = this._zoneManager.getCanvasHeight();
      this._render();
    }
    return true;
  }
  onFlushed(e) {
    this._render();
    return true;
  }
  onScrollChanged(e) {
    if (e.scrollHeightChanged) {
      this._zoneManager.setOuterHeight(e.scrollHeight);
      this._render();
    }
    return true;
  }
  onZonesChanged(e) {
    this._render();
    return true;
  }
  // ---- end view event handlers
  getDomNode() {
    return this._domNode.domNode;
  }
  setLayout(position) {
    this._domNode.setTop(position.top);
    this._domNode.setRight(position.right);
    let hasChanged2 = false;
    hasChanged2 = this._zoneManager.setDOMWidth(position.width) || hasChanged2;
    hasChanged2 = this._zoneManager.setDOMHeight(position.height) || hasChanged2;
    if (hasChanged2) {
      this._domNode.setWidth(this._zoneManager.getDOMWidth());
      this._domNode.setHeight(this._zoneManager.getDOMHeight());
      this._domNode.domNode.width = this._zoneManager.getCanvasWidth();
      this._domNode.domNode.height = this._zoneManager.getCanvasHeight();
      this._render();
    }
  }
  setZones(zones) {
    this._zoneManager.setZones(zones);
    this._render();
  }
  _render() {
    if (this._zoneManager.getOuterHeight() === 0) {
      return false;
    }
    const width = this._zoneManager.getCanvasWidth();
    const height = this._zoneManager.getCanvasHeight();
    const colorZones = this._zoneManager.resolveColorZones();
    const id2Color = this._zoneManager.getId2Color();
    const ctx = this._domNode.domNode.getContext("2d");
    ctx.clearRect(0, 0, width, height);
    if (colorZones.length > 0) {
      this._renderOneLane(ctx, colorZones, id2Color, width);
    }
    return true;
  }
  _renderOneLane(ctx, colorZones, id2Color, width) {
    let currentColorId = 0;
    let currentFrom = 0;
    let currentTo = 0;
    for (const zone of colorZones) {
      const zoneColorId = zone.colorId;
      const zoneFrom = zone.from;
      const zoneTo = zone.to;
      if (zoneColorId !== currentColorId) {
        ctx.fillRect(0, currentFrom, width, currentTo - currentFrom);
        currentColorId = zoneColorId;
        ctx.fillStyle = id2Color[currentColorId];
        currentFrom = zoneFrom;
        currentTo = zoneTo;
      } else {
        if (currentTo >= zoneFrom) {
          currentTo = Math.max(currentTo, zoneTo);
        } else {
          ctx.fillRect(0, currentFrom, width, currentTo - currentFrom);
          currentFrom = zoneFrom;
          currentTo = zoneTo;
        }
      }
    }
    ctx.fillRect(0, currentFrom, width, currentTo - currentFrom);
  }
}
const rulers = "";
class Rulers extends ViewPart {
  constructor(context) {
    super(context);
    this.domNode = createFastDomNode(document.createElement("div"));
    this.domNode.setAttribute("role", "presentation");
    this.domNode.setAttribute("aria-hidden", "true");
    this.domNode.setClassName("view-rulers");
    this._renderedRulers = [];
    const options = this._context.configuration.options;
    this._rulers = options.get(
      100
      /* EditorOption.rulers */
    );
    this._typicalHalfwidthCharacterWidth = options.get(
      49
      /* EditorOption.fontInfo */
    ).typicalHalfwidthCharacterWidth;
  }
  dispose() {
    super.dispose();
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    const options = this._context.configuration.options;
    this._rulers = options.get(
      100
      /* EditorOption.rulers */
    );
    this._typicalHalfwidthCharacterWidth = options.get(
      49
      /* EditorOption.fontInfo */
    ).typicalHalfwidthCharacterWidth;
    return true;
  }
  onScrollChanged(e) {
    return e.scrollHeightChanged;
  }
  // --- end event handlers
  prepareRender(ctx) {
  }
  _ensureRulersCount() {
    const currentCount = this._renderedRulers.length;
    const desiredCount = this._rulers.length;
    if (currentCount === desiredCount) {
      return;
    }
    if (currentCount < desiredCount) {
      const { tabSize } = this._context.viewModel.model.getOptions();
      const rulerWidth = tabSize;
      let addCount = desiredCount - currentCount;
      while (addCount > 0) {
        const node2 = createFastDomNode(document.createElement("div"));
        node2.setClassName("view-ruler");
        node2.setWidth(rulerWidth);
        this.domNode.appendChild(node2);
        this._renderedRulers.push(node2);
        addCount--;
      }
      return;
    }
    let removeCount = currentCount - desiredCount;
    while (removeCount > 0) {
      const node2 = this._renderedRulers.pop();
      this.domNode.removeChild(node2);
      removeCount--;
    }
  }
  render(ctx) {
    this._ensureRulersCount();
    for (let i = 0, len = this._rulers.length; i < len; i++) {
      const node2 = this._renderedRulers[i];
      const ruler = this._rulers[i];
      node2.setBoxShadow(ruler.color ? `1px 0 0 0 ${ruler.color} inset` : ``);
      node2.setHeight(Math.min(ctx.scrollHeight, 1e6));
      node2.setLeft(ruler.column * this._typicalHalfwidthCharacterWidth);
    }
  }
}
const scrollDecoration = "";
class ScrollDecorationViewPart extends ViewPart {
  constructor(context) {
    super(context);
    this._scrollTop = 0;
    this._width = 0;
    this._updateWidth();
    this._shouldShow = false;
    const options = this._context.configuration.options;
    const scrollbar = options.get(
      101
      /* EditorOption.scrollbar */
    );
    this._useShadows = scrollbar.useShadows;
    this._domNode = createFastDomNode(document.createElement("div"));
    this._domNode.setAttribute("role", "presentation");
    this._domNode.setAttribute("aria-hidden", "true");
  }
  dispose() {
    super.dispose();
  }
  _updateShouldShow() {
    const newShouldShow = this._useShadows && this._scrollTop > 0;
    if (this._shouldShow !== newShouldShow) {
      this._shouldShow = newShouldShow;
      return true;
    }
    return false;
  }
  getDomNode() {
    return this._domNode;
  }
  _updateWidth() {
    const options = this._context.configuration.options;
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    if (layoutInfo.minimap.renderMinimap === 0 || layoutInfo.minimap.minimapWidth > 0 && layoutInfo.minimap.minimapLeft === 0) {
      this._width = layoutInfo.width;
    } else {
      this._width = layoutInfo.width - layoutInfo.verticalScrollbarWidth;
    }
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    const options = this._context.configuration.options;
    const scrollbar = options.get(
      101
      /* EditorOption.scrollbar */
    );
    this._useShadows = scrollbar.useShadows;
    this._updateWidth();
    this._updateShouldShow();
    return true;
  }
  onScrollChanged(e) {
    this._scrollTop = e.scrollTop;
    return this._updateShouldShow();
  }
  // --- end event handlers
  prepareRender(ctx) {
  }
  render(ctx) {
    this._domNode.setWidth(this._width);
    this._domNode.setClassName(this._shouldShow ? "scroll-decoration" : "");
  }
}
const selections = "";
class HorizontalRangeWithStyle {
  constructor(other) {
    this.left = other.left;
    this.width = other.width;
    this.startStyle = null;
    this.endStyle = null;
  }
}
class LineVisibleRangesWithStyle {
  constructor(lineNumber, ranges) {
    this.lineNumber = lineNumber;
    this.ranges = ranges;
  }
}
function toStyledRange(item) {
  return new HorizontalRangeWithStyle(item);
}
function toStyled(item) {
  return new LineVisibleRangesWithStyle(item.lineNumber, item.ranges.map(toStyledRange));
}
class SelectionsOverlay extends DynamicViewOverlay {
  constructor(context) {
    super();
    this._previousFrameVisibleRangesWithStyle = [];
    this._context = context;
    const options = this._context.configuration.options;
    this._lineHeight = options.get(
      65
      /* EditorOption.lineHeight */
    );
    this._roundedSelection = options.get(
      99
      /* EditorOption.roundedSelection */
    );
    this._typicalHalfwidthCharacterWidth = options.get(
      49
      /* EditorOption.fontInfo */
    ).typicalHalfwidthCharacterWidth;
    this._selections = [];
    this._renderResult = null;
    this._context.addEventHandler(this);
  }
  dispose() {
    this._context.removeEventHandler(this);
    this._renderResult = null;
    super.dispose();
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    const options = this._context.configuration.options;
    this._lineHeight = options.get(
      65
      /* EditorOption.lineHeight */
    );
    this._roundedSelection = options.get(
      99
      /* EditorOption.roundedSelection */
    );
    this._typicalHalfwidthCharacterWidth = options.get(
      49
      /* EditorOption.fontInfo */
    ).typicalHalfwidthCharacterWidth;
    return true;
  }
  onCursorStateChanged(e) {
    this._selections = e.selections.slice(0);
    return true;
  }
  onDecorationsChanged(e) {
    return true;
  }
  onFlushed(e) {
    return true;
  }
  onLinesChanged(e) {
    return true;
  }
  onLinesDeleted(e) {
    return true;
  }
  onLinesInserted(e) {
    return true;
  }
  onScrollChanged(e) {
    return e.scrollTopChanged;
  }
  onZonesChanged(e) {
    return true;
  }
  // --- end event handlers
  _visibleRangesHaveGaps(linesVisibleRanges) {
    for (let i = 0, len = linesVisibleRanges.length; i < len; i++) {
      const lineVisibleRanges = linesVisibleRanges[i];
      if (lineVisibleRanges.ranges.length > 1) {
        return true;
      }
    }
    return false;
  }
  _enrichVisibleRangesWithStyle(viewport, linesVisibleRanges, previousFrame) {
    const epsilon = this._typicalHalfwidthCharacterWidth / 4;
    let previousFrameTop = null;
    let previousFrameBottom = null;
    if (previousFrame && previousFrame.length > 0 && linesVisibleRanges.length > 0) {
      const topLineNumber = linesVisibleRanges[0].lineNumber;
      if (topLineNumber === viewport.startLineNumber) {
        for (let i = 0; !previousFrameTop && i < previousFrame.length; i++) {
          if (previousFrame[i].lineNumber === topLineNumber) {
            previousFrameTop = previousFrame[i].ranges[0];
          }
        }
      }
      const bottomLineNumber = linesVisibleRanges[linesVisibleRanges.length - 1].lineNumber;
      if (bottomLineNumber === viewport.endLineNumber) {
        for (let i = previousFrame.length - 1; !previousFrameBottom && i >= 0; i--) {
          if (previousFrame[i].lineNumber === bottomLineNumber) {
            previousFrameBottom = previousFrame[i].ranges[0];
          }
        }
      }
      if (previousFrameTop && !previousFrameTop.startStyle) {
        previousFrameTop = null;
      }
      if (previousFrameBottom && !previousFrameBottom.startStyle) {
        previousFrameBottom = null;
      }
    }
    for (let i = 0, len = linesVisibleRanges.length; i < len; i++) {
      const curLineRange = linesVisibleRanges[i].ranges[0];
      const curLeft = curLineRange.left;
      const curRight = curLineRange.left + curLineRange.width;
      const startStyle = {
        top: 0,
        bottom: 0
        /* CornerStyle.EXTERN */
      };
      const endStyle = {
        top: 0,
        bottom: 0
        /* CornerStyle.EXTERN */
      };
      if (i > 0) {
        const prevLeft = linesVisibleRanges[i - 1].ranges[0].left;
        const prevRight = linesVisibleRanges[i - 1].ranges[0].left + linesVisibleRanges[i - 1].ranges[0].width;
        if (abs(curLeft - prevLeft) < epsilon) {
          startStyle.top = 2;
        } else if (curLeft > prevLeft) {
          startStyle.top = 1;
        }
        if (abs(curRight - prevRight) < epsilon) {
          endStyle.top = 2;
        } else if (prevLeft < curRight && curRight < prevRight) {
          endStyle.top = 1;
        }
      } else if (previousFrameTop) {
        startStyle.top = previousFrameTop.startStyle.top;
        endStyle.top = previousFrameTop.endStyle.top;
      }
      if (i + 1 < len) {
        const nextLeft = linesVisibleRanges[i + 1].ranges[0].left;
        const nextRight = linesVisibleRanges[i + 1].ranges[0].left + linesVisibleRanges[i + 1].ranges[0].width;
        if (abs(curLeft - nextLeft) < epsilon) {
          startStyle.bottom = 2;
        } else if (nextLeft < curLeft && curLeft < nextRight) {
          startStyle.bottom = 1;
        }
        if (abs(curRight - nextRight) < epsilon) {
          endStyle.bottom = 2;
        } else if (curRight < nextRight) {
          endStyle.bottom = 1;
        }
      } else if (previousFrameBottom) {
        startStyle.bottom = previousFrameBottom.startStyle.bottom;
        endStyle.bottom = previousFrameBottom.endStyle.bottom;
      }
      curLineRange.startStyle = startStyle;
      curLineRange.endStyle = endStyle;
    }
  }
  _getVisibleRangesWithStyle(selection, ctx, previousFrame) {
    const _linesVisibleRanges = ctx.linesVisibleRangesForRange(selection, true) || [];
    const linesVisibleRanges = _linesVisibleRanges.map(toStyled);
    const visibleRangesHaveGaps = this._visibleRangesHaveGaps(linesVisibleRanges);
    if (!visibleRangesHaveGaps && this._roundedSelection) {
      this._enrichVisibleRangesWithStyle(ctx.visibleRange, linesVisibleRanges, previousFrame);
    }
    return linesVisibleRanges;
  }
  _createSelectionPiece(top, height, className3, left, width) {
    return '<div class="cslr ' + className3 + '" style="top:' + top.toString() + "px;left:" + left.toString() + "px;width:" + width.toString() + "px;height:" + height + 'px;"></div>';
  }
  _actualRenderOneSelection(output2, visibleStartLineNumber, hasMultipleSelections, visibleRanges) {
    if (visibleRanges.length === 0) {
      return;
    }
    const visibleRangesHaveStyle = !!visibleRanges[0].ranges[0].startStyle;
    const fullLineHeight = this._lineHeight.toString();
    const reducedLineHeight = (this._lineHeight - 1).toString();
    const firstLineNumber = visibleRanges[0].lineNumber;
    const lastLineNumber = visibleRanges[visibleRanges.length - 1].lineNumber;
    for (let i = 0, len = visibleRanges.length; i < len; i++) {
      const lineVisibleRanges = visibleRanges[i];
      const lineNumber = lineVisibleRanges.lineNumber;
      const lineIndex = lineNumber - visibleStartLineNumber;
      const lineHeight = hasMultipleSelections ? lineNumber === lastLineNumber || lineNumber === firstLineNumber ? reducedLineHeight : fullLineHeight : fullLineHeight;
      const top = hasMultipleSelections ? lineNumber === firstLineNumber ? 1 : 0 : 0;
      let innerCornerOutput = "";
      let restOfSelectionOutput = "";
      for (let j = 0, lenJ = lineVisibleRanges.ranges.length; j < lenJ; j++) {
        const visibleRange = lineVisibleRanges.ranges[j];
        if (visibleRangesHaveStyle) {
          const startStyle = visibleRange.startStyle;
          const endStyle = visibleRange.endStyle;
          if (startStyle.top === 1 || startStyle.bottom === 1) {
            innerCornerOutput += this._createSelectionPiece(top, lineHeight, SelectionsOverlay.SELECTION_CLASS_NAME, visibleRange.left - SelectionsOverlay.ROUNDED_PIECE_WIDTH, SelectionsOverlay.ROUNDED_PIECE_WIDTH);
            let className4 = SelectionsOverlay.EDITOR_BACKGROUND_CLASS_NAME;
            if (startStyle.top === 1) {
              className4 += " " + SelectionsOverlay.SELECTION_TOP_RIGHT;
            }
            if (startStyle.bottom === 1) {
              className4 += " " + SelectionsOverlay.SELECTION_BOTTOM_RIGHT;
            }
            innerCornerOutput += this._createSelectionPiece(top, lineHeight, className4, visibleRange.left - SelectionsOverlay.ROUNDED_PIECE_WIDTH, SelectionsOverlay.ROUNDED_PIECE_WIDTH);
          }
          if (endStyle.top === 1 || endStyle.bottom === 1) {
            innerCornerOutput += this._createSelectionPiece(top, lineHeight, SelectionsOverlay.SELECTION_CLASS_NAME, visibleRange.left + visibleRange.width, SelectionsOverlay.ROUNDED_PIECE_WIDTH);
            let className4 = SelectionsOverlay.EDITOR_BACKGROUND_CLASS_NAME;
            if (endStyle.top === 1) {
              className4 += " " + SelectionsOverlay.SELECTION_TOP_LEFT;
            }
            if (endStyle.bottom === 1) {
              className4 += " " + SelectionsOverlay.SELECTION_BOTTOM_LEFT;
            }
            innerCornerOutput += this._createSelectionPiece(top, lineHeight, className4, visibleRange.left + visibleRange.width, SelectionsOverlay.ROUNDED_PIECE_WIDTH);
          }
        }
        let className3 = SelectionsOverlay.SELECTION_CLASS_NAME;
        if (visibleRangesHaveStyle) {
          const startStyle = visibleRange.startStyle;
          const endStyle = visibleRange.endStyle;
          if (startStyle.top === 0) {
            className3 += " " + SelectionsOverlay.SELECTION_TOP_LEFT;
          }
          if (startStyle.bottom === 0) {
            className3 += " " + SelectionsOverlay.SELECTION_BOTTOM_LEFT;
          }
          if (endStyle.top === 0) {
            className3 += " " + SelectionsOverlay.SELECTION_TOP_RIGHT;
          }
          if (endStyle.bottom === 0) {
            className3 += " " + SelectionsOverlay.SELECTION_BOTTOM_RIGHT;
          }
        }
        restOfSelectionOutput += this._createSelectionPiece(top, lineHeight, className3, visibleRange.left, visibleRange.width);
      }
      output2[lineIndex][0] += innerCornerOutput;
      output2[lineIndex][1] += restOfSelectionOutput;
    }
  }
  prepareRender(ctx) {
    const output = [];
    const visibleStartLineNumber = ctx.visibleRange.startLineNumber;
    const visibleEndLineNumber = ctx.visibleRange.endLineNumber;
    for (let lineNumber = visibleStartLineNumber; lineNumber <= visibleEndLineNumber; lineNumber++) {
      const lineIndex = lineNumber - visibleStartLineNumber;
      output[lineIndex] = ["", ""];
    }
    const thisFrameVisibleRangesWithStyle = [];
    for (let i = 0, len = this._selections.length; i < len; i++) {
      const selection = this._selections[i];
      if (selection.isEmpty()) {
        thisFrameVisibleRangesWithStyle[i] = null;
        continue;
      }
      const visibleRangesWithStyle = this._getVisibleRangesWithStyle(selection, ctx, this._previousFrameVisibleRangesWithStyle[i]);
      thisFrameVisibleRangesWithStyle[i] = visibleRangesWithStyle;
      this._actualRenderOneSelection(output, visibleStartLineNumber, this._selections.length > 1, visibleRangesWithStyle);
    }
    this._previousFrameVisibleRangesWithStyle = thisFrameVisibleRangesWithStyle;
    this._renderResult = output.map(([internalCorners, restOfSelection]) => internalCorners + restOfSelection);
  }
  render(startLineNumber, lineNumber) {
    if (!this._renderResult) {
      return "";
    }
    const lineIndex = lineNumber - startLineNumber;
    if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
      return "";
    }
    return this._renderResult[lineIndex];
  }
}
SelectionsOverlay.SELECTION_CLASS_NAME = "selected-text";
SelectionsOverlay.SELECTION_TOP_LEFT = "top-left-radius";
SelectionsOverlay.SELECTION_BOTTOM_LEFT = "bottom-left-radius";
SelectionsOverlay.SELECTION_TOP_RIGHT = "top-right-radius";
SelectionsOverlay.SELECTION_BOTTOM_RIGHT = "bottom-right-radius";
SelectionsOverlay.EDITOR_BACKGROUND_CLASS_NAME = "monaco-editor-background";
SelectionsOverlay.ROUNDED_PIECE_WIDTH = 10;
registerThemingParticipant((theme, collector) => {
  const editorSelectionForegroundColor = theme.getColor(editorSelectionForeground);
  if (editorSelectionForegroundColor && !editorSelectionForegroundColor.isTransparent()) {
    collector.addRule(`.monaco-editor .view-line span.inline-selected-text { color: ${editorSelectionForegroundColor}; }`);
  }
});
function abs(n2) {
  return n2 < 0 ? -n2 : n2;
}
const viewCursors = "";
class ViewCursorRenderData {
  constructor(top, left, paddingLeft, width, height, textContent, textContentClassName) {
    this.top = top;
    this.left = left;
    this.paddingLeft = paddingLeft;
    this.width = width;
    this.height = height;
    this.textContent = textContent;
    this.textContentClassName = textContentClassName;
  }
}
class ViewCursor {
  constructor(context) {
    this._context = context;
    const options = this._context.configuration.options;
    const fontInfo = options.get(
      49
      /* EditorOption.fontInfo */
    );
    this._cursorStyle = options.get(
      27
      /* EditorOption.cursorStyle */
    );
    this._lineHeight = options.get(
      65
      /* EditorOption.lineHeight */
    );
    this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
    this._lineCursorWidth = Math.min(options.get(
      30
      /* EditorOption.cursorWidth */
    ), this._typicalHalfwidthCharacterWidth);
    this._isVisible = true;
    this._domNode = createFastDomNode(document.createElement("div"));
    this._domNode.setClassName(`cursor ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`);
    this._domNode.setHeight(this._lineHeight);
    this._domNode.setTop(0);
    this._domNode.setLeft(0);
    applyFontInfo(this._domNode, fontInfo);
    this._domNode.setDisplay("none");
    this._position = new Position$2(1, 1);
    this._lastRenderedContent = "";
    this._renderData = null;
  }
  getDomNode() {
    return this._domNode;
  }
  getPosition() {
    return this._position;
  }
  show() {
    if (!this._isVisible) {
      this._domNode.setVisibility("inherit");
      this._isVisible = true;
    }
  }
  hide() {
    if (this._isVisible) {
      this._domNode.setVisibility("hidden");
      this._isVisible = false;
    }
  }
  onConfigurationChanged(e) {
    const options = this._context.configuration.options;
    const fontInfo = options.get(
      49
      /* EditorOption.fontInfo */
    );
    this._cursorStyle = options.get(
      27
      /* EditorOption.cursorStyle */
    );
    this._lineHeight = options.get(
      65
      /* EditorOption.lineHeight */
    );
    this._typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
    this._lineCursorWidth = Math.min(options.get(
      30
      /* EditorOption.cursorWidth */
    ), this._typicalHalfwidthCharacterWidth);
    applyFontInfo(this._domNode, fontInfo);
    return true;
  }
  onCursorPositionChanged(position, pauseAnimation) {
    if (pauseAnimation) {
      this._domNode.domNode.style.transitionProperty = "none";
    } else {
      this._domNode.domNode.style.transitionProperty = "";
    }
    this._position = position;
    return true;
  }
  /**
   * If `this._position` is inside a grapheme, returns the position where the grapheme starts.
   * Also returns the next grapheme.
   */
  _getGraphemeAwarePosition() {
    const { lineNumber, column } = this._position;
    const lineContent = this._context.viewModel.getLineContent(lineNumber);
    const [startOffset, endOffset] = getCharContainingOffset(lineContent, column - 1);
    return [new Position$2(lineNumber, startOffset + 1), lineContent.substring(startOffset, endOffset)];
  }
  _prepareRender(ctx) {
    let textContent = "";
    let textContentClassName = "";
    const [position, nextGrapheme] = this._getGraphemeAwarePosition();
    if (this._cursorStyle === TextEditorCursorStyle$1.Line || this._cursorStyle === TextEditorCursorStyle$1.LineThin) {
      const visibleRange = ctx.visibleRangeForPosition(position);
      if (!visibleRange || visibleRange.outsideRenderedLine) {
        return null;
      }
      let width2;
      if (this._cursorStyle === TextEditorCursorStyle$1.Line) {
        width2 = computeScreenAwareSize(this._lineCursorWidth > 0 ? this._lineCursorWidth : 2);
        if (width2 > 2) {
          textContent = nextGrapheme;
          textContentClassName = this._getTokenClassName(position);
        }
      } else {
        width2 = computeScreenAwareSize(1);
      }
      let left = visibleRange.left;
      let paddingLeft = 0;
      if (width2 >= 2 && left >= 1) {
        paddingLeft = 1;
        left -= paddingLeft;
      }
      const top2 = ctx.getVerticalOffsetForLineNumber(position.lineNumber) - ctx.bigNumbersDelta;
      return new ViewCursorRenderData(top2, left, paddingLeft, width2, this._lineHeight, textContent, textContentClassName);
    }
    const visibleRangeForCharacter = ctx.linesVisibleRangesForRange(new Range$2(position.lineNumber, position.column, position.lineNumber, position.column + nextGrapheme.length), false);
    if (!visibleRangeForCharacter || visibleRangeForCharacter.length === 0) {
      return null;
    }
    const firstVisibleRangeForCharacter = visibleRangeForCharacter[0];
    if (firstVisibleRangeForCharacter.outsideRenderedLine || firstVisibleRangeForCharacter.ranges.length === 0) {
      return null;
    }
    const range2 = firstVisibleRangeForCharacter.ranges[0];
    const width = nextGrapheme === "	" ? this._typicalHalfwidthCharacterWidth : range2.width < 1 ? this._typicalHalfwidthCharacterWidth : range2.width;
    if (this._cursorStyle === TextEditorCursorStyle$1.Block) {
      textContent = nextGrapheme;
      textContentClassName = this._getTokenClassName(position);
    }
    let top = ctx.getVerticalOffsetForLineNumber(position.lineNumber) - ctx.bigNumbersDelta;
    let height = this._lineHeight;
    if (this._cursorStyle === TextEditorCursorStyle$1.Underline || this._cursorStyle === TextEditorCursorStyle$1.UnderlineThin) {
      top += this._lineHeight - 2;
      height = 2;
    }
    return new ViewCursorRenderData(top, range2.left, 0, width, height, textContent, textContentClassName);
  }
  _getTokenClassName(position) {
    const lineData = this._context.viewModel.getViewLineData(position.lineNumber);
    const tokenIndex = lineData.tokens.findTokenIndexAtOffset(position.column - 1);
    return lineData.tokens.getClassName(tokenIndex);
  }
  prepareRender(ctx) {
    this._renderData = this._prepareRender(ctx);
  }
  render(ctx) {
    if (!this._renderData) {
      this._domNode.setDisplay("none");
      return null;
    }
    if (this._lastRenderedContent !== this._renderData.textContent) {
      this._lastRenderedContent = this._renderData.textContent;
      this._domNode.domNode.textContent = this._lastRenderedContent;
    }
    this._domNode.setClassName(`cursor ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME} ${this._renderData.textContentClassName}`);
    this._domNode.setDisplay("block");
    this._domNode.setTop(this._renderData.top);
    this._domNode.setLeft(this._renderData.left);
    this._domNode.setPaddingLeft(this._renderData.paddingLeft);
    this._domNode.setWidth(this._renderData.width);
    this._domNode.setLineHeight(this._renderData.height);
    this._domNode.setHeight(this._renderData.height);
    return {
      domNode: this._domNode.domNode,
      position: this._position,
      contentLeft: this._renderData.left,
      height: this._renderData.height,
      width: 2
    };
  }
}
class ViewCursors extends ViewPart {
  constructor(context) {
    super(context);
    const options = this._context.configuration.options;
    this._readOnly = options.get(
      89
      /* EditorOption.readOnly */
    );
    this._cursorBlinking = options.get(
      25
      /* EditorOption.cursorBlinking */
    );
    this._cursorStyle = options.get(
      27
      /* EditorOption.cursorStyle */
    );
    this._cursorSmoothCaretAnimation = options.get(
      26
      /* EditorOption.cursorSmoothCaretAnimation */
    );
    this._selectionIsEmpty = true;
    this._isComposingInput = false;
    this._isVisible = false;
    this._primaryCursor = new ViewCursor(this._context);
    this._secondaryCursors = [];
    this._renderData = [];
    this._domNode = createFastDomNode(document.createElement("div"));
    this._domNode.setAttribute("role", "presentation");
    this._domNode.setAttribute("aria-hidden", "true");
    this._updateDomClassName();
    this._domNode.appendChild(this._primaryCursor.getDomNode());
    this._startCursorBlinkAnimation = new TimeoutTimer();
    this._cursorFlatBlinkInterval = new IntervalTimer();
    this._blinkingEnabled = false;
    this._editorHasFocus = false;
    this._updateBlinking();
  }
  dispose() {
    super.dispose();
    this._startCursorBlinkAnimation.dispose();
    this._cursorFlatBlinkInterval.dispose();
  }
  getDomNode() {
    return this._domNode;
  }
  // --- begin event handlers
  onCompositionStart(e) {
    this._isComposingInput = true;
    this._updateBlinking();
    return true;
  }
  onCompositionEnd(e) {
    this._isComposingInput = false;
    this._updateBlinking();
    return true;
  }
  onConfigurationChanged(e) {
    const options = this._context.configuration.options;
    this._readOnly = options.get(
      89
      /* EditorOption.readOnly */
    );
    this._cursorBlinking = options.get(
      25
      /* EditorOption.cursorBlinking */
    );
    this._cursorStyle = options.get(
      27
      /* EditorOption.cursorStyle */
    );
    this._cursorSmoothCaretAnimation = options.get(
      26
      /* EditorOption.cursorSmoothCaretAnimation */
    );
    this._updateBlinking();
    this._updateDomClassName();
    this._primaryCursor.onConfigurationChanged(e);
    for (let i = 0, len = this._secondaryCursors.length; i < len; i++) {
      this._secondaryCursors[i].onConfigurationChanged(e);
    }
    return true;
  }
  _onCursorPositionChanged(position, secondaryPositions, reason) {
    const pauseAnimation = this._secondaryCursors.length !== secondaryPositions.length || this._cursorSmoothCaretAnimation === "explicit" && reason !== 3;
    this._primaryCursor.onCursorPositionChanged(position, pauseAnimation);
    this._updateBlinking();
    if (this._secondaryCursors.length < secondaryPositions.length) {
      const addCnt = secondaryPositions.length - this._secondaryCursors.length;
      for (let i = 0; i < addCnt; i++) {
        const newCursor = new ViewCursor(this._context);
        this._domNode.domNode.insertBefore(newCursor.getDomNode().domNode, this._primaryCursor.getDomNode().domNode.nextSibling);
        this._secondaryCursors.push(newCursor);
      }
    } else if (this._secondaryCursors.length > secondaryPositions.length) {
      const removeCnt = this._secondaryCursors.length - secondaryPositions.length;
      for (let i = 0; i < removeCnt; i++) {
        this._domNode.removeChild(this._secondaryCursors[0].getDomNode());
        this._secondaryCursors.splice(0, 1);
      }
    }
    for (let i = 0; i < secondaryPositions.length; i++) {
      this._secondaryCursors[i].onCursorPositionChanged(secondaryPositions[i], pauseAnimation);
    }
  }
  onCursorStateChanged(e) {
    const positions = [];
    for (let i = 0, len = e.selections.length; i < len; i++) {
      positions[i] = e.selections[i].getPosition();
    }
    this._onCursorPositionChanged(positions[0], positions.slice(1), e.reason);
    const selectionIsEmpty = e.selections[0].isEmpty();
    if (this._selectionIsEmpty !== selectionIsEmpty) {
      this._selectionIsEmpty = selectionIsEmpty;
      this._updateDomClassName();
    }
    return true;
  }
  onDecorationsChanged(e) {
    return true;
  }
  onFlushed(e) {
    return true;
  }
  onFocusChanged(e) {
    this._editorHasFocus = e.isFocused;
    this._updateBlinking();
    return false;
  }
  onLinesChanged(e) {
    return true;
  }
  onLinesDeleted(e) {
    return true;
  }
  onLinesInserted(e) {
    return true;
  }
  onScrollChanged(e) {
    return true;
  }
  onTokensChanged(e) {
    const shouldRender = (position) => {
      for (let i = 0, len = e.ranges.length; i < len; i++) {
        if (e.ranges[i].fromLineNumber <= position.lineNumber && position.lineNumber <= e.ranges[i].toLineNumber) {
          return true;
        }
      }
      return false;
    };
    if (shouldRender(this._primaryCursor.getPosition())) {
      return true;
    }
    for (const secondaryCursor of this._secondaryCursors) {
      if (shouldRender(secondaryCursor.getPosition())) {
        return true;
      }
    }
    return false;
  }
  onZonesChanged(e) {
    return true;
  }
  // --- end event handlers
  // ---- blinking logic
  _getCursorBlinking() {
    if (this._isComposingInput) {
      return 0;
    }
    if (!this._editorHasFocus) {
      return 0;
    }
    if (this._readOnly) {
      return 5;
    }
    return this._cursorBlinking;
  }
  _updateBlinking() {
    this._startCursorBlinkAnimation.cancel();
    this._cursorFlatBlinkInterval.cancel();
    const blinkingStyle = this._getCursorBlinking();
    const isHidden = blinkingStyle === 0;
    const isSolid = blinkingStyle === 5;
    if (isHidden) {
      this._hide();
    } else {
      this._show();
    }
    this._blinkingEnabled = false;
    this._updateDomClassName();
    if (!isHidden && !isSolid) {
      if (blinkingStyle === 1) {
        this._cursorFlatBlinkInterval.cancelAndSet(() => {
          if (this._isVisible) {
            this._hide();
          } else {
            this._show();
          }
        }, ViewCursors.BLINK_INTERVAL);
      } else {
        this._startCursorBlinkAnimation.setIfNotSet(() => {
          this._blinkingEnabled = true;
          this._updateDomClassName();
        }, ViewCursors.BLINK_INTERVAL);
      }
    }
  }
  // --- end blinking logic
  _updateDomClassName() {
    this._domNode.setClassName(this._getClassName());
  }
  _getClassName() {
    let result2 = "cursors-layer";
    if (!this._selectionIsEmpty) {
      result2 += " has-selection";
    }
    switch (this._cursorStyle) {
      case TextEditorCursorStyle$1.Line:
        result2 += " cursor-line-style";
        break;
      case TextEditorCursorStyle$1.Block:
        result2 += " cursor-block-style";
        break;
      case TextEditorCursorStyle$1.Underline:
        result2 += " cursor-underline-style";
        break;
      case TextEditorCursorStyle$1.LineThin:
        result2 += " cursor-line-thin-style";
        break;
      case TextEditorCursorStyle$1.BlockOutline:
        result2 += " cursor-block-outline-style";
        break;
      case TextEditorCursorStyle$1.UnderlineThin:
        result2 += " cursor-underline-thin-style";
        break;
      default:
        result2 += " cursor-line-style";
    }
    if (this._blinkingEnabled) {
      switch (this._getCursorBlinking()) {
        case 1:
          result2 += " cursor-blink";
          break;
        case 2:
          result2 += " cursor-smooth";
          break;
        case 3:
          result2 += " cursor-phase";
          break;
        case 4:
          result2 += " cursor-expand";
          break;
        case 5:
          result2 += " cursor-solid";
          break;
        default:
          result2 += " cursor-solid";
      }
    } else {
      result2 += " cursor-solid";
    }
    if (this._cursorSmoothCaretAnimation === "on" || this._cursorSmoothCaretAnimation === "explicit") {
      result2 += " cursor-smooth-caret-animation";
    }
    return result2;
  }
  _show() {
    this._primaryCursor.show();
    for (let i = 0, len = this._secondaryCursors.length; i < len; i++) {
      this._secondaryCursors[i].show();
    }
    this._isVisible = true;
  }
  _hide() {
    this._primaryCursor.hide();
    for (let i = 0, len = this._secondaryCursors.length; i < len; i++) {
      this._secondaryCursors[i].hide();
    }
    this._isVisible = false;
  }
  // ---- IViewPart implementation
  prepareRender(ctx) {
    this._primaryCursor.prepareRender(ctx);
    for (let i = 0, len = this._secondaryCursors.length; i < len; i++) {
      this._secondaryCursors[i].prepareRender(ctx);
    }
  }
  render(ctx) {
    const renderData = [];
    let renderDataLen = 0;
    const primaryRenderData = this._primaryCursor.render(ctx);
    if (primaryRenderData) {
      renderData[renderDataLen++] = primaryRenderData;
    }
    for (let i = 0, len = this._secondaryCursors.length; i < len; i++) {
      const secondaryRenderData = this._secondaryCursors[i].render(ctx);
      if (secondaryRenderData) {
        renderData[renderDataLen++] = secondaryRenderData;
      }
    }
    this._renderData = renderData;
  }
  getLastRenderData() {
    return this._renderData;
  }
}
ViewCursors.BLINK_INTERVAL = 500;
registerThemingParticipant((theme, collector) => {
  const caret2 = theme.getColor(editorCursorForeground);
  if (caret2) {
    let caretBackground = theme.getColor(editorCursorBackground);
    if (!caretBackground) {
      caretBackground = caret2.opposite();
    }
    collector.addRule(`.monaco-editor .cursors-layer .cursor { background-color: ${caret2}; border-color: ${caret2}; color: ${caretBackground}; }`);
    if (isHighContrast(theme.type)) {
      collector.addRule(`.monaco-editor .cursors-layer.has-selection .cursor { border-left: 1px solid ${caretBackground}; border-right: 1px solid ${caretBackground}; }`);
    }
  }
});
const invalidFunc$1 = () => {
  throw new Error(`Invalid change accessor`);
};
class ViewZones extends ViewPart {
  constructor(context) {
    super(context);
    const options = this._context.configuration.options;
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    this._lineHeight = options.get(
      65
      /* EditorOption.lineHeight */
    );
    this._contentWidth = layoutInfo.contentWidth;
    this._contentLeft = layoutInfo.contentLeft;
    this.domNode = createFastDomNode(document.createElement("div"));
    this.domNode.setClassName("view-zones");
    this.domNode.setPosition("absolute");
    this.domNode.setAttribute("role", "presentation");
    this.domNode.setAttribute("aria-hidden", "true");
    this.marginDomNode = createFastDomNode(document.createElement("div"));
    this.marginDomNode.setClassName("margin-view-zones");
    this.marginDomNode.setPosition("absolute");
    this.marginDomNode.setAttribute("role", "presentation");
    this.marginDomNode.setAttribute("aria-hidden", "true");
    this._zones = {};
  }
  dispose() {
    super.dispose();
    this._zones = {};
  }
  // ---- begin view event handlers
  _recomputeWhitespacesProps() {
    const whitespaces = this._context.viewLayout.getWhitespaces();
    const oldWhitespaces = /* @__PURE__ */ new Map();
    for (const whitespace2 of whitespaces) {
      oldWhitespaces.set(whitespace2.id, whitespace2);
    }
    let hadAChange = false;
    this._context.viewModel.changeWhitespace((whitespaceAccessor) => {
      const keys = Object.keys(this._zones);
      for (let i = 0, len = keys.length; i < len; i++) {
        const id3 = keys[i];
        const zone = this._zones[id3];
        const props = this._computeWhitespaceProps(zone.delegate);
        zone.isInHiddenArea = props.isInHiddenArea;
        const oldWhitespace = oldWhitespaces.get(id3);
        if (oldWhitespace && (oldWhitespace.afterLineNumber !== props.afterViewLineNumber || oldWhitespace.height !== props.heightInPx)) {
          whitespaceAccessor.changeOneWhitespace(id3, props.afterViewLineNumber, props.heightInPx);
          this._safeCallOnComputedHeight(zone.delegate, props.heightInPx);
          hadAChange = true;
        }
      }
    });
    return hadAChange;
  }
  onConfigurationChanged(e) {
    const options = this._context.configuration.options;
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    this._lineHeight = options.get(
      65
      /* EditorOption.lineHeight */
    );
    this._contentWidth = layoutInfo.contentWidth;
    this._contentLeft = layoutInfo.contentLeft;
    if (e.hasChanged(
      65
      /* EditorOption.lineHeight */
    )) {
      this._recomputeWhitespacesProps();
    }
    return true;
  }
  onLineMappingChanged(e) {
    return this._recomputeWhitespacesProps();
  }
  onLinesDeleted(e) {
    return true;
  }
  onScrollChanged(e) {
    return e.scrollTopChanged || e.scrollWidthChanged;
  }
  onZonesChanged(e) {
    return true;
  }
  onLinesInserted(e) {
    return true;
  }
  // ---- end view event handlers
  _getZoneOrdinal(zone) {
    var _a2, _b2;
    return (_b2 = (_a2 = zone.ordinal) !== null && _a2 !== void 0 ? _a2 : zone.afterColumn) !== null && _b2 !== void 0 ? _b2 : 1e4;
  }
  _computeWhitespaceProps(zone) {
    if (zone.afterLineNumber === 0) {
      return {
        isInHiddenArea: false,
        afterViewLineNumber: 0,
        heightInPx: this._heightInPixels(zone),
        minWidthInPx: this._minWidthInPixels(zone)
      };
    }
    let zoneAfterModelPosition;
    if (typeof zone.afterColumn !== "undefined") {
      zoneAfterModelPosition = this._context.viewModel.model.validatePosition({
        lineNumber: zone.afterLineNumber,
        column: zone.afterColumn
      });
    } else {
      const validAfterLineNumber = this._context.viewModel.model.validatePosition({
        lineNumber: zone.afterLineNumber,
        column: 1
      }).lineNumber;
      zoneAfterModelPosition = new Position$2(validAfterLineNumber, this._context.viewModel.model.getLineMaxColumn(validAfterLineNumber));
    }
    let zoneBeforeModelPosition;
    if (zoneAfterModelPosition.column === this._context.viewModel.model.getLineMaxColumn(zoneAfterModelPosition.lineNumber)) {
      zoneBeforeModelPosition = this._context.viewModel.model.validatePosition({
        lineNumber: zoneAfterModelPosition.lineNumber + 1,
        column: 1
      });
    } else {
      zoneBeforeModelPosition = this._context.viewModel.model.validatePosition({
        lineNumber: zoneAfterModelPosition.lineNumber,
        column: zoneAfterModelPosition.column + 1
      });
    }
    const viewPosition = this._context.viewModel.coordinatesConverter.convertModelPositionToViewPosition(zoneAfterModelPosition, zone.afterColumnAffinity, true);
    const isVisible = zone.showInHiddenAreas || this._context.viewModel.coordinatesConverter.modelPositionIsVisible(zoneBeforeModelPosition);
    return {
      isInHiddenArea: !isVisible,
      afterViewLineNumber: viewPosition.lineNumber,
      heightInPx: isVisible ? this._heightInPixels(zone) : 0,
      minWidthInPx: this._minWidthInPixels(zone)
    };
  }
  changeViewZones(callback) {
    let zonesHaveChanged = false;
    this._context.viewModel.changeWhitespace((whitespaceAccessor) => {
      const changeAccessor = {
        addZone: (zone) => {
          zonesHaveChanged = true;
          return this._addZone(whitespaceAccessor, zone);
        },
        removeZone: (id3) => {
          if (!id3) {
            return;
          }
          zonesHaveChanged = this._removeZone(whitespaceAccessor, id3) || zonesHaveChanged;
        },
        layoutZone: (id3) => {
          if (!id3) {
            return;
          }
          zonesHaveChanged = this._layoutZone(whitespaceAccessor, id3) || zonesHaveChanged;
        }
      };
      safeInvoke1Arg(callback, changeAccessor);
      changeAccessor.addZone = invalidFunc$1;
      changeAccessor.removeZone = invalidFunc$1;
      changeAccessor.layoutZone = invalidFunc$1;
    });
    return zonesHaveChanged;
  }
  _addZone(whitespaceAccessor, zone) {
    const props = this._computeWhitespaceProps(zone);
    const whitespaceId = whitespaceAccessor.insertWhitespace(props.afterViewLineNumber, this._getZoneOrdinal(zone), props.heightInPx, props.minWidthInPx);
    const myZone = {
      whitespaceId,
      delegate: zone,
      isInHiddenArea: props.isInHiddenArea,
      isVisible: false,
      domNode: createFastDomNode(zone.domNode),
      marginDomNode: zone.marginDomNode ? createFastDomNode(zone.marginDomNode) : null
    };
    this._safeCallOnComputedHeight(myZone.delegate, props.heightInPx);
    myZone.domNode.setPosition("absolute");
    myZone.domNode.domNode.style.width = "100%";
    myZone.domNode.setDisplay("none");
    myZone.domNode.setAttribute("monaco-view-zone", myZone.whitespaceId);
    this.domNode.appendChild(myZone.domNode);
    if (myZone.marginDomNode) {
      myZone.marginDomNode.setPosition("absolute");
      myZone.marginDomNode.domNode.style.width = "100%";
      myZone.marginDomNode.setDisplay("none");
      myZone.marginDomNode.setAttribute("monaco-view-zone", myZone.whitespaceId);
      this.marginDomNode.appendChild(myZone.marginDomNode);
    }
    this._zones[myZone.whitespaceId] = myZone;
    this.setShouldRender();
    return myZone.whitespaceId;
  }
  _removeZone(whitespaceAccessor, id3) {
    if (this._zones.hasOwnProperty(id3)) {
      const zone = this._zones[id3];
      delete this._zones[id3];
      whitespaceAccessor.removeWhitespace(zone.whitespaceId);
      zone.domNode.removeAttribute("monaco-visible-view-zone");
      zone.domNode.removeAttribute("monaco-view-zone");
      zone.domNode.domNode.parentNode.removeChild(zone.domNode.domNode);
      if (zone.marginDomNode) {
        zone.marginDomNode.removeAttribute("monaco-visible-view-zone");
        zone.marginDomNode.removeAttribute("monaco-view-zone");
        zone.marginDomNode.domNode.parentNode.removeChild(zone.marginDomNode.domNode);
      }
      this.setShouldRender();
      return true;
    }
    return false;
  }
  _layoutZone(whitespaceAccessor, id3) {
    if (this._zones.hasOwnProperty(id3)) {
      const zone = this._zones[id3];
      const props = this._computeWhitespaceProps(zone.delegate);
      zone.isInHiddenArea = props.isInHiddenArea;
      whitespaceAccessor.changeOneWhitespace(zone.whitespaceId, props.afterViewLineNumber, props.heightInPx);
      this._safeCallOnComputedHeight(zone.delegate, props.heightInPx);
      this.setShouldRender();
      return true;
    }
    return false;
  }
  shouldSuppressMouseDownOnViewZone(id3) {
    if (this._zones.hasOwnProperty(id3)) {
      const zone = this._zones[id3];
      return Boolean(zone.delegate.suppressMouseDown);
    }
    return false;
  }
  _heightInPixels(zone) {
    if (typeof zone.heightInPx === "number") {
      return zone.heightInPx;
    }
    if (typeof zone.heightInLines === "number") {
      return this._lineHeight * zone.heightInLines;
    }
    return this._lineHeight;
  }
  _minWidthInPixels(zone) {
    if (typeof zone.minWidthInPx === "number") {
      return zone.minWidthInPx;
    }
    return 0;
  }
  _safeCallOnComputedHeight(zone, height) {
    if (typeof zone.onComputedHeight === "function") {
      try {
        zone.onComputedHeight(height);
      } catch (e) {
        onUnexpectedError(e);
      }
    }
  }
  _safeCallOnDomNodeTop(zone, top) {
    if (typeof zone.onDomNodeTop === "function") {
      try {
        zone.onDomNodeTop(top);
      } catch (e) {
        onUnexpectedError(e);
      }
    }
  }
  prepareRender(ctx) {
  }
  render(ctx) {
    const visibleWhitespaces = ctx.viewportData.whitespaceViewportData;
    const visibleZones = {};
    let hasVisibleZone = false;
    for (const visibleWhitespace of visibleWhitespaces) {
      if (this._zones[visibleWhitespace.id].isInHiddenArea) {
        continue;
      }
      visibleZones[visibleWhitespace.id] = visibleWhitespace;
      hasVisibleZone = true;
    }
    const keys = Object.keys(this._zones);
    for (let i = 0, len = keys.length; i < len; i++) {
      const id3 = keys[i];
      const zone = this._zones[id3];
      let newTop = 0;
      let newHeight = 0;
      let newDisplay = "none";
      if (visibleZones.hasOwnProperty(id3)) {
        newTop = visibleZones[id3].verticalOffset - ctx.bigNumbersDelta;
        newHeight = visibleZones[id3].height;
        newDisplay = "block";
        if (!zone.isVisible) {
          zone.domNode.setAttribute("monaco-visible-view-zone", "true");
          zone.isVisible = true;
        }
        this._safeCallOnDomNodeTop(zone.delegate, ctx.getScrolledTopFromAbsoluteTop(visibleZones[id3].verticalOffset));
      } else {
        if (zone.isVisible) {
          zone.domNode.removeAttribute("monaco-visible-view-zone");
          zone.isVisible = false;
        }
        this._safeCallOnDomNodeTop(zone.delegate, ctx.getScrolledTopFromAbsoluteTop(-1e6));
      }
      zone.domNode.setTop(newTop);
      zone.domNode.setHeight(newHeight);
      zone.domNode.setDisplay(newDisplay);
      if (zone.marginDomNode) {
        zone.marginDomNode.setTop(newTop);
        zone.marginDomNode.setHeight(newHeight);
        zone.marginDomNode.setDisplay(newDisplay);
      }
    }
    if (hasVisibleZone) {
      this.domNode.setWidth(Math.max(ctx.scrollWidth, this._contentWidth));
      this.marginDomNode.setWidth(this._contentLeft);
    }
  }
}
function safeInvoke1Arg(func, arg1) {
  try {
    return func(arg1);
  } catch (e) {
    onUnexpectedError(e);
  }
}
class EditorTheme {
  get type() {
    return this._theme.type;
  }
  get value() {
    return this._theme;
  }
  constructor(theme) {
    this._theme = theme;
  }
  update(theme) {
    this._theme = theme;
  }
  getColor(color) {
    return this._theme.getColor(color);
  }
}
class ViewContext {
  constructor(configuration, theme, model) {
    this.configuration = configuration;
    this.theme = new EditorTheme(theme);
    this.viewModel = model;
    this.viewLayout = model.viewLayout;
  }
  addEventHandler(eventHandler) {
    this.viewModel.addViewEventHandler(eventHandler);
  }
  removeEventHandler(eventHandler) {
    this.viewModel.removeViewEventHandler(eventHandler);
  }
}
class ViewportData {
  constructor(selections2, partialData, whitespaceViewportData, model) {
    this.selections = selections2;
    this.startLineNumber = partialData.startLineNumber | 0;
    this.endLineNumber = partialData.endLineNumber | 0;
    this.relativeVerticalOffset = partialData.relativeVerticalOffset;
    this.bigNumbersDelta = partialData.bigNumbersDelta | 0;
    this.whitespaceViewportData = whitespaceViewportData;
    this._model = model;
    this.visibleRange = new Range$2(partialData.startLineNumber, this._model.getLineMinColumn(partialData.startLineNumber), partialData.endLineNumber, this._model.getLineMaxColumn(partialData.endLineNumber));
  }
  getViewLineRenderingData(lineNumber) {
    return this._model.getViewportViewLineRenderingData(this.visibleRange, lineNumber);
  }
  getDecorationsInViewport() {
    return this._model.getDecorationsInViewport(this.visibleRange);
  }
}
const blockDecorations = "";
class BlockDecorations extends ViewPart {
  constructor(context) {
    super(context);
    this.blocks = [];
    this.contentWidth = -1;
    this.contentLeft = 0;
    this.domNode = createFastDomNode(document.createElement("div"));
    this.domNode.setAttribute("role", "presentation");
    this.domNode.setAttribute("aria-hidden", "true");
    this.domNode.setClassName("blockDecorations-container");
    this.update();
  }
  update() {
    let didChange = false;
    const options = this._context.configuration.options;
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    const newContentWidth = layoutInfo.contentWidth - layoutInfo.verticalScrollbarWidth;
    if (this.contentWidth !== newContentWidth) {
      this.contentWidth = newContentWidth;
      didChange = true;
    }
    const newContentLeft = layoutInfo.contentLeft;
    if (this.contentLeft !== newContentLeft) {
      this.contentLeft = newContentLeft;
      didChange = true;
    }
    return didChange;
  }
  dispose() {
    super.dispose();
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    return this.update();
  }
  onScrollChanged(e) {
    return e.scrollTopChanged || e.scrollLeftChanged;
  }
  onDecorationsChanged(e) {
    return true;
  }
  onZonesChanged(e) {
    return true;
  }
  // --- end event handlers
  prepareRender(ctx) {
  }
  render(ctx) {
    var _a2;
    let count = 0;
    const decorations2 = ctx.getDecorationsInViewport();
    for (const decoration2 of decorations2) {
      if (!decoration2.options.blockClassName) {
        continue;
      }
      let block = this.blocks[count];
      if (!block) {
        block = this.blocks[count] = createFastDomNode(document.createElement("div"));
        this.domNode.appendChild(block);
      }
      let top;
      let bottom;
      if (decoration2.options.blockIsAfterEnd) {
        top = ctx.getVerticalOffsetAfterLineNumber(decoration2.range.endLineNumber, false);
        bottom = ctx.getVerticalOffsetAfterLineNumber(decoration2.range.endLineNumber, true);
      } else {
        top = ctx.getVerticalOffsetForLineNumber(decoration2.range.startLineNumber, true);
        bottom = decoration2.range.isEmpty() && !decoration2.options.blockDoesNotCollapse ? ctx.getVerticalOffsetForLineNumber(decoration2.range.startLineNumber, false) : ctx.getVerticalOffsetAfterLineNumber(decoration2.range.endLineNumber, true);
      }
      const [paddingTop, paddingRight, paddingBottom, paddingLeft] = (_a2 = decoration2.options.blockPadding) !== null && _a2 !== void 0 ? _a2 : [0, 0, 0, 0];
      block.setClassName("blockDecorations-block " + decoration2.options.blockClassName);
      block.setLeft(this.contentLeft - paddingLeft);
      block.setWidth(this.contentWidth + paddingLeft + paddingRight);
      block.setTop(top - ctx.scrollTop - paddingTop);
      block.setHeight(bottom - top + paddingTop + paddingBottom);
      count++;
    }
    for (let i = count; i < this.blocks.length; i++) {
      this.blocks[i].domNode.remove();
    }
    this.blocks.length = count;
  }
}
const whitespace = "";
class WhitespaceOverlay extends DynamicViewOverlay {
  constructor(context) {
    super();
    this._context = context;
    this._options = new WhitespaceOptions(this._context.configuration);
    this._selection = [];
    this._renderResult = null;
    this._context.addEventHandler(this);
  }
  dispose() {
    this._context.removeEventHandler(this);
    this._renderResult = null;
    super.dispose();
  }
  // --- begin event handlers
  onConfigurationChanged(e) {
    const newOptions = new WhitespaceOptions(this._context.configuration);
    if (this._options.equals(newOptions)) {
      return e.hasChanged(
        142
        /* EditorOption.layoutInfo */
      );
    }
    this._options = newOptions;
    return true;
  }
  onCursorStateChanged(e) {
    this._selection = e.selections;
    if (this._options.renderWhitespace === "selection") {
      return true;
    }
    return false;
  }
  onDecorationsChanged(e) {
    return true;
  }
  onFlushed(e) {
    return true;
  }
  onLinesChanged(e) {
    return true;
  }
  onLinesDeleted(e) {
    return true;
  }
  onLinesInserted(e) {
    return true;
  }
  onScrollChanged(e) {
    return e.scrollTopChanged;
  }
  onZonesChanged(e) {
    return true;
  }
  // --- end event handlers
  prepareRender(ctx) {
    if (this._options.renderWhitespace === "none") {
      this._renderResult = null;
      return;
    }
    const startLineNumber = ctx.visibleRange.startLineNumber;
    const endLineNumber = ctx.visibleRange.endLineNumber;
    const lineCount = endLineNumber - startLineNumber + 1;
    const needed = new Array(lineCount);
    for (let i = 0; i < lineCount; i++) {
      needed[i] = true;
    }
    const viewportData = this._context.viewModel.getMinimapLinesRenderingData(ctx.viewportData.startLineNumber, ctx.viewportData.endLineNumber, needed);
    this._renderResult = [];
    for (let lineNumber = ctx.viewportData.startLineNumber; lineNumber <= ctx.viewportData.endLineNumber; lineNumber++) {
      const lineIndex = lineNumber - ctx.viewportData.startLineNumber;
      const lineData = viewportData.data[lineIndex];
      let selectionsOnLine = null;
      if (this._options.renderWhitespace === "selection") {
        const selections2 = this._selection;
        for (const selection of selections2) {
          if (selection.endLineNumber < lineNumber || selection.startLineNumber > lineNumber) {
            continue;
          }
          const startColumn = selection.startLineNumber === lineNumber ? selection.startColumn : lineData.minColumn;
          const endColumn = selection.endLineNumber === lineNumber ? selection.endColumn : lineData.maxColumn;
          if (startColumn < endColumn) {
            if (!selectionsOnLine) {
              selectionsOnLine = [];
            }
            selectionsOnLine.push(new LineRange$1(startColumn - 1, endColumn - 1));
          }
        }
      }
      this._renderResult[lineIndex] = this._applyRenderWhitespace(ctx, lineNumber, selectionsOnLine, lineData);
    }
  }
  _applyRenderWhitespace(ctx, lineNumber, selections2, lineData) {
    if (this._options.renderWhitespace === "selection" && !selections2) {
      return "";
    }
    if (this._options.renderWhitespace === "trailing" && lineData.continuesWithWrappedLine) {
      return "";
    }
    const color = this._context.theme.getColor(editorWhitespaces);
    const USE_SVG = this._options.renderWithSVG;
    const lineContent = lineData.content;
    const len = this._options.stopRenderingLineAfter === -1 ? lineContent.length : Math.min(this._options.stopRenderingLineAfter, lineContent.length);
    const continuesWithWrappedLine = lineData.continuesWithWrappedLine;
    const fauxIndentLength = lineData.minColumn - 1;
    const onlyBoundary = this._options.renderWhitespace === "boundary";
    const onlyTrailing = this._options.renderWhitespace === "trailing";
    const lineHeight = this._options.lineHeight;
    const middotWidth = this._options.middotWidth;
    const wsmiddotWidth = this._options.wsmiddotWidth;
    const spaceWidth = this._options.spaceWidth;
    const wsmiddotDiff = Math.abs(wsmiddotWidth - spaceWidth);
    const middotDiff = Math.abs(middotWidth - spaceWidth);
    const renderSpaceCharCode = wsmiddotDiff < middotDiff ? 11825 : 183;
    const canUseHalfwidthRightwardsArrow = this._options.canUseHalfwidthRightwardsArrow;
    let result2 = "";
    let lineIsEmptyOrWhitespace = false;
    let firstNonWhitespaceIndex$1 = firstNonWhitespaceIndex(lineContent);
    let lastNonWhitespaceIndex$1;
    if (firstNonWhitespaceIndex$1 === -1) {
      lineIsEmptyOrWhitespace = true;
      firstNonWhitespaceIndex$1 = len;
      lastNonWhitespaceIndex$1 = len;
    } else {
      lastNonWhitespaceIndex$1 = lastNonWhitespaceIndex(lineContent);
    }
    let currentSelectionIndex = 0;
    let currentSelection = selections2 && selections2[currentSelectionIndex];
    let maxLeft = 0;
    for (let charIndex = fauxIndentLength; charIndex < len; charIndex++) {
      const chCode = lineContent.charCodeAt(charIndex);
      if (currentSelection && charIndex >= currentSelection.endOffset) {
        currentSelectionIndex++;
        currentSelection = selections2 && selections2[currentSelectionIndex];
      }
      if (chCode !== 9 && chCode !== 32) {
        continue;
      }
      if (onlyTrailing && !lineIsEmptyOrWhitespace && charIndex <= lastNonWhitespaceIndex$1) {
        continue;
      }
      if (onlyBoundary && charIndex >= firstNonWhitespaceIndex$1 && charIndex <= lastNonWhitespaceIndex$1 && chCode === 32) {
        const prevChCode = charIndex - 1 >= 0 ? lineContent.charCodeAt(charIndex - 1) : 0;
        const nextChCode = charIndex + 1 < len ? lineContent.charCodeAt(charIndex + 1) : 0;
        if (prevChCode !== 32 && nextChCode !== 32) {
          continue;
        }
      }
      if (onlyBoundary && continuesWithWrappedLine && charIndex === len - 1) {
        const prevCharCode = charIndex - 1 >= 0 ? lineContent.charCodeAt(charIndex - 1) : 0;
        const isSingleTrailingSpace = chCode === 32 && (prevCharCode !== 32 && prevCharCode !== 9);
        if (isSingleTrailingSpace) {
          continue;
        }
      }
      if (selections2 && (!currentSelection || currentSelection.startOffset > charIndex || currentSelection.endOffset <= charIndex)) {
        continue;
      }
      const visibleRange = ctx.visibleRangeForPosition(new Position$2(lineNumber, charIndex + 1));
      if (!visibleRange) {
        continue;
      }
      if (USE_SVG) {
        maxLeft = Math.max(maxLeft, visibleRange.left);
        if (chCode === 9) {
          result2 += this._renderArrow(lineHeight, spaceWidth, visibleRange.left);
        } else {
          result2 += `<circle cx="${(visibleRange.left + spaceWidth / 2).toFixed(2)}" cy="${(lineHeight / 2).toFixed(2)}" r="${(spaceWidth / 7).toFixed(2)}" />`;
        }
      } else {
        if (chCode === 9) {
          result2 += `<div class="mwh" style="left:${visibleRange.left}px;height:${lineHeight}px;">${canUseHalfwidthRightwardsArrow ? String.fromCharCode(65515) : String.fromCharCode(8594)}</div>`;
        } else {
          result2 += `<div class="mwh" style="left:${visibleRange.left}px;height:${lineHeight}px;">${String.fromCharCode(renderSpaceCharCode)}</div>`;
        }
      }
    }
    if (USE_SVG) {
      maxLeft = Math.round(maxLeft + spaceWidth);
      return `<svg style="position:absolute;width:${maxLeft}px;height:${lineHeight}px" viewBox="0 0 ${maxLeft} ${lineHeight}" xmlns="http://www.w3.org/2000/svg" fill="${color}">` + result2 + `</svg>`;
    }
    return result2;
  }
  _renderArrow(lineHeight, spaceWidth, left) {
    const strokeWidth = spaceWidth / 7;
    const width = spaceWidth;
    const dy = lineHeight / 2;
    const dx = left;
    const p1 = { x: 0, y: strokeWidth / 2 };
    const p2 = { x: 100 / 125 * width, y: p1.y };
    const p3 = { x: p2.x - 0.2 * p2.x, y: p2.y + 0.2 * p2.x };
    const p4 = { x: p3.x + 0.1 * p2.x, y: p3.y + 0.1 * p2.x };
    const p5 = { x: p4.x + 0.35 * p2.x, y: p4.y - 0.35 * p2.x };
    const p6 = { x: p5.x, y: -p5.y };
    const p7 = { x: p4.x, y: -p4.y };
    const p8 = { x: p3.x, y: -p3.y };
    const p9 = { x: p2.x, y: -p2.y };
    const p10 = { x: p1.x, y: -p1.y };
    const p11 = [p1, p2, p3, p4, p5, p6, p7, p8, p9, p10];
    const parts = p11.map((p12) => `${(dx + p12.x).toFixed(2)} ${(dy + p12.y).toFixed(2)}`).join(" L ");
    return `<path d="M ${parts}" />`;
  }
  render(startLineNumber, lineNumber) {
    if (!this._renderResult) {
      return "";
    }
    const lineIndex = lineNumber - startLineNumber;
    if (lineIndex < 0 || lineIndex >= this._renderResult.length) {
      return "";
    }
    return this._renderResult[lineIndex];
  }
}
class WhitespaceOptions {
  constructor(config2) {
    const options = config2.options;
    const fontInfo = options.get(
      49
      /* EditorOption.fontInfo */
    );
    const experimentalWhitespaceRendering = options.get(
      37
      /* EditorOption.experimentalWhitespaceRendering */
    );
    if (experimentalWhitespaceRendering === "off") {
      this.renderWhitespace = "none";
      this.renderWithSVG = false;
    } else if (experimentalWhitespaceRendering === "svg") {
      this.renderWhitespace = options.get(
        97
        /* EditorOption.renderWhitespace */
      );
      this.renderWithSVG = true;
    } else {
      this.renderWhitespace = options.get(
        97
        /* EditorOption.renderWhitespace */
      );
      this.renderWithSVG = false;
    }
    this.spaceWidth = fontInfo.spaceWidth;
    this.middotWidth = fontInfo.middotWidth;
    this.wsmiddotWidth = fontInfo.wsmiddotWidth;
    this.canUseHalfwidthRightwardsArrow = fontInfo.canUseHalfwidthRightwardsArrow;
    this.lineHeight = options.get(
      65
      /* EditorOption.lineHeight */
    );
    this.stopRenderingLineAfter = options.get(
      115
      /* EditorOption.stopRenderingLineAfter */
    );
  }
  equals(other) {
    return this.renderWhitespace === other.renderWhitespace && this.renderWithSVG === other.renderWithSVG && this.spaceWidth === other.spaceWidth && this.middotWidth === other.middotWidth && this.wsmiddotWidth === other.wsmiddotWidth && this.canUseHalfwidthRightwardsArrow === other.canUseHalfwidthRightwardsArrow && this.lineHeight === other.lineHeight && this.stopRenderingLineAfter === other.stopRenderingLineAfter;
  }
}
var __decorate$24 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1_ = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let View$1 = class View extends ViewEventHandler {
  constructor(commandDelegate, configuration, colorTheme, model, userInputEvents, overflowWidgetsDomNode, _instantiationService) {
    super();
    this._instantiationService = _instantiationService;
    this._shouldRecomputeGlyphMarginLanes = false;
    this._selections = [new Selection$1(1, 1, 1, 1)];
    this._renderAnimationFrame = null;
    const viewController = new ViewController(configuration, model, userInputEvents, commandDelegate);
    this._context = new ViewContext(configuration, colorTheme, model);
    this._context.addEventHandler(this);
    this._viewParts = [];
    this._textAreaHandler = this._instantiationService.createInstance(TextAreaHandler, this._context, viewController, this._createTextAreaHandlerHelper());
    this._viewParts.push(this._textAreaHandler);
    this._linesContent = createFastDomNode(document.createElement("div"));
    this._linesContent.setClassName("lines-content monaco-editor-background");
    this._linesContent.setPosition("absolute");
    this.domNode = createFastDomNode(document.createElement("div"));
    this.domNode.setClassName(this._getEditorClassName());
    this.domNode.setAttribute("role", "code");
    this._overflowGuardContainer = createFastDomNode(document.createElement("div"));
    PartFingerprints.write(
      this._overflowGuardContainer,
      3
      /* PartFingerprint.OverflowGuard */
    );
    this._overflowGuardContainer.setClassName("overflow-guard");
    this._scrollbar = new EditorScrollbar2(this._context, this._linesContent, this.domNode, this._overflowGuardContainer);
    this._viewParts.push(this._scrollbar);
    this._viewLines = new ViewLines(this._context, this._linesContent);
    this._viewZones = new ViewZones(this._context);
    this._viewParts.push(this._viewZones);
    const decorationsOverviewRuler = new DecorationsOverviewRuler(this._context);
    this._viewParts.push(decorationsOverviewRuler);
    const scrollDecoration2 = new ScrollDecorationViewPart(this._context);
    this._viewParts.push(scrollDecoration2);
    const contentViewOverlays = new ContentViewOverlays(this._context);
    this._viewParts.push(contentViewOverlays);
    contentViewOverlays.addDynamicOverlay(new CurrentLineHighlightOverlay(this._context));
    contentViewOverlays.addDynamicOverlay(new SelectionsOverlay(this._context));
    contentViewOverlays.addDynamicOverlay(new IndentGuidesOverlay(this._context));
    contentViewOverlays.addDynamicOverlay(new DecorationsOverlay(this._context));
    contentViewOverlays.addDynamicOverlay(new WhitespaceOverlay(this._context));
    const marginViewOverlays = new MarginViewOverlays(this._context);
    this._viewParts.push(marginViewOverlays);
    marginViewOverlays.addDynamicOverlay(new CurrentLineMarginHighlightOverlay(this._context));
    marginViewOverlays.addDynamicOverlay(new MarginViewLineDecorationsOverlay(this._context));
    marginViewOverlays.addDynamicOverlay(new LinesDecorationsOverlay(this._context));
    marginViewOverlays.addDynamicOverlay(new LineNumbersOverlay(this._context));
    this._glyphMarginWidgets = new GlyphMarginWidgets(this._context);
    this._viewParts.push(this._glyphMarginWidgets);
    const margin2 = new Margin(this._context);
    margin2.getDomNode().appendChild(this._viewZones.marginDomNode);
    margin2.getDomNode().appendChild(marginViewOverlays.getDomNode());
    margin2.getDomNode().appendChild(this._glyphMarginWidgets.domNode);
    this._viewParts.push(margin2);
    this._contentWidgets = new ViewContentWidgets(this._context, this.domNode);
    this._viewParts.push(this._contentWidgets);
    this._viewCursors = new ViewCursors(this._context);
    this._viewParts.push(this._viewCursors);
    this._overlayWidgets = new ViewOverlayWidgets(this._context);
    this._viewParts.push(this._overlayWidgets);
    const rulers2 = new Rulers(this._context);
    this._viewParts.push(rulers2);
    const blockOutline = new BlockDecorations(this._context);
    this._viewParts.push(blockOutline);
    const minimap2 = new Minimap(this._context);
    this._viewParts.push(minimap2);
    if (decorationsOverviewRuler) {
      const overviewRulerData = this._scrollbar.getOverviewRulerLayoutInfo();
      overviewRulerData.parent.insertBefore(decorationsOverviewRuler.getDomNode(), overviewRulerData.insertBefore);
    }
    this._linesContent.appendChild(contentViewOverlays.getDomNode());
    this._linesContent.appendChild(rulers2.domNode);
    this._linesContent.appendChild(this._viewZones.domNode);
    this._linesContent.appendChild(this._viewLines.getDomNode());
    this._linesContent.appendChild(this._contentWidgets.domNode);
    this._linesContent.appendChild(this._viewCursors.getDomNode());
    this._overflowGuardContainer.appendChild(margin2.getDomNode());
    this._overflowGuardContainer.appendChild(this._scrollbar.getDomNode());
    this._overflowGuardContainer.appendChild(scrollDecoration2.getDomNode());
    this._overflowGuardContainer.appendChild(this._textAreaHandler.textArea);
    this._overflowGuardContainer.appendChild(this._textAreaHandler.textAreaCover);
    this._overflowGuardContainer.appendChild(this._overlayWidgets.getDomNode());
    this._overflowGuardContainer.appendChild(minimap2.getDomNode());
    this._overflowGuardContainer.appendChild(blockOutline.domNode);
    this.domNode.appendChild(this._overflowGuardContainer);
    if (overflowWidgetsDomNode) {
      overflowWidgetsDomNode.appendChild(this._contentWidgets.overflowingContentWidgetsDomNode.domNode);
    } else {
      this.domNode.appendChild(this._contentWidgets.overflowingContentWidgetsDomNode);
    }
    this._applyLayout();
    this._pointerHandler = this._register(new PointerHandler(this._context, viewController, this._createPointerHandlerHelper()));
  }
  _flushAccumulatedAndRenderNow() {
    if (this._shouldRecomputeGlyphMarginLanes) {
      this._shouldRecomputeGlyphMarginLanes = false;
      this._context.configuration.setGlyphMarginDecorationLaneCount(this._computeGlyphMarginLaneCount());
    }
    inputLatency.onRenderStart();
    this._renderNow();
  }
  _computeGlyphMarginLaneCount() {
    const model = this._context.viewModel.model;
    let glyphs = [];
    glyphs = glyphs.concat(model.getAllMarginDecorations().map((decoration2) => {
      var _a2, _b2;
      const lane = (_b2 = (_a2 = decoration2.options.glyphMargin) === null || _a2 === void 0 ? void 0 : _a2.position) !== null && _b2 !== void 0 ? _b2 : GlyphMarginLane$1.Left;
      return { range: decoration2.range, lane };
    }));
    glyphs = glyphs.concat(this._glyphMarginWidgets.getWidgets().map((widget) => {
      const range2 = model.validateRange(widget.preference.range);
      return { range: range2, lane: widget.preference.lane };
    }));
    glyphs.sort((a, b) => Range$2.compareRangesUsingStarts(a.range, b.range));
    let leftDecRange = null;
    let rightDecRange = null;
    for (const decoration2 of glyphs) {
      if (decoration2.lane === GlyphMarginLane$1.Left && (!leftDecRange || Range$2.compareRangesUsingEnds(leftDecRange, decoration2.range) < 0)) {
        leftDecRange = decoration2.range;
      }
      if (decoration2.lane === GlyphMarginLane$1.Right && (!rightDecRange || Range$2.compareRangesUsingEnds(rightDecRange, decoration2.range) < 0)) {
        rightDecRange = decoration2.range;
      }
      if (leftDecRange && rightDecRange) {
        if (leftDecRange.endLineNumber < rightDecRange.startLineNumber) {
          leftDecRange = null;
          continue;
        }
        if (rightDecRange.endLineNumber < leftDecRange.startLineNumber) {
          rightDecRange = null;
          continue;
        }
        return 2;
      }
    }
    return 1;
  }
  _createPointerHandlerHelper() {
    return {
      viewDomNode: this.domNode.domNode,
      linesContentDomNode: this._linesContent.domNode,
      viewLinesDomNode: this._viewLines.getDomNode().domNode,
      focusTextArea: () => {
        this.focus();
      },
      dispatchTextAreaEvent: (event) => {
        this._textAreaHandler.textArea.domNode.dispatchEvent(event);
      },
      getLastRenderData: () => {
        const lastViewCursorsRenderData = this._viewCursors.getLastRenderData() || [];
        const lastTextareaPosition = this._textAreaHandler.getLastRenderData();
        return new PointerHandlerLastRenderData(lastViewCursorsRenderData, lastTextareaPosition);
      },
      renderNow: () => {
        this.render(true, false);
      },
      shouldSuppressMouseDownOnViewZone: (viewZoneId) => {
        return this._viewZones.shouldSuppressMouseDownOnViewZone(viewZoneId);
      },
      shouldSuppressMouseDownOnWidget: (widgetId) => {
        return this._contentWidgets.shouldSuppressMouseDownOnWidget(widgetId);
      },
      getPositionFromDOMInfo: (spanNode, offset) => {
        this._flushAccumulatedAndRenderNow();
        return this._viewLines.getPositionFromDOMInfo(spanNode, offset);
      },
      visibleRangeForPosition: (lineNumber, column) => {
        this._flushAccumulatedAndRenderNow();
        return this._viewLines.visibleRangeForPosition(new Position$2(lineNumber, column));
      },
      getLineWidth: (lineNumber) => {
        this._flushAccumulatedAndRenderNow();
        return this._viewLines.getLineWidth(lineNumber);
      }
    };
  }
  _createTextAreaHandlerHelper() {
    return {
      visibleRangeForPosition: (position) => {
        this._flushAccumulatedAndRenderNow();
        return this._viewLines.visibleRangeForPosition(position);
      }
    };
  }
  _applyLayout() {
    const options = this._context.configuration.options;
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    this.domNode.setWidth(layoutInfo.width);
    this.domNode.setHeight(layoutInfo.height);
    this._overflowGuardContainer.setWidth(layoutInfo.width);
    this._overflowGuardContainer.setHeight(layoutInfo.height);
    this._linesContent.setWidth(1e6);
    this._linesContent.setHeight(1e6);
  }
  _getEditorClassName() {
    const focused = this._textAreaHandler.isFocused() ? " focused" : "";
    return this._context.configuration.options.get(
      139
      /* EditorOption.editorClassName */
    ) + " " + getThemeTypeSelector(this._context.theme.type) + focused;
  }
  // --- begin event handlers
  handleEvents(events) {
    super.handleEvents(events);
    this._scheduleRender();
  }
  onConfigurationChanged(e) {
    this.domNode.setClassName(this._getEditorClassName());
    this._applyLayout();
    return false;
  }
  onCursorStateChanged(e) {
    this._selections = e.selections;
    return false;
  }
  onDecorationsChanged(e) {
    if (e.affectsGlyphMargin) {
      this._shouldRecomputeGlyphMarginLanes = true;
    }
    return false;
  }
  onFocusChanged(e) {
    this.domNode.setClassName(this._getEditorClassName());
    return false;
  }
  onThemeChanged(e) {
    this._context.theme.update(e.theme);
    this.domNode.setClassName(this._getEditorClassName());
    return false;
  }
  // --- end event handlers
  dispose() {
    if (this._renderAnimationFrame !== null) {
      this._renderAnimationFrame.dispose();
      this._renderAnimationFrame = null;
    }
    this._contentWidgets.overflowingContentWidgetsDomNode.domNode.remove();
    this._context.removeEventHandler(this);
    this._viewLines.dispose();
    for (const viewPart of this._viewParts) {
      viewPart.dispose();
    }
    super.dispose();
  }
  _scheduleRender() {
    if (this._renderAnimationFrame === null) {
      this._renderAnimationFrame = runAtThisOrScheduleAtNextAnimationFrame(this._onRenderScheduled.bind(this), 100);
    }
  }
  _onRenderScheduled() {
    this._renderAnimationFrame = null;
    this._flushAccumulatedAndRenderNow();
  }
  _renderNow() {
    safeInvokeNoArg(() => this._actualRender());
  }
  _getViewPartsToRender() {
    const result2 = [];
    let resultLen = 0;
    for (const viewPart of this._viewParts) {
      if (viewPart.shouldRender()) {
        result2[resultLen++] = viewPart;
      }
    }
    return result2;
  }
  _actualRender() {
    if (!isInDOM(this.domNode.domNode)) {
      return;
    }
    let viewPartsToRender = this._getViewPartsToRender();
    if (!this._viewLines.shouldRender() && viewPartsToRender.length === 0) {
      return;
    }
    const partialViewportData = this._context.viewLayout.getLinesViewportData();
    this._context.viewModel.setViewport(partialViewportData.startLineNumber, partialViewportData.endLineNumber, partialViewportData.centeredLineNumber);
    const viewportData = new ViewportData(this._selections, partialViewportData, this._context.viewLayout.getWhitespaceViewportData(), this._context.viewModel);
    if (this._contentWidgets.shouldRender()) {
      this._contentWidgets.onBeforeRender(viewportData);
    }
    if (this._viewLines.shouldRender()) {
      this._viewLines.renderText(viewportData);
      this._viewLines.onDidRender();
      viewPartsToRender = this._getViewPartsToRender();
    }
    const renderingContext = new RenderingContext(this._context.viewLayout, viewportData, this._viewLines);
    for (const viewPart of viewPartsToRender) {
      viewPart.prepareRender(renderingContext);
    }
    for (const viewPart of viewPartsToRender) {
      viewPart.render(renderingContext);
      viewPart.onDidRender();
    }
  }
  // --- BEGIN CodeEditor helpers
  delegateVerticalScrollbarPointerDown(browserEvent) {
    this._scrollbar.delegateVerticalScrollbarPointerDown(browserEvent);
  }
  delegateScrollFromMouseWheelEvent(browserEvent) {
    this._scrollbar.delegateScrollFromMouseWheelEvent(browserEvent);
  }
  restoreState(scrollPosition) {
    this._context.viewModel.viewLayout.setScrollPosition(
      {
        scrollTop: scrollPosition.scrollTop,
        scrollLeft: scrollPosition.scrollLeft
      },
      1
      /* ScrollType.Immediate */
    );
    this._context.viewModel.visibleLinesStabilized();
  }
  getOffsetForColumn(modelLineNumber, modelColumn) {
    const modelPosition = this._context.viewModel.model.validatePosition({
      lineNumber: modelLineNumber,
      column: modelColumn
    });
    const viewPosition = this._context.viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);
    this._flushAccumulatedAndRenderNow();
    const visibleRange = this._viewLines.visibleRangeForPosition(new Position$2(viewPosition.lineNumber, viewPosition.column));
    if (!visibleRange) {
      return -1;
    }
    return visibleRange.left;
  }
  getTargetAtClientPoint(clientX, clientY) {
    const mouseTarget = this._pointerHandler.getTargetAtClientPoint(clientX, clientY);
    if (!mouseTarget) {
      return null;
    }
    return ViewUserInputEvents.convertViewToModelMouseTarget(mouseTarget, this._context.viewModel.coordinatesConverter);
  }
  createOverviewRuler(cssClassName) {
    return new OverviewRuler(this._context, cssClassName);
  }
  change(callback) {
    this._viewZones.changeViewZones(callback);
    this._scheduleRender();
  }
  render(now, everything) {
    if (everything) {
      this._viewLines.forceShouldRender();
      for (const viewPart of this._viewParts) {
        viewPart.forceShouldRender();
      }
    }
    if (now) {
      this._flushAccumulatedAndRenderNow();
    } else {
      this._scheduleRender();
    }
  }
  writeScreenReaderContent(reason) {
    this._textAreaHandler.writeScreenReaderContent(reason);
  }
  focus() {
    this._textAreaHandler.focusTextArea();
  }
  isFocused() {
    return this._textAreaHandler.isFocused();
  }
  setAriaOptions(options) {
    this._textAreaHandler.setAriaOptions(options);
  }
  addContentWidget(widgetData) {
    this._contentWidgets.addWidget(widgetData.widget);
    this.layoutContentWidget(widgetData);
    this._scheduleRender();
  }
  layoutContentWidget(widgetData) {
    var _a2, _b2, _c2, _d2, _e2, _f2, _g2, _h2;
    this._contentWidgets.setWidgetPosition(widgetData.widget, (_b2 = (_a2 = widgetData.position) === null || _a2 === void 0 ? void 0 : _a2.position) !== null && _b2 !== void 0 ? _b2 : null, (_d2 = (_c2 = widgetData.position) === null || _c2 === void 0 ? void 0 : _c2.secondaryPosition) !== null && _d2 !== void 0 ? _d2 : null, (_f2 = (_e2 = widgetData.position) === null || _e2 === void 0 ? void 0 : _e2.preference) !== null && _f2 !== void 0 ? _f2 : null, (_h2 = (_g2 = widgetData.position) === null || _g2 === void 0 ? void 0 : _g2.positionAffinity) !== null && _h2 !== void 0 ? _h2 : null);
    this._scheduleRender();
  }
  removeContentWidget(widgetData) {
    this._contentWidgets.removeWidget(widgetData.widget);
    this._scheduleRender();
  }
  addOverlayWidget(widgetData) {
    this._overlayWidgets.addWidget(widgetData.widget);
    this.layoutOverlayWidget(widgetData);
    this._scheduleRender();
  }
  layoutOverlayWidget(widgetData) {
    const newPreference = widgetData.position ? widgetData.position.preference : null;
    const shouldRender = this._overlayWidgets.setWidgetPosition(widgetData.widget, newPreference);
    if (shouldRender) {
      this._scheduleRender();
    }
  }
  removeOverlayWidget(widgetData) {
    this._overlayWidgets.removeWidget(widgetData.widget);
    this._scheduleRender();
  }
  addGlyphMarginWidget(widgetData) {
    this._glyphMarginWidgets.addWidget(widgetData.widget);
    this._shouldRecomputeGlyphMarginLanes = true;
    this._scheduleRender();
  }
  layoutGlyphMarginWidget(widgetData) {
    const newPreference = widgetData.position;
    const shouldRender = this._glyphMarginWidgets.setWidgetPosition(widgetData.widget, newPreference);
    if (shouldRender) {
      this._shouldRecomputeGlyphMarginLanes = true;
      this._scheduleRender();
    }
  }
  removeGlyphMarginWidget(widgetData) {
    this._glyphMarginWidgets.removeWidget(widgetData.widget);
    this._shouldRecomputeGlyphMarginLanes = true;
    this._scheduleRender();
  }
};
View$1 = __decorate$24([
  __param$1_(6, IInstantiationService)
], View$1);
function safeInvokeNoArg(func) {
  try {
    return func();
  } catch (e) {
    onUnexpectedError(e);
  }
}
class InternalEditorAction {
  constructor(id3, label, alias, precondition, run, contextKeyService) {
    this.id = id3;
    this.label = label;
    this.alias = alias;
    this._precondition = precondition;
    this._run = run;
    this._contextKeyService = contextKeyService;
  }
  isSupported() {
    return this._contextKeyService.contextMatchesRules(this._precondition);
  }
  run(args) {
    if (!this.isSupported()) {
      return Promise.resolve(void 0);
    }
    return this._run(args);
  }
}
const EditorType = {
  ICodeEditor: "vs.editor.ICodeEditor",
  IDiffEditor: "vs.editor.IDiffEditor"
};
function countEOL(text2) {
  let eolCount = 0;
  let firstLineLength = 0;
  let lastLineStart = 0;
  let eol = 0;
  for (let i = 0, len = text2.length; i < len; i++) {
    const chr = text2.charCodeAt(i);
    if (chr === 13) {
      if (eolCount === 0) {
        firstLineLength = i;
      }
      eolCount++;
      if (i + 1 < len && text2.charCodeAt(i + 1) === 10) {
        eol |= 2;
        i++;
      } else {
        eol |= 3;
      }
      lastLineStart = i + 1;
    } else if (chr === 10) {
      eol |= 1;
      if (eolCount === 0) {
        firstLineLength = i;
      }
      eolCount++;
      lastLineStart = i + 1;
    }
  }
  if (eolCount === 0) {
    firstLineLength = text2.length;
  }
  return [eolCount, firstLineLength, text2.length - lastLineStart, eol];
}
class LineRange2 {
  static fromRange(range2) {
    return new LineRange2(range2.startLineNumber, range2.endLineNumber);
  }
  static subtract(a, b) {
    if (!b) {
      return [a];
    }
    if (a.startLineNumber < b.startLineNumber && b.endLineNumberExclusive < a.endLineNumberExclusive) {
      return [
        new LineRange2(a.startLineNumber, b.startLineNumber),
        new LineRange2(b.endLineNumberExclusive, a.endLineNumberExclusive)
      ];
    } else if (b.startLineNumber <= a.startLineNumber && a.endLineNumberExclusive <= b.endLineNumberExclusive) {
      return [];
    } else if (b.endLineNumberExclusive < a.endLineNumberExclusive) {
      return [new LineRange2(Math.max(b.endLineNumberExclusive, a.startLineNumber), a.endLineNumberExclusive)];
    } else {
      return [new LineRange2(a.startLineNumber, Math.min(b.startLineNumber, a.endLineNumberExclusive))];
    }
  }
  /**
   * @param lineRanges An array of sorted line ranges.
   */
  static joinMany(lineRanges) {
    if (lineRanges.length === 0) {
      return [];
    }
    let result2 = lineRanges[0];
    for (let i = 1; i < lineRanges.length; i++) {
      result2 = this.join(result2, lineRanges[i]);
    }
    return result2;
  }
  /**
   * @param lineRanges1 Must be sorted.
   * @param lineRanges2 Must be sorted.
   */
  static join(lineRanges1, lineRanges2) {
    if (lineRanges1.length === 0) {
      return lineRanges2;
    }
    if (lineRanges2.length === 0) {
      return lineRanges1;
    }
    const result2 = [];
    let i1 = 0;
    let i2 = 0;
    let current = null;
    while (i1 < lineRanges1.length || i2 < lineRanges2.length) {
      let next = null;
      if (i1 < lineRanges1.length && i2 < lineRanges2.length) {
        const lineRange1 = lineRanges1[i1];
        const lineRange2 = lineRanges2[i2];
        if (lineRange1.startLineNumber < lineRange2.startLineNumber) {
          next = lineRange1;
          i1++;
        } else {
          next = lineRange2;
          i2++;
        }
      } else if (i1 < lineRanges1.length) {
        next = lineRanges1[i1];
        i1++;
      } else {
        next = lineRanges2[i2];
        i2++;
      }
      if (current === null) {
        current = next;
      } else {
        if (current.endLineNumberExclusive >= next.startLineNumber) {
          current = new LineRange2(current.startLineNumber, Math.max(current.endLineNumberExclusive, next.endLineNumberExclusive));
        } else {
          result2.push(current);
          current = next;
        }
      }
    }
    if (current !== null) {
      result2.push(current);
    }
    return result2;
  }
  static ofLength(startLineNumber, length2) {
    return new LineRange2(startLineNumber, startLineNumber + length2);
  }
  /**
   * @internal
   */
  static deserialize(lineRange) {
    return new LineRange2(lineRange[0], lineRange[1]);
  }
  constructor(startLineNumber, endLineNumberExclusive) {
    if (startLineNumber > endLineNumberExclusive) {
      throw new BugIndicatingError(`startLineNumber ${startLineNumber} cannot be after endLineNumberExclusive ${endLineNumberExclusive}`);
    }
    this.startLineNumber = startLineNumber;
    this.endLineNumberExclusive = endLineNumberExclusive;
  }
  /**
   * Indicates if this line range contains the given line number.
   */
  contains(lineNumber) {
    return this.startLineNumber <= lineNumber && lineNumber < this.endLineNumberExclusive;
  }
  /**
   * Indicates if this line range is empty.
   */
  get isEmpty() {
    return this.startLineNumber === this.endLineNumberExclusive;
  }
  /**
   * Moves this line range by the given offset of line numbers.
   */
  delta(offset) {
    return new LineRange2(this.startLineNumber + offset, this.endLineNumberExclusive + offset);
  }
  /**
   * The number of lines this line range spans.
   */
  get length() {
    return this.endLineNumberExclusive - this.startLineNumber;
  }
  /**
   * Creates a line range that combines this and the given line range.
   */
  join(other) {
    return new LineRange2(Math.min(this.startLineNumber, other.startLineNumber), Math.max(this.endLineNumberExclusive, other.endLineNumberExclusive));
  }
  toString() {
    return `[${this.startLineNumber},${this.endLineNumberExclusive})`;
  }
  /**
   * The resulting range is empty if the ranges do not intersect, but touch.
   * If the ranges don't even touch, the result is undefined.
   */
  intersect(other) {
    const startLineNumber = Math.max(this.startLineNumber, other.startLineNumber);
    const endLineNumberExclusive = Math.min(this.endLineNumberExclusive, other.endLineNumberExclusive);
    if (startLineNumber <= endLineNumberExclusive) {
      return new LineRange2(startLineNumber, endLineNumberExclusive);
    }
    return void 0;
  }
  intersectsStrict(other) {
    return this.startLineNumber < other.endLineNumberExclusive && other.startLineNumber < this.endLineNumberExclusive;
  }
  overlapOrTouch(other) {
    return this.startLineNumber <= other.endLineNumberExclusive && other.startLineNumber <= this.endLineNumberExclusive;
  }
  equals(b) {
    return this.startLineNumber === b.startLineNumber && this.endLineNumberExclusive === b.endLineNumberExclusive;
  }
  toInclusiveRange() {
    if (this.isEmpty) {
      return null;
    }
    return new Range$2(this.startLineNumber, 1, this.endLineNumberExclusive - 1, Number.MAX_SAFE_INTEGER);
  }
  toExclusiveRange() {
    return new Range$2(this.startLineNumber, 1, this.endLineNumberExclusive, 1);
  }
  mapToLineArray(f) {
    const result2 = [];
    for (let lineNumber = this.startLineNumber; lineNumber < this.endLineNumberExclusive; lineNumber++) {
      result2.push(f(lineNumber));
    }
    return result2;
  }
  forEach(f) {
    for (let lineNumber = this.startLineNumber; lineNumber < this.endLineNumberExclusive; lineNumber++) {
      f(lineNumber);
    }
  }
  /**
   * @internal
   */
  serialize() {
    return [this.startLineNumber, this.endLineNumberExclusive];
  }
  includes(lineNumber) {
    return this.startLineNumber <= lineNumber && lineNumber < this.endLineNumberExclusive;
  }
}
class BracketInfo {
  constructor(range2, nestingLevel, nestingLevelOfEqualBracketType, isInvalid) {
    this.range = range2;
    this.nestingLevel = nestingLevel;
    this.nestingLevelOfEqualBracketType = nestingLevelOfEqualBracketType;
    this.isInvalid = isInvalid;
  }
}
class BracketPairInfo {
  constructor(range2, openingBracketRange, closingBracketRange, nestingLevel, nestingLevelOfEqualBracketType, bracketPairNode) {
    this.range = range2;
    this.openingBracketRange = openingBracketRange;
    this.closingBracketRange = closingBracketRange;
    this.nestingLevel = nestingLevel;
    this.nestingLevelOfEqualBracketType = nestingLevelOfEqualBracketType;
    this.bracketPairNode = bracketPairNode;
  }
  get openingBracketInfo() {
    return this.bracketPairNode.openingBracket.bracketInfo;
  }
}
class BracketPairWithMinIndentationInfo extends BracketPairInfo {
  constructor(range2, openingBracketRange, closingBracketRange, nestingLevel, nestingLevelOfEqualBracketType, bracketPairNode, minVisibleColumnIndentation) {
    super(range2, openingBracketRange, closingBracketRange, nestingLevel, nestingLevelOfEqualBracketType, bracketPairNode);
    this.minVisibleColumnIndentation = minVisibleColumnIndentation;
  }
}
class LengthObj {
  constructor(lineCount, columnCount) {
    this.lineCount = lineCount;
    this.columnCount = columnCount;
  }
  toLength() {
    return toLength(this.lineCount, this.columnCount);
  }
  toString() {
    return `${this.lineCount},${this.columnCount}`;
  }
}
LengthObj.zero = new LengthObj(0, 0);
function lengthDiff(startLineCount, startColumnCount, endLineCount, endColumnCount) {
  return startLineCount !== endLineCount ? toLength(endLineCount - startLineCount, endColumnCount) : toLength(0, endColumnCount - startColumnCount);
}
const lengthZero = 0;
function lengthIsZero(length2) {
  return length2 === 0;
}
const factor = Math.pow(2, 26);
function toLength(lineCount, columnCount) {
  return lineCount * factor + columnCount;
}
function lengthToObj(length2) {
  const l = length2;
  const lineCount = Math.floor(l / factor);
  const columnCount = l - lineCount * factor;
  return new LengthObj(lineCount, columnCount);
}
function lengthGetLineCount(length2) {
  return Math.floor(length2 / factor);
}
function lengthGetColumnCountIfZeroLineCount(length2) {
  return length2;
}
function lengthAdd(l1, l2) {
  let r = l1 + l2;
  if (l2 >= factor) {
    r = r - l1 % factor;
  }
  return r;
}
function sumLengths(items, lengthFn) {
  return items.reduce((a, b) => lengthAdd(a, lengthFn(b)), lengthZero);
}
function lengthEquals(length1, length2) {
  return length1 === length2;
}
function lengthDiffNonNegative(length1, length2) {
  const l1 = length1;
  const l2 = length2;
  const diff = l2 - l1;
  if (diff <= 0) {
    return lengthZero;
  }
  const lineCount1 = Math.floor(l1 / factor);
  const lineCount2 = Math.floor(l2 / factor);
  const colCount2 = l2 - lineCount2 * factor;
  if (lineCount1 === lineCount2) {
    const colCount1 = l1 - lineCount1 * factor;
    return toLength(0, colCount2 - colCount1);
  } else {
    return toLength(lineCount2 - lineCount1, colCount2);
  }
}
function lengthLessThan(length1, length2) {
  return length1 < length2;
}
function lengthLessThanEqual(length1, length2) {
  return length1 <= length2;
}
function lengthGreaterThanEqual(length1, length2) {
  return length1 >= length2;
}
function lengthToPosition(length2) {
  const l = length2;
  const lineCount = Math.floor(l / factor);
  const colCount = l - lineCount * factor;
  return new Position$2(lineCount + 1, colCount + 1);
}
function positionToLength(position) {
  return toLength(position.lineNumber - 1, position.column - 1);
}
function lengthsToRange(lengthStart, lengthEnd) {
  const l = lengthStart;
  const lineCount = Math.floor(l / factor);
  const colCount = l - lineCount * factor;
  const l2 = lengthEnd;
  const lineCount2 = Math.floor(l2 / factor);
  const colCount2 = l2 - lineCount2 * factor;
  return new Range$2(lineCount + 1, colCount + 1, lineCount2 + 1, colCount2 + 1);
}
function lengthOfRange(range2) {
  if (range2.startLineNumber === range2.endLineNumber) {
    return new LengthObj(0, range2.endColumn - range2.startColumn);
  } else {
    return new LengthObj(range2.endLineNumber - range2.startLineNumber, range2.endColumn - 1);
  }
}
function lengthOfString(str2) {
  const lines = splitLines(str2);
  return toLength(lines.length - 1, lines[lines.length - 1].length);
}
class TextEditInfo {
  static fromModelContentChanges(changes) {
    const edits = changes.map((c) => {
      const range2 = Range$2.lift(c.range);
      return new TextEditInfo(positionToLength(range2.getStartPosition()), positionToLength(range2.getEndPosition()), lengthOfString(c.text));
    }).reverse();
    return edits;
  }
  constructor(startOffset, endOffset, newLength) {
    this.startOffset = startOffset;
    this.endOffset = endOffset;
    this.newLength = newLength;
  }
  toString() {
    return `[${lengthToObj(this.startOffset)}...${lengthToObj(this.endOffset)}) -> ${lengthToObj(this.newLength)}`;
  }
}
class BeforeEditPositionMapper {
  /**
   * @param edits Must be sorted by offset in ascending order.
  */
  constructor(edits) {
    this.nextEditIdx = 0;
    this.deltaOldToNewLineCount = 0;
    this.deltaOldToNewColumnCount = 0;
    this.deltaLineIdxInOld = -1;
    this.edits = edits.map((edit) => TextEditInfoCache.from(edit));
  }
  /**
   * @param offset Must be equal to or greater than the last offset this method has been called with.
  */
  getOffsetBeforeChange(offset) {
    this.adjustNextEdit(offset);
    return this.translateCurToOld(offset);
  }
  /**
   * @param offset Must be equal to or greater than the last offset this method has been called with.
   * Returns null if there is no edit anymore.
  */
  getDistanceToNextChange(offset) {
    this.adjustNextEdit(offset);
    const nextEdit = this.edits[this.nextEditIdx];
    const nextChangeOffset = nextEdit ? this.translateOldToCur(nextEdit.offsetObj) : null;
    if (nextChangeOffset === null) {
      return null;
    }
    return lengthDiffNonNegative(offset, nextChangeOffset);
  }
  translateOldToCur(oldOffsetObj) {
    if (oldOffsetObj.lineCount === this.deltaLineIdxInOld) {
      return toLength(oldOffsetObj.lineCount + this.deltaOldToNewLineCount, oldOffsetObj.columnCount + this.deltaOldToNewColumnCount);
    } else {
      return toLength(oldOffsetObj.lineCount + this.deltaOldToNewLineCount, oldOffsetObj.columnCount);
    }
  }
  translateCurToOld(newOffset) {
    const offsetObj = lengthToObj(newOffset);
    if (offsetObj.lineCount - this.deltaOldToNewLineCount === this.deltaLineIdxInOld) {
      return toLength(offsetObj.lineCount - this.deltaOldToNewLineCount, offsetObj.columnCount - this.deltaOldToNewColumnCount);
    } else {
      return toLength(offsetObj.lineCount - this.deltaOldToNewLineCount, offsetObj.columnCount);
    }
  }
  adjustNextEdit(offset) {
    while (this.nextEditIdx < this.edits.length) {
      const nextEdit = this.edits[this.nextEditIdx];
      const nextEditEndOffsetInCur = this.translateOldToCur(nextEdit.endOffsetAfterObj);
      if (lengthLessThanEqual(nextEditEndOffsetInCur, offset)) {
        this.nextEditIdx++;
        const nextEditEndOffsetInCurObj = lengthToObj(nextEditEndOffsetInCur);
        const nextEditEndOffsetBeforeInCurObj = lengthToObj(this.translateOldToCur(nextEdit.endOffsetBeforeObj));
        const lineDelta = nextEditEndOffsetInCurObj.lineCount - nextEditEndOffsetBeforeInCurObj.lineCount;
        this.deltaOldToNewLineCount += lineDelta;
        const previousColumnDelta = this.deltaLineIdxInOld === nextEdit.endOffsetBeforeObj.lineCount ? this.deltaOldToNewColumnCount : 0;
        const columnDelta = nextEditEndOffsetInCurObj.columnCount - nextEditEndOffsetBeforeInCurObj.columnCount;
        this.deltaOldToNewColumnCount = previousColumnDelta + columnDelta;
        this.deltaLineIdxInOld = nextEdit.endOffsetBeforeObj.lineCount;
      } else {
        break;
      }
    }
  }
}
class TextEditInfoCache {
  static from(edit) {
    return new TextEditInfoCache(edit.startOffset, edit.endOffset, edit.newLength);
  }
  constructor(startOffset, endOffset, textLength) {
    this.endOffsetBeforeObj = lengthToObj(endOffset);
    this.endOffsetAfterObj = lengthToObj(lengthAdd(startOffset, textLength));
    this.offsetObj = lengthToObj(startOffset);
  }
}
const emptyArr = [];
class SmallImmutableSet {
  static create(items, additionalItems) {
    if (items <= 128 && additionalItems.length === 0) {
      let cached = SmallImmutableSet.cache[items];
      if (!cached) {
        cached = new SmallImmutableSet(items, additionalItems);
        SmallImmutableSet.cache[items] = cached;
      }
      return cached;
    }
    return new SmallImmutableSet(items, additionalItems);
  }
  static getEmpty() {
    return this.empty;
  }
  constructor(items, additionalItems) {
    this.items = items;
    this.additionalItems = additionalItems;
  }
  add(value, keyProvider) {
    const key = keyProvider.getKey(value);
    let idx = key >> 5;
    if (idx === 0) {
      const newItem = 1 << key | this.items;
      if (newItem === this.items) {
        return this;
      }
      return SmallImmutableSet.create(newItem, this.additionalItems);
    }
    idx--;
    const newItems = this.additionalItems.slice(0);
    while (newItems.length < idx) {
      newItems.push(0);
    }
    newItems[idx] |= 1 << (key & 31);
    return SmallImmutableSet.create(this.items, newItems);
  }
  merge(other) {
    const merged = this.items | other.items;
    if (this.additionalItems === emptyArr && other.additionalItems === emptyArr) {
      if (merged === this.items) {
        return this;
      }
      if (merged === other.items) {
        return other;
      }
      return SmallImmutableSet.create(merged, emptyArr);
    }
    const newItems = [];
    for (let i = 0; i < Math.max(this.additionalItems.length, other.additionalItems.length); i++) {
      const item1 = this.additionalItems[i] || 0;
      const item2 = other.additionalItems[i] || 0;
      newItems.push(item1 | item2);
    }
    return SmallImmutableSet.create(merged, newItems);
  }
  intersects(other) {
    if ((this.items & other.items) !== 0) {
      return true;
    }
    for (let i = 0; i < Math.min(this.additionalItems.length, other.additionalItems.length); i++) {
      if ((this.additionalItems[i] & other.additionalItems[i]) !== 0) {
        return true;
      }
    }
    return false;
  }
}
SmallImmutableSet.cache = new Array(129);
SmallImmutableSet.empty = SmallImmutableSet.create(0, emptyArr);
const identityKeyProvider = {
  getKey(value) {
    return value;
  }
};
class DenseKeyProvider {
  constructor() {
    this.items = /* @__PURE__ */ new Map();
  }
  getKey(value) {
    let existing = this.items.get(value);
    if (existing === void 0) {
      existing = this.items.size;
      this.items.set(value, existing);
    }
    return existing;
  }
}
class BaseAstNode {
  /**
   * The length of the entire node, which should equal the sum of lengths of all children.
  */
  get length() {
    return this._length;
  }
  constructor(length2) {
    this._length = length2;
  }
}
class PairAstNode extends BaseAstNode {
  static create(openingBracket, child, closingBracket) {
    let length2 = openingBracket.length;
    if (child) {
      length2 = lengthAdd(length2, child.length);
    }
    if (closingBracket) {
      length2 = lengthAdd(length2, closingBracket.length);
    }
    return new PairAstNode(length2, openingBracket, child, closingBracket, child ? child.missingOpeningBracketIds : SmallImmutableSet.getEmpty());
  }
  get kind() {
    return 2;
  }
  get listHeight() {
    return 0;
  }
  get childrenLength() {
    return 3;
  }
  getChild(idx) {
    switch (idx) {
      case 0:
        return this.openingBracket;
      case 1:
        return this.child;
      case 2:
        return this.closingBracket;
    }
    throw new Error("Invalid child index");
  }
  /**
   * Avoid using this property, it allocates an array!
  */
  get children() {
    const result2 = [];
    result2.push(this.openingBracket);
    if (this.child) {
      result2.push(this.child);
    }
    if (this.closingBracket) {
      result2.push(this.closingBracket);
    }
    return result2;
  }
  constructor(length2, openingBracket, child, closingBracket, missingOpeningBracketIds) {
    super(length2);
    this.openingBracket = openingBracket;
    this.child = child;
    this.closingBracket = closingBracket;
    this.missingOpeningBracketIds = missingOpeningBracketIds;
  }
  canBeReused(openBracketIds) {
    if (this.closingBracket === null) {
      return false;
    }
    if (openBracketIds.intersects(this.missingOpeningBracketIds)) {
      return false;
    }
    return true;
  }
  deepClone() {
    return new PairAstNode(this.length, this.openingBracket.deepClone(), this.child && this.child.deepClone(), this.closingBracket && this.closingBracket.deepClone(), this.missingOpeningBracketIds);
  }
  computeMinIndentation(offset, textModel) {
    return this.child ? this.child.computeMinIndentation(lengthAdd(offset, this.openingBracket.length), textModel) : Number.MAX_SAFE_INTEGER;
  }
}
class ListAstNode extends BaseAstNode {
  /**
   * This method uses more memory-efficient list nodes that can only store 2 or 3 children.
  */
  static create23(item1, item2, item3, immutable = false) {
    let length2 = item1.length;
    let missingBracketIds = item1.missingOpeningBracketIds;
    if (item1.listHeight !== item2.listHeight) {
      throw new Error("Invalid list heights");
    }
    length2 = lengthAdd(length2, item2.length);
    missingBracketIds = missingBracketIds.merge(item2.missingOpeningBracketIds);
    if (item3) {
      if (item1.listHeight !== item3.listHeight) {
        throw new Error("Invalid list heights");
      }
      length2 = lengthAdd(length2, item3.length);
      missingBracketIds = missingBracketIds.merge(item3.missingOpeningBracketIds);
    }
    return immutable ? new Immutable23ListAstNode(length2, item1.listHeight + 1, item1, item2, item3, missingBracketIds) : new TwoThreeListAstNode(length2, item1.listHeight + 1, item1, item2, item3, missingBracketIds);
  }
  static getEmpty() {
    return new ImmutableArrayListAstNode(lengthZero, 0, [], SmallImmutableSet.getEmpty());
  }
  get kind() {
    return 4;
  }
  get missingOpeningBracketIds() {
    return this._missingOpeningBracketIds;
  }
  /**
   * Use ListAstNode.create.
  */
  constructor(length2, listHeight, _missingOpeningBracketIds) {
    super(length2);
    this.listHeight = listHeight;
    this._missingOpeningBracketIds = _missingOpeningBracketIds;
    this.cachedMinIndentation = -1;
  }
  throwIfImmutable() {
  }
  makeLastElementMutable() {
    this.throwIfImmutable();
    const childCount = this.childrenLength;
    if (childCount === 0) {
      return void 0;
    }
    const lastChild = this.getChild(childCount - 1);
    const mutable = lastChild.kind === 4 ? lastChild.toMutable() : lastChild;
    if (lastChild !== mutable) {
      this.setChild(childCount - 1, mutable);
    }
    return mutable;
  }
  makeFirstElementMutable() {
    this.throwIfImmutable();
    const childCount = this.childrenLength;
    if (childCount === 0) {
      return void 0;
    }
    const firstChild = this.getChild(0);
    const mutable = firstChild.kind === 4 ? firstChild.toMutable() : firstChild;
    if (firstChild !== mutable) {
      this.setChild(0, mutable);
    }
    return mutable;
  }
  canBeReused(openBracketIds) {
    if (openBracketIds.intersects(this.missingOpeningBracketIds)) {
      return false;
    }
    if (this.childrenLength === 0) {
      return false;
    }
    let lastChild = this;
    while (lastChild.kind === 4) {
      const lastLength = lastChild.childrenLength;
      if (lastLength === 0) {
        throw new BugIndicatingError();
      }
      lastChild = lastChild.getChild(lastLength - 1);
    }
    return lastChild.canBeReused(openBracketIds);
  }
  handleChildrenChanged() {
    this.throwIfImmutable();
    const count = this.childrenLength;
    let length2 = this.getChild(0).length;
    let unopenedBrackets = this.getChild(0).missingOpeningBracketIds;
    for (let i = 1; i < count; i++) {
      const child = this.getChild(i);
      length2 = lengthAdd(length2, child.length);
      unopenedBrackets = unopenedBrackets.merge(child.missingOpeningBracketIds);
    }
    this._length = length2;
    this._missingOpeningBracketIds = unopenedBrackets;
    this.cachedMinIndentation = -1;
  }
  computeMinIndentation(offset, textModel) {
    if (this.cachedMinIndentation !== -1) {
      return this.cachedMinIndentation;
    }
    let minIndentation = Number.MAX_SAFE_INTEGER;
    let childOffset = offset;
    for (let i = 0; i < this.childrenLength; i++) {
      const child = this.getChild(i);
      if (child) {
        minIndentation = Math.min(minIndentation, child.computeMinIndentation(childOffset, textModel));
        childOffset = lengthAdd(childOffset, child.length);
      }
    }
    this.cachedMinIndentation = minIndentation;
    return minIndentation;
  }
}
class TwoThreeListAstNode extends ListAstNode {
  get childrenLength() {
    return this._item3 !== null ? 3 : 2;
  }
  getChild(idx) {
    switch (idx) {
      case 0:
        return this._item1;
      case 1:
        return this._item2;
      case 2:
        return this._item3;
    }
    throw new Error("Invalid child index");
  }
  setChild(idx, node2) {
    switch (idx) {
      case 0:
        this._item1 = node2;
        return;
      case 1:
        this._item2 = node2;
        return;
      case 2:
        this._item3 = node2;
        return;
    }
    throw new Error("Invalid child index");
  }
  get children() {
    return this._item3 ? [this._item1, this._item2, this._item3] : [this._item1, this._item2];
  }
  get item1() {
    return this._item1;
  }
  get item2() {
    return this._item2;
  }
  get item3() {
    return this._item3;
  }
  constructor(length2, listHeight, _item1, _item2, _item3, missingOpeningBracketIds) {
    super(length2, listHeight, missingOpeningBracketIds);
    this._item1 = _item1;
    this._item2 = _item2;
    this._item3 = _item3;
  }
  deepClone() {
    return new TwoThreeListAstNode(this.length, this.listHeight, this._item1.deepClone(), this._item2.deepClone(), this._item3 ? this._item3.deepClone() : null, this.missingOpeningBracketIds);
  }
  appendChildOfSameHeight(node2) {
    if (this._item3) {
      throw new Error("Cannot append to a full (2,3) tree node");
    }
    this.throwIfImmutable();
    this._item3 = node2;
    this.handleChildrenChanged();
  }
  unappendChild() {
    if (!this._item3) {
      throw new Error("Cannot remove from a non-full (2,3) tree node");
    }
    this.throwIfImmutable();
    const result2 = this._item3;
    this._item3 = null;
    this.handleChildrenChanged();
    return result2;
  }
  prependChildOfSameHeight(node2) {
    if (this._item3) {
      throw new Error("Cannot prepend to a full (2,3) tree node");
    }
    this.throwIfImmutable();
    this._item3 = this._item2;
    this._item2 = this._item1;
    this._item1 = node2;
    this.handleChildrenChanged();
  }
  unprependChild() {
    if (!this._item3) {
      throw new Error("Cannot remove from a non-full (2,3) tree node");
    }
    this.throwIfImmutable();
    const result2 = this._item1;
    this._item1 = this._item2;
    this._item2 = this._item3;
    this._item3 = null;
    this.handleChildrenChanged();
    return result2;
  }
  toMutable() {
    return this;
  }
}
class Immutable23ListAstNode extends TwoThreeListAstNode {
  toMutable() {
    return new TwoThreeListAstNode(this.length, this.listHeight, this.item1, this.item2, this.item3, this.missingOpeningBracketIds);
  }
  throwIfImmutable() {
    throw new Error("this instance is immutable");
  }
}
class ArrayListAstNode extends ListAstNode {
  get childrenLength() {
    return this._children.length;
  }
  getChild(idx) {
    return this._children[idx];
  }
  setChild(idx, child) {
    this._children[idx] = child;
  }
  get children() {
    return this._children;
  }
  constructor(length2, listHeight, _children, missingOpeningBracketIds) {
    super(length2, listHeight, missingOpeningBracketIds);
    this._children = _children;
  }
  deepClone() {
    const children = new Array(this._children.length);
    for (let i = 0; i < this._children.length; i++) {
      children[i] = this._children[i].deepClone();
    }
    return new ArrayListAstNode(this.length, this.listHeight, children, this.missingOpeningBracketIds);
  }
  appendChildOfSameHeight(node2) {
    this.throwIfImmutable();
    this._children.push(node2);
    this.handleChildrenChanged();
  }
  unappendChild() {
    this.throwIfImmutable();
    const item = this._children.pop();
    this.handleChildrenChanged();
    return item;
  }
  prependChildOfSameHeight(node2) {
    this.throwIfImmutable();
    this._children.unshift(node2);
    this.handleChildrenChanged();
  }
  unprependChild() {
    this.throwIfImmutable();
    const item = this._children.shift();
    this.handleChildrenChanged();
    return item;
  }
  toMutable() {
    return this;
  }
}
class ImmutableArrayListAstNode extends ArrayListAstNode {
  toMutable() {
    return new ArrayListAstNode(this.length, this.listHeight, [...this.children], this.missingOpeningBracketIds);
  }
  throwIfImmutable() {
    throw new Error("this instance is immutable");
  }
}
const emptyArray = [];
class ImmutableLeafAstNode extends BaseAstNode {
  get listHeight() {
    return 0;
  }
  get childrenLength() {
    return 0;
  }
  getChild(idx) {
    return null;
  }
  get children() {
    return emptyArray;
  }
  deepClone() {
    return this;
  }
}
class TextAstNode extends ImmutableLeafAstNode {
  get kind() {
    return 0;
  }
  get missingOpeningBracketIds() {
    return SmallImmutableSet.getEmpty();
  }
  canBeReused(_openedBracketIds) {
    return true;
  }
  computeMinIndentation(offset, textModel) {
    const start = lengthToObj(offset);
    const startLineNumber = (start.columnCount === 0 ? start.lineCount : start.lineCount + 1) + 1;
    const endLineNumber = lengthGetLineCount(lengthAdd(offset, this.length)) + 1;
    let result2 = Number.MAX_SAFE_INTEGER;
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      const firstNonWsColumn = textModel.getLineFirstNonWhitespaceColumn(lineNumber);
      const lineContent = textModel.getLineContent(lineNumber);
      if (firstNonWsColumn === 0) {
        continue;
      }
      const visibleColumn = CursorColumns.visibleColumnFromColumn(lineContent, firstNonWsColumn, textModel.getOptions().tabSize);
      result2 = Math.min(result2, visibleColumn);
    }
    return result2;
  }
}
class BracketAstNode extends ImmutableLeafAstNode {
  static create(length2, bracketInfo, bracketIds) {
    const node2 = new BracketAstNode(length2, bracketInfo, bracketIds);
    return node2;
  }
  get kind() {
    return 1;
  }
  get missingOpeningBracketIds() {
    return SmallImmutableSet.getEmpty();
  }
  constructor(length2, bracketInfo, bracketIds) {
    super(length2);
    this.bracketInfo = bracketInfo;
    this.bracketIds = bracketIds;
  }
  get text() {
    return this.bracketInfo.bracketText;
  }
  get languageId() {
    return this.bracketInfo.languageId;
  }
  canBeReused(_openedBracketIds) {
    return false;
  }
  computeMinIndentation(offset, textModel) {
    return Number.MAX_SAFE_INTEGER;
  }
}
class InvalidBracketAstNode extends ImmutableLeafAstNode {
  get kind() {
    return 3;
  }
  constructor(closingBrackets, length2) {
    super(length2);
    this.missingOpeningBracketIds = closingBrackets;
  }
  canBeReused(openedBracketIds) {
    return !openedBracketIds.intersects(this.missingOpeningBracketIds);
  }
  computeMinIndentation(offset, textModel) {
    return Number.MAX_SAFE_INTEGER;
  }
}
class TokenMetadata {
  static getLanguageId(metadata) {
    return (metadata & 255) >>> 0;
  }
  static getTokenType(metadata) {
    return (metadata & 768) >>> 8;
  }
  static containsBalancedBrackets(metadata) {
    return (metadata & 1024) !== 0;
  }
  static getFontStyle(metadata) {
    return (metadata & 30720) >>> 11;
  }
  static getForeground(metadata) {
    return (metadata & 16744448) >>> 15;
  }
  static getBackground(metadata) {
    return (metadata & 4278190080) >>> 24;
  }
  static getClassNameFromMetadata(metadata) {
    const foreground2 = this.getForeground(metadata);
    let className3 = "mtk" + foreground2;
    const fontStyle = this.getFontStyle(metadata);
    if (fontStyle & 1) {
      className3 += " mtki";
    }
    if (fontStyle & 2) {
      className3 += " mtkb";
    }
    if (fontStyle & 4) {
      className3 += " mtku";
    }
    if (fontStyle & 8) {
      className3 += " mtks";
    }
    return className3;
  }
  static getInlineStyleFromMetadata(metadata, colorMap) {
    const foreground2 = this.getForeground(metadata);
    const fontStyle = this.getFontStyle(metadata);
    let result2 = `color: ${colorMap[foreground2]};`;
    if (fontStyle & 1) {
      result2 += "font-style: italic;";
    }
    if (fontStyle & 2) {
      result2 += "font-weight: bold;";
    }
    let textDecoration = "";
    if (fontStyle & 4) {
      textDecoration += " underline";
    }
    if (fontStyle & 8) {
      textDecoration += " line-through";
    }
    if (textDecoration) {
      result2 += `text-decoration:${textDecoration};`;
    }
    return result2;
  }
  static getPresentationFromMetadata(metadata) {
    const foreground2 = this.getForeground(metadata);
    const fontStyle = this.getFontStyle(metadata);
    return {
      foreground: foreground2,
      italic: Boolean(
        fontStyle & 1
        /* FontStyle.Italic */
      ),
      bold: Boolean(
        fontStyle & 2
        /* FontStyle.Bold */
      ),
      underline: Boolean(
        fontStyle & 4
        /* FontStyle.Underline */
      ),
      strikethrough: Boolean(
        fontStyle & 8
        /* FontStyle.Strikethrough */
      )
    };
  }
}
let Token$2 = class Token2 {
  constructor(length2, kind, bracketId, bracketIds, astNode) {
    this.length = length2;
    this.kind = kind;
    this.bracketId = bracketId;
    this.bracketIds = bracketIds;
    this.astNode = astNode;
  }
};
class TextBufferTokenizer {
  constructor(textModel, bracketTokens) {
    this.textModel = textModel;
    this.bracketTokens = bracketTokens;
    this.reader = new NonPeekableTextBufferTokenizer(this.textModel, this.bracketTokens);
    this._offset = lengthZero;
    this.didPeek = false;
    this.peeked = null;
    this.textBufferLineCount = textModel.getLineCount();
    this.textBufferLastLineLength = textModel.getLineLength(this.textBufferLineCount);
  }
  get offset() {
    return this._offset;
  }
  get length() {
    return toLength(this.textBufferLineCount - 1, this.textBufferLastLineLength);
  }
  skip(length2) {
    this.didPeek = false;
    this._offset = lengthAdd(this._offset, length2);
    const obj = lengthToObj(this._offset);
    this.reader.setPosition(obj.lineCount, obj.columnCount);
  }
  read() {
    let token;
    if (this.peeked) {
      this.didPeek = false;
      token = this.peeked;
    } else {
      token = this.reader.read();
    }
    if (token) {
      this._offset = lengthAdd(this._offset, token.length);
    }
    return token;
  }
  peek() {
    if (!this.didPeek) {
      this.peeked = this.reader.read();
      this.didPeek = true;
    }
    return this.peeked;
  }
}
class NonPeekableTextBufferTokenizer {
  constructor(textModel, bracketTokens) {
    this.textModel = textModel;
    this.bracketTokens = bracketTokens;
    this.lineIdx = 0;
    this.line = null;
    this.lineCharOffset = 0;
    this.lineTokens = null;
    this.lineTokenOffset = 0;
    this.peekedToken = null;
    this.textBufferLineCount = textModel.getLineCount();
    this.textBufferLastLineLength = textModel.getLineLength(this.textBufferLineCount);
  }
  setPosition(lineIdx, column) {
    if (lineIdx === this.lineIdx) {
      this.lineCharOffset = column;
      if (this.line !== null) {
        this.lineTokenOffset = this.lineCharOffset === 0 ? 0 : this.lineTokens.findTokenIndexAtOffset(this.lineCharOffset);
      }
    } else {
      this.lineIdx = lineIdx;
      this.lineCharOffset = column;
      this.line = null;
    }
    this.peekedToken = null;
  }
  read() {
    if (this.peekedToken) {
      const token = this.peekedToken;
      this.peekedToken = null;
      this.lineCharOffset += lengthGetColumnCountIfZeroLineCount(token.length);
      return token;
    }
    if (this.lineIdx > this.textBufferLineCount - 1 || this.lineIdx === this.textBufferLineCount - 1 && this.lineCharOffset >= this.textBufferLastLineLength) {
      return null;
    }
    if (this.line === null) {
      this.lineTokens = this.textModel.tokenization.getLineTokens(this.lineIdx + 1);
      this.line = this.lineTokens.getLineContent();
      this.lineTokenOffset = this.lineCharOffset === 0 ? 0 : this.lineTokens.findTokenIndexAtOffset(this.lineCharOffset);
    }
    const startLineIdx = this.lineIdx;
    const startLineCharOffset = this.lineCharOffset;
    let lengthHeuristic = 0;
    while (true) {
      const lineTokens = this.lineTokens;
      const tokenCount = lineTokens.getCount();
      let peekedBracketToken = null;
      if (this.lineTokenOffset < tokenCount) {
        const tokenMetadata = lineTokens.getMetadata(this.lineTokenOffset);
        while (this.lineTokenOffset + 1 < tokenCount && tokenMetadata === lineTokens.getMetadata(this.lineTokenOffset + 1)) {
          this.lineTokenOffset++;
        }
        const isOther = TokenMetadata.getTokenType(tokenMetadata) === 0;
        const containsBracketType = TokenMetadata.containsBalancedBrackets(tokenMetadata);
        const endOffset = lineTokens.getEndOffset(this.lineTokenOffset);
        if (containsBracketType && isOther && this.lineCharOffset < endOffset) {
          const languageId = lineTokens.getLanguageId(this.lineTokenOffset);
          const text2 = this.line.substring(this.lineCharOffset, endOffset);
          const brackets = this.bracketTokens.getSingleLanguageBracketTokens(languageId);
          const regexp = brackets.regExpGlobal;
          if (regexp) {
            regexp.lastIndex = 0;
            const match2 = regexp.exec(text2);
            if (match2) {
              peekedBracketToken = brackets.getToken(match2[0]);
              if (peekedBracketToken) {
                this.lineCharOffset += match2.index;
              }
            }
          }
        }
        lengthHeuristic += endOffset - this.lineCharOffset;
        if (peekedBracketToken) {
          if (startLineIdx !== this.lineIdx || startLineCharOffset !== this.lineCharOffset) {
            this.peekedToken = peekedBracketToken;
            break;
          } else {
            this.lineCharOffset += lengthGetColumnCountIfZeroLineCount(peekedBracketToken.length);
            return peekedBracketToken;
          }
        } else {
          this.lineTokenOffset++;
          this.lineCharOffset = endOffset;
        }
      } else {
        if (this.lineIdx === this.textBufferLineCount - 1) {
          break;
        }
        this.lineIdx++;
        this.lineTokens = this.textModel.tokenization.getLineTokens(this.lineIdx + 1);
        this.lineTokenOffset = 0;
        this.line = this.lineTokens.getLineContent();
        this.lineCharOffset = 0;
        lengthHeuristic += 33;
        if (lengthHeuristic > 1e3) {
          break;
        }
      }
      if (lengthHeuristic > 1500) {
        break;
      }
    }
    const length2 = lengthDiff(startLineIdx, startLineCharOffset, this.lineIdx, this.lineCharOffset);
    return new Token$2(length2, 0, -1, SmallImmutableSet.getEmpty(), new TextAstNode(length2));
  }
}
class FastTokenizer {
  constructor(text2, brackets) {
    this.text = text2;
    this._offset = lengthZero;
    this.idx = 0;
    const regExpStr = brackets.getRegExpStr();
    const regexp = regExpStr ? new RegExp(regExpStr + "|\n", "gi") : null;
    const tokens = [];
    let match2;
    let curLineCount = 0;
    let lastLineBreakOffset = 0;
    let lastTokenEndOffset = 0;
    let lastTokenEndLine = 0;
    const smallTextTokens0Line = [];
    for (let i = 0; i < 60; i++) {
      smallTextTokens0Line.push(new Token$2(toLength(0, i), 0, -1, SmallImmutableSet.getEmpty(), new TextAstNode(toLength(0, i))));
    }
    const smallTextTokens1Line = [];
    for (let i = 0; i < 60; i++) {
      smallTextTokens1Line.push(new Token$2(toLength(1, i), 0, -1, SmallImmutableSet.getEmpty(), new TextAstNode(toLength(1, i))));
    }
    if (regexp) {
      regexp.lastIndex = 0;
      while ((match2 = regexp.exec(text2)) !== null) {
        const curOffset = match2.index;
        const value = match2[0];
        if (value === "\n") {
          curLineCount++;
          lastLineBreakOffset = curOffset + 1;
        } else {
          if (lastTokenEndOffset !== curOffset) {
            let token;
            if (lastTokenEndLine === curLineCount) {
              const colCount = curOffset - lastTokenEndOffset;
              if (colCount < smallTextTokens0Line.length) {
                token = smallTextTokens0Line[colCount];
              } else {
                const length2 = toLength(0, colCount);
                token = new Token$2(length2, 0, -1, SmallImmutableSet.getEmpty(), new TextAstNode(length2));
              }
            } else {
              const lineCount = curLineCount - lastTokenEndLine;
              const colCount = curOffset - lastLineBreakOffset;
              if (lineCount === 1 && colCount < smallTextTokens1Line.length) {
                token = smallTextTokens1Line[colCount];
              } else {
                const length2 = toLength(lineCount, colCount);
                token = new Token$2(length2, 0, -1, SmallImmutableSet.getEmpty(), new TextAstNode(length2));
              }
            }
            tokens.push(token);
          }
          tokens.push(brackets.getToken(value));
          lastTokenEndOffset = curOffset + value.length;
          lastTokenEndLine = curLineCount;
        }
      }
    }
    const offset = text2.length;
    if (lastTokenEndOffset !== offset) {
      const length2 = lastTokenEndLine === curLineCount ? toLength(0, offset - lastTokenEndOffset) : toLength(curLineCount - lastTokenEndLine, offset - lastLineBreakOffset);
      tokens.push(new Token$2(length2, 0, -1, SmallImmutableSet.getEmpty(), new TextAstNode(length2)));
    }
    this.length = toLength(curLineCount, offset - lastLineBreakOffset);
    this.tokens = tokens;
  }
  get offset() {
    return this._offset;
  }
  read() {
    return this.tokens[this.idx++] || null;
  }
  peek() {
    return this.tokens[this.idx] || null;
  }
  skip(length2) {
    throw new NotSupportedError();
  }
}
class BracketTokens {
  static createFromLanguage(configuration, denseKeyProvider) {
    function getId2(bracketInfo) {
      return denseKeyProvider.getKey(`${bracketInfo.languageId}:::${bracketInfo.bracketText}`);
    }
    const map2 = /* @__PURE__ */ new Map();
    for (const openingBracket of configuration.bracketsNew.openingBrackets) {
      const length2 = toLength(0, openingBracket.bracketText.length);
      const openingTextId = getId2(openingBracket);
      const bracketIds = SmallImmutableSet.getEmpty().add(openingTextId, identityKeyProvider);
      map2.set(openingBracket.bracketText, new Token$2(length2, 1, openingTextId, bracketIds, BracketAstNode.create(length2, openingBracket, bracketIds)));
    }
    for (const closingBracket of configuration.bracketsNew.closingBrackets) {
      const length2 = toLength(0, closingBracket.bracketText.length);
      let bracketIds = SmallImmutableSet.getEmpty();
      const closingBrackets = closingBracket.getOpeningBrackets();
      for (const bracket of closingBrackets) {
        bracketIds = bracketIds.add(getId2(bracket), identityKeyProvider);
      }
      map2.set(closingBracket.bracketText, new Token$2(length2, 2, getId2(closingBrackets[0]), bracketIds, BracketAstNode.create(length2, closingBracket, bracketIds)));
    }
    return new BracketTokens(map2);
  }
  constructor(map2) {
    this.map = map2;
    this.hasRegExp = false;
    this._regExpGlobal = null;
  }
  getRegExpStr() {
    if (this.isEmpty) {
      return null;
    } else {
      const keys = [...this.map.keys()];
      keys.sort();
      keys.reverse();
      return keys.map((k) => prepareBracketForRegExp(k)).join("|");
    }
  }
  /**
   * Returns null if there is no such regexp (because there are no brackets).
  */
  get regExpGlobal() {
    if (!this.hasRegExp) {
      const regExpStr = this.getRegExpStr();
      this._regExpGlobal = regExpStr ? new RegExp(regExpStr, "gi") : null;
      this.hasRegExp = true;
    }
    return this._regExpGlobal;
  }
  getToken(value) {
    return this.map.get(value.toLowerCase());
  }
  findClosingTokenText(openingBracketIds) {
    for (const [closingText, info] of this.map) {
      if (info.kind === 2 && info.bracketIds.intersects(openingBracketIds)) {
        return closingText;
      }
    }
    return void 0;
  }
  get isEmpty() {
    return this.map.size === 0;
  }
}
function prepareBracketForRegExp(str2) {
  let escaped = escapeRegExpCharacters(str2);
  if (/^[\w ]+/.test(str2)) {
    escaped = `\\b${escaped}`;
  }
  if (/[\w ]+$/.test(str2)) {
    escaped = `${escaped}\\b`;
  }
  return escaped;
}
class LanguageAgnosticBracketTokens {
  constructor(denseKeyProvider, getLanguageConfiguration) {
    this.denseKeyProvider = denseKeyProvider;
    this.getLanguageConfiguration = getLanguageConfiguration;
    this.languageIdToBracketTokens = /* @__PURE__ */ new Map();
  }
  didLanguageChange(languageId) {
    return this.languageIdToBracketTokens.has(languageId);
  }
  getSingleLanguageBracketTokens(languageId) {
    let singleLanguageBracketTokens = this.languageIdToBracketTokens.get(languageId);
    if (!singleLanguageBracketTokens) {
      singleLanguageBracketTokens = BracketTokens.createFromLanguage(this.getLanguageConfiguration(languageId), this.denseKeyProvider);
      this.languageIdToBracketTokens.set(languageId, singleLanguageBracketTokens);
    }
    return singleLanguageBracketTokens;
  }
}
function concat23Trees(items) {
  if (items.length === 0) {
    return null;
  }
  if (items.length === 1) {
    return items[0];
  }
  let i = 0;
  function readNode() {
    if (i >= items.length) {
      return null;
    }
    const start = i;
    const height = items[start].listHeight;
    i++;
    while (i < items.length && items[i].listHeight === height) {
      i++;
    }
    if (i - start >= 2) {
      return concat23TreesOfSameHeight(start === 0 && i === items.length ? items : items.slice(start, i), false);
    } else {
      return items[start];
    }
  }
  let first2 = readNode();
  let second = readNode();
  if (!second) {
    return first2;
  }
  for (let item = readNode(); item; item = readNode()) {
    if (heightDiff(first2, second) <= heightDiff(second, item)) {
      first2 = concat$1(first2, second);
      second = item;
    } else {
      second = concat$1(second, item);
    }
  }
  const result2 = concat$1(first2, second);
  return result2;
}
function concat23TreesOfSameHeight(items, createImmutableLists = false) {
  if (items.length === 0) {
    return null;
  }
  if (items.length === 1) {
    return items[0];
  }
  let length2 = items.length;
  while (length2 > 3) {
    const newLength = length2 >> 1;
    for (let i = 0; i < newLength; i++) {
      const j = i << 1;
      items[i] = ListAstNode.create23(items[j], items[j + 1], j + 3 === length2 ? items[j + 2] : null, createImmutableLists);
    }
    length2 = newLength;
  }
  return ListAstNode.create23(items[0], items[1], length2 >= 3 ? items[2] : null, createImmutableLists);
}
function heightDiff(node1, node2) {
  return Math.abs(node1.listHeight - node2.listHeight);
}
function concat$1(node1, node2) {
  if (node1.listHeight === node2.listHeight) {
    return ListAstNode.create23(node1, node2, null, false);
  } else if (node1.listHeight > node2.listHeight) {
    return append(node1, node2);
  } else {
    return prepend(node2, node1);
  }
}
function append(list2, nodeToAppend) {
  list2 = list2.toMutable();
  let curNode = list2;
  const parents = [];
  let nodeToAppendOfCorrectHeight;
  while (true) {
    if (nodeToAppend.listHeight === curNode.listHeight) {
      nodeToAppendOfCorrectHeight = nodeToAppend;
      break;
    }
    if (curNode.kind !== 4) {
      throw new Error("unexpected");
    }
    parents.push(curNode);
    curNode = curNode.makeLastElementMutable();
  }
  for (let i = parents.length - 1; i >= 0; i--) {
    const parent = parents[i];
    if (nodeToAppendOfCorrectHeight) {
      if (parent.childrenLength >= 3) {
        nodeToAppendOfCorrectHeight = ListAstNode.create23(parent.unappendChild(), nodeToAppendOfCorrectHeight, null, false);
      } else {
        parent.appendChildOfSameHeight(nodeToAppendOfCorrectHeight);
        nodeToAppendOfCorrectHeight = void 0;
      }
    } else {
      parent.handleChildrenChanged();
    }
  }
  if (nodeToAppendOfCorrectHeight) {
    return ListAstNode.create23(list2, nodeToAppendOfCorrectHeight, null, false);
  } else {
    return list2;
  }
}
function prepend(list2, nodeToAppend) {
  list2 = list2.toMutable();
  let curNode = list2;
  const parents = [];
  while (nodeToAppend.listHeight !== curNode.listHeight) {
    if (curNode.kind !== 4) {
      throw new Error("unexpected");
    }
    parents.push(curNode);
    curNode = curNode.makeFirstElementMutable();
  }
  let nodeToPrependOfCorrectHeight = nodeToAppend;
  for (let i = parents.length - 1; i >= 0; i--) {
    const parent = parents[i];
    if (nodeToPrependOfCorrectHeight) {
      if (parent.childrenLength >= 3) {
        nodeToPrependOfCorrectHeight = ListAstNode.create23(nodeToPrependOfCorrectHeight, parent.unprependChild(), null, false);
      } else {
        parent.prependChildOfSameHeight(nodeToPrependOfCorrectHeight);
        nodeToPrependOfCorrectHeight = void 0;
      }
    } else {
      parent.handleChildrenChanged();
    }
  }
  if (nodeToPrependOfCorrectHeight) {
    return ListAstNode.create23(nodeToPrependOfCorrectHeight, list2, null, false);
  } else {
    return list2;
  }
}
class NodeReader {
  constructor(node2) {
    this.lastOffset = lengthZero;
    this.nextNodes = [node2];
    this.offsets = [lengthZero];
    this.idxs = [];
  }
  /**
   * Returns the longest node at `offset` that satisfies the predicate.
   * @param offset must be greater than or equal to the last offset this method has been called with!
  */
  readLongestNodeAt(offset, predicate) {
    if (lengthLessThan(offset, this.lastOffset)) {
      throw new Error("Invalid offset");
    }
    this.lastOffset = offset;
    while (true) {
      const curNode = lastOrUndefined(this.nextNodes);
      if (!curNode) {
        return void 0;
      }
      const curNodeOffset = lastOrUndefined(this.offsets);
      if (lengthLessThan(offset, curNodeOffset)) {
        return void 0;
      }
      if (lengthLessThan(curNodeOffset, offset)) {
        if (lengthAdd(curNodeOffset, curNode.length) <= offset) {
          this.nextNodeAfterCurrent();
        } else {
          const nextChildIdx = getNextChildIdx(curNode);
          if (nextChildIdx !== -1) {
            this.nextNodes.push(curNode.getChild(nextChildIdx));
            this.offsets.push(curNodeOffset);
            this.idxs.push(nextChildIdx);
          } else {
            this.nextNodeAfterCurrent();
          }
        }
      } else {
        if (predicate(curNode)) {
          this.nextNodeAfterCurrent();
          return curNode;
        } else {
          const nextChildIdx = getNextChildIdx(curNode);
          if (nextChildIdx === -1) {
            this.nextNodeAfterCurrent();
            return void 0;
          } else {
            this.nextNodes.push(curNode.getChild(nextChildIdx));
            this.offsets.push(curNodeOffset);
            this.idxs.push(nextChildIdx);
          }
        }
      }
    }
  }
  // Navigates to the longest node that continues after the current node.
  nextNodeAfterCurrent() {
    while (true) {
      const currentOffset = lastOrUndefined(this.offsets);
      const currentNode = lastOrUndefined(this.nextNodes);
      this.nextNodes.pop();
      this.offsets.pop();
      if (this.idxs.length === 0) {
        break;
      }
      const parent = lastOrUndefined(this.nextNodes);
      const nextChildIdx = getNextChildIdx(parent, this.idxs[this.idxs.length - 1]);
      if (nextChildIdx !== -1) {
        this.nextNodes.push(parent.getChild(nextChildIdx));
        this.offsets.push(lengthAdd(currentOffset, currentNode.length));
        this.idxs[this.idxs.length - 1] = nextChildIdx;
        break;
      } else {
        this.idxs.pop();
      }
    }
  }
}
function getNextChildIdx(node2, curIdx = -1) {
  while (true) {
    curIdx++;
    if (curIdx >= node2.childrenLength) {
      return -1;
    }
    if (node2.getChild(curIdx)) {
      return curIdx;
    }
  }
}
function lastOrUndefined(arr) {
  return arr.length > 0 ? arr[arr.length - 1] : void 0;
}
function parseDocument(tokenizer3, edits, oldNode, createImmutableLists) {
  const parser2 = new Parser$3(tokenizer3, edits, oldNode, createImmutableLists);
  return parser2.parseDocument();
}
let Parser$3 = class Parser2 {
  constructor(tokenizer3, edits, oldNode, createImmutableLists) {
    this.tokenizer = tokenizer3;
    this.createImmutableLists = createImmutableLists;
    this._itemsConstructed = 0;
    this._itemsFromCache = 0;
    if (oldNode && createImmutableLists) {
      throw new Error("Not supported");
    }
    this.oldNodeReader = oldNode ? new NodeReader(oldNode) : void 0;
    this.positionMapper = new BeforeEditPositionMapper(edits);
  }
  parseDocument() {
    this._itemsConstructed = 0;
    this._itemsFromCache = 0;
    let result2 = this.parseList(SmallImmutableSet.getEmpty(), 0);
    if (!result2) {
      result2 = ListAstNode.getEmpty();
    }
    return result2;
  }
  parseList(openedBracketIds, level) {
    const items = [];
    while (true) {
      let child = this.tryReadChildFromCache(openedBracketIds);
      if (!child) {
        const token = this.tokenizer.peek();
        if (!token || token.kind === 2 && token.bracketIds.intersects(openedBracketIds)) {
          break;
        }
        child = this.parseChild(openedBracketIds, level + 1);
      }
      if (child.kind === 4 && child.childrenLength === 0) {
        continue;
      }
      items.push(child);
    }
    const result2 = this.oldNodeReader ? concat23Trees(items) : concat23TreesOfSameHeight(items, this.createImmutableLists);
    return result2;
  }
  tryReadChildFromCache(openedBracketIds) {
    if (this.oldNodeReader) {
      const maxCacheableLength = this.positionMapper.getDistanceToNextChange(this.tokenizer.offset);
      if (maxCacheableLength === null || !lengthIsZero(maxCacheableLength)) {
        const cachedNode = this.oldNodeReader.readLongestNodeAt(this.positionMapper.getOffsetBeforeChange(this.tokenizer.offset), (curNode) => {
          if (maxCacheableLength !== null && !lengthLessThan(curNode.length, maxCacheableLength)) {
            return false;
          }
          const canBeReused = curNode.canBeReused(openedBracketIds);
          return canBeReused;
        });
        if (cachedNode) {
          this._itemsFromCache++;
          this.tokenizer.skip(cachedNode.length);
          return cachedNode;
        }
      }
    }
    return void 0;
  }
  parseChild(openedBracketIds, level) {
    this._itemsConstructed++;
    const token = this.tokenizer.read();
    switch (token.kind) {
      case 2:
        return new InvalidBracketAstNode(token.bracketIds, token.length);
      case 0:
        return token.astNode;
      case 1: {
        if (level > 300) {
          return new TextAstNode(token.length);
        }
        const set2 = openedBracketIds.merge(token.bracketIds);
        const child = this.parseList(set2, level + 1);
        const nextToken = this.tokenizer.peek();
        if (nextToken && nextToken.kind === 2 && (nextToken.bracketId === token.bracketId || nextToken.bracketIds.intersects(token.bracketIds))) {
          this.tokenizer.read();
          return PairAstNode.create(token.astNode, child, nextToken.astNode);
        } else {
          return PairAstNode.create(token.astNode, child, null);
        }
      }
      default:
        throw new Error("unexpected");
    }
  }
};
function combineTextEditInfos(textEditInfoFirst, textEditInfoSecond) {
  if (textEditInfoFirst.length === 0) {
    return textEditInfoSecond;
  }
  if (textEditInfoSecond.length === 0) {
    return textEditInfoFirst;
  }
  const s0ToS1Map = new ArrayQueue(toLengthMapping(textEditInfoFirst));
  const s1ToS2Map = toLengthMapping(textEditInfoSecond);
  s1ToS2Map.push({ modified: false, lengthBefore: void 0, lengthAfter: void 0 });
  let curItem = s0ToS1Map.dequeue();
  function nextS0ToS1MapWithS1LengthOf(s1Length) {
    if (s1Length === void 0) {
      const arr = s0ToS1Map.takeWhile((v) => true) || [];
      if (curItem) {
        arr.unshift(curItem);
      }
      return arr;
    }
    const result3 = [];
    while (curItem && !lengthIsZero(s1Length)) {
      const [item, remainingItem] = curItem.splitAt(s1Length);
      result3.push(item);
      s1Length = lengthDiffNonNegative(item.lengthAfter, s1Length);
      curItem = remainingItem !== null && remainingItem !== void 0 ? remainingItem : s0ToS1Map.dequeue();
    }
    if (!lengthIsZero(s1Length)) {
      result3.push(new LengthMapping(false, s1Length, s1Length));
    }
    return result3;
  }
  const result2 = [];
  function pushEdit(startOffset, endOffset, newLength) {
    if (result2.length > 0 && lengthEquals(result2[result2.length - 1].endOffset, startOffset)) {
      const lastResult = result2[result2.length - 1];
      result2[result2.length - 1] = new TextEditInfo(lastResult.startOffset, endOffset, lengthAdd(lastResult.newLength, newLength));
    } else {
      result2.push({ startOffset, endOffset, newLength });
    }
  }
  let s0offset = lengthZero;
  for (const s1ToS2 of s1ToS2Map) {
    const s0ToS1Map2 = nextS0ToS1MapWithS1LengthOf(s1ToS2.lengthBefore);
    if (s1ToS2.modified) {
      const s0Length = sumLengths(s0ToS1Map2, (s) => s.lengthBefore);
      const s0EndOffset = lengthAdd(s0offset, s0Length);
      pushEdit(s0offset, s0EndOffset, s1ToS2.lengthAfter);
      s0offset = s0EndOffset;
    } else {
      for (const s1 of s0ToS1Map2) {
        const s0startOffset = s0offset;
        s0offset = lengthAdd(s0offset, s1.lengthBefore);
        if (s1.modified) {
          pushEdit(s0startOffset, s0offset, s1.lengthAfter);
        }
      }
    }
  }
  return result2;
}
class LengthMapping {
  constructor(modified, lengthBefore, lengthAfter) {
    this.modified = modified;
    this.lengthBefore = lengthBefore;
    this.lengthAfter = lengthAfter;
  }
  splitAt(lengthAfter) {
    const remainingLengthAfter = lengthDiffNonNegative(lengthAfter, this.lengthAfter);
    if (lengthEquals(remainingLengthAfter, lengthZero)) {
      return [this, void 0];
    } else if (this.modified) {
      return [
        new LengthMapping(this.modified, this.lengthBefore, lengthAfter),
        new LengthMapping(this.modified, lengthZero, remainingLengthAfter)
      ];
    } else {
      return [
        new LengthMapping(this.modified, lengthAfter, lengthAfter),
        new LengthMapping(this.modified, remainingLengthAfter, remainingLengthAfter)
      ];
    }
  }
  toString() {
    return `${this.modified ? "M" : "U"}:${lengthToObj(this.lengthBefore)} -> ${lengthToObj(this.lengthAfter)}`;
  }
}
function toLengthMapping(textEditInfos) {
  const result2 = [];
  let lastOffset = lengthZero;
  for (const textEditInfo of textEditInfos) {
    const spaceLength = lengthDiffNonNegative(lastOffset, textEditInfo.startOffset);
    if (!lengthIsZero(spaceLength)) {
      result2.push(new LengthMapping(false, spaceLength, spaceLength));
    }
    const lengthBefore = lengthDiffNonNegative(textEditInfo.startOffset, textEditInfo.endOffset);
    result2.push(new LengthMapping(true, lengthBefore, textEditInfo.newLength));
    lastOffset = textEditInfo.endOffset;
  }
  return result2;
}
class BracketPairsTree extends Disposable {
  didLanguageChange(languageId) {
    return this.brackets.didLanguageChange(languageId);
  }
  constructor(textModel, getLanguageConfiguration) {
    super();
    this.textModel = textModel;
    this.getLanguageConfiguration = getLanguageConfiguration;
    this.didChangeEmitter = new Emitter$1();
    this.denseKeyProvider = new DenseKeyProvider();
    this.brackets = new LanguageAgnosticBracketTokens(this.denseKeyProvider, this.getLanguageConfiguration);
    this.onDidChange = this.didChangeEmitter.event;
    this.queuedTextEditsForInitialAstWithoutTokens = [];
    this.queuedTextEdits = [];
    if (!textModel.tokenization.hasTokens) {
      const brackets = this.brackets.getSingleLanguageBracketTokens(this.textModel.getLanguageId());
      const tokenizer3 = new FastTokenizer(this.textModel.getValue(), brackets);
      this.initialAstWithoutTokens = parseDocument(tokenizer3, [], void 0, true);
      this.astWithTokens = this.initialAstWithoutTokens;
    } else if (textModel.tokenization.backgroundTokenizationState === 2) {
      this.initialAstWithoutTokens = void 0;
      this.astWithTokens = this.parseDocumentFromTextBuffer([], void 0, false);
    } else {
      this.initialAstWithoutTokens = this.parseDocumentFromTextBuffer([], void 0, true);
      this.astWithTokens = this.initialAstWithoutTokens;
    }
  }
  //#region TextModel events
  handleDidChangeBackgroundTokenizationState() {
    if (this.textModel.tokenization.backgroundTokenizationState === 2) {
      const wasUndefined = this.initialAstWithoutTokens === void 0;
      this.initialAstWithoutTokens = void 0;
      if (!wasUndefined) {
        this.didChangeEmitter.fire();
      }
    }
  }
  handleDidChangeTokens({ ranges }) {
    const edits = ranges.map((r) => new TextEditInfo(toLength(r.fromLineNumber - 1, 0), toLength(r.toLineNumber, 0), toLength(r.toLineNumber - r.fromLineNumber + 1, 0)));
    this.handleEdits(edits, true);
    if (!this.initialAstWithoutTokens) {
      this.didChangeEmitter.fire();
    }
  }
  handleContentChanged(change) {
    const edits = TextEditInfo.fromModelContentChanges(change.changes);
    this.handleEdits(edits, false);
  }
  handleEdits(edits, tokenChange) {
    const result2 = combineTextEditInfos(this.queuedTextEdits, edits);
    this.queuedTextEdits = result2;
    if (this.initialAstWithoutTokens && !tokenChange) {
      this.queuedTextEditsForInitialAstWithoutTokens = combineTextEditInfos(this.queuedTextEditsForInitialAstWithoutTokens, edits);
    }
  }
  //#endregion
  flushQueue() {
    if (this.queuedTextEdits.length > 0) {
      this.astWithTokens = this.parseDocumentFromTextBuffer(this.queuedTextEdits, this.astWithTokens, false);
      this.queuedTextEdits = [];
    }
    if (this.queuedTextEditsForInitialAstWithoutTokens.length > 0) {
      if (this.initialAstWithoutTokens) {
        this.initialAstWithoutTokens = this.parseDocumentFromTextBuffer(this.queuedTextEditsForInitialAstWithoutTokens, this.initialAstWithoutTokens, false);
      }
      this.queuedTextEditsForInitialAstWithoutTokens = [];
    }
  }
  /**
   * @pure (only if isPure = true)
  */
  parseDocumentFromTextBuffer(edits, previousAst, immutable) {
    const previousAstClone = previousAst;
    const tokenizer3 = new TextBufferTokenizer(this.textModel, this.brackets);
    const result2 = parseDocument(tokenizer3, edits, previousAstClone, immutable);
    return result2;
  }
  getBracketsInRange(range2, onlyColorizedBrackets) {
    this.flushQueue();
    const startOffset = toLength(range2.startLineNumber - 1, range2.startColumn - 1);
    const endOffset = toLength(range2.endLineNumber - 1, range2.endColumn - 1);
    return new CallbackIterable((cb) => {
      const node2 = this.initialAstWithoutTokens || this.astWithTokens;
      collectBrackets(node2, lengthZero, node2.length, startOffset, endOffset, cb, 0, 0, /* @__PURE__ */ new Map(), onlyColorizedBrackets);
    });
  }
  getBracketPairsInRange(range2, includeMinIndentation) {
    this.flushQueue();
    const startLength = positionToLength(range2.getStartPosition());
    const endLength = positionToLength(range2.getEndPosition());
    return new CallbackIterable((cb) => {
      const node2 = this.initialAstWithoutTokens || this.astWithTokens;
      const context = new CollectBracketPairsContext(cb, includeMinIndentation, this.textModel);
      collectBracketPairs(node2, lengthZero, node2.length, startLength, endLength, context, 0, /* @__PURE__ */ new Map());
    });
  }
  getFirstBracketAfter(position) {
    this.flushQueue();
    const node2 = this.initialAstWithoutTokens || this.astWithTokens;
    return getFirstBracketAfter(node2, lengthZero, node2.length, positionToLength(position));
  }
  getFirstBracketBefore(position) {
    this.flushQueue();
    const node2 = this.initialAstWithoutTokens || this.astWithTokens;
    return getFirstBracketBefore(node2, lengthZero, node2.length, positionToLength(position));
  }
}
function getFirstBracketBefore(node2, nodeOffsetStart, nodeOffsetEnd, position) {
  if (node2.kind === 4 || node2.kind === 2) {
    const lengths = [];
    for (const child of node2.children) {
      nodeOffsetEnd = lengthAdd(nodeOffsetStart, child.length);
      lengths.push({ nodeOffsetStart, nodeOffsetEnd });
      nodeOffsetStart = nodeOffsetEnd;
    }
    for (let i = lengths.length - 1; i >= 0; i--) {
      const { nodeOffsetStart: nodeOffsetStart2, nodeOffsetEnd: nodeOffsetEnd2 } = lengths[i];
      if (lengthLessThan(nodeOffsetStart2, position)) {
        const result2 = getFirstBracketBefore(node2.children[i], nodeOffsetStart2, nodeOffsetEnd2, position);
        if (result2) {
          return result2;
        }
      }
    }
    return null;
  } else if (node2.kind === 3) {
    return null;
  } else if (node2.kind === 1) {
    const range2 = lengthsToRange(nodeOffsetStart, nodeOffsetEnd);
    return {
      bracketInfo: node2.bracketInfo,
      range: range2
    };
  }
  return null;
}
function getFirstBracketAfter(node2, nodeOffsetStart, nodeOffsetEnd, position) {
  if (node2.kind === 4 || node2.kind === 2) {
    for (const child of node2.children) {
      nodeOffsetEnd = lengthAdd(nodeOffsetStart, child.length);
      if (lengthLessThan(position, nodeOffsetEnd)) {
        const result2 = getFirstBracketAfter(child, nodeOffsetStart, nodeOffsetEnd, position);
        if (result2) {
          return result2;
        }
      }
      nodeOffsetStart = nodeOffsetEnd;
    }
    return null;
  } else if (node2.kind === 3) {
    return null;
  } else if (node2.kind === 1) {
    const range2 = lengthsToRange(nodeOffsetStart, nodeOffsetEnd);
    return {
      bracketInfo: node2.bracketInfo,
      range: range2
    };
  }
  return null;
}
function collectBrackets(node2, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, push2, level, nestingLevelOfEqualBracketType, levelPerBracketType, onlyColorizedBrackets, parentPairIsIncomplete = false) {
  if (level > 200) {
    return true;
  }
  whileLoop:
    while (true) {
      switch (node2.kind) {
        case 4: {
          const childCount = node2.childrenLength;
          for (let i = 0; i < childCount; i++) {
            const child = node2.getChild(i);
            if (!child) {
              continue;
            }
            nodeOffsetEnd = lengthAdd(nodeOffsetStart, child.length);
            if (lengthLessThanEqual(nodeOffsetStart, endOffset) && lengthGreaterThanEqual(nodeOffsetEnd, startOffset)) {
              const childEndsAfterEnd = lengthGreaterThanEqual(nodeOffsetEnd, endOffset);
              if (childEndsAfterEnd) {
                node2 = child;
                continue whileLoop;
              }
              const shouldContinue = collectBrackets(child, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, push2, level, 0, levelPerBracketType, onlyColorizedBrackets);
              if (!shouldContinue) {
                return false;
              }
            }
            nodeOffsetStart = nodeOffsetEnd;
          }
          return true;
        }
        case 2: {
          const colorize2 = !onlyColorizedBrackets || !node2.closingBracket || node2.closingBracket.bracketInfo.closesColorized(node2.openingBracket.bracketInfo);
          let levelPerBracket = 0;
          if (levelPerBracketType) {
            let existing = levelPerBracketType.get(node2.openingBracket.text);
            if (existing === void 0) {
              existing = 0;
            }
            levelPerBracket = existing;
            if (colorize2) {
              existing++;
              levelPerBracketType.set(node2.openingBracket.text, existing);
            }
          }
          const childCount = node2.childrenLength;
          for (let i = 0; i < childCount; i++) {
            const child = node2.getChild(i);
            if (!child) {
              continue;
            }
            nodeOffsetEnd = lengthAdd(nodeOffsetStart, child.length);
            if (lengthLessThanEqual(nodeOffsetStart, endOffset) && lengthGreaterThanEqual(nodeOffsetEnd, startOffset)) {
              const childEndsAfterEnd = lengthGreaterThanEqual(nodeOffsetEnd, endOffset);
              if (childEndsAfterEnd && child.kind !== 1) {
                node2 = child;
                if (colorize2) {
                  level++;
                  nestingLevelOfEqualBracketType = levelPerBracket + 1;
                } else {
                  nestingLevelOfEqualBracketType = levelPerBracket;
                }
                continue whileLoop;
              }
              if (colorize2 || child.kind !== 1 || !node2.closingBracket) {
                const shouldContinue = collectBrackets(child, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, push2, colorize2 ? level + 1 : level, colorize2 ? levelPerBracket + 1 : levelPerBracket, levelPerBracketType, onlyColorizedBrackets, !node2.closingBracket);
                if (!shouldContinue) {
                  return false;
                }
              }
            }
            nodeOffsetStart = nodeOffsetEnd;
          }
          levelPerBracketType === null || levelPerBracketType === void 0 ? void 0 : levelPerBracketType.set(node2.openingBracket.text, levelPerBracket);
          return true;
        }
        case 3: {
          const range2 = lengthsToRange(nodeOffsetStart, nodeOffsetEnd);
          return push2(new BracketInfo(range2, level - 1, 0, true));
        }
        case 1: {
          const range2 = lengthsToRange(nodeOffsetStart, nodeOffsetEnd);
          return push2(new BracketInfo(range2, level - 1, nestingLevelOfEqualBracketType - 1, parentPairIsIncomplete));
        }
        case 0:
          return true;
      }
    }
}
class CollectBracketPairsContext {
  constructor(push2, includeMinIndentation, textModel) {
    this.push = push2;
    this.includeMinIndentation = includeMinIndentation;
    this.textModel = textModel;
  }
}
function collectBracketPairs(node2, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, context, level, levelPerBracketType) {
  var _a2;
  if (level > 200) {
    return true;
  }
  let shouldContinue = true;
  if (node2.kind === 2) {
    let levelPerBracket = 0;
    if (levelPerBracketType) {
      let existing = levelPerBracketType.get(node2.openingBracket.text);
      if (existing === void 0) {
        existing = 0;
      }
      levelPerBracket = existing;
      existing++;
      levelPerBracketType.set(node2.openingBracket.text, existing);
    }
    const openingBracketEnd = lengthAdd(nodeOffsetStart, node2.openingBracket.length);
    let minIndentation = -1;
    if (context.includeMinIndentation) {
      minIndentation = node2.computeMinIndentation(nodeOffsetStart, context.textModel);
    }
    shouldContinue = context.push(new BracketPairWithMinIndentationInfo(lengthsToRange(nodeOffsetStart, nodeOffsetEnd), lengthsToRange(nodeOffsetStart, openingBracketEnd), node2.closingBracket ? lengthsToRange(lengthAdd(openingBracketEnd, ((_a2 = node2.child) === null || _a2 === void 0 ? void 0 : _a2.length) || lengthZero), nodeOffsetEnd) : void 0, level, levelPerBracket, node2, minIndentation));
    nodeOffsetStart = openingBracketEnd;
    if (shouldContinue && node2.child) {
      const child = node2.child;
      nodeOffsetEnd = lengthAdd(nodeOffsetStart, child.length);
      if (lengthLessThanEqual(nodeOffsetStart, endOffset) && lengthGreaterThanEqual(nodeOffsetEnd, startOffset)) {
        shouldContinue = collectBracketPairs(child, nodeOffsetStart, nodeOffsetEnd, startOffset, endOffset, context, level + 1, levelPerBracketType);
        if (!shouldContinue) {
          return false;
        }
      }
    }
    levelPerBracketType === null || levelPerBracketType === void 0 ? void 0 : levelPerBracketType.set(node2.openingBracket.text, levelPerBracket);
  } else {
    let curOffset = nodeOffsetStart;
    for (const child of node2.children) {
      const childOffset = curOffset;
      curOffset = lengthAdd(curOffset, child.length);
      if (lengthLessThanEqual(childOffset, endOffset) && lengthLessThanEqual(startOffset, curOffset)) {
        shouldContinue = collectBracketPairs(child, childOffset, curOffset, startOffset, endOffset, context, level, levelPerBracketType);
        if (!shouldContinue) {
          return false;
        }
      }
    }
  }
  return shouldContinue;
}
class BracketPairsTextModelPart extends Disposable {
  get canBuildAST() {
    const maxSupportedDocumentLength = (
      /* max lines */
      5e4 * /* average column count */
      100
    );
    return this.textModel.getValueLength() <= maxSupportedDocumentLength;
  }
  constructor(textModel, languageConfigurationService) {
    super();
    this.textModel = textModel;
    this.languageConfigurationService = languageConfigurationService;
    this.bracketPairsTree = this._register(new MutableDisposable());
    this.onDidChangeEmitter = new Emitter$1();
    this.onDidChange = this.onDidChangeEmitter.event;
    this.bracketsRequested = false;
    this._register(this.languageConfigurationService.onDidChange((e) => {
      var _a2;
      if (!e.languageId || ((_a2 = this.bracketPairsTree.value) === null || _a2 === void 0 ? void 0 : _a2.object.didLanguageChange(e.languageId))) {
        this.bracketPairsTree.clear();
        this.updateBracketPairsTree();
      }
    }));
  }
  //#region TextModel events
  handleDidChangeOptions(e) {
    this.bracketPairsTree.clear();
    this.updateBracketPairsTree();
  }
  handleDidChangeLanguage(e) {
    this.bracketPairsTree.clear();
    this.updateBracketPairsTree();
  }
  handleDidChangeContent(change) {
    var _a2;
    (_a2 = this.bracketPairsTree.value) === null || _a2 === void 0 ? void 0 : _a2.object.handleContentChanged(change);
  }
  handleDidChangeBackgroundTokenizationState() {
    var _a2;
    (_a2 = this.bracketPairsTree.value) === null || _a2 === void 0 ? void 0 : _a2.object.handleDidChangeBackgroundTokenizationState();
  }
  handleDidChangeTokens(e) {
    var _a2;
    (_a2 = this.bracketPairsTree.value) === null || _a2 === void 0 ? void 0 : _a2.object.handleDidChangeTokens(e);
  }
  //#endregion
  updateBracketPairsTree() {
    if (this.bracketsRequested && this.canBuildAST) {
      if (!this.bracketPairsTree.value) {
        const store = new DisposableStore();
        this.bracketPairsTree.value = createDisposableRef(store.add(new BracketPairsTree(this.textModel, (languageId) => {
          return this.languageConfigurationService.getLanguageConfiguration(languageId);
        })), store);
        store.add(this.bracketPairsTree.value.object.onDidChange((e) => this.onDidChangeEmitter.fire(e)));
        this.onDidChangeEmitter.fire();
      }
    } else {
      if (this.bracketPairsTree.value) {
        this.bracketPairsTree.clear();
        this.onDidChangeEmitter.fire();
      }
    }
  }
  /**
   * Returns all bracket pairs that intersect the given range.
   * The result is sorted by the start position.
  */
  getBracketPairsInRange(range2) {
    var _a2;
    this.bracketsRequested = true;
    this.updateBracketPairsTree();
    return ((_a2 = this.bracketPairsTree.value) === null || _a2 === void 0 ? void 0 : _a2.object.getBracketPairsInRange(range2, false)) || CallbackIterable.empty;
  }
  getBracketPairsInRangeWithMinIndentation(range2) {
    var _a2;
    this.bracketsRequested = true;
    this.updateBracketPairsTree();
    return ((_a2 = this.bracketPairsTree.value) === null || _a2 === void 0 ? void 0 : _a2.object.getBracketPairsInRange(range2, true)) || CallbackIterable.empty;
  }
  getBracketsInRange(range2, onlyColorizedBrackets = false) {
    var _a2;
    this.bracketsRequested = true;
    this.updateBracketPairsTree();
    return ((_a2 = this.bracketPairsTree.value) === null || _a2 === void 0 ? void 0 : _a2.object.getBracketsInRange(range2, onlyColorizedBrackets)) || CallbackIterable.empty;
  }
  findMatchingBracketUp(_bracket, _position, maxDuration) {
    const position = this.textModel.validatePosition(_position);
    const languageId = this.textModel.getLanguageIdAtPosition(position.lineNumber, position.column);
    if (this.canBuildAST) {
      const closingBracketInfo = this.languageConfigurationService.getLanguageConfiguration(languageId).bracketsNew.getClosingBracketInfo(_bracket);
      if (!closingBracketInfo) {
        return null;
      }
      const bracketPair = this.getBracketPairsInRange(Range$2.fromPositions(_position, _position)).findLast((b) => closingBracketInfo.closes(b.openingBracketInfo));
      if (bracketPair) {
        return bracketPair.openingBracketRange;
      }
      return null;
    } else {
      const bracket = _bracket.toLowerCase();
      const bracketsSupport = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets;
      if (!bracketsSupport) {
        return null;
      }
      const data = bracketsSupport.textIsBracket[bracket];
      if (!data) {
        return null;
      }
      return stripBracketSearchCanceled(this._findMatchingBracketUp(data, position, createTimeBasedContinueBracketSearchPredicate(maxDuration)));
    }
  }
  matchBracket(position, maxDuration) {
    if (this.canBuildAST) {
      const bracketPair = this.getBracketPairsInRange(Range$2.fromPositions(position, position)).filter((item) => item.closingBracketRange !== void 0 && (item.openingBracketRange.containsPosition(position) || item.closingBracketRange.containsPosition(position))).findLastMaxBy(compareBy((item) => item.openingBracketRange.containsPosition(position) ? item.openingBracketRange : item.closingBracketRange, Range$2.compareRangesUsingStarts));
      if (bracketPair) {
        return [bracketPair.openingBracketRange, bracketPair.closingBracketRange];
      }
      return null;
    } else {
      const continueSearchPredicate = createTimeBasedContinueBracketSearchPredicate(maxDuration);
      return this._matchBracket(this.textModel.validatePosition(position), continueSearchPredicate);
    }
  }
  _establishBracketSearchOffsets(position, lineTokens, modeBrackets, tokenIndex) {
    const tokenCount = lineTokens.getCount();
    const currentLanguageId = lineTokens.getLanguageId(tokenIndex);
    let searchStartOffset = Math.max(0, position.column - 1 - modeBrackets.maxBracketLength);
    for (let i = tokenIndex - 1; i >= 0; i--) {
      const tokenEndOffset = lineTokens.getEndOffset(i);
      if (tokenEndOffset <= searchStartOffset) {
        break;
      }
      if (ignoreBracketsInToken(lineTokens.getStandardTokenType(i)) || lineTokens.getLanguageId(i) !== currentLanguageId) {
        searchStartOffset = tokenEndOffset;
        break;
      }
    }
    let searchEndOffset = Math.min(lineTokens.getLineContent().length, position.column - 1 + modeBrackets.maxBracketLength);
    for (let i = tokenIndex + 1; i < tokenCount; i++) {
      const tokenStartOffset = lineTokens.getStartOffset(i);
      if (tokenStartOffset >= searchEndOffset) {
        break;
      }
      if (ignoreBracketsInToken(lineTokens.getStandardTokenType(i)) || lineTokens.getLanguageId(i) !== currentLanguageId) {
        searchEndOffset = tokenStartOffset;
        break;
      }
    }
    return { searchStartOffset, searchEndOffset };
  }
  _matchBracket(position, continueSearchPredicate) {
    const lineNumber = position.lineNumber;
    const lineTokens = this.textModel.tokenization.getLineTokens(lineNumber);
    const lineText = this.textModel.getLineContent(lineNumber);
    const tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
    if (tokenIndex < 0) {
      return null;
    }
    const currentModeBrackets = this.languageConfigurationService.getLanguageConfiguration(lineTokens.getLanguageId(tokenIndex)).brackets;
    if (currentModeBrackets && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex))) {
      let { searchStartOffset, searchEndOffset } = this._establishBracketSearchOffsets(position, lineTokens, currentModeBrackets, tokenIndex);
      let bestResult = null;
      while (true) {
        const foundBracket = BracketsUtils.findNextBracketInRange(currentModeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (!foundBracket) {
          break;
        }
        if (foundBracket.startColumn <= position.column && position.column <= foundBracket.endColumn) {
          const foundBracketText = lineText.substring(foundBracket.startColumn - 1, foundBracket.endColumn - 1).toLowerCase();
          const r = this._matchFoundBracket(foundBracket, currentModeBrackets.textIsBracket[foundBracketText], currentModeBrackets.textIsOpenBracket[foundBracketText], continueSearchPredicate);
          if (r) {
            if (r instanceof BracketSearchCanceled) {
              return null;
            }
            bestResult = r;
          }
        }
        searchStartOffset = foundBracket.endColumn - 1;
      }
      if (bestResult) {
        return bestResult;
      }
    }
    if (tokenIndex > 0 && lineTokens.getStartOffset(tokenIndex) === position.column - 1) {
      const prevTokenIndex = tokenIndex - 1;
      const prevModeBrackets = this.languageConfigurationService.getLanguageConfiguration(lineTokens.getLanguageId(prevTokenIndex)).brackets;
      if (prevModeBrackets && !ignoreBracketsInToken(lineTokens.getStandardTokenType(prevTokenIndex))) {
        const { searchStartOffset, searchEndOffset } = this._establishBracketSearchOffsets(position, lineTokens, prevModeBrackets, prevTokenIndex);
        const foundBracket = BracketsUtils.findPrevBracketInRange(prevModeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (foundBracket && foundBracket.startColumn <= position.column && position.column <= foundBracket.endColumn) {
          const foundBracketText = lineText.substring(foundBracket.startColumn - 1, foundBracket.endColumn - 1).toLowerCase();
          const r = this._matchFoundBracket(foundBracket, prevModeBrackets.textIsBracket[foundBracketText], prevModeBrackets.textIsOpenBracket[foundBracketText], continueSearchPredicate);
          if (r) {
            if (r instanceof BracketSearchCanceled) {
              return null;
            }
            return r;
          }
        }
      }
    }
    return null;
  }
  _matchFoundBracket(foundBracket, data, isOpen, continueSearchPredicate) {
    if (!data) {
      return null;
    }
    const matched = isOpen ? this._findMatchingBracketDown(data, foundBracket.getEndPosition(), continueSearchPredicate) : this._findMatchingBracketUp(data, foundBracket.getStartPosition(), continueSearchPredicate);
    if (!matched) {
      return null;
    }
    if (matched instanceof BracketSearchCanceled) {
      return matched;
    }
    return [foundBracket, matched];
  }
  _findMatchingBracketUp(bracket, position, continueSearchPredicate) {
    const languageId = bracket.languageId;
    const reversedBracketRegex = bracket.reversedRegex;
    let count = -1;
    let totalCallCount = 0;
    const searchPrevMatchingBracketInRange = (lineNumber, lineText, searchStartOffset, searchEndOffset) => {
      while (true) {
        if (continueSearchPredicate && ++totalCallCount % 100 === 0 && !continueSearchPredicate()) {
          return BracketSearchCanceled.INSTANCE;
        }
        const r = BracketsUtils.findPrevBracketInRange(reversedBracketRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (!r) {
          break;
        }
        const hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase();
        if (bracket.isOpen(hitText)) {
          count++;
        } else if (bracket.isClose(hitText)) {
          count--;
        }
        if (count === 0) {
          return r;
        }
        searchEndOffset = r.startColumn - 1;
      }
      return null;
    };
    for (let lineNumber = position.lineNumber; lineNumber >= 1; lineNumber--) {
      const lineTokens = this.textModel.tokenization.getLineTokens(lineNumber);
      const tokenCount = lineTokens.getCount();
      const lineText = this.textModel.getLineContent(lineNumber);
      let tokenIndex = tokenCount - 1;
      let searchStartOffset = lineText.length;
      let searchEndOffset = lineText.length;
      if (lineNumber === position.lineNumber) {
        tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
        searchStartOffset = position.column - 1;
        searchEndOffset = position.column - 1;
      }
      let prevSearchInToken = true;
      for (; tokenIndex >= 0; tokenIndex--) {
        const searchInToken = lineTokens.getLanguageId(tokenIndex) === languageId && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex));
        if (searchInToken) {
          if (prevSearchInToken) {
            searchStartOffset = lineTokens.getStartOffset(tokenIndex);
          } else {
            searchStartOffset = lineTokens.getStartOffset(tokenIndex);
            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
          }
        } else {
          if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
            const r = searchPrevMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
            if (r) {
              return r;
            }
          }
        }
        prevSearchInToken = searchInToken;
      }
      if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
        const r = searchPrevMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (r) {
          return r;
        }
      }
    }
    return null;
  }
  _findMatchingBracketDown(bracket, position, continueSearchPredicate) {
    const languageId = bracket.languageId;
    const bracketRegex = bracket.forwardRegex;
    let count = 1;
    let totalCallCount = 0;
    const searchNextMatchingBracketInRange = (lineNumber, lineText, searchStartOffset, searchEndOffset) => {
      while (true) {
        if (continueSearchPredicate && ++totalCallCount % 100 === 0 && !continueSearchPredicate()) {
          return BracketSearchCanceled.INSTANCE;
        }
        const r = BracketsUtils.findNextBracketInRange(bracketRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (!r) {
          break;
        }
        const hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase();
        if (bracket.isOpen(hitText)) {
          count++;
        } else if (bracket.isClose(hitText)) {
          count--;
        }
        if (count === 0) {
          return r;
        }
        searchStartOffset = r.endColumn - 1;
      }
      return null;
    };
    const lineCount = this.textModel.getLineCount();
    for (let lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) {
      const lineTokens = this.textModel.tokenization.getLineTokens(lineNumber);
      const tokenCount = lineTokens.getCount();
      const lineText = this.textModel.getLineContent(lineNumber);
      let tokenIndex = 0;
      let searchStartOffset = 0;
      let searchEndOffset = 0;
      if (lineNumber === position.lineNumber) {
        tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
        searchStartOffset = position.column - 1;
        searchEndOffset = position.column - 1;
      }
      let prevSearchInToken = true;
      for (; tokenIndex < tokenCount; tokenIndex++) {
        const searchInToken = lineTokens.getLanguageId(tokenIndex) === languageId && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex));
        if (searchInToken) {
          if (prevSearchInToken) {
            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
          } else {
            searchStartOffset = lineTokens.getStartOffset(tokenIndex);
            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
          }
        } else {
          if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
            const r = searchNextMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
            if (r) {
              return r;
            }
          }
        }
        prevSearchInToken = searchInToken;
      }
      if (prevSearchInToken && searchStartOffset !== searchEndOffset) {
        const r = searchNextMatchingBracketInRange(lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (r) {
          return r;
        }
      }
    }
    return null;
  }
  findPrevBracket(_position) {
    var _a2;
    const position = this.textModel.validatePosition(_position);
    if (this.canBuildAST) {
      this.bracketsRequested = true;
      this.updateBracketPairsTree();
      return ((_a2 = this.bracketPairsTree.value) === null || _a2 === void 0 ? void 0 : _a2.object.getFirstBracketBefore(position)) || null;
    }
    let languageId = null;
    let modeBrackets = null;
    let bracketConfig = null;
    for (let lineNumber = position.lineNumber; lineNumber >= 1; lineNumber--) {
      const lineTokens = this.textModel.tokenization.getLineTokens(lineNumber);
      const tokenCount = lineTokens.getCount();
      const lineText = this.textModel.getLineContent(lineNumber);
      let tokenIndex = tokenCount - 1;
      let searchStartOffset = lineText.length;
      let searchEndOffset = lineText.length;
      if (lineNumber === position.lineNumber) {
        tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
        searchStartOffset = position.column - 1;
        searchEndOffset = position.column - 1;
        const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
        if (languageId !== tokenLanguageId) {
          languageId = tokenLanguageId;
          modeBrackets = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets;
          bracketConfig = this.languageConfigurationService.getLanguageConfiguration(languageId).bracketsNew;
        }
      }
      let prevSearchInToken = true;
      for (; tokenIndex >= 0; tokenIndex--) {
        const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
        if (languageId !== tokenLanguageId) {
          if (modeBrackets && bracketConfig && prevSearchInToken && searchStartOffset !== searchEndOffset) {
            const r = BracketsUtils.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
            if (r) {
              return this._toFoundBracket(bracketConfig, r);
            }
            prevSearchInToken = false;
          }
          languageId = tokenLanguageId;
          modeBrackets = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets;
          bracketConfig = this.languageConfigurationService.getLanguageConfiguration(languageId).bracketsNew;
        }
        const searchInToken = !!modeBrackets && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex));
        if (searchInToken) {
          if (prevSearchInToken) {
            searchStartOffset = lineTokens.getStartOffset(tokenIndex);
          } else {
            searchStartOffset = lineTokens.getStartOffset(tokenIndex);
            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
          }
        } else {
          if (bracketConfig && modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
            const r = BracketsUtils.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
            if (r) {
              return this._toFoundBracket(bracketConfig, r);
            }
          }
        }
        prevSearchInToken = searchInToken;
      }
      if (bracketConfig && modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
        const r = BracketsUtils.findPrevBracketInRange(modeBrackets.reversedRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (r) {
          return this._toFoundBracket(bracketConfig, r);
        }
      }
    }
    return null;
  }
  findNextBracket(_position) {
    var _a2;
    const position = this.textModel.validatePosition(_position);
    if (this.canBuildAST) {
      this.bracketsRequested = true;
      this.updateBracketPairsTree();
      return ((_a2 = this.bracketPairsTree.value) === null || _a2 === void 0 ? void 0 : _a2.object.getFirstBracketAfter(position)) || null;
    }
    const lineCount = this.textModel.getLineCount();
    let languageId = null;
    let modeBrackets = null;
    let bracketConfig = null;
    for (let lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) {
      const lineTokens = this.textModel.tokenization.getLineTokens(lineNumber);
      const tokenCount = lineTokens.getCount();
      const lineText = this.textModel.getLineContent(lineNumber);
      let tokenIndex = 0;
      let searchStartOffset = 0;
      let searchEndOffset = 0;
      if (lineNumber === position.lineNumber) {
        tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
        searchStartOffset = position.column - 1;
        searchEndOffset = position.column - 1;
        const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
        if (languageId !== tokenLanguageId) {
          languageId = tokenLanguageId;
          modeBrackets = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets;
          bracketConfig = this.languageConfigurationService.getLanguageConfiguration(languageId).bracketsNew;
        }
      }
      let prevSearchInToken = true;
      for (; tokenIndex < tokenCount; tokenIndex++) {
        const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
        if (languageId !== tokenLanguageId) {
          if (bracketConfig && modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
            const r = BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
            if (r) {
              return this._toFoundBracket(bracketConfig, r);
            }
            prevSearchInToken = false;
          }
          languageId = tokenLanguageId;
          modeBrackets = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets;
          bracketConfig = this.languageConfigurationService.getLanguageConfiguration(languageId).bracketsNew;
        }
        const searchInToken = !!modeBrackets && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex));
        if (searchInToken) {
          if (prevSearchInToken) {
            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
          } else {
            searchStartOffset = lineTokens.getStartOffset(tokenIndex);
            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
          }
        } else {
          if (bracketConfig && modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
            const r = BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
            if (r) {
              return this._toFoundBracket(bracketConfig, r);
            }
          }
        }
        prevSearchInToken = searchInToken;
      }
      if (bracketConfig && modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
        const r = BracketsUtils.findNextBracketInRange(modeBrackets.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (r) {
          return this._toFoundBracket(bracketConfig, r);
        }
      }
    }
    return null;
  }
  findEnclosingBrackets(_position, maxDuration) {
    const position = this.textModel.validatePosition(_position);
    if (this.canBuildAST) {
      const range2 = Range$2.fromPositions(position);
      const bracketPair = this.getBracketPairsInRange(Range$2.fromPositions(position, position)).findLast((item) => item.closingBracketRange !== void 0 && item.range.strictContainsRange(range2));
      if (bracketPair) {
        return [bracketPair.openingBracketRange, bracketPair.closingBracketRange];
      }
      return null;
    }
    const continueSearchPredicate = createTimeBasedContinueBracketSearchPredicate(maxDuration);
    const lineCount = this.textModel.getLineCount();
    const savedCounts = /* @__PURE__ */ new Map();
    let counts = [];
    const resetCounts = (languageId2, modeBrackets2) => {
      if (!savedCounts.has(languageId2)) {
        const tmp = [];
        for (let i = 0, len = modeBrackets2 ? modeBrackets2.brackets.length : 0; i < len; i++) {
          tmp[i] = 0;
        }
        savedCounts.set(languageId2, tmp);
      }
      counts = savedCounts.get(languageId2);
    };
    let totalCallCount = 0;
    const searchInRange = (modeBrackets2, lineNumber, lineText, searchStartOffset, searchEndOffset) => {
      while (true) {
        if (continueSearchPredicate && ++totalCallCount % 100 === 0 && !continueSearchPredicate()) {
          return BracketSearchCanceled.INSTANCE;
        }
        const r = BracketsUtils.findNextBracketInRange(modeBrackets2.forwardRegex, lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (!r) {
          break;
        }
        const hitText = lineText.substring(r.startColumn - 1, r.endColumn - 1).toLowerCase();
        const bracket = modeBrackets2.textIsBracket[hitText];
        if (bracket) {
          if (bracket.isOpen(hitText)) {
            counts[bracket.index]++;
          } else if (bracket.isClose(hitText)) {
            counts[bracket.index]--;
          }
          if (counts[bracket.index] === -1) {
            return this._matchFoundBracket(r, bracket, false, continueSearchPredicate);
          }
        }
        searchStartOffset = r.endColumn - 1;
      }
      return null;
    };
    let languageId = null;
    let modeBrackets = null;
    for (let lineNumber = position.lineNumber; lineNumber <= lineCount; lineNumber++) {
      const lineTokens = this.textModel.tokenization.getLineTokens(lineNumber);
      const tokenCount = lineTokens.getCount();
      const lineText = this.textModel.getLineContent(lineNumber);
      let tokenIndex = 0;
      let searchStartOffset = 0;
      let searchEndOffset = 0;
      if (lineNumber === position.lineNumber) {
        tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
        searchStartOffset = position.column - 1;
        searchEndOffset = position.column - 1;
        const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
        if (languageId !== tokenLanguageId) {
          languageId = tokenLanguageId;
          modeBrackets = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets;
          resetCounts(languageId, modeBrackets);
        }
      }
      let prevSearchInToken = true;
      for (; tokenIndex < tokenCount; tokenIndex++) {
        const tokenLanguageId = lineTokens.getLanguageId(tokenIndex);
        if (languageId !== tokenLanguageId) {
          if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
            const r = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset);
            if (r) {
              return stripBracketSearchCanceled(r);
            }
            prevSearchInToken = false;
          }
          languageId = tokenLanguageId;
          modeBrackets = this.languageConfigurationService.getLanguageConfiguration(languageId).brackets;
          resetCounts(languageId, modeBrackets);
        }
        const searchInToken = !!modeBrackets && !ignoreBracketsInToken(lineTokens.getStandardTokenType(tokenIndex));
        if (searchInToken) {
          if (prevSearchInToken) {
            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
          } else {
            searchStartOffset = lineTokens.getStartOffset(tokenIndex);
            searchEndOffset = lineTokens.getEndOffset(tokenIndex);
          }
        } else {
          if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
            const r = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset);
            if (r) {
              return stripBracketSearchCanceled(r);
            }
          }
        }
        prevSearchInToken = searchInToken;
      }
      if (modeBrackets && prevSearchInToken && searchStartOffset !== searchEndOffset) {
        const r = searchInRange(modeBrackets, lineNumber, lineText, searchStartOffset, searchEndOffset);
        if (r) {
          return stripBracketSearchCanceled(r);
        }
      }
    }
    return null;
  }
  _toFoundBracket(bracketConfig, r) {
    if (!r) {
      return null;
    }
    let text2 = this.textModel.getValueInRange(r);
    text2 = text2.toLowerCase();
    const bracketInfo = bracketConfig.getBracketInfo(text2);
    if (!bracketInfo) {
      return null;
    }
    return {
      range: r,
      bracketInfo
    };
  }
}
function createDisposableRef(object2, disposable) {
  return {
    object: object2,
    dispose: () => disposable === null || disposable === void 0 ? void 0 : disposable.dispose()
  };
}
function createTimeBasedContinueBracketSearchPredicate(maxDuration) {
  if (typeof maxDuration === "undefined") {
    return () => true;
  } else {
    const startTime2 = Date.now();
    return () => {
      return Date.now() - startTime2 <= maxDuration;
    };
  }
}
class BracketSearchCanceled {
  constructor() {
    this._searchCanceledBrand = void 0;
  }
}
BracketSearchCanceled.INSTANCE = new BracketSearchCanceled();
function stripBracketSearchCanceled(result2) {
  if (result2 instanceof BracketSearchCanceled) {
    return null;
  }
  return result2;
}
class ColorizedBracketPairsDecorationProvider extends Disposable {
  constructor(textModel) {
    super();
    this.textModel = textModel;
    this.colorProvider = new ColorProvider();
    this.onDidChangeEmitter = new Emitter$1();
    this.onDidChange = this.onDidChangeEmitter.event;
    this.colorizationOptions = textModel.getOptions().bracketPairColorizationOptions;
    this._register(textModel.bracketPairs.onDidChange((e) => {
      this.onDidChangeEmitter.fire();
    }));
  }
  //#region TextModel events
  handleDidChangeOptions(e) {
    this.colorizationOptions = this.textModel.getOptions().bracketPairColorizationOptions;
  }
  //#endregion
  getDecorationsInRange(range2, ownerId, filterOutValidation, onlyMinimapDecorations) {
    if (onlyMinimapDecorations) {
      return [];
    }
    if (ownerId === void 0) {
      return [];
    }
    if (!this.colorizationOptions.enabled) {
      return [];
    }
    const result2 = this.textModel.bracketPairs.getBracketsInRange(range2, true).map((bracket) => ({
      id: `bracket${bracket.range.toString()}-${bracket.nestingLevel}`,
      options: {
        description: "BracketPairColorization",
        inlineClassName: this.colorProvider.getInlineClassName(bracket, this.colorizationOptions.independentColorPoolPerBracketType)
      },
      ownerId: 0,
      range: bracket.range
    })).toArray();
    return result2;
  }
  getAllDecorations(ownerId, filterOutValidation) {
    if (ownerId === void 0) {
      return [];
    }
    if (!this.colorizationOptions.enabled) {
      return [];
    }
    return this.getDecorationsInRange(new Range$2(1, 1, this.textModel.getLineCount(), 1), ownerId, filterOutValidation);
  }
}
class ColorProvider {
  constructor() {
    this.unexpectedClosingBracketClassName = "unexpected-closing-bracket";
  }
  getInlineClassName(bracket, independentColorPoolPerBracketType) {
    if (bracket.isInvalid) {
      return this.unexpectedClosingBracketClassName;
    }
    return this.getInlineClassNameOfLevel(independentColorPoolPerBracketType ? bracket.nestingLevelOfEqualBracketType : bracket.nestingLevel);
  }
  getInlineClassNameOfLevel(level) {
    return `bracket-highlighting-${level % 30}`;
  }
}
registerThemingParticipant((theme, collector) => {
  const colors = [
    editorBracketHighlightingForeground1,
    editorBracketHighlightingForeground2,
    editorBracketHighlightingForeground3,
    editorBracketHighlightingForeground4,
    editorBracketHighlightingForeground5,
    editorBracketHighlightingForeground6
  ];
  const colorProvider = new ColorProvider();
  collector.addRule(`.monaco-editor .${colorProvider.unexpectedClosingBracketClassName} { color: ${theme.getColor(editorBracketHighlightingUnexpectedBracketForeground)}; }`);
  const colorValues = colors.map((c) => theme.getColor(c)).filter((c) => !!c).filter((c) => !c.isTransparent());
  for (let level = 0; level < 30; level++) {
    const color = colorValues[level % colorValues.length];
    collector.addRule(`.monaco-editor .${colorProvider.getInlineClassNameOfLevel(level)} { color: ${color}; }`);
  }
});
function escapeNewLine(str2) {
  return str2.replace(/\n/g, "\\n").replace(/\r/g, "\\r");
}
class TextChange {
  get oldLength() {
    return this.oldText.length;
  }
  get oldEnd() {
    return this.oldPosition + this.oldText.length;
  }
  get newLength() {
    return this.newText.length;
  }
  get newEnd() {
    return this.newPosition + this.newText.length;
  }
  constructor(oldPosition, oldText, newPosition, newText) {
    this.oldPosition = oldPosition;
    this.oldText = oldText;
    this.newPosition = newPosition;
    this.newText = newText;
  }
  toString() {
    if (this.oldText.length === 0) {
      return `(insert@${this.oldPosition} "${escapeNewLine(this.newText)}")`;
    }
    if (this.newText.length === 0) {
      return `(delete@${this.oldPosition} "${escapeNewLine(this.oldText)}")`;
    }
    return `(replace@${this.oldPosition} "${escapeNewLine(this.oldText)}" with "${escapeNewLine(this.newText)}")`;
  }
  static _writeStringSize(str2) {
    return 4 + 2 * str2.length;
  }
  static _writeString(b, str2, offset) {
    const len = str2.length;
    writeUInt32BE(b, len, offset);
    offset += 4;
    for (let i = 0; i < len; i++) {
      writeUInt16LE(b, str2.charCodeAt(i), offset);
      offset += 2;
    }
    return offset;
  }
  static _readString(b, offset) {
    const len = readUInt32BE(b, offset);
    offset += 4;
    return decodeUTF16LE(b, offset, len);
  }
  writeSize() {
    return 4 + 4 + TextChange._writeStringSize(this.oldText) + TextChange._writeStringSize(this.newText);
  }
  write(b, offset) {
    writeUInt32BE(b, this.oldPosition, offset);
    offset += 4;
    writeUInt32BE(b, this.newPosition, offset);
    offset += 4;
    offset = TextChange._writeString(b, this.oldText, offset);
    offset = TextChange._writeString(b, this.newText, offset);
    return offset;
  }
  static read(b, offset, dest) {
    const oldPosition = readUInt32BE(b, offset);
    offset += 4;
    const newPosition = readUInt32BE(b, offset);
    offset += 4;
    const oldText = TextChange._readString(b, offset);
    offset += TextChange._writeStringSize(oldText);
    const newText = TextChange._readString(b, offset);
    offset += TextChange._writeStringSize(newText);
    dest.push(new TextChange(oldPosition, oldText, newPosition, newText));
    return offset;
  }
}
function compressConsecutiveTextChanges(prevEdits, currEdits) {
  if (prevEdits === null || prevEdits.length === 0) {
    return currEdits;
  }
  const compressor = new TextChangeCompressor(prevEdits, currEdits);
  return compressor.compress();
}
class TextChangeCompressor {
  constructor(prevEdits, currEdits) {
    this._prevEdits = prevEdits;
    this._currEdits = currEdits;
    this._result = [];
    this._resultLen = 0;
    this._prevLen = this._prevEdits.length;
    this._prevDeltaOffset = 0;
    this._currLen = this._currEdits.length;
    this._currDeltaOffset = 0;
  }
  compress() {
    let prevIndex = 0;
    let currIndex = 0;
    let prevEdit = this._getPrev(prevIndex);
    let currEdit = this._getCurr(currIndex);
    while (prevIndex < this._prevLen || currIndex < this._currLen) {
      if (prevEdit === null) {
        this._acceptCurr(currEdit);
        currEdit = this._getCurr(++currIndex);
        continue;
      }
      if (currEdit === null) {
        this._acceptPrev(prevEdit);
        prevEdit = this._getPrev(++prevIndex);
        continue;
      }
      if (currEdit.oldEnd <= prevEdit.newPosition) {
        this._acceptCurr(currEdit);
        currEdit = this._getCurr(++currIndex);
        continue;
      }
      if (prevEdit.newEnd <= currEdit.oldPosition) {
        this._acceptPrev(prevEdit);
        prevEdit = this._getPrev(++prevIndex);
        continue;
      }
      if (currEdit.oldPosition < prevEdit.newPosition) {
        const [e1, e2] = TextChangeCompressor._splitCurr(currEdit, prevEdit.newPosition - currEdit.oldPosition);
        this._acceptCurr(e1);
        currEdit = e2;
        continue;
      }
      if (prevEdit.newPosition < currEdit.oldPosition) {
        const [e1, e2] = TextChangeCompressor._splitPrev(prevEdit, currEdit.oldPosition - prevEdit.newPosition);
        this._acceptPrev(e1);
        prevEdit = e2;
        continue;
      }
      let mergePrev;
      let mergeCurr;
      if (currEdit.oldEnd === prevEdit.newEnd) {
        mergePrev = prevEdit;
        mergeCurr = currEdit;
        prevEdit = this._getPrev(++prevIndex);
        currEdit = this._getCurr(++currIndex);
      } else if (currEdit.oldEnd < prevEdit.newEnd) {
        const [e1, e2] = TextChangeCompressor._splitPrev(prevEdit, currEdit.oldLength);
        mergePrev = e1;
        mergeCurr = currEdit;
        prevEdit = e2;
        currEdit = this._getCurr(++currIndex);
      } else {
        const [e1, e2] = TextChangeCompressor._splitCurr(currEdit, prevEdit.newLength);
        mergePrev = prevEdit;
        mergeCurr = e1;
        prevEdit = this._getPrev(++prevIndex);
        currEdit = e2;
      }
      this._result[this._resultLen++] = new TextChange(mergePrev.oldPosition, mergePrev.oldText, mergeCurr.newPosition, mergeCurr.newText);
      this._prevDeltaOffset += mergePrev.newLength - mergePrev.oldLength;
      this._currDeltaOffset += mergeCurr.newLength - mergeCurr.oldLength;
    }
    const merged = TextChangeCompressor._merge(this._result);
    const cleaned = TextChangeCompressor._removeNoOps(merged);
    return cleaned;
  }
  _acceptCurr(currEdit) {
    this._result[this._resultLen++] = TextChangeCompressor._rebaseCurr(this._prevDeltaOffset, currEdit);
    this._currDeltaOffset += currEdit.newLength - currEdit.oldLength;
  }
  _getCurr(currIndex) {
    return currIndex < this._currLen ? this._currEdits[currIndex] : null;
  }
  _acceptPrev(prevEdit) {
    this._result[this._resultLen++] = TextChangeCompressor._rebasePrev(this._currDeltaOffset, prevEdit);
    this._prevDeltaOffset += prevEdit.newLength - prevEdit.oldLength;
  }
  _getPrev(prevIndex) {
    return prevIndex < this._prevLen ? this._prevEdits[prevIndex] : null;
  }
  static _rebaseCurr(prevDeltaOffset, currEdit) {
    return new TextChange(currEdit.oldPosition - prevDeltaOffset, currEdit.oldText, currEdit.newPosition, currEdit.newText);
  }
  static _rebasePrev(currDeltaOffset, prevEdit) {
    return new TextChange(prevEdit.oldPosition, prevEdit.oldText, prevEdit.newPosition + currDeltaOffset, prevEdit.newText);
  }
  static _splitPrev(edit, offset) {
    const preText = edit.newText.substr(0, offset);
    const postText = edit.newText.substr(offset);
    return [
      new TextChange(edit.oldPosition, edit.oldText, edit.newPosition, preText),
      new TextChange(edit.oldEnd, "", edit.newPosition + offset, postText)
    ];
  }
  static _splitCurr(edit, offset) {
    const preText = edit.oldText.substr(0, offset);
    const postText = edit.oldText.substr(offset);
    return [
      new TextChange(edit.oldPosition, preText, edit.newPosition, edit.newText),
      new TextChange(edit.oldPosition + offset, postText, edit.newEnd, "")
    ];
  }
  static _merge(edits) {
    if (edits.length === 0) {
      return edits;
    }
    const result2 = [];
    let resultLen = 0;
    let prev = edits[0];
    for (let i = 1; i < edits.length; i++) {
      const curr = edits[i];
      if (prev.oldEnd === curr.oldPosition) {
        prev = new TextChange(prev.oldPosition, prev.oldText + curr.oldText, prev.newPosition, prev.newText + curr.newText);
      } else {
        result2[resultLen++] = prev;
        prev = curr;
      }
    }
    result2[resultLen++] = prev;
    return result2;
  }
  static _removeNoOps(edits) {
    if (edits.length === 0) {
      return edits;
    }
    const result2 = [];
    let resultLen = 0;
    for (let i = 0; i < edits.length; i++) {
      const edit = edits[i];
      if (edit.oldText === edit.newText) {
        continue;
      }
      result2[resultLen++] = edit;
    }
    return result2;
  }
}
function isPathSeparator(code) {
  return code === 47 || code === 92;
}
function toSlashes(osPath) {
  return osPath.replace(/[\\/]/g, posix.sep);
}
function toPosixPath(osPath) {
  if (osPath.indexOf("/") === -1) {
    osPath = toSlashes(osPath);
  }
  if (/^[a-zA-Z]:(\/|$)/.test(osPath)) {
    osPath = "/" + osPath;
  }
  return osPath;
}
function getRoot(path2, sep2 = posix.sep) {
  if (!path2) {
    return "";
  }
  const len = path2.length;
  const firstLetter = path2.charCodeAt(0);
  if (isPathSeparator(firstLetter)) {
    if (isPathSeparator(path2.charCodeAt(1))) {
      if (!isPathSeparator(path2.charCodeAt(2))) {
        let pos2 = 3;
        const start = pos2;
        for (; pos2 < len; pos2++) {
          if (isPathSeparator(path2.charCodeAt(pos2))) {
            break;
          }
        }
        if (start !== pos2 && !isPathSeparator(path2.charCodeAt(pos2 + 1))) {
          pos2 += 1;
          for (; pos2 < len; pos2++) {
            if (isPathSeparator(path2.charCodeAt(pos2))) {
              return path2.slice(0, pos2 + 1).replace(/[\\/]/g, sep2);
            }
          }
        }
      }
    }
    return sep2;
  } else if (isWindowsDriveLetter(firstLetter)) {
    if (path2.charCodeAt(1) === 58) {
      if (isPathSeparator(path2.charCodeAt(2))) {
        return path2.slice(0, 2) + sep2;
      } else {
        return path2.slice(0, 2);
      }
    }
  }
  let pos = path2.indexOf("://");
  if (pos !== -1) {
    pos += 3;
    for (; pos < len; pos++) {
      if (isPathSeparator(path2.charCodeAt(pos))) {
        return path2.slice(0, pos + 1);
      }
    }
  }
  return "";
}
function isEqualOrParent(base2, parentCandidate, ignoreCase, separator = sep$2) {
  if (base2 === parentCandidate) {
    return true;
  }
  if (!base2 || !parentCandidate) {
    return false;
  }
  if (parentCandidate.length > base2.length) {
    return false;
  }
  if (ignoreCase) {
    const beginsWith = startsWithIgnoreCase(base2, parentCandidate);
    if (!beginsWith) {
      return false;
    }
    if (parentCandidate.length === base2.length) {
      return true;
    }
    let sepOffset = parentCandidate.length;
    if (parentCandidate.charAt(parentCandidate.length - 1) === separator) {
      sepOffset--;
    }
    return base2.charAt(sepOffset) === separator;
  }
  if (parentCandidate.charAt(parentCandidate.length - 1) !== separator) {
    parentCandidate += separator;
  }
  return base2.indexOf(parentCandidate) === 0;
}
function isWindowsDriveLetter(char0) {
  return char0 >= 65 && char0 <= 90 || char0 >= 97 && char0 <= 122;
}
function hasDriveLetter(path2, isWindowsOS = isWindows) {
  if (isWindowsOS) {
    return isWindowsDriveLetter(path2.charCodeAt(0)) && path2.charCodeAt(1) === 58;
  }
  return false;
}
function originalFSPath(uri) {
  return uriToFsPath(uri, true);
}
class ExtUri {
  constructor(_ignorePathCasing) {
    this._ignorePathCasing = _ignorePathCasing;
  }
  compare(uri1, uri2, ignoreFragment = false) {
    if (uri1 === uri2) {
      return 0;
    }
    return compare(this.getComparisonKey(uri1, ignoreFragment), this.getComparisonKey(uri2, ignoreFragment));
  }
  isEqual(uri1, uri2, ignoreFragment = false) {
    if (uri1 === uri2) {
      return true;
    }
    if (!uri1 || !uri2) {
      return false;
    }
    return this.getComparisonKey(uri1, ignoreFragment) === this.getComparisonKey(uri2, ignoreFragment);
  }
  getComparisonKey(uri, ignoreFragment = false) {
    return uri.with({
      path: this._ignorePathCasing(uri) ? uri.path.toLowerCase() : void 0,
      fragment: ignoreFragment ? null : void 0
    }).toString();
  }
  isEqualOrParent(base2, parentCandidate, ignoreFragment = false) {
    if (base2.scheme === parentCandidate.scheme) {
      if (base2.scheme === Schemas.file) {
        return isEqualOrParent(originalFSPath(base2), originalFSPath(parentCandidate), this._ignorePathCasing(base2)) && base2.query === parentCandidate.query && (ignoreFragment || base2.fragment === parentCandidate.fragment);
      }
      if (isEqualAuthority(base2.authority, parentCandidate.authority)) {
        return isEqualOrParent(base2.path, parentCandidate.path, this._ignorePathCasing(base2), "/") && base2.query === parentCandidate.query && (ignoreFragment || base2.fragment === parentCandidate.fragment);
      }
    }
    return false;
  }
  // --- path math
  joinPath(resource, ...pathFragment) {
    return URI.joinPath(resource, ...pathFragment);
  }
  basenameOrAuthority(resource) {
    return basename$1(resource) || resource.authority;
  }
  basename(resource) {
    return posix.basename(resource.path);
  }
  extname(resource) {
    return posix.extname(resource.path);
  }
  dirname(resource) {
    if (resource.path.length === 0) {
      return resource;
    }
    let dirname2;
    if (resource.scheme === Schemas.file) {
      dirname2 = URI.file(dirname$4(originalFSPath(resource))).path;
    } else {
      dirname2 = posix.dirname(resource.path);
      if (resource.authority && dirname2.length && dirname2.charCodeAt(0) !== 47) {
        console.error(`dirname("${resource.toString})) resulted in a relative path`);
        dirname2 = "/";
      }
    }
    return resource.with({
      path: dirname2
    });
  }
  normalizePath(resource) {
    if (!resource.path.length) {
      return resource;
    }
    let normalizedPath;
    if (resource.scheme === Schemas.file) {
      normalizedPath = URI.file(normalize(originalFSPath(resource))).path;
    } else {
      normalizedPath = posix.normalize(resource.path);
    }
    return resource.with({
      path: normalizedPath
    });
  }
  relativePath(from2, to) {
    if (from2.scheme !== to.scheme || !isEqualAuthority(from2.authority, to.authority)) {
      return void 0;
    }
    if (from2.scheme === Schemas.file) {
      const relativePath2 = relative$2(originalFSPath(from2), originalFSPath(to));
      return isWindows ? toSlashes(relativePath2) : relativePath2;
    }
    let fromPath = from2.path || "/";
    const toPath = to.path || "/";
    if (this._ignorePathCasing(from2)) {
      let i = 0;
      for (const len = Math.min(fromPath.length, toPath.length); i < len; i++) {
        if (fromPath.charCodeAt(i) !== toPath.charCodeAt(i)) {
          if (fromPath.charAt(i).toLowerCase() !== toPath.charAt(i).toLowerCase()) {
            break;
          }
        }
      }
      fromPath = toPath.substr(0, i) + fromPath.substr(i);
    }
    return posix.relative(fromPath, toPath);
  }
  resolvePath(base2, path2) {
    if (base2.scheme === Schemas.file) {
      const newURI = URI.file(resolve$3(originalFSPath(base2), path2));
      return base2.with({
        authority: newURI.authority,
        path: newURI.path
      });
    }
    path2 = toPosixPath(path2);
    return base2.with({
      path: posix.resolve(base2.path, path2)
    });
  }
  // --- misc
  isAbsolutePath(resource) {
    return !!resource.path && resource.path[0] === "/";
  }
  isEqualAuthority(a1, a2) {
    return a1 === a2 || a1 !== void 0 && a2 !== void 0 && equalsIgnoreCase(a1, a2);
  }
  hasTrailingPathSeparator(resource, sep2 = sep$2) {
    if (resource.scheme === Schemas.file) {
      const fsp = originalFSPath(resource);
      return fsp.length > getRoot(fsp).length && fsp[fsp.length - 1] === sep2;
    } else {
      const p2 = resource.path;
      return p2.length > 1 && p2.charCodeAt(p2.length - 1) === 47 && !/^[a-zA-Z]:(\/$|\\$)/.test(resource.fsPath);
    }
  }
  removeTrailingPathSeparator(resource, sep2 = sep$2) {
    if (hasTrailingPathSeparator(resource, sep2)) {
      return resource.with({ path: resource.path.substr(0, resource.path.length - 1) });
    }
    return resource;
  }
  addTrailingPathSeparator(resource, sep2 = sep$2) {
    let isRootSep = false;
    if (resource.scheme === Schemas.file) {
      const fsp = originalFSPath(resource);
      isRootSep = fsp !== void 0 && fsp.length === getRoot(fsp).length && fsp[fsp.length - 1] === sep2;
    } else {
      sep2 = "/";
      const p2 = resource.path;
      isRootSep = p2.length === 1 && p2.charCodeAt(p2.length - 1) === 47;
    }
    if (!isRootSep && !hasTrailingPathSeparator(resource, sep2)) {
      return resource.with({ path: resource.path + "/" });
    }
    return resource;
  }
}
const extUri = new ExtUri(() => false);
const isEqual = extUri.isEqual.bind(extUri);
extUri.isEqualOrParent.bind(extUri);
extUri.getComparisonKey.bind(extUri);
const basenameOrAuthority = extUri.basenameOrAuthority.bind(extUri);
const basename$1 = extUri.basename.bind(extUri);
const extname$1 = extUri.extname.bind(extUri);
const dirname$3 = extUri.dirname.bind(extUri);
const joinPath = extUri.joinPath.bind(extUri);
const normalizePath = extUri.normalizePath.bind(extUri);
const relativePath = extUri.relativePath.bind(extUri);
const resolvePath = extUri.resolvePath.bind(extUri);
extUri.isAbsolutePath.bind(extUri);
const isEqualAuthority = extUri.isEqualAuthority.bind(extUri);
const hasTrailingPathSeparator = extUri.hasTrailingPathSeparator.bind(extUri);
extUri.removeTrailingPathSeparator.bind(extUri);
extUri.addTrailingPathSeparator.bind(extUri);
var DataUri;
(function(DataUri2) {
  DataUri2.META_DATA_LABEL = "label";
  DataUri2.META_DATA_DESCRIPTION = "description";
  DataUri2.META_DATA_SIZE = "size";
  DataUri2.META_DATA_MIME = "mime";
  function parseMetaData(dataUri) {
    const metadata = /* @__PURE__ */ new Map();
    const meta = dataUri.path.substring(dataUri.path.indexOf(";") + 1, dataUri.path.lastIndexOf(";"));
    meta.split(";").forEach((property) => {
      const [key, value] = property.split(":");
      if (key && value) {
        metadata.set(key, value);
      }
    });
    const mime = dataUri.path.substring(0, dataUri.path.indexOf(";"));
    if (mime) {
      metadata.set(DataUri2.META_DATA_MIME, mime);
    }
    return metadata;
  }
  DataUri2.parseMetaData = parseMetaData;
})(DataUri || (DataUri = {}));
function uriGetComparisonKey(resource) {
  return resource.toString();
}
class SingleModelEditStackData {
  static create(model, beforeCursorState) {
    const alternativeVersionId = model.getAlternativeVersionId();
    const eol = getModelEOL(model);
    return new SingleModelEditStackData(alternativeVersionId, alternativeVersionId, eol, eol, beforeCursorState, beforeCursorState, []);
  }
  constructor(beforeVersionId, afterVersionId, beforeEOL, afterEOL, beforeCursorState, afterCursorState, changes) {
    this.beforeVersionId = beforeVersionId;
    this.afterVersionId = afterVersionId;
    this.beforeEOL = beforeEOL;
    this.afterEOL = afterEOL;
    this.beforeCursorState = beforeCursorState;
    this.afterCursorState = afterCursorState;
    this.changes = changes;
  }
  append(model, textChanges, afterEOL, afterVersionId, afterCursorState) {
    if (textChanges.length > 0) {
      this.changes = compressConsecutiveTextChanges(this.changes, textChanges);
    }
    this.afterEOL = afterEOL;
    this.afterVersionId = afterVersionId;
    this.afterCursorState = afterCursorState;
  }
  static _writeSelectionsSize(selections2) {
    return 4 + 4 * 4 * (selections2 ? selections2.length : 0);
  }
  static _writeSelections(b, selections2, offset) {
    writeUInt32BE(b, selections2 ? selections2.length : 0, offset);
    offset += 4;
    if (selections2) {
      for (const selection of selections2) {
        writeUInt32BE(b, selection.selectionStartLineNumber, offset);
        offset += 4;
        writeUInt32BE(b, selection.selectionStartColumn, offset);
        offset += 4;
        writeUInt32BE(b, selection.positionLineNumber, offset);
        offset += 4;
        writeUInt32BE(b, selection.positionColumn, offset);
        offset += 4;
      }
    }
    return offset;
  }
  static _readSelections(b, offset, dest) {
    const count = readUInt32BE(b, offset);
    offset += 4;
    for (let i = 0; i < count; i++) {
      const selectionStartLineNumber = readUInt32BE(b, offset);
      offset += 4;
      const selectionStartColumn = readUInt32BE(b, offset);
      offset += 4;
      const positionLineNumber = readUInt32BE(b, offset);
      offset += 4;
      const positionColumn = readUInt32BE(b, offset);
      offset += 4;
      dest.push(new Selection$1(selectionStartLineNumber, selectionStartColumn, positionLineNumber, positionColumn));
    }
    return offset;
  }
  serialize() {
    let necessarySize = 4 + 4 + 1 + 1 + SingleModelEditStackData._writeSelectionsSize(this.beforeCursorState) + SingleModelEditStackData._writeSelectionsSize(this.afterCursorState) + 4;
    for (const change of this.changes) {
      necessarySize += change.writeSize();
    }
    const b = new Uint8Array(necessarySize);
    let offset = 0;
    writeUInt32BE(b, this.beforeVersionId, offset);
    offset += 4;
    writeUInt32BE(b, this.afterVersionId, offset);
    offset += 4;
    writeUInt8(b, this.beforeEOL, offset);
    offset += 1;
    writeUInt8(b, this.afterEOL, offset);
    offset += 1;
    offset = SingleModelEditStackData._writeSelections(b, this.beforeCursorState, offset);
    offset = SingleModelEditStackData._writeSelections(b, this.afterCursorState, offset);
    writeUInt32BE(b, this.changes.length, offset);
    offset += 4;
    for (const change of this.changes) {
      offset = change.write(b, offset);
    }
    return b.buffer;
  }
  static deserialize(source) {
    const b = new Uint8Array(source);
    let offset = 0;
    const beforeVersionId = readUInt32BE(b, offset);
    offset += 4;
    const afterVersionId = readUInt32BE(b, offset);
    offset += 4;
    const beforeEOL = readUInt8(b, offset);
    offset += 1;
    const afterEOL = readUInt8(b, offset);
    offset += 1;
    const beforeCursorState = [];
    offset = SingleModelEditStackData._readSelections(b, offset, beforeCursorState);
    const afterCursorState = [];
    offset = SingleModelEditStackData._readSelections(b, offset, afterCursorState);
    const changeCount = readUInt32BE(b, offset);
    offset += 4;
    const changes = [];
    for (let i = 0; i < changeCount; i++) {
      offset = TextChange.read(b, offset, changes);
    }
    return new SingleModelEditStackData(beforeVersionId, afterVersionId, beforeEOL, afterEOL, beforeCursorState, afterCursorState, changes);
  }
}
class SingleModelEditStackElement {
  get type() {
    return 0;
  }
  get resource() {
    if (URI.isUri(this.model)) {
      return this.model;
    }
    return this.model.uri;
  }
  constructor(label, code, model, beforeCursorState) {
    this.label = label;
    this.code = code;
    this.model = model;
    this._data = SingleModelEditStackData.create(model, beforeCursorState);
  }
  toString() {
    const data = this._data instanceof SingleModelEditStackData ? this._data : SingleModelEditStackData.deserialize(this._data);
    return data.changes.map((change) => change.toString()).join(", ");
  }
  matchesResource(resource) {
    const uri = URI.isUri(this.model) ? this.model : this.model.uri;
    return uri.toString() === resource.toString();
  }
  setModel(model) {
    this.model = model;
  }
  canAppend(model) {
    return this.model === model && this._data instanceof SingleModelEditStackData;
  }
  append(model, textChanges, afterEOL, afterVersionId, afterCursorState) {
    if (this._data instanceof SingleModelEditStackData) {
      this._data.append(model, textChanges, afterEOL, afterVersionId, afterCursorState);
    }
  }
  close() {
    if (this._data instanceof SingleModelEditStackData) {
      this._data = this._data.serialize();
    }
  }
  open() {
    if (!(this._data instanceof SingleModelEditStackData)) {
      this._data = SingleModelEditStackData.deserialize(this._data);
    }
  }
  undo() {
    if (URI.isUri(this.model)) {
      throw new Error(`Invalid SingleModelEditStackElement`);
    }
    if (this._data instanceof SingleModelEditStackData) {
      this._data = this._data.serialize();
    }
    const data = SingleModelEditStackData.deserialize(this._data);
    this.model._applyUndo(data.changes, data.beforeEOL, data.beforeVersionId, data.beforeCursorState);
  }
  redo() {
    if (URI.isUri(this.model)) {
      throw new Error(`Invalid SingleModelEditStackElement`);
    }
    if (this._data instanceof SingleModelEditStackData) {
      this._data = this._data.serialize();
    }
    const data = SingleModelEditStackData.deserialize(this._data);
    this.model._applyRedo(data.changes, data.afterEOL, data.afterVersionId, data.afterCursorState);
  }
  heapSize() {
    if (this._data instanceof SingleModelEditStackData) {
      this._data = this._data.serialize();
    }
    return this._data.byteLength + 168;
  }
}
class MultiModelEditStackElement {
  get resources() {
    return this._editStackElementsArr.map((editStackElement) => editStackElement.resource);
  }
  constructor(label, code, editStackElements) {
    this.label = label;
    this.code = code;
    this.type = 1;
    this._isOpen = true;
    this._editStackElementsArr = editStackElements.slice(0);
    this._editStackElementsMap = /* @__PURE__ */ new Map();
    for (const editStackElement of this._editStackElementsArr) {
      const key = uriGetComparisonKey(editStackElement.resource);
      this._editStackElementsMap.set(key, editStackElement);
    }
    this._delegate = null;
  }
  prepareUndoRedo() {
    if (this._delegate) {
      return this._delegate.prepareUndoRedo(this);
    }
  }
  matchesResource(resource) {
    const key = uriGetComparisonKey(resource);
    return this._editStackElementsMap.has(key);
  }
  setModel(model) {
    const key = uriGetComparisonKey(URI.isUri(model) ? model : model.uri);
    if (this._editStackElementsMap.has(key)) {
      this._editStackElementsMap.get(key).setModel(model);
    }
  }
  canAppend(model) {
    if (!this._isOpen) {
      return false;
    }
    const key = uriGetComparisonKey(model.uri);
    if (this._editStackElementsMap.has(key)) {
      const editStackElement = this._editStackElementsMap.get(key);
      return editStackElement.canAppend(model);
    }
    return false;
  }
  append(model, textChanges, afterEOL, afterVersionId, afterCursorState) {
    const key = uriGetComparisonKey(model.uri);
    const editStackElement = this._editStackElementsMap.get(key);
    editStackElement.append(model, textChanges, afterEOL, afterVersionId, afterCursorState);
  }
  close() {
    this._isOpen = false;
  }
  open() {
  }
  undo() {
    this._isOpen = false;
    for (const editStackElement of this._editStackElementsArr) {
      editStackElement.undo();
    }
  }
  redo() {
    for (const editStackElement of this._editStackElementsArr) {
      editStackElement.redo();
    }
  }
  heapSize(resource) {
    const key = uriGetComparisonKey(resource);
    if (this._editStackElementsMap.has(key)) {
      const editStackElement = this._editStackElementsMap.get(key);
      return editStackElement.heapSize();
    }
    return 0;
  }
  split() {
    return this._editStackElementsArr;
  }
  toString() {
    const result2 = [];
    for (const editStackElement of this._editStackElementsArr) {
      result2.push(`${basename$1(editStackElement.resource)}: ${editStackElement}`);
    }
    return `{${result2.join(", ")}}`;
  }
}
function getModelEOL(model) {
  const eol = model.getEOL();
  if (eol === "\n") {
    return 0;
  } else {
    return 1;
  }
}
function isEditStackElement(element) {
  if (!element) {
    return false;
  }
  return element instanceof SingleModelEditStackElement || element instanceof MultiModelEditStackElement;
}
class EditStack {
  constructor(model, undoRedoService) {
    this._model = model;
    this._undoRedoService = undoRedoService;
  }
  pushStackElement() {
    const lastElement = this._undoRedoService.getLastElement(this._model.uri);
    if (isEditStackElement(lastElement)) {
      lastElement.close();
    }
  }
  popStackElement() {
    const lastElement = this._undoRedoService.getLastElement(this._model.uri);
    if (isEditStackElement(lastElement)) {
      lastElement.open();
    }
  }
  clear() {
    this._undoRedoService.removeElements(this._model.uri);
  }
  _getOrCreateEditStackElement(beforeCursorState, group2) {
    const lastElement = this._undoRedoService.getLastElement(this._model.uri);
    if (isEditStackElement(lastElement) && lastElement.canAppend(this._model)) {
      return lastElement;
    }
    const newElement = new SingleModelEditStackElement(localize("edit", "Typing"), "undoredo.textBufferEdit", this._model, beforeCursorState);
    this._undoRedoService.pushElement(newElement, group2);
    return newElement;
  }
  pushEOL(eol) {
    const editStackElement = this._getOrCreateEditStackElement(null, void 0);
    this._model.setEOL(eol);
    editStackElement.append(this._model, [], getModelEOL(this._model), this._model.getAlternativeVersionId(), null);
  }
  pushEditOperation(beforeCursorState, editOperations, cursorStateComputer, group2) {
    const editStackElement = this._getOrCreateEditStackElement(beforeCursorState, group2);
    const inverseEditOperations = this._model.applyEdits(editOperations, true);
    const afterCursorState = EditStack._computeCursorState(cursorStateComputer, inverseEditOperations);
    const textChanges = inverseEditOperations.map((op, index) => ({ index, textChange: op.textChange }));
    textChanges.sort((a, b) => {
      if (a.textChange.oldPosition === b.textChange.oldPosition) {
        return a.index - b.index;
      }
      return a.textChange.oldPosition - b.textChange.oldPosition;
    });
    editStackElement.append(this._model, textChanges.map((op) => op.textChange), getModelEOL(this._model), this._model.getAlternativeVersionId(), afterCursorState);
    return afterCursorState;
  }
  static _computeCursorState(cursorStateComputer, inverseEditOperations) {
    try {
      return cursorStateComputer ? cursorStateComputer(inverseEditOperations) : null;
    } catch (e) {
      onUnexpectedError(e);
      return null;
    }
  }
}
class SpacesDiffResult {
  constructor() {
    this.spacesDiff = 0;
    this.looksLikeAlignment = false;
  }
}
function spacesDiff(a, aLength, b, bLength, result2) {
  result2.spacesDiff = 0;
  result2.looksLikeAlignment = false;
  let i;
  for (i = 0; i < aLength && i < bLength; i++) {
    const aCharCode = a.charCodeAt(i);
    const bCharCode = b.charCodeAt(i);
    if (aCharCode !== bCharCode) {
      break;
    }
  }
  let aSpacesCnt = 0, aTabsCount = 0;
  for (let j = i; j < aLength; j++) {
    const aCharCode = a.charCodeAt(j);
    if (aCharCode === 32) {
      aSpacesCnt++;
    } else {
      aTabsCount++;
    }
  }
  let bSpacesCnt = 0, bTabsCount = 0;
  for (let j = i; j < bLength; j++) {
    const bCharCode = b.charCodeAt(j);
    if (bCharCode === 32) {
      bSpacesCnt++;
    } else {
      bTabsCount++;
    }
  }
  if (aSpacesCnt > 0 && aTabsCount > 0) {
    return;
  }
  if (bSpacesCnt > 0 && bTabsCount > 0) {
    return;
  }
  const tabsDiff = Math.abs(aTabsCount - bTabsCount);
  const spacesDiff2 = Math.abs(aSpacesCnt - bSpacesCnt);
  if (tabsDiff === 0) {
    result2.spacesDiff = spacesDiff2;
    if (spacesDiff2 > 0 && 0 <= bSpacesCnt - 1 && bSpacesCnt - 1 < a.length && bSpacesCnt < b.length) {
      if (b.charCodeAt(bSpacesCnt) !== 32 && a.charCodeAt(bSpacesCnt - 1) === 32) {
        if (a.charCodeAt(a.length - 1) === 44) {
          result2.looksLikeAlignment = true;
        }
      }
    }
    return;
  }
  if (spacesDiff2 % tabsDiff === 0) {
    result2.spacesDiff = spacesDiff2 / tabsDiff;
    return;
  }
}
function guessIndentation(source, defaultTabSize, defaultInsertSpaces) {
  const linesCount = Math.min(source.getLineCount(), 1e4);
  let linesIndentedWithTabsCount = 0;
  let linesIndentedWithSpacesCount = 0;
  let previousLineText = "";
  let previousLineIndentation = 0;
  const ALLOWED_TAB_SIZE_GUESSES = [2, 4, 6, 8, 3, 5, 7];
  const MAX_ALLOWED_TAB_SIZE_GUESS = 8;
  const spacesDiffCount = [0, 0, 0, 0, 0, 0, 0, 0, 0];
  const tmp = new SpacesDiffResult();
  for (let lineNumber = 1; lineNumber <= linesCount; lineNumber++) {
    const currentLineLength = source.getLineLength(lineNumber);
    const currentLineText = source.getLineContent(lineNumber);
    const useCurrentLineText = currentLineLength <= 65536;
    let currentLineHasContent = false;
    let currentLineIndentation = 0;
    let currentLineSpacesCount = 0;
    let currentLineTabsCount = 0;
    for (let j = 0, lenJ = currentLineLength; j < lenJ; j++) {
      const charCode = useCurrentLineText ? currentLineText.charCodeAt(j) : source.getLineCharCode(lineNumber, j);
      if (charCode === 9) {
        currentLineTabsCount++;
      } else if (charCode === 32) {
        currentLineSpacesCount++;
      } else {
        currentLineHasContent = true;
        currentLineIndentation = j;
        break;
      }
    }
    if (!currentLineHasContent) {
      continue;
    }
    if (currentLineTabsCount > 0) {
      linesIndentedWithTabsCount++;
    } else if (currentLineSpacesCount > 1) {
      linesIndentedWithSpacesCount++;
    }
    spacesDiff(previousLineText, previousLineIndentation, currentLineText, currentLineIndentation, tmp);
    if (tmp.looksLikeAlignment) {
      if (!(defaultInsertSpaces && defaultTabSize === tmp.spacesDiff)) {
        continue;
      }
    }
    const currentSpacesDiff = tmp.spacesDiff;
    if (currentSpacesDiff <= MAX_ALLOWED_TAB_SIZE_GUESS) {
      spacesDiffCount[currentSpacesDiff]++;
    }
    previousLineText = currentLineText;
    previousLineIndentation = currentLineIndentation;
  }
  let insertSpaces = defaultInsertSpaces;
  if (linesIndentedWithTabsCount !== linesIndentedWithSpacesCount) {
    insertSpaces = linesIndentedWithTabsCount < linesIndentedWithSpacesCount;
  }
  let tabSize = defaultTabSize;
  if (insertSpaces) {
    let tabSizeScore = insertSpaces ? 0 : 0.1 * linesCount;
    ALLOWED_TAB_SIZE_GUESSES.forEach((possibleTabSize) => {
      const possibleTabSizeScore = spacesDiffCount[possibleTabSize];
      if (possibleTabSizeScore > tabSizeScore) {
        tabSizeScore = possibleTabSizeScore;
        tabSize = possibleTabSize;
      }
    });
    if (tabSize === 4 && spacesDiffCount[4] > 0 && spacesDiffCount[2] > 0 && spacesDiffCount[2] >= spacesDiffCount[4] / 2) {
      tabSize = 2;
    }
  }
  return {
    insertSpaces,
    tabSize
  };
}
function getNodeColor(node2) {
  return (node2.metadata & 1) >>> 0;
}
function setNodeColor(node2, color) {
  node2.metadata = node2.metadata & 254 | color << 0;
}
function getNodeIsVisited(node2) {
  return (node2.metadata & 2) >>> 1 === 1;
}
function setNodeIsVisited(node2, value) {
  node2.metadata = node2.metadata & 253 | (value ? 1 : 0) << 1;
}
function getNodeIsForValidation(node2) {
  return (node2.metadata & 4) >>> 2 === 1;
}
function setNodeIsForValidation(node2, value) {
  node2.metadata = node2.metadata & 251 | (value ? 1 : 0) << 2;
}
function getNodeIsInGlyphMargin(node2) {
  return (node2.metadata & 64) >>> 6 === 1;
}
function setNodeIsInGlyphMargin(node2, value) {
  node2.metadata = node2.metadata & 191 | (value ? 1 : 0) << 6;
}
function getNodeStickiness(node2) {
  return (node2.metadata & 24) >>> 3;
}
function _setNodeStickiness(node2, stickiness) {
  node2.metadata = node2.metadata & 231 | stickiness << 3;
}
function getCollapseOnReplaceEdit(node2) {
  return (node2.metadata & 32) >>> 5 === 1;
}
function setCollapseOnReplaceEdit(node2, value) {
  node2.metadata = node2.metadata & 223 | (value ? 1 : 0) << 5;
}
class IntervalNode {
  constructor(id3, start, end) {
    this.metadata = 0;
    this.parent = this;
    this.left = this;
    this.right = this;
    setNodeColor(
      this,
      1
      /* NodeColor.Red */
    );
    this.start = start;
    this.end = end;
    this.delta = 0;
    this.maxEnd = end;
    this.id = id3;
    this.ownerId = 0;
    this.options = null;
    setNodeIsForValidation(this, false);
    setNodeIsInGlyphMargin(this, false);
    _setNodeStickiness(
      this,
      1
      /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
    );
    setCollapseOnReplaceEdit(this, false);
    this.cachedVersionId = 0;
    this.cachedAbsoluteStart = start;
    this.cachedAbsoluteEnd = end;
    this.range = null;
    setNodeIsVisited(this, false);
  }
  reset(versionId, start, end, range2) {
    this.start = start;
    this.end = end;
    this.maxEnd = end;
    this.cachedVersionId = versionId;
    this.cachedAbsoluteStart = start;
    this.cachedAbsoluteEnd = end;
    this.range = range2;
  }
  setOptions(options) {
    this.options = options;
    const className3 = this.options.className;
    setNodeIsForValidation(this, className3 === "squiggly-error" || className3 === "squiggly-warning" || className3 === "squiggly-info");
    setNodeIsInGlyphMargin(this, this.options.glyphMarginClassName !== null);
    _setNodeStickiness(this, this.options.stickiness);
    setCollapseOnReplaceEdit(this, this.options.collapseOnReplaceEdit);
  }
  setCachedOffsets(absoluteStart, absoluteEnd, cachedVersionId) {
    if (this.cachedVersionId !== cachedVersionId) {
      this.range = null;
    }
    this.cachedVersionId = cachedVersionId;
    this.cachedAbsoluteStart = absoluteStart;
    this.cachedAbsoluteEnd = absoluteEnd;
  }
  detach() {
    this.parent = null;
    this.left = null;
    this.right = null;
  }
}
const SENTINEL$1 = new IntervalNode(null, 0, 0);
SENTINEL$1.parent = SENTINEL$1;
SENTINEL$1.left = SENTINEL$1;
SENTINEL$1.right = SENTINEL$1;
setNodeColor(
  SENTINEL$1,
  0
  /* NodeColor.Black */
);
class IntervalTree {
  constructor() {
    this.root = SENTINEL$1;
    this.requestNormalizeDelta = false;
  }
  intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations) {
    if (this.root === SENTINEL$1) {
      return [];
    }
    return intervalSearch(this, start, end, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
  }
  search(filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations) {
    if (this.root === SENTINEL$1) {
      return [];
    }
    return search(this, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
  }
  /**
   * Will not set `cachedAbsoluteStart` nor `cachedAbsoluteEnd` on the returned nodes!
   */
  collectNodesFromOwner(ownerId) {
    return collectNodesFromOwner(this, ownerId);
  }
  /**
   * Will not set `cachedAbsoluteStart` nor `cachedAbsoluteEnd` on the returned nodes!
   */
  collectNodesPostOrder() {
    return collectNodesPostOrder(this);
  }
  insert(node2) {
    rbTreeInsert(this, node2);
    this._normalizeDeltaIfNecessary();
  }
  delete(node2) {
    rbTreeDelete(this, node2);
    this._normalizeDeltaIfNecessary();
  }
  resolveNode(node2, cachedVersionId) {
    const initialNode = node2;
    let delta = 0;
    while (node2 !== this.root) {
      if (node2 === node2.parent.right) {
        delta += node2.parent.delta;
      }
      node2 = node2.parent;
    }
    const nodeStart = initialNode.start + delta;
    const nodeEnd = initialNode.end + delta;
    initialNode.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId);
  }
  acceptReplace(offset, length2, textLength, forceMoveMarkers) {
    const nodesOfInterest = searchForEditing(this, offset, offset + length2);
    for (let i = 0, len = nodesOfInterest.length; i < len; i++) {
      const node2 = nodesOfInterest[i];
      rbTreeDelete(this, node2);
    }
    this._normalizeDeltaIfNecessary();
    noOverlapReplace(this, offset, offset + length2, textLength);
    this._normalizeDeltaIfNecessary();
    for (let i = 0, len = nodesOfInterest.length; i < len; i++) {
      const node2 = nodesOfInterest[i];
      node2.start = node2.cachedAbsoluteStart;
      node2.end = node2.cachedAbsoluteEnd;
      nodeAcceptEdit(node2, offset, offset + length2, textLength, forceMoveMarkers);
      node2.maxEnd = node2.end;
      rbTreeInsert(this, node2);
    }
    this._normalizeDeltaIfNecessary();
  }
  _normalizeDeltaIfNecessary() {
    if (!this.requestNormalizeDelta) {
      return;
    }
    this.requestNormalizeDelta = false;
    normalizeDelta(this);
  }
}
function normalizeDelta(T) {
  let node2 = T.root;
  let delta = 0;
  while (node2 !== SENTINEL$1) {
    if (node2.left !== SENTINEL$1 && !getNodeIsVisited(node2.left)) {
      node2 = node2.left;
      continue;
    }
    if (node2.right !== SENTINEL$1 && !getNodeIsVisited(node2.right)) {
      delta += node2.delta;
      node2 = node2.right;
      continue;
    }
    node2.start = delta + node2.start;
    node2.end = delta + node2.end;
    node2.delta = 0;
    recomputeMaxEnd(node2);
    setNodeIsVisited(node2, true);
    setNodeIsVisited(node2.left, false);
    setNodeIsVisited(node2.right, false);
    if (node2 === node2.parent.right) {
      delta -= node2.parent.delta;
    }
    node2 = node2.parent;
  }
  setNodeIsVisited(T.root, false);
}
function adjustMarkerBeforeColumn(markerOffset, markerStickToPreviousCharacter, checkOffset2, moveSemantics) {
  if (markerOffset < checkOffset2) {
    return true;
  }
  if (markerOffset > checkOffset2) {
    return false;
  }
  if (moveSemantics === 1) {
    return false;
  }
  if (moveSemantics === 2) {
    return true;
  }
  return markerStickToPreviousCharacter;
}
function nodeAcceptEdit(node2, start, end, textLength, forceMoveMarkers) {
  const nodeStickiness = getNodeStickiness(node2);
  const startStickToPreviousCharacter = nodeStickiness === 0 || nodeStickiness === 2;
  const endStickToPreviousCharacter = nodeStickiness === 1 || nodeStickiness === 2;
  const deletingCnt = end - start;
  const insertingCnt = textLength;
  const commonLength = Math.min(deletingCnt, insertingCnt);
  const nodeStart = node2.start;
  let startDone = false;
  const nodeEnd = node2.end;
  let endDone = false;
  if (start <= nodeStart && nodeEnd <= end && getCollapseOnReplaceEdit(node2)) {
    node2.start = start;
    startDone = true;
    node2.end = start;
    endDone = true;
  }
  {
    const moveSemantics = forceMoveMarkers ? 1 : deletingCnt > 0 ? 2 : 0;
    if (!startDone && adjustMarkerBeforeColumn(nodeStart, startStickToPreviousCharacter, start, moveSemantics)) {
      startDone = true;
    }
    if (!endDone && adjustMarkerBeforeColumn(nodeEnd, endStickToPreviousCharacter, start, moveSemantics)) {
      endDone = true;
    }
  }
  if (commonLength > 0 && !forceMoveMarkers) {
    const moveSemantics = deletingCnt > insertingCnt ? 2 : 0;
    if (!startDone && adjustMarkerBeforeColumn(nodeStart, startStickToPreviousCharacter, start + commonLength, moveSemantics)) {
      startDone = true;
    }
    if (!endDone && adjustMarkerBeforeColumn(nodeEnd, endStickToPreviousCharacter, start + commonLength, moveSemantics)) {
      endDone = true;
    }
  }
  {
    const moveSemantics = forceMoveMarkers ? 1 : 0;
    if (!startDone && adjustMarkerBeforeColumn(nodeStart, startStickToPreviousCharacter, end, moveSemantics)) {
      node2.start = start + insertingCnt;
      startDone = true;
    }
    if (!endDone && adjustMarkerBeforeColumn(nodeEnd, endStickToPreviousCharacter, end, moveSemantics)) {
      node2.end = start + insertingCnt;
      endDone = true;
    }
  }
  const deltaColumn = insertingCnt - deletingCnt;
  if (!startDone) {
    node2.start = Math.max(0, nodeStart + deltaColumn);
  }
  if (!endDone) {
    node2.end = Math.max(0, nodeEnd + deltaColumn);
  }
  if (node2.start > node2.end) {
    node2.end = node2.start;
  }
}
function searchForEditing(T, start, end) {
  let node2 = T.root;
  let delta = 0;
  let nodeMaxEnd = 0;
  let nodeStart = 0;
  let nodeEnd = 0;
  const result2 = [];
  let resultLen = 0;
  while (node2 !== SENTINEL$1) {
    if (getNodeIsVisited(node2)) {
      setNodeIsVisited(node2.left, false);
      setNodeIsVisited(node2.right, false);
      if (node2 === node2.parent.right) {
        delta -= node2.parent.delta;
      }
      node2 = node2.parent;
      continue;
    }
    if (!getNodeIsVisited(node2.left)) {
      nodeMaxEnd = delta + node2.maxEnd;
      if (nodeMaxEnd < start) {
        setNodeIsVisited(node2, true);
        continue;
      }
      if (node2.left !== SENTINEL$1) {
        node2 = node2.left;
        continue;
      }
    }
    nodeStart = delta + node2.start;
    if (nodeStart > end) {
      setNodeIsVisited(node2, true);
      continue;
    }
    nodeEnd = delta + node2.end;
    if (nodeEnd >= start) {
      node2.setCachedOffsets(nodeStart, nodeEnd, 0);
      result2[resultLen++] = node2;
    }
    setNodeIsVisited(node2, true);
    if (node2.right !== SENTINEL$1 && !getNodeIsVisited(node2.right)) {
      delta += node2.delta;
      node2 = node2.right;
      continue;
    }
  }
  setNodeIsVisited(T.root, false);
  return result2;
}
function noOverlapReplace(T, start, end, textLength) {
  let node2 = T.root;
  let delta = 0;
  let nodeMaxEnd = 0;
  let nodeStart = 0;
  const editDelta = textLength - (end - start);
  while (node2 !== SENTINEL$1) {
    if (getNodeIsVisited(node2)) {
      setNodeIsVisited(node2.left, false);
      setNodeIsVisited(node2.right, false);
      if (node2 === node2.parent.right) {
        delta -= node2.parent.delta;
      }
      recomputeMaxEnd(node2);
      node2 = node2.parent;
      continue;
    }
    if (!getNodeIsVisited(node2.left)) {
      nodeMaxEnd = delta + node2.maxEnd;
      if (nodeMaxEnd < start) {
        setNodeIsVisited(node2, true);
        continue;
      }
      if (node2.left !== SENTINEL$1) {
        node2 = node2.left;
        continue;
      }
    }
    nodeStart = delta + node2.start;
    if (nodeStart > end) {
      node2.start += editDelta;
      node2.end += editDelta;
      node2.delta += editDelta;
      if (node2.delta < -1073741824 || node2.delta > 1073741824) {
        T.requestNormalizeDelta = true;
      }
      setNodeIsVisited(node2, true);
      continue;
    }
    setNodeIsVisited(node2, true);
    if (node2.right !== SENTINEL$1 && !getNodeIsVisited(node2.right)) {
      delta += node2.delta;
      node2 = node2.right;
      continue;
    }
  }
  setNodeIsVisited(T.root, false);
}
function collectNodesFromOwner(T, ownerId) {
  let node2 = T.root;
  const result2 = [];
  let resultLen = 0;
  while (node2 !== SENTINEL$1) {
    if (getNodeIsVisited(node2)) {
      setNodeIsVisited(node2.left, false);
      setNodeIsVisited(node2.right, false);
      node2 = node2.parent;
      continue;
    }
    if (node2.left !== SENTINEL$1 && !getNodeIsVisited(node2.left)) {
      node2 = node2.left;
      continue;
    }
    if (node2.ownerId === ownerId) {
      result2[resultLen++] = node2;
    }
    setNodeIsVisited(node2, true);
    if (node2.right !== SENTINEL$1 && !getNodeIsVisited(node2.right)) {
      node2 = node2.right;
      continue;
    }
  }
  setNodeIsVisited(T.root, false);
  return result2;
}
function collectNodesPostOrder(T) {
  let node2 = T.root;
  const result2 = [];
  let resultLen = 0;
  while (node2 !== SENTINEL$1) {
    if (getNodeIsVisited(node2)) {
      setNodeIsVisited(node2.left, false);
      setNodeIsVisited(node2.right, false);
      node2 = node2.parent;
      continue;
    }
    if (node2.left !== SENTINEL$1 && !getNodeIsVisited(node2.left)) {
      node2 = node2.left;
      continue;
    }
    if (node2.right !== SENTINEL$1 && !getNodeIsVisited(node2.right)) {
      node2 = node2.right;
      continue;
    }
    result2[resultLen++] = node2;
    setNodeIsVisited(node2, true);
  }
  setNodeIsVisited(T.root, false);
  return result2;
}
function search(T, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations) {
  let node2 = T.root;
  let delta = 0;
  let nodeStart = 0;
  let nodeEnd = 0;
  const result2 = [];
  let resultLen = 0;
  while (node2 !== SENTINEL$1) {
    if (getNodeIsVisited(node2)) {
      setNodeIsVisited(node2.left, false);
      setNodeIsVisited(node2.right, false);
      if (node2 === node2.parent.right) {
        delta -= node2.parent.delta;
      }
      node2 = node2.parent;
      continue;
    }
    if (node2.left !== SENTINEL$1 && !getNodeIsVisited(node2.left)) {
      node2 = node2.left;
      continue;
    }
    nodeStart = delta + node2.start;
    nodeEnd = delta + node2.end;
    node2.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId);
    let include = true;
    if (filterOwnerId && node2.ownerId && node2.ownerId !== filterOwnerId) {
      include = false;
    }
    if (filterOutValidation && getNodeIsForValidation(node2)) {
      include = false;
    }
    if (onlyMarginDecorations && !getNodeIsInGlyphMargin(node2)) {
      include = false;
    }
    if (include) {
      result2[resultLen++] = node2;
    }
    setNodeIsVisited(node2, true);
    if (node2.right !== SENTINEL$1 && !getNodeIsVisited(node2.right)) {
      delta += node2.delta;
      node2 = node2.right;
      continue;
    }
  }
  setNodeIsVisited(T.root, false);
  return result2;
}
function intervalSearch(T, intervalStart, intervalEnd, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations) {
  let node2 = T.root;
  let delta = 0;
  let nodeMaxEnd = 0;
  let nodeStart = 0;
  let nodeEnd = 0;
  const result2 = [];
  let resultLen = 0;
  while (node2 !== SENTINEL$1) {
    if (getNodeIsVisited(node2)) {
      setNodeIsVisited(node2.left, false);
      setNodeIsVisited(node2.right, false);
      if (node2 === node2.parent.right) {
        delta -= node2.parent.delta;
      }
      node2 = node2.parent;
      continue;
    }
    if (!getNodeIsVisited(node2.left)) {
      nodeMaxEnd = delta + node2.maxEnd;
      if (nodeMaxEnd < intervalStart) {
        setNodeIsVisited(node2, true);
        continue;
      }
      if (node2.left !== SENTINEL$1) {
        node2 = node2.left;
        continue;
      }
    }
    nodeStart = delta + node2.start;
    if (nodeStart > intervalEnd) {
      setNodeIsVisited(node2, true);
      continue;
    }
    nodeEnd = delta + node2.end;
    if (nodeEnd >= intervalStart) {
      node2.setCachedOffsets(nodeStart, nodeEnd, cachedVersionId);
      let include = true;
      if (filterOwnerId && node2.ownerId && node2.ownerId !== filterOwnerId) {
        include = false;
      }
      if (filterOutValidation && getNodeIsForValidation(node2)) {
        include = false;
      }
      if (onlyMarginDecorations && !getNodeIsInGlyphMargin(node2)) {
        include = false;
      }
      if (include) {
        result2[resultLen++] = node2;
      }
    }
    setNodeIsVisited(node2, true);
    if (node2.right !== SENTINEL$1 && !getNodeIsVisited(node2.right)) {
      delta += node2.delta;
      node2 = node2.right;
      continue;
    }
  }
  setNodeIsVisited(T.root, false);
  return result2;
}
function rbTreeInsert(T, newNode) {
  if (T.root === SENTINEL$1) {
    newNode.parent = SENTINEL$1;
    newNode.left = SENTINEL$1;
    newNode.right = SENTINEL$1;
    setNodeColor(
      newNode,
      0
      /* NodeColor.Black */
    );
    T.root = newNode;
    return T.root;
  }
  treeInsert(T, newNode);
  recomputeMaxEndWalkToRoot(newNode.parent);
  let x = newNode;
  while (x !== T.root && getNodeColor(x.parent) === 1) {
    if (x.parent === x.parent.parent.left) {
      const y = x.parent.parent.right;
      if (getNodeColor(y) === 1) {
        setNodeColor(
          x.parent,
          0
          /* NodeColor.Black */
        );
        setNodeColor(
          y,
          0
          /* NodeColor.Black */
        );
        setNodeColor(
          x.parent.parent,
          1
          /* NodeColor.Red */
        );
        x = x.parent.parent;
      } else {
        if (x === x.parent.right) {
          x = x.parent;
          leftRotate$2(T, x);
        }
        setNodeColor(
          x.parent,
          0
          /* NodeColor.Black */
        );
        setNodeColor(
          x.parent.parent,
          1
          /* NodeColor.Red */
        );
        rightRotate$1(T, x.parent.parent);
      }
    } else {
      const y = x.parent.parent.left;
      if (getNodeColor(y) === 1) {
        setNodeColor(
          x.parent,
          0
          /* NodeColor.Black */
        );
        setNodeColor(
          y,
          0
          /* NodeColor.Black */
        );
        setNodeColor(
          x.parent.parent,
          1
          /* NodeColor.Red */
        );
        x = x.parent.parent;
      } else {
        if (x === x.parent.left) {
          x = x.parent;
          rightRotate$1(T, x);
        }
        setNodeColor(
          x.parent,
          0
          /* NodeColor.Black */
        );
        setNodeColor(
          x.parent.parent,
          1
          /* NodeColor.Red */
        );
        leftRotate$2(T, x.parent.parent);
      }
    }
  }
  setNodeColor(
    T.root,
    0
    /* NodeColor.Black */
  );
  return newNode;
}
function treeInsert(T, z) {
  let delta = 0;
  let x = T.root;
  const zAbsoluteStart = z.start;
  const zAbsoluteEnd = z.end;
  while (true) {
    const cmp3 = intervalCompare(zAbsoluteStart, zAbsoluteEnd, x.start + delta, x.end + delta);
    if (cmp3 < 0) {
      if (x.left === SENTINEL$1) {
        z.start -= delta;
        z.end -= delta;
        z.maxEnd -= delta;
        x.left = z;
        break;
      } else {
        x = x.left;
      }
    } else {
      if (x.right === SENTINEL$1) {
        z.start -= delta + x.delta;
        z.end -= delta + x.delta;
        z.maxEnd -= delta + x.delta;
        x.right = z;
        break;
      } else {
        delta += x.delta;
        x = x.right;
      }
    }
  }
  z.parent = x;
  z.left = SENTINEL$1;
  z.right = SENTINEL$1;
  setNodeColor(
    z,
    1
    /* NodeColor.Red */
  );
}
function rbTreeDelete(T, z) {
  let x;
  let y;
  if (z.left === SENTINEL$1) {
    x = z.right;
    y = z;
    x.delta += z.delta;
    if (x.delta < -1073741824 || x.delta > 1073741824) {
      T.requestNormalizeDelta = true;
    }
    x.start += z.delta;
    x.end += z.delta;
  } else if (z.right === SENTINEL$1) {
    x = z.left;
    y = z;
  } else {
    y = leftest$1(z.right);
    x = y.right;
    x.start += y.delta;
    x.end += y.delta;
    x.delta += y.delta;
    if (x.delta < -1073741824 || x.delta > 1073741824) {
      T.requestNormalizeDelta = true;
    }
    y.start += z.delta;
    y.end += z.delta;
    y.delta = z.delta;
    if (y.delta < -1073741824 || y.delta > 1073741824) {
      T.requestNormalizeDelta = true;
    }
  }
  if (y === T.root) {
    T.root = x;
    setNodeColor(
      x,
      0
      /* NodeColor.Black */
    );
    z.detach();
    resetSentinel$1();
    recomputeMaxEnd(x);
    T.root.parent = SENTINEL$1;
    return;
  }
  const yWasRed = getNodeColor(y) === 1;
  if (y === y.parent.left) {
    y.parent.left = x;
  } else {
    y.parent.right = x;
  }
  if (y === z) {
    x.parent = y.parent;
  } else {
    if (y.parent === z) {
      x.parent = y;
    } else {
      x.parent = y.parent;
    }
    y.left = z.left;
    y.right = z.right;
    y.parent = z.parent;
    setNodeColor(y, getNodeColor(z));
    if (z === T.root) {
      T.root = y;
    } else {
      if (z === z.parent.left) {
        z.parent.left = y;
      } else {
        z.parent.right = y;
      }
    }
    if (y.left !== SENTINEL$1) {
      y.left.parent = y;
    }
    if (y.right !== SENTINEL$1) {
      y.right.parent = y;
    }
  }
  z.detach();
  if (yWasRed) {
    recomputeMaxEndWalkToRoot(x.parent);
    if (y !== z) {
      recomputeMaxEndWalkToRoot(y);
      recomputeMaxEndWalkToRoot(y.parent);
    }
    resetSentinel$1();
    return;
  }
  recomputeMaxEndWalkToRoot(x);
  recomputeMaxEndWalkToRoot(x.parent);
  if (y !== z) {
    recomputeMaxEndWalkToRoot(y);
    recomputeMaxEndWalkToRoot(y.parent);
  }
  let w;
  while (x !== T.root && getNodeColor(x) === 0) {
    if (x === x.parent.left) {
      w = x.parent.right;
      if (getNodeColor(w) === 1) {
        setNodeColor(
          w,
          0
          /* NodeColor.Black */
        );
        setNodeColor(
          x.parent,
          1
          /* NodeColor.Red */
        );
        leftRotate$2(T, x.parent);
        w = x.parent.right;
      }
      if (getNodeColor(w.left) === 0 && getNodeColor(w.right) === 0) {
        setNodeColor(
          w,
          1
          /* NodeColor.Red */
        );
        x = x.parent;
      } else {
        if (getNodeColor(w.right) === 0) {
          setNodeColor(
            w.left,
            0
            /* NodeColor.Black */
          );
          setNodeColor(
            w,
            1
            /* NodeColor.Red */
          );
          rightRotate$1(T, w);
          w = x.parent.right;
        }
        setNodeColor(w, getNodeColor(x.parent));
        setNodeColor(
          x.parent,
          0
          /* NodeColor.Black */
        );
        setNodeColor(
          w.right,
          0
          /* NodeColor.Black */
        );
        leftRotate$2(T, x.parent);
        x = T.root;
      }
    } else {
      w = x.parent.left;
      if (getNodeColor(w) === 1) {
        setNodeColor(
          w,
          0
          /* NodeColor.Black */
        );
        setNodeColor(
          x.parent,
          1
          /* NodeColor.Red */
        );
        rightRotate$1(T, x.parent);
        w = x.parent.left;
      }
      if (getNodeColor(w.left) === 0 && getNodeColor(w.right) === 0) {
        setNodeColor(
          w,
          1
          /* NodeColor.Red */
        );
        x = x.parent;
      } else {
        if (getNodeColor(w.left) === 0) {
          setNodeColor(
            w.right,
            0
            /* NodeColor.Black */
          );
          setNodeColor(
            w,
            1
            /* NodeColor.Red */
          );
          leftRotate$2(T, w);
          w = x.parent.left;
        }
        setNodeColor(w, getNodeColor(x.parent));
        setNodeColor(
          x.parent,
          0
          /* NodeColor.Black */
        );
        setNodeColor(
          w.left,
          0
          /* NodeColor.Black */
        );
        rightRotate$1(T, x.parent);
        x = T.root;
      }
    }
  }
  setNodeColor(
    x,
    0
    /* NodeColor.Black */
  );
  resetSentinel$1();
}
function leftest$1(node2) {
  while (node2.left !== SENTINEL$1) {
    node2 = node2.left;
  }
  return node2;
}
function resetSentinel$1() {
  SENTINEL$1.parent = SENTINEL$1;
  SENTINEL$1.delta = 0;
  SENTINEL$1.start = 0;
  SENTINEL$1.end = 0;
}
function leftRotate$2(T, x) {
  const y = x.right;
  y.delta += x.delta;
  if (y.delta < -1073741824 || y.delta > 1073741824) {
    T.requestNormalizeDelta = true;
  }
  y.start += x.delta;
  y.end += x.delta;
  x.right = y.left;
  if (y.left !== SENTINEL$1) {
    y.left.parent = x;
  }
  y.parent = x.parent;
  if (x.parent === SENTINEL$1) {
    T.root = y;
  } else if (x === x.parent.left) {
    x.parent.left = y;
  } else {
    x.parent.right = y;
  }
  y.left = x;
  x.parent = y;
  recomputeMaxEnd(x);
  recomputeMaxEnd(y);
}
function rightRotate$1(T, y) {
  const x = y.left;
  y.delta -= x.delta;
  if (y.delta < -1073741824 || y.delta > 1073741824) {
    T.requestNormalizeDelta = true;
  }
  y.start -= x.delta;
  y.end -= x.delta;
  y.left = x.right;
  if (x.right !== SENTINEL$1) {
    x.right.parent = y;
  }
  x.parent = y.parent;
  if (y.parent === SENTINEL$1) {
    T.root = x;
  } else if (y === y.parent.right) {
    y.parent.right = x;
  } else {
    y.parent.left = x;
  }
  x.right = y;
  y.parent = x;
  recomputeMaxEnd(y);
  recomputeMaxEnd(x);
}
function computeMaxEnd(node2) {
  let maxEnd = node2.end;
  if (node2.left !== SENTINEL$1) {
    const leftMaxEnd = node2.left.maxEnd;
    if (leftMaxEnd > maxEnd) {
      maxEnd = leftMaxEnd;
    }
  }
  if (node2.right !== SENTINEL$1) {
    const rightMaxEnd = node2.right.maxEnd + node2.delta;
    if (rightMaxEnd > maxEnd) {
      maxEnd = rightMaxEnd;
    }
  }
  return maxEnd;
}
function recomputeMaxEnd(node2) {
  node2.maxEnd = computeMaxEnd(node2);
}
function recomputeMaxEndWalkToRoot(node2) {
  while (node2 !== SENTINEL$1) {
    const maxEnd = computeMaxEnd(node2);
    if (node2.maxEnd === maxEnd) {
      return;
    }
    node2.maxEnd = maxEnd;
    node2 = node2.parent;
  }
}
function intervalCompare(aStart, aEnd, bStart, bEnd) {
  if (aStart === bStart) {
    return aEnd - bEnd;
  }
  return aStart - bStart;
}
class TreeNode {
  constructor(piece, color) {
    this.piece = piece;
    this.color = color;
    this.size_left = 0;
    this.lf_left = 0;
    this.parent = this;
    this.left = this;
    this.right = this;
  }
  next() {
    if (this.right !== SENTINEL) {
      return leftest(this.right);
    }
    let node2 = this;
    while (node2.parent !== SENTINEL) {
      if (node2.parent.left === node2) {
        break;
      }
      node2 = node2.parent;
    }
    if (node2.parent === SENTINEL) {
      return SENTINEL;
    } else {
      return node2.parent;
    }
  }
  prev() {
    if (this.left !== SENTINEL) {
      return righttest(this.left);
    }
    let node2 = this;
    while (node2.parent !== SENTINEL) {
      if (node2.parent.right === node2) {
        break;
      }
      node2 = node2.parent;
    }
    if (node2.parent === SENTINEL) {
      return SENTINEL;
    } else {
      return node2.parent;
    }
  }
  detach() {
    this.parent = null;
    this.left = null;
    this.right = null;
  }
}
const SENTINEL = new TreeNode(
  null,
  0
  /* NodeColor.Black */
);
SENTINEL.parent = SENTINEL;
SENTINEL.left = SENTINEL;
SENTINEL.right = SENTINEL;
SENTINEL.color = 0;
function leftest(node2) {
  while (node2.left !== SENTINEL) {
    node2 = node2.left;
  }
  return node2;
}
function righttest(node2) {
  while (node2.right !== SENTINEL) {
    node2 = node2.right;
  }
  return node2;
}
function calculateSize(node2) {
  if (node2 === SENTINEL) {
    return 0;
  }
  return node2.size_left + node2.piece.length + calculateSize(node2.right);
}
function calculateLF(node2) {
  if (node2 === SENTINEL) {
    return 0;
  }
  return node2.lf_left + node2.piece.lineFeedCnt + calculateLF(node2.right);
}
function resetSentinel() {
  SENTINEL.parent = SENTINEL;
}
function leftRotate$1(tree2, x) {
  const y = x.right;
  y.size_left += x.size_left + (x.piece ? x.piece.length : 0);
  y.lf_left += x.lf_left + (x.piece ? x.piece.lineFeedCnt : 0);
  x.right = y.left;
  if (y.left !== SENTINEL) {
    y.left.parent = x;
  }
  y.parent = x.parent;
  if (x.parent === SENTINEL) {
    tree2.root = y;
  } else if (x.parent.left === x) {
    x.parent.left = y;
  } else {
    x.parent.right = y;
  }
  y.left = x;
  x.parent = y;
}
function rightRotate(tree2, y) {
  const x = y.left;
  y.left = x.right;
  if (x.right !== SENTINEL) {
    x.right.parent = y;
  }
  x.parent = y.parent;
  y.size_left -= x.size_left + (x.piece ? x.piece.length : 0);
  y.lf_left -= x.lf_left + (x.piece ? x.piece.lineFeedCnt : 0);
  if (y.parent === SENTINEL) {
    tree2.root = x;
  } else if (y === y.parent.right) {
    y.parent.right = x;
  } else {
    y.parent.left = x;
  }
  x.right = y;
  y.parent = x;
}
function rbDelete(tree2, z) {
  let x;
  let y;
  if (z.left === SENTINEL) {
    y = z;
    x = y.right;
  } else if (z.right === SENTINEL) {
    y = z;
    x = y.left;
  } else {
    y = leftest(z.right);
    x = y.right;
  }
  if (y === tree2.root) {
    tree2.root = x;
    x.color = 0;
    z.detach();
    resetSentinel();
    tree2.root.parent = SENTINEL;
    return;
  }
  const yWasRed = y.color === 1;
  if (y === y.parent.left) {
    y.parent.left = x;
  } else {
    y.parent.right = x;
  }
  if (y === z) {
    x.parent = y.parent;
    recomputeTreeMetadata(tree2, x);
  } else {
    if (y.parent === z) {
      x.parent = y;
    } else {
      x.parent = y.parent;
    }
    recomputeTreeMetadata(tree2, x);
    y.left = z.left;
    y.right = z.right;
    y.parent = z.parent;
    y.color = z.color;
    if (z === tree2.root) {
      tree2.root = y;
    } else {
      if (z === z.parent.left) {
        z.parent.left = y;
      } else {
        z.parent.right = y;
      }
    }
    if (y.left !== SENTINEL) {
      y.left.parent = y;
    }
    if (y.right !== SENTINEL) {
      y.right.parent = y;
    }
    y.size_left = z.size_left;
    y.lf_left = z.lf_left;
    recomputeTreeMetadata(tree2, y);
  }
  z.detach();
  if (x.parent.left === x) {
    const newSizeLeft = calculateSize(x);
    const newLFLeft = calculateLF(x);
    if (newSizeLeft !== x.parent.size_left || newLFLeft !== x.parent.lf_left) {
      const delta = newSizeLeft - x.parent.size_left;
      const lf_delta = newLFLeft - x.parent.lf_left;
      x.parent.size_left = newSizeLeft;
      x.parent.lf_left = newLFLeft;
      updateTreeMetadata(tree2, x.parent, delta, lf_delta);
    }
  }
  recomputeTreeMetadata(tree2, x.parent);
  if (yWasRed) {
    resetSentinel();
    return;
  }
  let w;
  while (x !== tree2.root && x.color === 0) {
    if (x === x.parent.left) {
      w = x.parent.right;
      if (w.color === 1) {
        w.color = 0;
        x.parent.color = 1;
        leftRotate$1(tree2, x.parent);
        w = x.parent.right;
      }
      if (w.left.color === 0 && w.right.color === 0) {
        w.color = 1;
        x = x.parent;
      } else {
        if (w.right.color === 0) {
          w.left.color = 0;
          w.color = 1;
          rightRotate(tree2, w);
          w = x.parent.right;
        }
        w.color = x.parent.color;
        x.parent.color = 0;
        w.right.color = 0;
        leftRotate$1(tree2, x.parent);
        x = tree2.root;
      }
    } else {
      w = x.parent.left;
      if (w.color === 1) {
        w.color = 0;
        x.parent.color = 1;
        rightRotate(tree2, x.parent);
        w = x.parent.left;
      }
      if (w.left.color === 0 && w.right.color === 0) {
        w.color = 1;
        x = x.parent;
      } else {
        if (w.left.color === 0) {
          w.right.color = 0;
          w.color = 1;
          leftRotate$1(tree2, w);
          w = x.parent.left;
        }
        w.color = x.parent.color;
        x.parent.color = 0;
        w.left.color = 0;
        rightRotate(tree2, x.parent);
        x = tree2.root;
      }
    }
  }
  x.color = 0;
  resetSentinel();
}
function fixInsert(tree2, x) {
  recomputeTreeMetadata(tree2, x);
  while (x !== tree2.root && x.parent.color === 1) {
    if (x.parent === x.parent.parent.left) {
      const y = x.parent.parent.right;
      if (y.color === 1) {
        x.parent.color = 0;
        y.color = 0;
        x.parent.parent.color = 1;
        x = x.parent.parent;
      } else {
        if (x === x.parent.right) {
          x = x.parent;
          leftRotate$1(tree2, x);
        }
        x.parent.color = 0;
        x.parent.parent.color = 1;
        rightRotate(tree2, x.parent.parent);
      }
    } else {
      const y = x.parent.parent.left;
      if (y.color === 1) {
        x.parent.color = 0;
        y.color = 0;
        x.parent.parent.color = 1;
        x = x.parent.parent;
      } else {
        if (x === x.parent.left) {
          x = x.parent;
          rightRotate(tree2, x);
        }
        x.parent.color = 0;
        x.parent.parent.color = 1;
        leftRotate$1(tree2, x.parent.parent);
      }
    }
  }
  tree2.root.color = 0;
}
function updateTreeMetadata(tree2, x, delta, lineFeedCntDelta) {
  while (x !== tree2.root && x !== SENTINEL) {
    if (x.parent.left === x) {
      x.parent.size_left += delta;
      x.parent.lf_left += lineFeedCntDelta;
    }
    x = x.parent;
  }
}
function recomputeTreeMetadata(tree2, x) {
  let delta = 0;
  let lf_delta = 0;
  if (x === tree2.root) {
    return;
  }
  while (x !== tree2.root && x === x.parent.right) {
    x = x.parent;
  }
  if (x === tree2.root) {
    return;
  }
  x = x.parent;
  delta = calculateSize(x.left) - x.size_left;
  lf_delta = calculateLF(x.left) - x.lf_left;
  x.size_left += delta;
  x.lf_left += lf_delta;
  while (x !== tree2.root && (delta !== 0 || lf_delta !== 0)) {
    if (x.parent.left === x) {
      x.parent.size_left += delta;
      x.parent.lf_left += lf_delta;
    }
    x = x.parent;
  }
}
const LIMIT_FIND_COUNT$1 = 999;
class SearchParams {
  constructor(searchString, isRegex, matchCase, wordSeparators2) {
    this.searchString = searchString;
    this.isRegex = isRegex;
    this.matchCase = matchCase;
    this.wordSeparators = wordSeparators2;
  }
  parseSearchRequest() {
    if (this.searchString === "") {
      return null;
    }
    let multiline;
    if (this.isRegex) {
      multiline = isMultilineRegexSource(this.searchString);
    } else {
      multiline = this.searchString.indexOf("\n") >= 0;
    }
    let regex = null;
    try {
      regex = createRegExp(this.searchString, this.isRegex, {
        matchCase: this.matchCase,
        wholeWord: false,
        multiline,
        global: true,
        unicode: true
      });
    } catch (err) {
      return null;
    }
    if (!regex) {
      return null;
    }
    let canUseSimpleSearch = !this.isRegex && !multiline;
    if (canUseSimpleSearch && this.searchString.toLowerCase() !== this.searchString.toUpperCase()) {
      canUseSimpleSearch = this.matchCase;
    }
    return new SearchData(regex, this.wordSeparators ? getMapForWordSeparators(this.wordSeparators) : null, canUseSimpleSearch ? this.searchString : null);
  }
}
function isMultilineRegexSource(searchString) {
  if (!searchString || searchString.length === 0) {
    return false;
  }
  for (let i = 0, len = searchString.length; i < len; i++) {
    const chCode = searchString.charCodeAt(i);
    if (chCode === 10) {
      return true;
    }
    if (chCode === 92) {
      i++;
      if (i >= len) {
        break;
      }
      const nextChCode = searchString.charCodeAt(i);
      if (nextChCode === 110 || nextChCode === 114 || nextChCode === 87) {
        return true;
      }
    }
  }
  return false;
}
function createFindMatch(range2, rawMatches, captureMatches) {
  if (!captureMatches) {
    return new FindMatch(range2, null);
  }
  const matches = [];
  for (let i = 0, len = rawMatches.length; i < len; i++) {
    matches[i] = rawMatches[i];
  }
  return new FindMatch(range2, matches);
}
class LineFeedCounter {
  constructor(text2) {
    const lineFeedsOffsets = [];
    let lineFeedsOffsetsLen = 0;
    for (let i = 0, textLen = text2.length; i < textLen; i++) {
      if (text2.charCodeAt(i) === 10) {
        lineFeedsOffsets[lineFeedsOffsetsLen++] = i;
      }
    }
    this._lineFeedsOffsets = lineFeedsOffsets;
  }
  findLineFeedCountBeforeOffset(offset) {
    const lineFeedsOffsets = this._lineFeedsOffsets;
    let min = 0;
    let max = lineFeedsOffsets.length - 1;
    if (max === -1) {
      return 0;
    }
    if (offset <= lineFeedsOffsets[0]) {
      return 0;
    }
    while (min < max) {
      const mid = min + ((max - min) / 2 >> 0);
      if (lineFeedsOffsets[mid] >= offset) {
        max = mid - 1;
      } else {
        if (lineFeedsOffsets[mid + 1] >= offset) {
          min = mid;
          max = mid;
        } else {
          min = mid + 1;
        }
      }
    }
    return min + 1;
  }
}
class TextModelSearch {
  static findMatches(model, searchParams, searchRange, captureMatches, limitResultCount) {
    const searchData = searchParams.parseSearchRequest();
    if (!searchData) {
      return [];
    }
    if (searchData.regex.multiline) {
      return this._doFindMatchesMultiline(model, searchRange, new Searcher(searchData.wordSeparators, searchData.regex), captureMatches, limitResultCount);
    }
    return this._doFindMatchesLineByLine(model, searchRange, searchData, captureMatches, limitResultCount);
  }
  /**
   * Multiline search always executes on the lines concatenated with \n.
   * We must therefore compensate for the count of \n in case the model is CRLF
   */
  static _getMultilineMatchRange(model, deltaOffset, text2, lfCounter, matchIndex, match0) {
    let startOffset;
    let lineFeedCountBeforeMatch = 0;
    if (lfCounter) {
      lineFeedCountBeforeMatch = lfCounter.findLineFeedCountBeforeOffset(matchIndex);
      startOffset = deltaOffset + matchIndex + lineFeedCountBeforeMatch;
    } else {
      startOffset = deltaOffset + matchIndex;
    }
    let endOffset;
    if (lfCounter) {
      const lineFeedCountBeforeEndOfMatch = lfCounter.findLineFeedCountBeforeOffset(matchIndex + match0.length);
      const lineFeedCountInMatch = lineFeedCountBeforeEndOfMatch - lineFeedCountBeforeMatch;
      endOffset = startOffset + match0.length + lineFeedCountInMatch;
    } else {
      endOffset = startOffset + match0.length;
    }
    const startPosition = model.getPositionAt(startOffset);
    const endPosition = model.getPositionAt(endOffset);
    return new Range$2(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);
  }
  static _doFindMatchesMultiline(model, searchRange, searcher, captureMatches, limitResultCount) {
    const deltaOffset = model.getOffsetAt(searchRange.getStartPosition());
    const text2 = model.getValueInRange(
      searchRange,
      1
      /* EndOfLinePreference.LF */
    );
    const lfCounter = model.getEOL() === "\r\n" ? new LineFeedCounter(text2) : null;
    const result2 = [];
    let counter = 0;
    let m;
    searcher.reset(0);
    while (m = searcher.next(text2)) {
      result2[counter++] = createFindMatch(this._getMultilineMatchRange(model, deltaOffset, text2, lfCounter, m.index, m[0]), m, captureMatches);
      if (counter >= limitResultCount) {
        return result2;
      }
    }
    return result2;
  }
  static _doFindMatchesLineByLine(model, searchRange, searchData, captureMatches, limitResultCount) {
    const result2 = [];
    let resultLen = 0;
    if (searchRange.startLineNumber === searchRange.endLineNumber) {
      const text3 = model.getLineContent(searchRange.startLineNumber).substring(searchRange.startColumn - 1, searchRange.endColumn - 1);
      resultLen = this._findMatchesInLine(searchData, text3, searchRange.startLineNumber, searchRange.startColumn - 1, resultLen, result2, captureMatches, limitResultCount);
      return result2;
    }
    const text2 = model.getLineContent(searchRange.startLineNumber).substring(searchRange.startColumn - 1);
    resultLen = this._findMatchesInLine(searchData, text2, searchRange.startLineNumber, searchRange.startColumn - 1, resultLen, result2, captureMatches, limitResultCount);
    for (let lineNumber = searchRange.startLineNumber + 1; lineNumber < searchRange.endLineNumber && resultLen < limitResultCount; lineNumber++) {
      resultLen = this._findMatchesInLine(searchData, model.getLineContent(lineNumber), lineNumber, 0, resultLen, result2, captureMatches, limitResultCount);
    }
    if (resultLen < limitResultCount) {
      const text3 = model.getLineContent(searchRange.endLineNumber).substring(0, searchRange.endColumn - 1);
      resultLen = this._findMatchesInLine(searchData, text3, searchRange.endLineNumber, 0, resultLen, result2, captureMatches, limitResultCount);
    }
    return result2;
  }
  static _findMatchesInLine(searchData, text2, lineNumber, deltaOffset, resultLen, result2, captureMatches, limitResultCount) {
    const wordSeparators2 = searchData.wordSeparators;
    if (!captureMatches && searchData.simpleSearch) {
      const searchString = searchData.simpleSearch;
      const searchStringLen = searchString.length;
      const textLength = text2.length;
      let lastMatchIndex = -searchStringLen;
      while ((lastMatchIndex = text2.indexOf(searchString, lastMatchIndex + searchStringLen)) !== -1) {
        if (!wordSeparators2 || isValidMatch(wordSeparators2, text2, textLength, lastMatchIndex, searchStringLen)) {
          result2[resultLen++] = new FindMatch(new Range$2(lineNumber, lastMatchIndex + 1 + deltaOffset, lineNumber, lastMatchIndex + 1 + searchStringLen + deltaOffset), null);
          if (resultLen >= limitResultCount) {
            return resultLen;
          }
        }
      }
      return resultLen;
    }
    const searcher = new Searcher(searchData.wordSeparators, searchData.regex);
    let m;
    searcher.reset(0);
    do {
      m = searcher.next(text2);
      if (m) {
        result2[resultLen++] = createFindMatch(new Range$2(lineNumber, m.index + 1 + deltaOffset, lineNumber, m.index + 1 + m[0].length + deltaOffset), m, captureMatches);
        if (resultLen >= limitResultCount) {
          return resultLen;
        }
      }
    } while (m);
    return resultLen;
  }
  static findNextMatch(model, searchParams, searchStart, captureMatches) {
    const searchData = searchParams.parseSearchRequest();
    if (!searchData) {
      return null;
    }
    const searcher = new Searcher(searchData.wordSeparators, searchData.regex);
    if (searchData.regex.multiline) {
      return this._doFindNextMatchMultiline(model, searchStart, searcher, captureMatches);
    }
    return this._doFindNextMatchLineByLine(model, searchStart, searcher, captureMatches);
  }
  static _doFindNextMatchMultiline(model, searchStart, searcher, captureMatches) {
    const searchTextStart = new Position$2(searchStart.lineNumber, 1);
    const deltaOffset = model.getOffsetAt(searchTextStart);
    const lineCount = model.getLineCount();
    const text2 = model.getValueInRange(
      new Range$2(searchTextStart.lineNumber, searchTextStart.column, lineCount, model.getLineMaxColumn(lineCount)),
      1
      /* EndOfLinePreference.LF */
    );
    const lfCounter = model.getEOL() === "\r\n" ? new LineFeedCounter(text2) : null;
    searcher.reset(searchStart.column - 1);
    const m = searcher.next(text2);
    if (m) {
      return createFindMatch(this._getMultilineMatchRange(model, deltaOffset, text2, lfCounter, m.index, m[0]), m, captureMatches);
    }
    if (searchStart.lineNumber !== 1 || searchStart.column !== 1) {
      return this._doFindNextMatchMultiline(model, new Position$2(1, 1), searcher, captureMatches);
    }
    return null;
  }
  static _doFindNextMatchLineByLine(model, searchStart, searcher, captureMatches) {
    const lineCount = model.getLineCount();
    const startLineNumber = searchStart.lineNumber;
    const text2 = model.getLineContent(startLineNumber);
    const r = this._findFirstMatchInLine(searcher, text2, startLineNumber, searchStart.column, captureMatches);
    if (r) {
      return r;
    }
    for (let i = 1; i <= lineCount; i++) {
      const lineIndex = (startLineNumber + i - 1) % lineCount;
      const text3 = model.getLineContent(lineIndex + 1);
      const r2 = this._findFirstMatchInLine(searcher, text3, lineIndex + 1, 1, captureMatches);
      if (r2) {
        return r2;
      }
    }
    return null;
  }
  static _findFirstMatchInLine(searcher, text2, lineNumber, fromColumn, captureMatches) {
    searcher.reset(fromColumn - 1);
    const m = searcher.next(text2);
    if (m) {
      return createFindMatch(new Range$2(lineNumber, m.index + 1, lineNumber, m.index + 1 + m[0].length), m, captureMatches);
    }
    return null;
  }
  static findPreviousMatch(model, searchParams, searchStart, captureMatches) {
    const searchData = searchParams.parseSearchRequest();
    if (!searchData) {
      return null;
    }
    const searcher = new Searcher(searchData.wordSeparators, searchData.regex);
    if (searchData.regex.multiline) {
      return this._doFindPreviousMatchMultiline(model, searchStart, searcher, captureMatches);
    }
    return this._doFindPreviousMatchLineByLine(model, searchStart, searcher, captureMatches);
  }
  static _doFindPreviousMatchMultiline(model, searchStart, searcher, captureMatches) {
    const matches = this._doFindMatchesMultiline(model, new Range$2(1, 1, searchStart.lineNumber, searchStart.column), searcher, captureMatches, 10 * LIMIT_FIND_COUNT$1);
    if (matches.length > 0) {
      return matches[matches.length - 1];
    }
    const lineCount = model.getLineCount();
    if (searchStart.lineNumber !== lineCount || searchStart.column !== model.getLineMaxColumn(lineCount)) {
      return this._doFindPreviousMatchMultiline(model, new Position$2(lineCount, model.getLineMaxColumn(lineCount)), searcher, captureMatches);
    }
    return null;
  }
  static _doFindPreviousMatchLineByLine(model, searchStart, searcher, captureMatches) {
    const lineCount = model.getLineCount();
    const startLineNumber = searchStart.lineNumber;
    const text2 = model.getLineContent(startLineNumber).substring(0, searchStart.column - 1);
    const r = this._findLastMatchInLine(searcher, text2, startLineNumber, captureMatches);
    if (r) {
      return r;
    }
    for (let i = 1; i <= lineCount; i++) {
      const lineIndex = (lineCount + startLineNumber - i - 1) % lineCount;
      const text3 = model.getLineContent(lineIndex + 1);
      const r2 = this._findLastMatchInLine(searcher, text3, lineIndex + 1, captureMatches);
      if (r2) {
        return r2;
      }
    }
    return null;
  }
  static _findLastMatchInLine(searcher, text2, lineNumber, captureMatches) {
    let bestResult = null;
    let m;
    searcher.reset(0);
    while (m = searcher.next(text2)) {
      bestResult = createFindMatch(new Range$2(lineNumber, m.index + 1, lineNumber, m.index + 1 + m[0].length), m, captureMatches);
    }
    return bestResult;
  }
}
function leftIsWordBounday(wordSeparators2, text2, textLength, matchStartIndex, matchLength) {
  if (matchStartIndex === 0) {
    return true;
  }
  const charBefore = text2.charCodeAt(matchStartIndex - 1);
  if (wordSeparators2.get(charBefore) !== 0) {
    return true;
  }
  if (charBefore === 13 || charBefore === 10) {
    return true;
  }
  if (matchLength > 0) {
    const firstCharInMatch = text2.charCodeAt(matchStartIndex);
    if (wordSeparators2.get(firstCharInMatch) !== 0) {
      return true;
    }
  }
  return false;
}
function rightIsWordBounday(wordSeparators2, text2, textLength, matchStartIndex, matchLength) {
  if (matchStartIndex + matchLength === textLength) {
    return true;
  }
  const charAfter = text2.charCodeAt(matchStartIndex + matchLength);
  if (wordSeparators2.get(charAfter) !== 0) {
    return true;
  }
  if (charAfter === 13 || charAfter === 10) {
    return true;
  }
  if (matchLength > 0) {
    const lastCharInMatch = text2.charCodeAt(matchStartIndex + matchLength - 1);
    if (wordSeparators2.get(lastCharInMatch) !== 0) {
      return true;
    }
  }
  return false;
}
function isValidMatch(wordSeparators2, text2, textLength, matchStartIndex, matchLength) {
  return leftIsWordBounday(wordSeparators2, text2, textLength, matchStartIndex, matchLength) && rightIsWordBounday(wordSeparators2, text2, textLength, matchStartIndex, matchLength);
}
class Searcher {
  constructor(wordSeparators2, searchRegex) {
    this._wordSeparators = wordSeparators2;
    this._searchRegex = searchRegex;
    this._prevMatchStartIndex = -1;
    this._prevMatchLength = 0;
  }
  reset(lastIndex2) {
    this._searchRegex.lastIndex = lastIndex2;
    this._prevMatchStartIndex = -1;
    this._prevMatchLength = 0;
  }
  next(text2) {
    const textLength = text2.length;
    let m;
    do {
      if (this._prevMatchStartIndex + this._prevMatchLength === textLength) {
        return null;
      }
      m = this._searchRegex.exec(text2);
      if (!m) {
        return null;
      }
      const matchStartIndex = m.index;
      const matchLength = m[0].length;
      if (matchStartIndex === this._prevMatchStartIndex && matchLength === this._prevMatchLength) {
        if (matchLength === 0) {
          if (getNextCodePoint(text2, textLength, this._searchRegex.lastIndex) > 65535) {
            this._searchRegex.lastIndex += 2;
          } else {
            this._searchRegex.lastIndex += 1;
          }
          continue;
        }
        return null;
      }
      this._prevMatchStartIndex = matchStartIndex;
      this._prevMatchLength = matchLength;
      if (!this._wordSeparators || isValidMatch(this._wordSeparators, text2, textLength, matchStartIndex, matchLength)) {
        return m;
      }
    } while (m);
    return null;
  }
}
const AverageBufferSize = 65535;
function createUintArray(arr) {
  let r;
  if (arr[arr.length - 1] < 65536) {
    r = new Uint16Array(arr.length);
  } else {
    r = new Uint32Array(arr.length);
  }
  r.set(arr, 0);
  return r;
}
class LineStarts {
  constructor(lineStarts, cr2, lf, crlf, isBasicASCII2) {
    this.lineStarts = lineStarts;
    this.cr = cr2;
    this.lf = lf;
    this.crlf = crlf;
    this.isBasicASCII = isBasicASCII2;
  }
}
function createLineStartsFast(str2, readonly2 = true) {
  const r = [0];
  let rLength = 1;
  for (let i = 0, len = str2.length; i < len; i++) {
    const chr = str2.charCodeAt(i);
    if (chr === 13) {
      if (i + 1 < len && str2.charCodeAt(i + 1) === 10) {
        r[rLength++] = i + 2;
        i++;
      } else {
        r[rLength++] = i + 1;
      }
    } else if (chr === 10) {
      r[rLength++] = i + 1;
    }
  }
  if (readonly2) {
    return createUintArray(r);
  } else {
    return r;
  }
}
function createLineStarts(r, str2) {
  r.length = 0;
  r[0] = 0;
  let rLength = 1;
  let cr2 = 0, lf = 0, crlf = 0;
  let isBasicASCII2 = true;
  for (let i = 0, len = str2.length; i < len; i++) {
    const chr = str2.charCodeAt(i);
    if (chr === 13) {
      if (i + 1 < len && str2.charCodeAt(i + 1) === 10) {
        crlf++;
        r[rLength++] = i + 2;
        i++;
      } else {
        cr2++;
        r[rLength++] = i + 1;
      }
    } else if (chr === 10) {
      lf++;
      r[rLength++] = i + 1;
    } else {
      if (isBasicASCII2) {
        if (chr !== 9 && (chr < 32 || chr > 126)) {
          isBasicASCII2 = false;
        }
      }
    }
  }
  const result2 = new LineStarts(createUintArray(r), cr2, lf, crlf, isBasicASCII2);
  r.length = 0;
  return result2;
}
class Piece {
  constructor(bufferIndex, start, end, lineFeedCnt, length2) {
    this.bufferIndex = bufferIndex;
    this.start = start;
    this.end = end;
    this.lineFeedCnt = lineFeedCnt;
    this.length = length2;
  }
}
class StringBuffer {
  constructor(buffer, lineStarts) {
    this.buffer = buffer;
    this.lineStarts = lineStarts;
  }
}
class PieceTreeSnapshot {
  constructor(tree2, BOM) {
    this._pieces = [];
    this._tree = tree2;
    this._BOM = BOM;
    this._index = 0;
    if (tree2.root !== SENTINEL) {
      tree2.iterate(tree2.root, (node2) => {
        if (node2 !== SENTINEL) {
          this._pieces.push(node2.piece);
        }
        return true;
      });
    }
  }
  read() {
    if (this._pieces.length === 0) {
      if (this._index === 0) {
        this._index++;
        return this._BOM;
      } else {
        return null;
      }
    }
    if (this._index > this._pieces.length - 1) {
      return null;
    }
    if (this._index === 0) {
      return this._BOM + this._tree.getPieceContent(this._pieces[this._index++]);
    }
    return this._tree.getPieceContent(this._pieces[this._index++]);
  }
}
class PieceTreeSearchCache {
  constructor(limit) {
    this._limit = limit;
    this._cache = [];
  }
  get(offset) {
    for (let i = this._cache.length - 1; i >= 0; i--) {
      const nodePos = this._cache[i];
      if (nodePos.nodeStartOffset <= offset && nodePos.nodeStartOffset + nodePos.node.piece.length >= offset) {
        return nodePos;
      }
    }
    return null;
  }
  get2(lineNumber) {
    for (let i = this._cache.length - 1; i >= 0; i--) {
      const nodePos = this._cache[i];
      if (nodePos.nodeStartLineNumber && nodePos.nodeStartLineNumber < lineNumber && nodePos.nodeStartLineNumber + nodePos.node.piece.lineFeedCnt >= lineNumber) {
        return nodePos;
      }
    }
    return null;
  }
  set(nodePosition) {
    if (this._cache.length >= this._limit) {
      this._cache.shift();
    }
    this._cache.push(nodePosition);
  }
  validate(offset) {
    let hasInvalidVal = false;
    const tmp = this._cache;
    for (let i = 0; i < tmp.length; i++) {
      const nodePos = tmp[i];
      if (nodePos.node.parent === null || nodePos.nodeStartOffset >= offset) {
        tmp[i] = null;
        hasInvalidVal = true;
        continue;
      }
    }
    if (hasInvalidVal) {
      const newArr = [];
      for (const entry of tmp) {
        if (entry !== null) {
          newArr.push(entry);
        }
      }
      this._cache = newArr;
    }
  }
}
class PieceTreeBase {
  constructor(chunks, eol, eolNormalized) {
    this.create(chunks, eol, eolNormalized);
  }
  create(chunks, eol, eolNormalized) {
    this._buffers = [
      new StringBuffer("", [0])
    ];
    this._lastChangeBufferPos = { line: 0, column: 0 };
    this.root = SENTINEL;
    this._lineCnt = 1;
    this._length = 0;
    this._EOL = eol;
    this._EOLLength = eol.length;
    this._EOLNormalized = eolNormalized;
    let lastNode = null;
    for (let i = 0, len = chunks.length; i < len; i++) {
      if (chunks[i].buffer.length > 0) {
        if (!chunks[i].lineStarts) {
          chunks[i].lineStarts = createLineStartsFast(chunks[i].buffer);
        }
        const piece = new Piece(i + 1, { line: 0, column: 0 }, { line: chunks[i].lineStarts.length - 1, column: chunks[i].buffer.length - chunks[i].lineStarts[chunks[i].lineStarts.length - 1] }, chunks[i].lineStarts.length - 1, chunks[i].buffer.length);
        this._buffers.push(chunks[i]);
        lastNode = this.rbInsertRight(lastNode, piece);
      }
    }
    this._searchCache = new PieceTreeSearchCache(1);
    this._lastVisitedLine = { lineNumber: 0, value: "" };
    this.computeBufferMetadata();
  }
  normalizeEOL(eol) {
    const averageBufferSize = AverageBufferSize;
    const min = averageBufferSize - Math.floor(averageBufferSize / 3);
    const max = min * 2;
    let tempChunk = "";
    let tempChunkLen = 0;
    const chunks = [];
    this.iterate(this.root, (node2) => {
      const str2 = this.getNodeContent(node2);
      const len = str2.length;
      if (tempChunkLen <= min || tempChunkLen + len < max) {
        tempChunk += str2;
        tempChunkLen += len;
        return true;
      }
      const text2 = tempChunk.replace(/\r\n|\r|\n/g, eol);
      chunks.push(new StringBuffer(text2, createLineStartsFast(text2)));
      tempChunk = str2;
      tempChunkLen = len;
      return true;
    });
    if (tempChunkLen > 0) {
      const text2 = tempChunk.replace(/\r\n|\r|\n/g, eol);
      chunks.push(new StringBuffer(text2, createLineStartsFast(text2)));
    }
    this.create(chunks, eol, true);
  }
  // #region Buffer API
  getEOL() {
    return this._EOL;
  }
  setEOL(newEOL) {
    this._EOL = newEOL;
    this._EOLLength = this._EOL.length;
    this.normalizeEOL(newEOL);
  }
  createSnapshot(BOM) {
    return new PieceTreeSnapshot(this, BOM);
  }
  getOffsetAt(lineNumber, column) {
    let leftLen = 0;
    let x = this.root;
    while (x !== SENTINEL) {
      if (x.left !== SENTINEL && x.lf_left + 1 >= lineNumber) {
        x = x.left;
      } else if (x.lf_left + x.piece.lineFeedCnt + 1 >= lineNumber) {
        leftLen += x.size_left;
        const accumualtedValInCurrentIndex = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
        return leftLen += accumualtedValInCurrentIndex + column - 1;
      } else {
        lineNumber -= x.lf_left + x.piece.lineFeedCnt;
        leftLen += x.size_left + x.piece.length;
        x = x.right;
      }
    }
    return leftLen;
  }
  getPositionAt(offset) {
    offset = Math.floor(offset);
    offset = Math.max(0, offset);
    let x = this.root;
    let lfCnt = 0;
    const originalOffset = offset;
    while (x !== SENTINEL) {
      if (x.size_left !== 0 && x.size_left >= offset) {
        x = x.left;
      } else if (x.size_left + x.piece.length >= offset) {
        const out = this.getIndexOf(x, offset - x.size_left);
        lfCnt += x.lf_left + out.index;
        if (out.index === 0) {
          const lineStartOffset = this.getOffsetAt(lfCnt + 1, 1);
          const column = originalOffset - lineStartOffset;
          return new Position$2(lfCnt + 1, column + 1);
        }
        return new Position$2(lfCnt + 1, out.remainder + 1);
      } else {
        offset -= x.size_left + x.piece.length;
        lfCnt += x.lf_left + x.piece.lineFeedCnt;
        if (x.right === SENTINEL) {
          const lineStartOffset = this.getOffsetAt(lfCnt + 1, 1);
          const column = originalOffset - offset - lineStartOffset;
          return new Position$2(lfCnt + 1, column + 1);
        } else {
          x = x.right;
        }
      }
    }
    return new Position$2(1, 1);
  }
  getValueInRange(range2, eol) {
    if (range2.startLineNumber === range2.endLineNumber && range2.startColumn === range2.endColumn) {
      return "";
    }
    const startPosition = this.nodeAt2(range2.startLineNumber, range2.startColumn);
    const endPosition = this.nodeAt2(range2.endLineNumber, range2.endColumn);
    const value = this.getValueInRange2(startPosition, endPosition);
    if (eol) {
      if (eol !== this._EOL || !this._EOLNormalized) {
        return value.replace(/\r\n|\r|\n/g, eol);
      }
      if (eol === this.getEOL() && this._EOLNormalized) {
        return value;
      }
      return value.replace(/\r\n|\r|\n/g, eol);
    }
    return value;
  }
  getValueInRange2(startPosition, endPosition) {
    if (startPosition.node === endPosition.node) {
      const node2 = startPosition.node;
      const buffer2 = this._buffers[node2.piece.bufferIndex].buffer;
      const startOffset2 = this.offsetInBuffer(node2.piece.bufferIndex, node2.piece.start);
      return buffer2.substring(startOffset2 + startPosition.remainder, startOffset2 + endPosition.remainder);
    }
    let x = startPosition.node;
    const buffer = this._buffers[x.piece.bufferIndex].buffer;
    const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
    let ret = buffer.substring(startOffset + startPosition.remainder, startOffset + x.piece.length);
    x = x.next();
    while (x !== SENTINEL) {
      const buffer2 = this._buffers[x.piece.bufferIndex].buffer;
      const startOffset2 = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
      if (x === endPosition.node) {
        ret += buffer2.substring(startOffset2, startOffset2 + endPosition.remainder);
        break;
      } else {
        ret += buffer2.substr(startOffset2, x.piece.length);
      }
      x = x.next();
    }
    return ret;
  }
  getLinesContent() {
    const lines = [];
    let linesLength = 0;
    let currentLine = "";
    let danglingCR = false;
    this.iterate(this.root, (node2) => {
      if (node2 === SENTINEL) {
        return true;
      }
      const piece = node2.piece;
      let pieceLength = piece.length;
      if (pieceLength === 0) {
        return true;
      }
      const buffer = this._buffers[piece.bufferIndex].buffer;
      const lineStarts = this._buffers[piece.bufferIndex].lineStarts;
      const pieceStartLine = piece.start.line;
      const pieceEndLine = piece.end.line;
      let pieceStartOffset = lineStarts[pieceStartLine] + piece.start.column;
      if (danglingCR) {
        if (buffer.charCodeAt(pieceStartOffset) === 10) {
          pieceStartOffset++;
          pieceLength--;
        }
        lines[linesLength++] = currentLine;
        currentLine = "";
        danglingCR = false;
        if (pieceLength === 0) {
          return true;
        }
      }
      if (pieceStartLine === pieceEndLine) {
        if (!this._EOLNormalized && buffer.charCodeAt(pieceStartOffset + pieceLength - 1) === 13) {
          danglingCR = true;
          currentLine += buffer.substr(pieceStartOffset, pieceLength - 1);
        } else {
          currentLine += buffer.substr(pieceStartOffset, pieceLength);
        }
        return true;
      }
      currentLine += this._EOLNormalized ? buffer.substring(pieceStartOffset, Math.max(pieceStartOffset, lineStarts[pieceStartLine + 1] - this._EOLLength)) : buffer.substring(pieceStartOffset, lineStarts[pieceStartLine + 1]).replace(/(\r\n|\r|\n)$/, "");
      lines[linesLength++] = currentLine;
      for (let line = pieceStartLine + 1; line < pieceEndLine; line++) {
        currentLine = this._EOLNormalized ? buffer.substring(lineStarts[line], lineStarts[line + 1] - this._EOLLength) : buffer.substring(lineStarts[line], lineStarts[line + 1]).replace(/(\r\n|\r|\n)$/, "");
        lines[linesLength++] = currentLine;
      }
      if (!this._EOLNormalized && buffer.charCodeAt(lineStarts[pieceEndLine] + piece.end.column - 1) === 13) {
        danglingCR = true;
        if (piece.end.column === 0) {
          linesLength--;
        } else {
          currentLine = buffer.substr(lineStarts[pieceEndLine], piece.end.column - 1);
        }
      } else {
        currentLine = buffer.substr(lineStarts[pieceEndLine], piece.end.column);
      }
      return true;
    });
    if (danglingCR) {
      lines[linesLength++] = currentLine;
      currentLine = "";
    }
    lines[linesLength++] = currentLine;
    return lines;
  }
  getLength() {
    return this._length;
  }
  getLineCount() {
    return this._lineCnt;
  }
  getLineContent(lineNumber) {
    if (this._lastVisitedLine.lineNumber === lineNumber) {
      return this._lastVisitedLine.value;
    }
    this._lastVisitedLine.lineNumber = lineNumber;
    if (lineNumber === this._lineCnt) {
      this._lastVisitedLine.value = this.getLineRawContent(lineNumber);
    } else if (this._EOLNormalized) {
      this._lastVisitedLine.value = this.getLineRawContent(lineNumber, this._EOLLength);
    } else {
      this._lastVisitedLine.value = this.getLineRawContent(lineNumber).replace(/(\r\n|\r|\n)$/, "");
    }
    return this._lastVisitedLine.value;
  }
  _getCharCode(nodePos) {
    if (nodePos.remainder === nodePos.node.piece.length) {
      const matchingNode = nodePos.node.next();
      if (!matchingNode) {
        return 0;
      }
      const buffer = this._buffers[matchingNode.piece.bufferIndex];
      const startOffset = this.offsetInBuffer(matchingNode.piece.bufferIndex, matchingNode.piece.start);
      return buffer.buffer.charCodeAt(startOffset);
    } else {
      const buffer = this._buffers[nodePos.node.piece.bufferIndex];
      const startOffset = this.offsetInBuffer(nodePos.node.piece.bufferIndex, nodePos.node.piece.start);
      const targetOffset = startOffset + nodePos.remainder;
      return buffer.buffer.charCodeAt(targetOffset);
    }
  }
  getLineCharCode(lineNumber, index) {
    const nodePos = this.nodeAt2(lineNumber, index + 1);
    return this._getCharCode(nodePos);
  }
  getLineLength(lineNumber) {
    if (lineNumber === this.getLineCount()) {
      const startOffset = this.getOffsetAt(lineNumber, 1);
      return this.getLength() - startOffset;
    }
    return this.getOffsetAt(lineNumber + 1, 1) - this.getOffsetAt(lineNumber, 1) - this._EOLLength;
  }
  findMatchesInNode(node2, searcher, startLineNumber, startColumn, startCursor, endCursor, searchData, captureMatches, limitResultCount, resultLen, result2) {
    const buffer = this._buffers[node2.piece.bufferIndex];
    const startOffsetInBuffer = this.offsetInBuffer(node2.piece.bufferIndex, node2.piece.start);
    const start = this.offsetInBuffer(node2.piece.bufferIndex, startCursor);
    const end = this.offsetInBuffer(node2.piece.bufferIndex, endCursor);
    let m;
    const ret = { line: 0, column: 0 };
    let searchText;
    let offsetInBuffer;
    if (searcher._wordSeparators) {
      searchText = buffer.buffer.substring(start, end);
      offsetInBuffer = (offset) => offset + start;
      searcher.reset(0);
    } else {
      searchText = buffer.buffer;
      offsetInBuffer = (offset) => offset;
      searcher.reset(start);
    }
    do {
      m = searcher.next(searchText);
      if (m) {
        if (offsetInBuffer(m.index) >= end) {
          return resultLen;
        }
        this.positionInBuffer(node2, offsetInBuffer(m.index) - startOffsetInBuffer, ret);
        const lineFeedCnt = this.getLineFeedCnt(node2.piece.bufferIndex, startCursor, ret);
        const retStartColumn = ret.line === startCursor.line ? ret.column - startCursor.column + startColumn : ret.column + 1;
        const retEndColumn = retStartColumn + m[0].length;
        result2[resultLen++] = createFindMatch(new Range$2(startLineNumber + lineFeedCnt, retStartColumn, startLineNumber + lineFeedCnt, retEndColumn), m, captureMatches);
        if (offsetInBuffer(m.index) + m[0].length >= end) {
          return resultLen;
        }
        if (resultLen >= limitResultCount) {
          return resultLen;
        }
      }
    } while (m);
    return resultLen;
  }
  findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount) {
    const result2 = [];
    let resultLen = 0;
    const searcher = new Searcher(searchData.wordSeparators, searchData.regex);
    let startPosition = this.nodeAt2(searchRange.startLineNumber, searchRange.startColumn);
    if (startPosition === null) {
      return [];
    }
    const endPosition = this.nodeAt2(searchRange.endLineNumber, searchRange.endColumn);
    if (endPosition === null) {
      return [];
    }
    let start = this.positionInBuffer(startPosition.node, startPosition.remainder);
    const end = this.positionInBuffer(endPosition.node, endPosition.remainder);
    if (startPosition.node === endPosition.node) {
      this.findMatchesInNode(startPosition.node, searcher, searchRange.startLineNumber, searchRange.startColumn, start, end, searchData, captureMatches, limitResultCount, resultLen, result2);
      return result2;
    }
    let startLineNumber = searchRange.startLineNumber;
    let currentNode = startPosition.node;
    while (currentNode !== endPosition.node) {
      const lineBreakCnt = this.getLineFeedCnt(currentNode.piece.bufferIndex, start, currentNode.piece.end);
      if (lineBreakCnt >= 1) {
        const lineStarts = this._buffers[currentNode.piece.bufferIndex].lineStarts;
        const startOffsetInBuffer = this.offsetInBuffer(currentNode.piece.bufferIndex, currentNode.piece.start);
        const nextLineStartOffset = lineStarts[start.line + lineBreakCnt];
        const startColumn3 = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn : 1;
        resultLen = this.findMatchesInNode(currentNode, searcher, startLineNumber, startColumn3, start, this.positionInBuffer(currentNode, nextLineStartOffset - startOffsetInBuffer), searchData, captureMatches, limitResultCount, resultLen, result2);
        if (resultLen >= limitResultCount) {
          return result2;
        }
        startLineNumber += lineBreakCnt;
      }
      const startColumn2 = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn - 1 : 0;
      if (startLineNumber === searchRange.endLineNumber) {
        const text2 = this.getLineContent(startLineNumber).substring(startColumn2, searchRange.endColumn - 1);
        resultLen = this._findMatchesInLine(searchData, searcher, text2, searchRange.endLineNumber, startColumn2, resultLen, result2, captureMatches, limitResultCount);
        return result2;
      }
      resultLen = this._findMatchesInLine(searchData, searcher, this.getLineContent(startLineNumber).substr(startColumn2), startLineNumber, startColumn2, resultLen, result2, captureMatches, limitResultCount);
      if (resultLen >= limitResultCount) {
        return result2;
      }
      startLineNumber++;
      startPosition = this.nodeAt2(startLineNumber, 1);
      currentNode = startPosition.node;
      start = this.positionInBuffer(startPosition.node, startPosition.remainder);
    }
    if (startLineNumber === searchRange.endLineNumber) {
      const startColumn2 = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn - 1 : 0;
      const text2 = this.getLineContent(startLineNumber).substring(startColumn2, searchRange.endColumn - 1);
      resultLen = this._findMatchesInLine(searchData, searcher, text2, searchRange.endLineNumber, startColumn2, resultLen, result2, captureMatches, limitResultCount);
      return result2;
    }
    const startColumn = startLineNumber === searchRange.startLineNumber ? searchRange.startColumn : 1;
    resultLen = this.findMatchesInNode(endPosition.node, searcher, startLineNumber, startColumn, start, end, searchData, captureMatches, limitResultCount, resultLen, result2);
    return result2;
  }
  _findMatchesInLine(searchData, searcher, text2, lineNumber, deltaOffset, resultLen, result2, captureMatches, limitResultCount) {
    const wordSeparators2 = searchData.wordSeparators;
    if (!captureMatches && searchData.simpleSearch) {
      const searchString = searchData.simpleSearch;
      const searchStringLen = searchString.length;
      const textLength = text2.length;
      let lastMatchIndex = -searchStringLen;
      while ((lastMatchIndex = text2.indexOf(searchString, lastMatchIndex + searchStringLen)) !== -1) {
        if (!wordSeparators2 || isValidMatch(wordSeparators2, text2, textLength, lastMatchIndex, searchStringLen)) {
          result2[resultLen++] = new FindMatch(new Range$2(lineNumber, lastMatchIndex + 1 + deltaOffset, lineNumber, lastMatchIndex + 1 + searchStringLen + deltaOffset), null);
          if (resultLen >= limitResultCount) {
            return resultLen;
          }
        }
      }
      return resultLen;
    }
    let m;
    searcher.reset(0);
    do {
      m = searcher.next(text2);
      if (m) {
        result2[resultLen++] = createFindMatch(new Range$2(lineNumber, m.index + 1 + deltaOffset, lineNumber, m.index + 1 + m[0].length + deltaOffset), m, captureMatches);
        if (resultLen >= limitResultCount) {
          return resultLen;
        }
      }
    } while (m);
    return resultLen;
  }
  // #endregion
  // #region Piece Table
  insert(offset, value, eolNormalized = false) {
    this._EOLNormalized = this._EOLNormalized && eolNormalized;
    this._lastVisitedLine.lineNumber = 0;
    this._lastVisitedLine.value = "";
    if (this.root !== SENTINEL) {
      const { node: node2, remainder, nodeStartOffset } = this.nodeAt(offset);
      const piece = node2.piece;
      const bufferIndex = piece.bufferIndex;
      const insertPosInBuffer = this.positionInBuffer(node2, remainder);
      if (node2.piece.bufferIndex === 0 && piece.end.line === this._lastChangeBufferPos.line && piece.end.column === this._lastChangeBufferPos.column && nodeStartOffset + piece.length === offset && value.length < AverageBufferSize) {
        this.appendToNode(node2, value);
        this.computeBufferMetadata();
        return;
      }
      if (nodeStartOffset === offset) {
        this.insertContentToNodeLeft(value, node2);
        this._searchCache.validate(offset);
      } else if (nodeStartOffset + node2.piece.length > offset) {
        const nodesToDel = [];
        let newRightPiece = new Piece(piece.bufferIndex, insertPosInBuffer, piece.end, this.getLineFeedCnt(piece.bufferIndex, insertPosInBuffer, piece.end), this.offsetInBuffer(bufferIndex, piece.end) - this.offsetInBuffer(bufferIndex, insertPosInBuffer));
        if (this.shouldCheckCRLF() && this.endWithCR(value)) {
          const headOfRight = this.nodeCharCodeAt(node2, remainder);
          if (headOfRight === 10) {
            const newStart = { line: newRightPiece.start.line + 1, column: 0 };
            newRightPiece = new Piece(newRightPiece.bufferIndex, newStart, newRightPiece.end, this.getLineFeedCnt(newRightPiece.bufferIndex, newStart, newRightPiece.end), newRightPiece.length - 1);
            value += "\n";
          }
        }
        if (this.shouldCheckCRLF() && this.startWithLF(value)) {
          const tailOfLeft = this.nodeCharCodeAt(node2, remainder - 1);
          if (tailOfLeft === 13) {
            const previousPos = this.positionInBuffer(node2, remainder - 1);
            this.deleteNodeTail(node2, previousPos);
            value = "\r" + value;
            if (node2.piece.length === 0) {
              nodesToDel.push(node2);
            }
          } else {
            this.deleteNodeTail(node2, insertPosInBuffer);
          }
        } else {
          this.deleteNodeTail(node2, insertPosInBuffer);
        }
        const newPieces = this.createNewPieces(value);
        if (newRightPiece.length > 0) {
          this.rbInsertRight(node2, newRightPiece);
        }
        let tmpNode = node2;
        for (let k = 0; k < newPieces.length; k++) {
          tmpNode = this.rbInsertRight(tmpNode, newPieces[k]);
        }
        this.deleteNodes(nodesToDel);
      } else {
        this.insertContentToNodeRight(value, node2);
      }
    } else {
      const pieces = this.createNewPieces(value);
      let node2 = this.rbInsertLeft(null, pieces[0]);
      for (let k = 1; k < pieces.length; k++) {
        node2 = this.rbInsertRight(node2, pieces[k]);
      }
    }
    this.computeBufferMetadata();
  }
  delete(offset, cnt) {
    this._lastVisitedLine.lineNumber = 0;
    this._lastVisitedLine.value = "";
    if (cnt <= 0 || this.root === SENTINEL) {
      return;
    }
    const startPosition = this.nodeAt(offset);
    const endPosition = this.nodeAt(offset + cnt);
    const startNode = startPosition.node;
    const endNode = endPosition.node;
    if (startNode === endNode) {
      const startSplitPosInBuffer2 = this.positionInBuffer(startNode, startPosition.remainder);
      const endSplitPosInBuffer2 = this.positionInBuffer(startNode, endPosition.remainder);
      if (startPosition.nodeStartOffset === offset) {
        if (cnt === startNode.piece.length) {
          const next = startNode.next();
          rbDelete(this, startNode);
          this.validateCRLFWithPrevNode(next);
          this.computeBufferMetadata();
          return;
        }
        this.deleteNodeHead(startNode, endSplitPosInBuffer2);
        this._searchCache.validate(offset);
        this.validateCRLFWithPrevNode(startNode);
        this.computeBufferMetadata();
        return;
      }
      if (startPosition.nodeStartOffset + startNode.piece.length === offset + cnt) {
        this.deleteNodeTail(startNode, startSplitPosInBuffer2);
        this.validateCRLFWithNextNode(startNode);
        this.computeBufferMetadata();
        return;
      }
      this.shrinkNode(startNode, startSplitPosInBuffer2, endSplitPosInBuffer2);
      this.computeBufferMetadata();
      return;
    }
    const nodesToDel = [];
    const startSplitPosInBuffer = this.positionInBuffer(startNode, startPosition.remainder);
    this.deleteNodeTail(startNode, startSplitPosInBuffer);
    this._searchCache.validate(offset);
    if (startNode.piece.length === 0) {
      nodesToDel.push(startNode);
    }
    const endSplitPosInBuffer = this.positionInBuffer(endNode, endPosition.remainder);
    this.deleteNodeHead(endNode, endSplitPosInBuffer);
    if (endNode.piece.length === 0) {
      nodesToDel.push(endNode);
    }
    const secondNode = startNode.next();
    for (let node2 = secondNode; node2 !== SENTINEL && node2 !== endNode; node2 = node2.next()) {
      nodesToDel.push(node2);
    }
    const prev = startNode.piece.length === 0 ? startNode.prev() : startNode;
    this.deleteNodes(nodesToDel);
    this.validateCRLFWithNextNode(prev);
    this.computeBufferMetadata();
  }
  insertContentToNodeLeft(value, node2) {
    const nodesToDel = [];
    if (this.shouldCheckCRLF() && this.endWithCR(value) && this.startWithLF(node2)) {
      const piece = node2.piece;
      const newStart = { line: piece.start.line + 1, column: 0 };
      const nPiece = new Piece(piece.bufferIndex, newStart, piece.end, this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end), piece.length - 1);
      node2.piece = nPiece;
      value += "\n";
      updateTreeMetadata(this, node2, -1, -1);
      if (node2.piece.length === 0) {
        nodesToDel.push(node2);
      }
    }
    const newPieces = this.createNewPieces(value);
    let newNode = this.rbInsertLeft(node2, newPieces[newPieces.length - 1]);
    for (let k = newPieces.length - 2; k >= 0; k--) {
      newNode = this.rbInsertLeft(newNode, newPieces[k]);
    }
    this.validateCRLFWithPrevNode(newNode);
    this.deleteNodes(nodesToDel);
  }
  insertContentToNodeRight(value, node2) {
    if (this.adjustCarriageReturnFromNext(value, node2)) {
      value += "\n";
    }
    const newPieces = this.createNewPieces(value);
    const newNode = this.rbInsertRight(node2, newPieces[0]);
    let tmpNode = newNode;
    for (let k = 1; k < newPieces.length; k++) {
      tmpNode = this.rbInsertRight(tmpNode, newPieces[k]);
    }
    this.validateCRLFWithPrevNode(newNode);
  }
  positionInBuffer(node2, remainder, ret) {
    const piece = node2.piece;
    const bufferIndex = node2.piece.bufferIndex;
    const lineStarts = this._buffers[bufferIndex].lineStarts;
    const startOffset = lineStarts[piece.start.line] + piece.start.column;
    const offset = startOffset + remainder;
    let low = piece.start.line;
    let high = piece.end.line;
    let mid = 0;
    let midStop = 0;
    let midStart = 0;
    while (low <= high) {
      mid = low + (high - low) / 2 | 0;
      midStart = lineStarts[mid];
      if (mid === high) {
        break;
      }
      midStop = lineStarts[mid + 1];
      if (offset < midStart) {
        high = mid - 1;
      } else if (offset >= midStop) {
        low = mid + 1;
      } else {
        break;
      }
    }
    if (ret) {
      ret.line = mid;
      ret.column = offset - midStart;
      return null;
    }
    return {
      line: mid,
      column: offset - midStart
    };
  }
  getLineFeedCnt(bufferIndex, start, end) {
    if (end.column === 0) {
      return end.line - start.line;
    }
    const lineStarts = this._buffers[bufferIndex].lineStarts;
    if (end.line === lineStarts.length - 1) {
      return end.line - start.line;
    }
    const nextLineStartOffset = lineStarts[end.line + 1];
    const endOffset = lineStarts[end.line] + end.column;
    if (nextLineStartOffset > endOffset + 1) {
      return end.line - start.line;
    }
    const previousCharOffset = endOffset - 1;
    const buffer = this._buffers[bufferIndex].buffer;
    if (buffer.charCodeAt(previousCharOffset) === 13) {
      return end.line - start.line + 1;
    } else {
      return end.line - start.line;
    }
  }
  offsetInBuffer(bufferIndex, cursor) {
    const lineStarts = this._buffers[bufferIndex].lineStarts;
    return lineStarts[cursor.line] + cursor.column;
  }
  deleteNodes(nodes) {
    for (let i = 0; i < nodes.length; i++) {
      rbDelete(this, nodes[i]);
    }
  }
  createNewPieces(text2) {
    if (text2.length > AverageBufferSize) {
      const newPieces = [];
      while (text2.length > AverageBufferSize) {
        const lastChar = text2.charCodeAt(AverageBufferSize - 1);
        let splitText;
        if (lastChar === 13 || lastChar >= 55296 && lastChar <= 56319) {
          splitText = text2.substring(0, AverageBufferSize - 1);
          text2 = text2.substring(AverageBufferSize - 1);
        } else {
          splitText = text2.substring(0, AverageBufferSize);
          text2 = text2.substring(AverageBufferSize);
        }
        const lineStarts3 = createLineStartsFast(splitText);
        newPieces.push(new Piece(
          this._buffers.length,
          /* buffer index */
          { line: 0, column: 0 },
          { line: lineStarts3.length - 1, column: splitText.length - lineStarts3[lineStarts3.length - 1] },
          lineStarts3.length - 1,
          splitText.length
        ));
        this._buffers.push(new StringBuffer(splitText, lineStarts3));
      }
      const lineStarts2 = createLineStartsFast(text2);
      newPieces.push(new Piece(
        this._buffers.length,
        /* buffer index */
        { line: 0, column: 0 },
        { line: lineStarts2.length - 1, column: text2.length - lineStarts2[lineStarts2.length - 1] },
        lineStarts2.length - 1,
        text2.length
      ));
      this._buffers.push(new StringBuffer(text2, lineStarts2));
      return newPieces;
    }
    let startOffset = this._buffers[0].buffer.length;
    const lineStarts = createLineStartsFast(text2, false);
    let start = this._lastChangeBufferPos;
    if (this._buffers[0].lineStarts[this._buffers[0].lineStarts.length - 1] === startOffset && startOffset !== 0 && this.startWithLF(text2) && this.endWithCR(this._buffers[0].buffer)) {
      this._lastChangeBufferPos = { line: this._lastChangeBufferPos.line, column: this._lastChangeBufferPos.column + 1 };
      start = this._lastChangeBufferPos;
      for (let i = 0; i < lineStarts.length; i++) {
        lineStarts[i] += startOffset + 1;
      }
      this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1));
      this._buffers[0].buffer += "_" + text2;
      startOffset += 1;
    } else {
      if (startOffset !== 0) {
        for (let i = 0; i < lineStarts.length; i++) {
          lineStarts[i] += startOffset;
        }
      }
      this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1));
      this._buffers[0].buffer += text2;
    }
    const endOffset = this._buffers[0].buffer.length;
    const endIndex = this._buffers[0].lineStarts.length - 1;
    const endColumn = endOffset - this._buffers[0].lineStarts[endIndex];
    const endPos = { line: endIndex, column: endColumn };
    const newPiece = new Piece(
      0,
      /** todo@peng */
      start,
      endPos,
      this.getLineFeedCnt(0, start, endPos),
      endOffset - startOffset
    );
    this._lastChangeBufferPos = endPos;
    return [newPiece];
  }
  getLineRawContent(lineNumber, endOffset = 0) {
    let x = this.root;
    let ret = "";
    const cache2 = this._searchCache.get2(lineNumber);
    if (cache2) {
      x = cache2.node;
      const prevAccumulatedValue = this.getAccumulatedValue(x, lineNumber - cache2.nodeStartLineNumber - 1);
      const buffer = this._buffers[x.piece.bufferIndex].buffer;
      const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
      if (cache2.nodeStartLineNumber + x.piece.lineFeedCnt === lineNumber) {
        ret = buffer.substring(startOffset + prevAccumulatedValue, startOffset + x.piece.length);
      } else {
        const accumulatedValue = this.getAccumulatedValue(x, lineNumber - cache2.nodeStartLineNumber);
        return buffer.substring(startOffset + prevAccumulatedValue, startOffset + accumulatedValue - endOffset);
      }
    } else {
      let nodeStartOffset = 0;
      const originalLineNumber = lineNumber;
      while (x !== SENTINEL) {
        if (x.left !== SENTINEL && x.lf_left >= lineNumber - 1) {
          x = x.left;
        } else if (x.lf_left + x.piece.lineFeedCnt > lineNumber - 1) {
          const prevAccumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
          const accumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 1);
          const buffer = this._buffers[x.piece.bufferIndex].buffer;
          const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
          nodeStartOffset += x.size_left;
          this._searchCache.set({
            node: x,
            nodeStartOffset,
            nodeStartLineNumber: originalLineNumber - (lineNumber - 1 - x.lf_left)
          });
          return buffer.substring(startOffset + prevAccumulatedValue, startOffset + accumulatedValue - endOffset);
        } else if (x.lf_left + x.piece.lineFeedCnt === lineNumber - 1) {
          const prevAccumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
          const buffer = this._buffers[x.piece.bufferIndex].buffer;
          const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
          ret = buffer.substring(startOffset + prevAccumulatedValue, startOffset + x.piece.length);
          break;
        } else {
          lineNumber -= x.lf_left + x.piece.lineFeedCnt;
          nodeStartOffset += x.size_left + x.piece.length;
          x = x.right;
        }
      }
    }
    x = x.next();
    while (x !== SENTINEL) {
      const buffer = this._buffers[x.piece.bufferIndex].buffer;
      if (x.piece.lineFeedCnt > 0) {
        const accumulatedValue = this.getAccumulatedValue(x, 0);
        const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
        ret += buffer.substring(startOffset, startOffset + accumulatedValue - endOffset);
        return ret;
      } else {
        const startOffset = this.offsetInBuffer(x.piece.bufferIndex, x.piece.start);
        ret += buffer.substr(startOffset, x.piece.length);
      }
      x = x.next();
    }
    return ret;
  }
  computeBufferMetadata() {
    let x = this.root;
    let lfCnt = 1;
    let len = 0;
    while (x !== SENTINEL) {
      lfCnt += x.lf_left + x.piece.lineFeedCnt;
      len += x.size_left + x.piece.length;
      x = x.right;
    }
    this._lineCnt = lfCnt;
    this._length = len;
    this._searchCache.validate(this._length);
  }
  // #region node operations
  getIndexOf(node2, accumulatedValue) {
    const piece = node2.piece;
    const pos = this.positionInBuffer(node2, accumulatedValue);
    const lineCnt = pos.line - piece.start.line;
    if (this.offsetInBuffer(piece.bufferIndex, piece.end) - this.offsetInBuffer(piece.bufferIndex, piece.start) === accumulatedValue) {
      const realLineCnt = this.getLineFeedCnt(node2.piece.bufferIndex, piece.start, pos);
      if (realLineCnt !== lineCnt) {
        return { index: realLineCnt, remainder: 0 };
      }
    }
    return { index: lineCnt, remainder: pos.column };
  }
  getAccumulatedValue(node2, index) {
    if (index < 0) {
      return 0;
    }
    const piece = node2.piece;
    const lineStarts = this._buffers[piece.bufferIndex].lineStarts;
    const expectedLineStartIndex = piece.start.line + index + 1;
    if (expectedLineStartIndex > piece.end.line) {
      return lineStarts[piece.end.line] + piece.end.column - lineStarts[piece.start.line] - piece.start.column;
    } else {
      return lineStarts[expectedLineStartIndex] - lineStarts[piece.start.line] - piece.start.column;
    }
  }
  deleteNodeTail(node2, pos) {
    const piece = node2.piece;
    const originalLFCnt = piece.lineFeedCnt;
    const originalEndOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);
    const newEnd = pos;
    const newEndOffset = this.offsetInBuffer(piece.bufferIndex, newEnd);
    const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, piece.start, newEnd);
    const lf_delta = newLineFeedCnt - originalLFCnt;
    const size_delta = newEndOffset - originalEndOffset;
    const newLength = piece.length + size_delta;
    node2.piece = new Piece(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength);
    updateTreeMetadata(this, node2, size_delta, lf_delta);
  }
  deleteNodeHead(node2, pos) {
    const piece = node2.piece;
    const originalLFCnt = piece.lineFeedCnt;
    const originalStartOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);
    const newStart = pos;
    const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end);
    const newStartOffset = this.offsetInBuffer(piece.bufferIndex, newStart);
    const lf_delta = newLineFeedCnt - originalLFCnt;
    const size_delta = originalStartOffset - newStartOffset;
    const newLength = piece.length + size_delta;
    node2.piece = new Piece(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength);
    updateTreeMetadata(this, node2, size_delta, lf_delta);
  }
  shrinkNode(node2, start, end) {
    const piece = node2.piece;
    const originalStartPos = piece.start;
    const originalEndPos = piece.end;
    const oldLength = piece.length;
    const oldLFCnt = piece.lineFeedCnt;
    const newEnd = start;
    const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, piece.start, newEnd);
    const newLength = this.offsetInBuffer(piece.bufferIndex, start) - this.offsetInBuffer(piece.bufferIndex, originalStartPos);
    node2.piece = new Piece(piece.bufferIndex, piece.start, newEnd, newLineFeedCnt, newLength);
    updateTreeMetadata(this, node2, newLength - oldLength, newLineFeedCnt - oldLFCnt);
    const newPiece = new Piece(piece.bufferIndex, end, originalEndPos, this.getLineFeedCnt(piece.bufferIndex, end, originalEndPos), this.offsetInBuffer(piece.bufferIndex, originalEndPos) - this.offsetInBuffer(piece.bufferIndex, end));
    const newNode = this.rbInsertRight(node2, newPiece);
    this.validateCRLFWithPrevNode(newNode);
  }
  appendToNode(node2, value) {
    if (this.adjustCarriageReturnFromNext(value, node2)) {
      value += "\n";
    }
    const hitCRLF = this.shouldCheckCRLF() && this.startWithLF(value) && this.endWithCR(node2);
    const startOffset = this._buffers[0].buffer.length;
    this._buffers[0].buffer += value;
    const lineStarts = createLineStartsFast(value, false);
    for (let i = 0; i < lineStarts.length; i++) {
      lineStarts[i] += startOffset;
    }
    if (hitCRLF) {
      const prevStartOffset = this._buffers[0].lineStarts[this._buffers[0].lineStarts.length - 2];
      this._buffers[0].lineStarts.pop();
      this._lastChangeBufferPos = { line: this._lastChangeBufferPos.line - 1, column: startOffset - prevStartOffset };
    }
    this._buffers[0].lineStarts = this._buffers[0].lineStarts.concat(lineStarts.slice(1));
    const endIndex = this._buffers[0].lineStarts.length - 1;
    const endColumn = this._buffers[0].buffer.length - this._buffers[0].lineStarts[endIndex];
    const newEnd = { line: endIndex, column: endColumn };
    const newLength = node2.piece.length + value.length;
    const oldLineFeedCnt = node2.piece.lineFeedCnt;
    const newLineFeedCnt = this.getLineFeedCnt(0, node2.piece.start, newEnd);
    const lf_delta = newLineFeedCnt - oldLineFeedCnt;
    node2.piece = new Piece(node2.piece.bufferIndex, node2.piece.start, newEnd, newLineFeedCnt, newLength);
    this._lastChangeBufferPos = newEnd;
    updateTreeMetadata(this, node2, value.length, lf_delta);
  }
  nodeAt(offset) {
    let x = this.root;
    const cache2 = this._searchCache.get(offset);
    if (cache2) {
      return {
        node: cache2.node,
        nodeStartOffset: cache2.nodeStartOffset,
        remainder: offset - cache2.nodeStartOffset
      };
    }
    let nodeStartOffset = 0;
    while (x !== SENTINEL) {
      if (x.size_left > offset) {
        x = x.left;
      } else if (x.size_left + x.piece.length >= offset) {
        nodeStartOffset += x.size_left;
        const ret = {
          node: x,
          remainder: offset - x.size_left,
          nodeStartOffset
        };
        this._searchCache.set(ret);
        return ret;
      } else {
        offset -= x.size_left + x.piece.length;
        nodeStartOffset += x.size_left + x.piece.length;
        x = x.right;
      }
    }
    return null;
  }
  nodeAt2(lineNumber, column) {
    let x = this.root;
    let nodeStartOffset = 0;
    while (x !== SENTINEL) {
      if (x.left !== SENTINEL && x.lf_left >= lineNumber - 1) {
        x = x.left;
      } else if (x.lf_left + x.piece.lineFeedCnt > lineNumber - 1) {
        const prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
        const accumulatedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 1);
        nodeStartOffset += x.size_left;
        return {
          node: x,
          remainder: Math.min(prevAccumualtedValue + column - 1, accumulatedValue),
          nodeStartOffset
        };
      } else if (x.lf_left + x.piece.lineFeedCnt === lineNumber - 1) {
        const prevAccumualtedValue = this.getAccumulatedValue(x, lineNumber - x.lf_left - 2);
        if (prevAccumualtedValue + column - 1 <= x.piece.length) {
          return {
            node: x,
            remainder: prevAccumualtedValue + column - 1,
            nodeStartOffset
          };
        } else {
          column -= x.piece.length - prevAccumualtedValue;
          break;
        }
      } else {
        lineNumber -= x.lf_left + x.piece.lineFeedCnt;
        nodeStartOffset += x.size_left + x.piece.length;
        x = x.right;
      }
    }
    x = x.next();
    while (x !== SENTINEL) {
      if (x.piece.lineFeedCnt > 0) {
        const accumulatedValue = this.getAccumulatedValue(x, 0);
        const nodeStartOffset2 = this.offsetOfNode(x);
        return {
          node: x,
          remainder: Math.min(column - 1, accumulatedValue),
          nodeStartOffset: nodeStartOffset2
        };
      } else {
        if (x.piece.length >= column - 1) {
          const nodeStartOffset2 = this.offsetOfNode(x);
          return {
            node: x,
            remainder: column - 1,
            nodeStartOffset: nodeStartOffset2
          };
        } else {
          column -= x.piece.length;
        }
      }
      x = x.next();
    }
    return null;
  }
  nodeCharCodeAt(node2, offset) {
    if (node2.piece.lineFeedCnt < 1) {
      return -1;
    }
    const buffer = this._buffers[node2.piece.bufferIndex];
    const newOffset = this.offsetInBuffer(node2.piece.bufferIndex, node2.piece.start) + offset;
    return buffer.buffer.charCodeAt(newOffset);
  }
  offsetOfNode(node2) {
    if (!node2) {
      return 0;
    }
    let pos = node2.size_left;
    while (node2 !== this.root) {
      if (node2.parent.right === node2) {
        pos += node2.parent.size_left + node2.parent.piece.length;
      }
      node2 = node2.parent;
    }
    return pos;
  }
  // #endregion
  // #region CRLF
  shouldCheckCRLF() {
    return !(this._EOLNormalized && this._EOL === "\n");
  }
  startWithLF(val) {
    if (typeof val === "string") {
      return val.charCodeAt(0) === 10;
    }
    if (val === SENTINEL || val.piece.lineFeedCnt === 0) {
      return false;
    }
    const piece = val.piece;
    const lineStarts = this._buffers[piece.bufferIndex].lineStarts;
    const line = piece.start.line;
    const startOffset = lineStarts[line] + piece.start.column;
    if (line === lineStarts.length - 1) {
      return false;
    }
    const nextLineOffset = lineStarts[line + 1];
    if (nextLineOffset > startOffset + 1) {
      return false;
    }
    return this._buffers[piece.bufferIndex].buffer.charCodeAt(startOffset) === 10;
  }
  endWithCR(val) {
    if (typeof val === "string") {
      return val.charCodeAt(val.length - 1) === 13;
    }
    if (val === SENTINEL || val.piece.lineFeedCnt === 0) {
      return false;
    }
    return this.nodeCharCodeAt(val, val.piece.length - 1) === 13;
  }
  validateCRLFWithPrevNode(nextNode) {
    if (this.shouldCheckCRLF() && this.startWithLF(nextNode)) {
      const node2 = nextNode.prev();
      if (this.endWithCR(node2)) {
        this.fixCRLF(node2, nextNode);
      }
    }
  }
  validateCRLFWithNextNode(node2) {
    if (this.shouldCheckCRLF() && this.endWithCR(node2)) {
      const nextNode = node2.next();
      if (this.startWithLF(nextNode)) {
        this.fixCRLF(node2, nextNode);
      }
    }
  }
  fixCRLF(prev, next) {
    const nodesToDel = [];
    const lineStarts = this._buffers[prev.piece.bufferIndex].lineStarts;
    let newEnd;
    if (prev.piece.end.column === 0) {
      newEnd = { line: prev.piece.end.line - 1, column: lineStarts[prev.piece.end.line] - lineStarts[prev.piece.end.line - 1] - 1 };
    } else {
      newEnd = { line: prev.piece.end.line, column: prev.piece.end.column - 1 };
    }
    const prevNewLength = prev.piece.length - 1;
    const prevNewLFCnt = prev.piece.lineFeedCnt - 1;
    prev.piece = new Piece(prev.piece.bufferIndex, prev.piece.start, newEnd, prevNewLFCnt, prevNewLength);
    updateTreeMetadata(this, prev, -1, -1);
    if (prev.piece.length === 0) {
      nodesToDel.push(prev);
    }
    const newStart = { line: next.piece.start.line + 1, column: 0 };
    const newLength = next.piece.length - 1;
    const newLineFeedCnt = this.getLineFeedCnt(next.piece.bufferIndex, newStart, next.piece.end);
    next.piece = new Piece(next.piece.bufferIndex, newStart, next.piece.end, newLineFeedCnt, newLength);
    updateTreeMetadata(this, next, -1, -1);
    if (next.piece.length === 0) {
      nodesToDel.push(next);
    }
    const pieces = this.createNewPieces("\r\n");
    this.rbInsertRight(prev, pieces[0]);
    for (let i = 0; i < nodesToDel.length; i++) {
      rbDelete(this, nodesToDel[i]);
    }
  }
  adjustCarriageReturnFromNext(value, node2) {
    if (this.shouldCheckCRLF() && this.endWithCR(value)) {
      const nextNode = node2.next();
      if (this.startWithLF(nextNode)) {
        value += "\n";
        if (nextNode.piece.length === 1) {
          rbDelete(this, nextNode);
        } else {
          const piece = nextNode.piece;
          const newStart = { line: piece.start.line + 1, column: 0 };
          const newLength = piece.length - 1;
          const newLineFeedCnt = this.getLineFeedCnt(piece.bufferIndex, newStart, piece.end);
          nextNode.piece = new Piece(piece.bufferIndex, newStart, piece.end, newLineFeedCnt, newLength);
          updateTreeMetadata(this, nextNode, -1, -1);
        }
        return true;
      }
    }
    return false;
  }
  // #endregion
  // #endregion
  // #region Tree operations
  iterate(node2, callback) {
    if (node2 === SENTINEL) {
      return callback(SENTINEL);
    }
    const leftRet = this.iterate(node2.left, callback);
    if (!leftRet) {
      return leftRet;
    }
    return callback(node2) && this.iterate(node2.right, callback);
  }
  getNodeContent(node2) {
    if (node2 === SENTINEL) {
      return "";
    }
    const buffer = this._buffers[node2.piece.bufferIndex];
    const piece = node2.piece;
    const startOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);
    const endOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);
    const currentContent = buffer.buffer.substring(startOffset, endOffset);
    return currentContent;
  }
  getPieceContent(piece) {
    const buffer = this._buffers[piece.bufferIndex];
    const startOffset = this.offsetInBuffer(piece.bufferIndex, piece.start);
    const endOffset = this.offsetInBuffer(piece.bufferIndex, piece.end);
    const currentContent = buffer.buffer.substring(startOffset, endOffset);
    return currentContent;
  }
  /**
   *      node              node
   *     /  \              /  \
   *    a   b    <----   a    b
   *                         /
   *                        z
   */
  rbInsertRight(node2, p2) {
    const z = new TreeNode(
      p2,
      1
      /* NodeColor.Red */
    );
    z.left = SENTINEL;
    z.right = SENTINEL;
    z.parent = SENTINEL;
    z.size_left = 0;
    z.lf_left = 0;
    const x = this.root;
    if (x === SENTINEL) {
      this.root = z;
      z.color = 0;
    } else if (node2.right === SENTINEL) {
      node2.right = z;
      z.parent = node2;
    } else {
      const nextNode = leftest(node2.right);
      nextNode.left = z;
      z.parent = nextNode;
    }
    fixInsert(this, z);
    return z;
  }
  /**
   *      node              node
   *     /  \              /  \
   *    a   b     ---->   a    b
   *                       \
   *                        z
   */
  rbInsertLeft(node2, p2) {
    const z = new TreeNode(
      p2,
      1
      /* NodeColor.Red */
    );
    z.left = SENTINEL;
    z.right = SENTINEL;
    z.parent = SENTINEL;
    z.size_left = 0;
    z.lf_left = 0;
    if (this.root === SENTINEL) {
      this.root = z;
      z.color = 0;
    } else if (node2.left === SENTINEL) {
      node2.left = z;
      z.parent = node2;
    } else {
      const prevNode = righttest(node2.left);
      prevNode.right = z;
      z.parent = prevNode;
    }
    fixInsert(this, z);
    return z;
  }
}
class PieceTreeTextBuffer extends Disposable {
  constructor(chunks, BOM, eol, containsRTL2, containsUnusualLineTerminators2, isBasicASCII2, eolNormalized) {
    super();
    this._onDidChangeContent = this._register(new Emitter$1());
    this._BOM = BOM;
    this._mightContainNonBasicASCII = !isBasicASCII2;
    this._mightContainRTL = containsRTL2;
    this._mightContainUnusualLineTerminators = containsUnusualLineTerminators2;
    this._pieceTree = new PieceTreeBase(chunks, eol, eolNormalized);
  }
  mightContainRTL() {
    return this._mightContainRTL;
  }
  mightContainUnusualLineTerminators() {
    return this._mightContainUnusualLineTerminators;
  }
  resetMightContainUnusualLineTerminators() {
    this._mightContainUnusualLineTerminators = false;
  }
  mightContainNonBasicASCII() {
    return this._mightContainNonBasicASCII;
  }
  getBOM() {
    return this._BOM;
  }
  getEOL() {
    return this._pieceTree.getEOL();
  }
  createSnapshot(preserveBOM) {
    return this._pieceTree.createSnapshot(preserveBOM ? this._BOM : "");
  }
  getOffsetAt(lineNumber, column) {
    return this._pieceTree.getOffsetAt(lineNumber, column);
  }
  getPositionAt(offset) {
    return this._pieceTree.getPositionAt(offset);
  }
  getRangeAt(start, length2) {
    const end = start + length2;
    const startPosition = this.getPositionAt(start);
    const endPosition = this.getPositionAt(end);
    return new Range$2(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column);
  }
  getValueInRange(range2, eol = 0) {
    if (range2.isEmpty()) {
      return "";
    }
    const lineEnding = this._getEndOfLine(eol);
    return this._pieceTree.getValueInRange(range2, lineEnding);
  }
  getValueLengthInRange(range2, eol = 0) {
    if (range2.isEmpty()) {
      return 0;
    }
    if (range2.startLineNumber === range2.endLineNumber) {
      return range2.endColumn - range2.startColumn;
    }
    const startOffset = this.getOffsetAt(range2.startLineNumber, range2.startColumn);
    const endOffset = this.getOffsetAt(range2.endLineNumber, range2.endColumn);
    let eolOffsetCompensation = 0;
    const desiredEOL = this._getEndOfLine(eol);
    const actualEOL = this.getEOL();
    if (desiredEOL.length !== actualEOL.length) {
      const delta = desiredEOL.length - actualEOL.length;
      const eolCount = range2.endLineNumber - range2.startLineNumber;
      eolOffsetCompensation = delta * eolCount;
    }
    return endOffset - startOffset + eolOffsetCompensation;
  }
  getCharacterCountInRange(range2, eol = 0) {
    if (this._mightContainNonBasicASCII) {
      let result2 = 0;
      const fromLineNumber = range2.startLineNumber;
      const toLineNumber = range2.endLineNumber;
      for (let lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {
        const lineContent = this.getLineContent(lineNumber);
        const fromOffset = lineNumber === fromLineNumber ? range2.startColumn - 1 : 0;
        const toOffset = lineNumber === toLineNumber ? range2.endColumn - 1 : lineContent.length;
        for (let offset = fromOffset; offset < toOffset; offset++) {
          if (isHighSurrogate(lineContent.charCodeAt(offset))) {
            result2 = result2 + 1;
            offset = offset + 1;
          } else {
            result2 = result2 + 1;
          }
        }
      }
      result2 += this._getEndOfLine(eol).length * (toLineNumber - fromLineNumber);
      return result2;
    }
    return this.getValueLengthInRange(range2, eol);
  }
  getLength() {
    return this._pieceTree.getLength();
  }
  getLineCount() {
    return this._pieceTree.getLineCount();
  }
  getLinesContent() {
    return this._pieceTree.getLinesContent();
  }
  getLineContent(lineNumber) {
    return this._pieceTree.getLineContent(lineNumber);
  }
  getLineCharCode(lineNumber, index) {
    return this._pieceTree.getLineCharCode(lineNumber, index);
  }
  getLineLength(lineNumber) {
    return this._pieceTree.getLineLength(lineNumber);
  }
  getLineFirstNonWhitespaceColumn(lineNumber) {
    const result2 = firstNonWhitespaceIndex(this.getLineContent(lineNumber));
    if (result2 === -1) {
      return 0;
    }
    return result2 + 1;
  }
  getLineLastNonWhitespaceColumn(lineNumber) {
    const result2 = lastNonWhitespaceIndex(this.getLineContent(lineNumber));
    if (result2 === -1) {
      return 0;
    }
    return result2 + 2;
  }
  _getEndOfLine(eol) {
    switch (eol) {
      case 1:
        return "\n";
      case 2:
        return "\r\n";
      case 0:
        return this.getEOL();
      default:
        throw new Error("Unknown EOL preference");
    }
  }
  setEOL(newEOL) {
    this._pieceTree.setEOL(newEOL);
  }
  applyEdits(rawOperations, recordTrimAutoWhitespace, computeUndoEdits) {
    let mightContainRTL = this._mightContainRTL;
    let mightContainUnusualLineTerminators = this._mightContainUnusualLineTerminators;
    let mightContainNonBasicASCII = this._mightContainNonBasicASCII;
    let canReduceOperations = true;
    let operations = [];
    for (let i = 0; i < rawOperations.length; i++) {
      const op = rawOperations[i];
      if (canReduceOperations && op._isTracked) {
        canReduceOperations = false;
      }
      const validatedRange = op.range;
      if (op.text) {
        let textMightContainNonBasicASCII = true;
        if (!mightContainNonBasicASCII) {
          textMightContainNonBasicASCII = !isBasicASCII(op.text);
          mightContainNonBasicASCII = textMightContainNonBasicASCII;
        }
        if (!mightContainRTL && textMightContainNonBasicASCII) {
          mightContainRTL = containsRTL(op.text);
        }
        if (!mightContainUnusualLineTerminators && textMightContainNonBasicASCII) {
          mightContainUnusualLineTerminators = containsUnusualLineTerminators(op.text);
        }
      }
      let validText = "";
      let eolCount = 0;
      let firstLineLength = 0;
      let lastLineLength2 = 0;
      if (op.text) {
        let strEOL;
        [eolCount, firstLineLength, lastLineLength2, strEOL] = countEOL(op.text);
        const bufferEOL = this.getEOL();
        const expectedStrEOL = bufferEOL === "\r\n" ? 2 : 1;
        if (strEOL === 0 || strEOL === expectedStrEOL) {
          validText = op.text;
        } else {
          validText = op.text.replace(/\r\n|\r|\n/g, bufferEOL);
        }
      }
      operations[i] = {
        sortIndex: i,
        identifier: op.identifier || null,
        range: validatedRange,
        rangeOffset: this.getOffsetAt(validatedRange.startLineNumber, validatedRange.startColumn),
        rangeLength: this.getValueLengthInRange(validatedRange),
        text: validText,
        eolCount,
        firstLineLength,
        lastLineLength: lastLineLength2,
        forceMoveMarkers: Boolean(op.forceMoveMarkers),
        isAutoWhitespaceEdit: op.isAutoWhitespaceEdit || false
      };
    }
    operations.sort(PieceTreeTextBuffer._sortOpsAscending);
    let hasTouchingRanges = false;
    for (let i = 0, count = operations.length - 1; i < count; i++) {
      const rangeEnd = operations[i].range.getEndPosition();
      const nextRangeStart = operations[i + 1].range.getStartPosition();
      if (nextRangeStart.isBeforeOrEqual(rangeEnd)) {
        if (nextRangeStart.isBefore(rangeEnd)) {
          throw new Error("Overlapping ranges are not allowed!");
        }
        hasTouchingRanges = true;
      }
    }
    if (canReduceOperations) {
      operations = this._reduceOperations(operations);
    }
    const reverseRanges = computeUndoEdits || recordTrimAutoWhitespace ? PieceTreeTextBuffer._getInverseEditRanges(operations) : [];
    const newTrimAutoWhitespaceCandidates = [];
    if (recordTrimAutoWhitespace) {
      for (let i = 0; i < operations.length; i++) {
        const op = operations[i];
        const reverseRange = reverseRanges[i];
        if (op.isAutoWhitespaceEdit && op.range.isEmpty()) {
          for (let lineNumber = reverseRange.startLineNumber; lineNumber <= reverseRange.endLineNumber; lineNumber++) {
            let currentLineContent = "";
            if (lineNumber === reverseRange.startLineNumber) {
              currentLineContent = this.getLineContent(op.range.startLineNumber);
              if (firstNonWhitespaceIndex(currentLineContent) !== -1) {
                continue;
              }
            }
            newTrimAutoWhitespaceCandidates.push({ lineNumber, oldContent: currentLineContent });
          }
        }
      }
    }
    let reverseOperations = null;
    if (computeUndoEdits) {
      let reverseRangeDeltaOffset = 0;
      reverseOperations = [];
      for (let i = 0; i < operations.length; i++) {
        const op = operations[i];
        const reverseRange = reverseRanges[i];
        const bufferText = this.getValueInRange(op.range);
        const reverseRangeOffset = op.rangeOffset + reverseRangeDeltaOffset;
        reverseRangeDeltaOffset += op.text.length - bufferText.length;
        reverseOperations[i] = {
          sortIndex: op.sortIndex,
          identifier: op.identifier,
          range: reverseRange,
          text: bufferText,
          textChange: new TextChange(op.rangeOffset, bufferText, reverseRangeOffset, op.text)
        };
      }
      if (!hasTouchingRanges) {
        reverseOperations.sort((a, b) => a.sortIndex - b.sortIndex);
      }
    }
    this._mightContainRTL = mightContainRTL;
    this._mightContainUnusualLineTerminators = mightContainUnusualLineTerminators;
    this._mightContainNonBasicASCII = mightContainNonBasicASCII;
    const contentChanges = this._doApplyEdits(operations);
    let trimAutoWhitespaceLineNumbers = null;
    if (recordTrimAutoWhitespace && newTrimAutoWhitespaceCandidates.length > 0) {
      newTrimAutoWhitespaceCandidates.sort((a, b) => b.lineNumber - a.lineNumber);
      trimAutoWhitespaceLineNumbers = [];
      for (let i = 0, len = newTrimAutoWhitespaceCandidates.length; i < len; i++) {
        const lineNumber = newTrimAutoWhitespaceCandidates[i].lineNumber;
        if (i > 0 && newTrimAutoWhitespaceCandidates[i - 1].lineNumber === lineNumber) {
          continue;
        }
        const prevContent = newTrimAutoWhitespaceCandidates[i].oldContent;
        const lineContent = this.getLineContent(lineNumber);
        if (lineContent.length === 0 || lineContent === prevContent || firstNonWhitespaceIndex(lineContent) !== -1) {
          continue;
        }
        trimAutoWhitespaceLineNumbers.push(lineNumber);
      }
    }
    this._onDidChangeContent.fire();
    return new ApplyEditsResult(reverseOperations, contentChanges, trimAutoWhitespaceLineNumbers);
  }
  /**
   * Transform operations such that they represent the same logic edit,
   * but that they also do not cause OOM crashes.
   */
  _reduceOperations(operations) {
    if (operations.length < 1e3) {
      return operations;
    }
    return [this._toSingleEditOperation(operations)];
  }
  _toSingleEditOperation(operations) {
    let forceMoveMarkers = false;
    const firstEditRange = operations[0].range;
    const lastEditRange = operations[operations.length - 1].range;
    const entireEditRange = new Range$2(firstEditRange.startLineNumber, firstEditRange.startColumn, lastEditRange.endLineNumber, lastEditRange.endColumn);
    let lastEndLineNumber = firstEditRange.startLineNumber;
    let lastEndColumn = firstEditRange.startColumn;
    const result2 = [];
    for (let i = 0, len = operations.length; i < len; i++) {
      const operation = operations[i];
      const range2 = operation.range;
      forceMoveMarkers = forceMoveMarkers || operation.forceMoveMarkers;
      result2.push(this.getValueInRange(new Range$2(lastEndLineNumber, lastEndColumn, range2.startLineNumber, range2.startColumn)));
      if (operation.text.length > 0) {
        result2.push(operation.text);
      }
      lastEndLineNumber = range2.endLineNumber;
      lastEndColumn = range2.endColumn;
    }
    const text2 = result2.join("");
    const [eolCount, firstLineLength, lastLineLength2] = countEOL(text2);
    return {
      sortIndex: 0,
      identifier: operations[0].identifier,
      range: entireEditRange,
      rangeOffset: this.getOffsetAt(entireEditRange.startLineNumber, entireEditRange.startColumn),
      rangeLength: this.getValueLengthInRange(
        entireEditRange,
        0
        /* EndOfLinePreference.TextDefined */
      ),
      text: text2,
      eolCount,
      firstLineLength,
      lastLineLength: lastLineLength2,
      forceMoveMarkers,
      isAutoWhitespaceEdit: false
    };
  }
  _doApplyEdits(operations) {
    operations.sort(PieceTreeTextBuffer._sortOpsDescending);
    const contentChanges = [];
    for (let i = 0; i < operations.length; i++) {
      const op = operations[i];
      const startLineNumber = op.range.startLineNumber;
      const startColumn = op.range.startColumn;
      const endLineNumber = op.range.endLineNumber;
      const endColumn = op.range.endColumn;
      if (startLineNumber === endLineNumber && startColumn === endColumn && op.text.length === 0) {
        continue;
      }
      if (op.text) {
        this._pieceTree.delete(op.rangeOffset, op.rangeLength);
        this._pieceTree.insert(op.rangeOffset, op.text, true);
      } else {
        this._pieceTree.delete(op.rangeOffset, op.rangeLength);
      }
      const contentChangeRange = new Range$2(startLineNumber, startColumn, endLineNumber, endColumn);
      contentChanges.push({
        range: contentChangeRange,
        rangeLength: op.rangeLength,
        text: op.text,
        rangeOffset: op.rangeOffset,
        forceMoveMarkers: op.forceMoveMarkers
      });
    }
    return contentChanges;
  }
  findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount) {
    return this._pieceTree.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);
  }
  /**
   * Assumes `operations` are validated and sorted ascending
   */
  static _getInverseEditRanges(operations) {
    const result2 = [];
    let prevOpEndLineNumber = 0;
    let prevOpEndColumn = 0;
    let prevOp = null;
    for (let i = 0, len = operations.length; i < len; i++) {
      const op = operations[i];
      let startLineNumber;
      let startColumn;
      if (prevOp) {
        if (prevOp.range.endLineNumber === op.range.startLineNumber) {
          startLineNumber = prevOpEndLineNumber;
          startColumn = prevOpEndColumn + (op.range.startColumn - prevOp.range.endColumn);
        } else {
          startLineNumber = prevOpEndLineNumber + (op.range.startLineNumber - prevOp.range.endLineNumber);
          startColumn = op.range.startColumn;
        }
      } else {
        startLineNumber = op.range.startLineNumber;
        startColumn = op.range.startColumn;
      }
      let resultRange;
      if (op.text.length > 0) {
        const lineCount = op.eolCount + 1;
        if (lineCount === 1) {
          resultRange = new Range$2(startLineNumber, startColumn, startLineNumber, startColumn + op.firstLineLength);
        } else {
          resultRange = new Range$2(startLineNumber, startColumn, startLineNumber + lineCount - 1, op.lastLineLength + 1);
        }
      } else {
        resultRange = new Range$2(startLineNumber, startColumn, startLineNumber, startColumn);
      }
      prevOpEndLineNumber = resultRange.endLineNumber;
      prevOpEndColumn = resultRange.endColumn;
      result2.push(resultRange);
      prevOp = op;
    }
    return result2;
  }
  static _sortOpsAscending(a, b) {
    const r = Range$2.compareRangesUsingEnds(a.range, b.range);
    if (r === 0) {
      return a.sortIndex - b.sortIndex;
    }
    return r;
  }
  static _sortOpsDescending(a, b) {
    const r = Range$2.compareRangesUsingEnds(a.range, b.range);
    if (r === 0) {
      return b.sortIndex - a.sortIndex;
    }
    return -r;
  }
}
class PieceTreeTextBufferFactory {
  constructor(_chunks, _bom, _cr, _lf, _crlf, _containsRTL, _containsUnusualLineTerminators, _isBasicASCII, _normalizeEOL) {
    this._chunks = _chunks;
    this._bom = _bom;
    this._cr = _cr;
    this._lf = _lf;
    this._crlf = _crlf;
    this._containsRTL = _containsRTL;
    this._containsUnusualLineTerminators = _containsUnusualLineTerminators;
    this._isBasicASCII = _isBasicASCII;
    this._normalizeEOL = _normalizeEOL;
  }
  _getEOL(defaultEOL) {
    const totalEOLCount = this._cr + this._lf + this._crlf;
    const totalCRCount = this._cr + this._crlf;
    if (totalEOLCount === 0) {
      return defaultEOL === 1 ? "\n" : "\r\n";
    }
    if (totalCRCount > totalEOLCount / 2) {
      return "\r\n";
    }
    return "\n";
  }
  create(defaultEOL) {
    const eol = this._getEOL(defaultEOL);
    const chunks = this._chunks;
    if (this._normalizeEOL && (eol === "\r\n" && (this._cr > 0 || this._lf > 0) || eol === "\n" && (this._cr > 0 || this._crlf > 0))) {
      for (let i = 0, len = chunks.length; i < len; i++) {
        const str2 = chunks[i].buffer.replace(/\r\n|\r|\n/g, eol);
        const newLineStart = createLineStartsFast(str2);
        chunks[i] = new StringBuffer(str2, newLineStart);
      }
    }
    const textBuffer = new PieceTreeTextBuffer(chunks, this._bom, eol, this._containsRTL, this._containsUnusualLineTerminators, this._isBasicASCII, this._normalizeEOL);
    return { textBuffer, disposable: textBuffer };
  }
}
class PieceTreeTextBufferBuilder {
  constructor() {
    this.chunks = [];
    this.BOM = "";
    this._hasPreviousChar = false;
    this._previousChar = 0;
    this._tmpLineStarts = [];
    this.cr = 0;
    this.lf = 0;
    this.crlf = 0;
    this.containsRTL = false;
    this.containsUnusualLineTerminators = false;
    this.isBasicASCII = true;
  }
  acceptChunk(chunk) {
    if (chunk.length === 0) {
      return;
    }
    if (this.chunks.length === 0) {
      if (startsWithUTF8BOM(chunk)) {
        this.BOM = UTF8_BOM_CHARACTER;
        chunk = chunk.substr(1);
      }
    }
    const lastChar = chunk.charCodeAt(chunk.length - 1);
    if (lastChar === 13 || lastChar >= 55296 && lastChar <= 56319) {
      this._acceptChunk1(chunk.substr(0, chunk.length - 1), false);
      this._hasPreviousChar = true;
      this._previousChar = lastChar;
    } else {
      this._acceptChunk1(chunk, false);
      this._hasPreviousChar = false;
      this._previousChar = lastChar;
    }
  }
  _acceptChunk1(chunk, allowEmptyStrings) {
    if (!allowEmptyStrings && chunk.length === 0) {
      return;
    }
    if (this._hasPreviousChar) {
      this._acceptChunk2(String.fromCharCode(this._previousChar) + chunk);
    } else {
      this._acceptChunk2(chunk);
    }
  }
  _acceptChunk2(chunk) {
    const lineStarts = createLineStarts(this._tmpLineStarts, chunk);
    this.chunks.push(new StringBuffer(chunk, lineStarts.lineStarts));
    this.cr += lineStarts.cr;
    this.lf += lineStarts.lf;
    this.crlf += lineStarts.crlf;
    if (!lineStarts.isBasicASCII) {
      this.isBasicASCII = false;
      if (!this.containsRTL) {
        this.containsRTL = containsRTL(chunk);
      }
      if (!this.containsUnusualLineTerminators) {
        this.containsUnusualLineTerminators = containsUnusualLineTerminators(chunk);
      }
    }
  }
  finish(normalizeEOL = true) {
    this._finish();
    return new PieceTreeTextBufferFactory(this.chunks, this.BOM, this.cr, this.lf, this.crlf, this.containsRTL, this.containsUnusualLineTerminators, this.isBasicASCII, normalizeEOL);
  }
  _finish() {
    if (this.chunks.length === 0) {
      this._acceptChunk1("", true);
    }
    if (this._hasPreviousChar) {
      this._hasPreviousChar = false;
      const lastChunk = this.chunks[this.chunks.length - 1];
      lastChunk.buffer += String.fromCharCode(this._previousChar);
      const newLineStarts = createLineStartsFast(lastChunk.buffer);
      lastChunk.lineStarts = newLineStarts;
      if (this._previousChar === 13) {
        this.cr++;
      }
    }
  }
}
class OffsetRange {
  static addRange(range2, sortedRanges) {
    let i = 0;
    while (i < sortedRanges.length && sortedRanges[i].endExclusive < range2.start) {
      i++;
    }
    let j = i;
    while (j < sortedRanges.length && sortedRanges[j].start <= range2.endExclusive) {
      j++;
    }
    if (i === j) {
      sortedRanges.splice(i, 0, range2);
    } else {
      const start = Math.min(range2.start, sortedRanges[i].start);
      const end = Math.max(range2.endExclusive, sortedRanges[j - 1].endExclusive);
      sortedRanges.splice(i, j - i, new OffsetRange(start, end));
    }
  }
  static tryCreate(start, endExclusive) {
    if (start > endExclusive) {
      return void 0;
    }
    return new OffsetRange(start, endExclusive);
  }
  constructor(start, endExclusive) {
    this.start = start;
    this.endExclusive = endExclusive;
    if (start > endExclusive) {
      throw new BugIndicatingError(`Invalid range: ${this.toString()}`);
    }
  }
  get isEmpty() {
    return this.start === this.endExclusive;
  }
  delta(offset) {
    return new OffsetRange(this.start + offset, this.endExclusive + offset);
  }
  get length() {
    return this.endExclusive - this.start;
  }
  toString() {
    return `[${this.start}, ${this.endExclusive})`;
  }
  equals(other) {
    return this.start === other.start && this.endExclusive === other.endExclusive;
  }
  containsRange(other) {
    return this.start <= other.start && other.endExclusive <= this.endExclusive;
  }
  contains(offset) {
    return this.start <= offset && offset < this.endExclusive;
  }
  /**
   * for all numbers n: range1.contains(n) or range2.contains(n) => range1.join(range2).contains(n)
   * The joined range is the smallest range that contains both ranges.
   */
  join(other) {
    return new OffsetRange(Math.min(this.start, other.start), Math.max(this.endExclusive, other.endExclusive));
  }
  /**
   * for all numbers n: range1.contains(n) and range2.contains(n) <=> range1.intersect(range2).contains(n)
   *
   * The resulting range is empty if the ranges do not intersect, but touch.
   * If the ranges don't even touch, the result is undefined.
   */
  intersect(other) {
    const start = Math.max(this.start, other.start);
    const end = Math.min(this.endExclusive, other.endExclusive);
    if (start <= end) {
      return new OffsetRange(start, end);
    }
    return void 0;
  }
}
const NullState = new class {
  clone() {
    return this;
  }
  equals(other) {
    return this === other;
  }
}();
function nullTokenize(languageId, state) {
  return new TokenizationResult([new Token$3(0, "", languageId)], state);
}
function nullTokenizeEncoded(languageId, state) {
  const tokens = new Uint32Array(2);
  tokens[0] = 0;
  tokens[1] = (languageId << 0 | 0 << 8 | 0 << 11 | 1 << 15 | 2 << 24) >>> 0;
  return new EncodedTokenizationResult(tokens, state === null ? NullState : state);
}
class FixedArray {
  constructor(_default) {
    this._default = _default;
    this._store = [];
  }
  get(index) {
    if (index < this._store.length) {
      return this._store[index];
    }
    return this._default;
  }
  set(index, value) {
    while (index >= this._store.length) {
      this._store[this._store.length] = this._default;
    }
    this._store[index] = value;
  }
  replace(index, oldLength, newLength) {
    if (index >= this._store.length) {
      return;
    }
    if (oldLength === 0) {
      this.insert(index, newLength);
      return;
    } else if (newLength === 0) {
      this.delete(index, oldLength);
      return;
    }
    const before = this._store.slice(0, index);
    const after = this._store.slice(index + oldLength);
    const insertArr = arrayFill(newLength, this._default);
    this._store = before.concat(insertArr, after);
  }
  delete(deleteIndex, deleteCount) {
    if (deleteCount === 0 || deleteIndex >= this._store.length) {
      return;
    }
    this._store.splice(deleteIndex, deleteCount);
  }
  insert(insertIndex, insertCount) {
    if (insertCount === 0 || insertIndex >= this._store.length) {
      return;
    }
    const arr = [];
    for (let i = 0; i < insertCount; i++) {
      arr[i] = this._default;
    }
    this._store = arrayInsert(this._store, insertIndex, arr);
  }
}
function arrayFill(length2, value) {
  const arr = [];
  for (let i = 0; i < length2; i++) {
    arr[i] = value;
  }
  return arr;
}
class ContiguousMultilineTokens {
  /**
   * (Inclusive) start line number for these tokens.
   */
  get startLineNumber() {
    return this._startLineNumber;
  }
  /**
   * (Inclusive) end line number for these tokens.
   */
  get endLineNumber() {
    return this._startLineNumber + this._tokens.length - 1;
  }
  constructor(startLineNumber, tokens) {
    this._startLineNumber = startLineNumber;
    this._tokens = tokens;
  }
  /**
   * @see {@link _tokens}
   */
  getLineTokens(lineNumber) {
    return this._tokens[lineNumber - this._startLineNumber];
  }
  appendLineTokens(lineTokens) {
    this._tokens.push(lineTokens);
  }
}
class ContiguousMultilineTokensBuilder {
  constructor() {
    this._tokens = [];
  }
  add(lineNumber, lineTokens) {
    if (this._tokens.length > 0) {
      const last2 = this._tokens[this._tokens.length - 1];
      if (last2.endLineNumber + 1 === lineNumber) {
        last2.appendLineTokens(lineTokens);
        return;
      }
    }
    this._tokens.push(new ContiguousMultilineTokens(lineNumber, [lineTokens]));
  }
  finalize() {
    return this._tokens;
  }
}
class LineTokens {
  static createEmpty(lineContent, decoder) {
    const defaultMetadata = LineTokens.defaultTokenMetadata;
    const tokens = new Uint32Array(2);
    tokens[0] = lineContent.length;
    tokens[1] = defaultMetadata;
    return new LineTokens(tokens, lineContent, decoder);
  }
  constructor(tokens, text2, decoder) {
    this._lineTokensBrand = void 0;
    this._tokens = tokens;
    this._tokensCount = this._tokens.length >>> 1;
    this._text = text2;
    this._languageIdCodec = decoder;
  }
  equals(other) {
    if (other instanceof LineTokens) {
      return this.slicedEquals(other, 0, this._tokensCount);
    }
    return false;
  }
  slicedEquals(other, sliceFromTokenIndex, sliceTokenCount) {
    if (this._text !== other._text) {
      return false;
    }
    if (this._tokensCount !== other._tokensCount) {
      return false;
    }
    const from2 = sliceFromTokenIndex << 1;
    const to = from2 + (sliceTokenCount << 1);
    for (let i = from2; i < to; i++) {
      if (this._tokens[i] !== other._tokens[i]) {
        return false;
      }
    }
    return true;
  }
  getLineContent() {
    return this._text;
  }
  getCount() {
    return this._tokensCount;
  }
  getStartOffset(tokenIndex) {
    if (tokenIndex > 0) {
      return this._tokens[tokenIndex - 1 << 1];
    }
    return 0;
  }
  getMetadata(tokenIndex) {
    const metadata = this._tokens[(tokenIndex << 1) + 1];
    return metadata;
  }
  getLanguageId(tokenIndex) {
    const metadata = this._tokens[(tokenIndex << 1) + 1];
    const languageId = TokenMetadata.getLanguageId(metadata);
    return this._languageIdCodec.decodeLanguageId(languageId);
  }
  getStandardTokenType(tokenIndex) {
    const metadata = this._tokens[(tokenIndex << 1) + 1];
    return TokenMetadata.getTokenType(metadata);
  }
  getForeground(tokenIndex) {
    const metadata = this._tokens[(tokenIndex << 1) + 1];
    return TokenMetadata.getForeground(metadata);
  }
  getClassName(tokenIndex) {
    const metadata = this._tokens[(tokenIndex << 1) + 1];
    return TokenMetadata.getClassNameFromMetadata(metadata);
  }
  getInlineStyle(tokenIndex, colorMap) {
    const metadata = this._tokens[(tokenIndex << 1) + 1];
    return TokenMetadata.getInlineStyleFromMetadata(metadata, colorMap);
  }
  getPresentation(tokenIndex) {
    const metadata = this._tokens[(tokenIndex << 1) + 1];
    return TokenMetadata.getPresentationFromMetadata(metadata);
  }
  getEndOffset(tokenIndex) {
    return this._tokens[tokenIndex << 1];
  }
  /**
   * Find the token containing offset `offset`.
   * @param offset The search offset
   * @return The index of the token containing the offset.
   */
  findTokenIndexAtOffset(offset) {
    return LineTokens.findIndexInTokensArray(this._tokens, offset);
  }
  inflate() {
    return this;
  }
  sliceAndInflate(startOffset, endOffset, deltaOffset) {
    return new SliceLineTokens(this, startOffset, endOffset, deltaOffset);
  }
  static convertToEndOffset(tokens, lineTextLength) {
    const tokenCount = tokens.length >>> 1;
    const lastTokenIndex = tokenCount - 1;
    for (let tokenIndex = 0; tokenIndex < lastTokenIndex; tokenIndex++) {
      tokens[tokenIndex << 1] = tokens[tokenIndex + 1 << 1];
    }
    tokens[lastTokenIndex << 1] = lineTextLength;
  }
  static findIndexInTokensArray(tokens, desiredIndex) {
    if (tokens.length <= 2) {
      return 0;
    }
    let low = 0;
    let high = (tokens.length >>> 1) - 1;
    while (low < high) {
      const mid = low + Math.floor((high - low) / 2);
      const endOffset = tokens[mid << 1];
      if (endOffset === desiredIndex) {
        return mid + 1;
      } else if (endOffset < desiredIndex) {
        low = mid + 1;
      } else if (endOffset > desiredIndex) {
        high = mid;
      }
    }
    return low;
  }
  /**
   * @pure
   * @param insertTokens Must be sorted by offset.
  */
  withInserted(insertTokens) {
    if (insertTokens.length === 0) {
      return this;
    }
    let nextOriginalTokenIdx = 0;
    let nextInsertTokenIdx = 0;
    let text2 = "";
    const newTokens = new Array();
    let originalEndOffset = 0;
    while (true) {
      const nextOriginalTokenEndOffset = nextOriginalTokenIdx < this._tokensCount ? this._tokens[nextOriginalTokenIdx << 1] : -1;
      const nextInsertToken = nextInsertTokenIdx < insertTokens.length ? insertTokens[nextInsertTokenIdx] : null;
      if (nextOriginalTokenEndOffset !== -1 && (nextInsertToken === null || nextOriginalTokenEndOffset <= nextInsertToken.offset)) {
        text2 += this._text.substring(originalEndOffset, nextOriginalTokenEndOffset);
        const metadata = this._tokens[(nextOriginalTokenIdx << 1) + 1];
        newTokens.push(text2.length, metadata);
        nextOriginalTokenIdx++;
        originalEndOffset = nextOriginalTokenEndOffset;
      } else if (nextInsertToken) {
        if (nextInsertToken.offset > originalEndOffset) {
          text2 += this._text.substring(originalEndOffset, nextInsertToken.offset);
          const metadata = this._tokens[(nextOriginalTokenIdx << 1) + 1];
          newTokens.push(text2.length, metadata);
          originalEndOffset = nextInsertToken.offset;
        }
        text2 += nextInsertToken.text;
        newTokens.push(text2.length, nextInsertToken.tokenMetadata);
        nextInsertTokenIdx++;
      } else {
        break;
      }
    }
    return new LineTokens(new Uint32Array(newTokens), text2, this._languageIdCodec);
  }
}
LineTokens.defaultTokenMetadata = (0 << 11 | 1 << 15 | 2 << 24) >>> 0;
class SliceLineTokens {
  constructor(source, startOffset, endOffset, deltaOffset) {
    this._source = source;
    this._startOffset = startOffset;
    this._endOffset = endOffset;
    this._deltaOffset = deltaOffset;
    this._firstTokenIndex = source.findTokenIndexAtOffset(startOffset);
    this._tokensCount = 0;
    for (let i = this._firstTokenIndex, len = source.getCount(); i < len; i++) {
      const tokenStartOffset = source.getStartOffset(i);
      if (tokenStartOffset >= endOffset) {
        break;
      }
      this._tokensCount++;
    }
  }
  getMetadata(tokenIndex) {
    return this._source.getMetadata(this._firstTokenIndex + tokenIndex);
  }
  getLanguageId(tokenIndex) {
    return this._source.getLanguageId(this._firstTokenIndex + tokenIndex);
  }
  getLineContent() {
    return this._source.getLineContent().substring(this._startOffset, this._endOffset);
  }
  equals(other) {
    if (other instanceof SliceLineTokens) {
      return this._startOffset === other._startOffset && this._endOffset === other._endOffset && this._deltaOffset === other._deltaOffset && this._source.slicedEquals(other._source, this._firstTokenIndex, this._tokensCount);
    }
    return false;
  }
  getCount() {
    return this._tokensCount;
  }
  getForeground(tokenIndex) {
    return this._source.getForeground(this._firstTokenIndex + tokenIndex);
  }
  getEndOffset(tokenIndex) {
    const tokenEndOffset = this._source.getEndOffset(this._firstTokenIndex + tokenIndex);
    return Math.min(this._endOffset, tokenEndOffset) - this._startOffset + this._deltaOffset;
  }
  getClassName(tokenIndex) {
    return this._source.getClassName(this._firstTokenIndex + tokenIndex);
  }
  getInlineStyle(tokenIndex, colorMap) {
    return this._source.getInlineStyle(this._firstTokenIndex + tokenIndex, colorMap);
  }
  getPresentation(tokenIndex) {
    return this._source.getPresentation(this._firstTokenIndex + tokenIndex);
  }
  findTokenIndexAtOffset(offset) {
    return this._source.findTokenIndexAtOffset(offset + this._startOffset - this._deltaOffset) - this._firstTokenIndex;
  }
}
class TokenizerWithStateStore {
  constructor(lineCount, tokenizationSupport) {
    this.tokenizationSupport = tokenizationSupport;
    this.initialState = this.tokenizationSupport.getInitialState();
    this.store = new TrackingTokenizationStateStore(lineCount);
  }
  getStartState(lineNumber) {
    return this.store.getStartState(lineNumber, this.initialState);
  }
  getFirstInvalidLine() {
    return this.store.getFirstInvalidLine(this.initialState);
  }
}
class TokenizerWithStateStoreAndTextModel extends TokenizerWithStateStore {
  constructor(lineCount, tokenizationSupport, _textModel, _languageIdCodec) {
    super(lineCount, tokenizationSupport);
    this._textModel = _textModel;
    this._languageIdCodec = _languageIdCodec;
  }
  updateTokensUntilLine(builder, lineNumber) {
    const languageId = this._textModel.getLanguageId();
    while (true) {
      const lineToTokenize = this.getFirstInvalidLine();
      if (!lineToTokenize || lineToTokenize.lineNumber > lineNumber) {
        break;
      }
      const text2 = this._textModel.getLineContent(lineToTokenize.lineNumber);
      const r = safeTokenize(this._languageIdCodec, languageId, this.tokenizationSupport, text2, true, lineToTokenize.startState);
      builder.add(lineToTokenize.lineNumber, r.tokens);
      this.store.setEndState(lineToTokenize.lineNumber, r.endState);
    }
  }
  /** assumes state is up to date */
  getTokenTypeIfInsertingCharacter(position, character) {
    const lineStartState = this.getStartState(position.lineNumber);
    if (!lineStartState) {
      return 0;
    }
    const languageId = this._textModel.getLanguageId();
    const lineContent = this._textModel.getLineContent(position.lineNumber);
    const text2 = lineContent.substring(0, position.column - 1) + character + lineContent.substring(position.column - 1);
    const r = safeTokenize(this._languageIdCodec, languageId, this.tokenizationSupport, text2, true, lineStartState);
    const lineTokens = new LineTokens(r.tokens, text2, this._languageIdCodec);
    if (lineTokens.getCount() === 0) {
      return 0;
    }
    const tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
    return lineTokens.getStandardTokenType(tokenIndex);
  }
  /** assumes state is up to date */
  tokenizeLineWithEdit(position, length2, newText) {
    const lineNumber = position.lineNumber;
    const column = position.column;
    const lineStartState = this.getStartState(lineNumber);
    if (!lineStartState) {
      return null;
    }
    const curLineContent = this._textModel.getLineContent(lineNumber);
    const newLineContent = curLineContent.substring(0, column - 1) + newText + curLineContent.substring(column - 1 + length2);
    const languageId = this._textModel.getLanguageIdAtPosition(lineNumber, 0);
    const result2 = safeTokenize(this._languageIdCodec, languageId, this.tokenizationSupport, newLineContent, true, lineStartState);
    const lineTokens = new LineTokens(result2.tokens, newLineContent, this._languageIdCodec);
    return lineTokens;
  }
  isCheapToTokenize(lineNumber) {
    const firstInvalidLineNumber = this.store.getFirstInvalidEndStateLineNumberOrMax();
    if (lineNumber < firstInvalidLineNumber) {
      return true;
    }
    if (lineNumber === firstInvalidLineNumber && this._textModel.getLineLength(lineNumber) < 2048) {
      return true;
    }
    return false;
  }
  /**
   * The result is not cached.
   */
  tokenizeHeuristically(builder, startLineNumber, endLineNumber) {
    if (endLineNumber <= this.store.getFirstInvalidEndStateLineNumberOrMax()) {
      return { heuristicTokens: false };
    }
    if (startLineNumber <= this.store.getFirstInvalidEndStateLineNumberOrMax()) {
      this.updateTokensUntilLine(builder, endLineNumber);
      return { heuristicTokens: false };
    }
    let state = this.guessStartState(startLineNumber);
    const languageId = this._textModel.getLanguageId();
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      const text2 = this._textModel.getLineContent(lineNumber);
      const r = safeTokenize(this._languageIdCodec, languageId, this.tokenizationSupport, text2, true, state);
      builder.add(lineNumber, r.tokens);
      state = r.endState;
    }
    return { heuristicTokens: true };
  }
  guessStartState(lineNumber) {
    let nonWhitespaceColumn = this._textModel.getLineFirstNonWhitespaceColumn(lineNumber);
    const likelyRelevantLines = [];
    let initialState = null;
    for (let i = lineNumber - 1; nonWhitespaceColumn > 1 && i >= 1; i--) {
      const newNonWhitespaceIndex = this._textModel.getLineFirstNonWhitespaceColumn(i);
      if (newNonWhitespaceIndex === 0) {
        continue;
      }
      if (newNonWhitespaceIndex < nonWhitespaceColumn) {
        likelyRelevantLines.push(this._textModel.getLineContent(i));
        nonWhitespaceColumn = newNonWhitespaceIndex;
        initialState = this.getStartState(i);
        if (initialState) {
          break;
        }
      }
    }
    if (!initialState) {
      initialState = this.tokenizationSupport.getInitialState();
    }
    likelyRelevantLines.reverse();
    const languageId = this._textModel.getLanguageId();
    let state = initialState;
    for (const line of likelyRelevantLines) {
      const r = safeTokenize(this._languageIdCodec, languageId, this.tokenizationSupport, line, false, state);
      state = r.endState;
    }
    return state;
  }
}
class TrackingTokenizationStateStore {
  constructor(lineCount) {
    this.lineCount = lineCount;
    this._tokenizationStateStore = new TokenizationStateStore();
    this._invalidEndStatesLineNumbers = new RangePriorityQueueImpl();
    this._invalidEndStatesLineNumbers.addRange(new OffsetRange(1, lineCount + 1));
  }
  getEndState(lineNumber) {
    return this._tokenizationStateStore.getEndState(lineNumber);
  }
  /**
   * @returns if the end state has changed.
   */
  setEndState(lineNumber, state) {
    if (!state) {
      throw new BugIndicatingError("Cannot set null/undefined state");
    }
    this._invalidEndStatesLineNumbers.delete(lineNumber);
    const r = this._tokenizationStateStore.setEndState(lineNumber, state);
    if (r && lineNumber < this.lineCount) {
      this._invalidEndStatesLineNumbers.addRange(new OffsetRange(lineNumber + 1, lineNumber + 2));
    }
    return r;
  }
  acceptChange(range2, newLineCount) {
    this.lineCount += newLineCount - range2.length;
    this._tokenizationStateStore.acceptChange(range2, newLineCount);
    this._invalidEndStatesLineNumbers.addRangeAndResize(new OffsetRange(range2.startLineNumber, range2.endLineNumberExclusive), newLineCount);
  }
  acceptChanges(changes) {
    for (const c of changes) {
      const [eolCount] = countEOL(c.text);
      this.acceptChange(new LineRange2(c.range.startLineNumber, c.range.endLineNumber + 1), eolCount + 1);
    }
  }
  invalidateEndStateRange(range2) {
    this._invalidEndStatesLineNumbers.addRange(new OffsetRange(range2.startLineNumber, range2.endLineNumberExclusive));
  }
  getFirstInvalidEndStateLineNumber() {
    return this._invalidEndStatesLineNumbers.min;
  }
  getFirstInvalidEndStateLineNumberOrMax() {
    return this.getFirstInvalidEndStateLineNumber() || Number.MAX_SAFE_INTEGER;
  }
  allStatesValid() {
    return this._invalidEndStatesLineNumbers.min === null;
  }
  getStartState(lineNumber, initialState) {
    if (lineNumber === 1) {
      return initialState;
    }
    return this.getEndState(lineNumber - 1);
  }
  getFirstInvalidLine(initialState) {
    const lineNumber = this.getFirstInvalidEndStateLineNumber();
    if (lineNumber === null) {
      return null;
    }
    const startState = this.getStartState(lineNumber, initialState);
    if (!startState) {
      throw new BugIndicatingError("Start state must be defined");
    }
    return { lineNumber, startState };
  }
}
class TokenizationStateStore {
  constructor() {
    this._lineEndStates = new FixedArray(null);
  }
  getEndState(lineNumber) {
    return this._lineEndStates.get(lineNumber);
  }
  setEndState(lineNumber, state) {
    const oldState = this._lineEndStates.get(lineNumber);
    if (oldState && oldState.equals(state)) {
      return false;
    }
    this._lineEndStates.set(lineNumber, state);
    return true;
  }
  acceptChange(range2, newLineCount) {
    let length2 = range2.length;
    if (newLineCount > 0 && length2 > 0) {
      length2--;
      newLineCount--;
    }
    this._lineEndStates.replace(range2.startLineNumber, length2, newLineCount);
  }
}
class RangePriorityQueueImpl {
  constructor() {
    this._ranges = [];
  }
  get min() {
    if (this._ranges.length === 0) {
      return null;
    }
    return this._ranges[0].start;
  }
  delete(value) {
    const idx = this._ranges.findIndex((r) => r.contains(value));
    if (idx !== -1) {
      const range2 = this._ranges[idx];
      if (range2.start === value) {
        if (range2.endExclusive === value + 1) {
          this._ranges.splice(idx, 1);
        } else {
          this._ranges[idx] = new OffsetRange(value + 1, range2.endExclusive);
        }
      } else {
        if (range2.endExclusive === value + 1) {
          this._ranges[idx] = new OffsetRange(range2.start, value);
        } else {
          this._ranges.splice(idx, 1, new OffsetRange(range2.start, value), new OffsetRange(value + 1, range2.endExclusive));
        }
      }
    }
  }
  addRange(range2) {
    OffsetRange.addRange(range2, this._ranges);
  }
  addRangeAndResize(range2, newLength) {
    let idxFirstMightBeIntersecting = 0;
    while (!(idxFirstMightBeIntersecting >= this._ranges.length || range2.start <= this._ranges[idxFirstMightBeIntersecting].endExclusive)) {
      idxFirstMightBeIntersecting++;
    }
    let idxFirstIsAfter = idxFirstMightBeIntersecting;
    while (!(idxFirstIsAfter >= this._ranges.length || range2.endExclusive < this._ranges[idxFirstIsAfter].start)) {
      idxFirstIsAfter++;
    }
    const delta = newLength - range2.length;
    for (let i = idxFirstIsAfter; i < this._ranges.length; i++) {
      this._ranges[i] = this._ranges[i].delta(delta);
    }
    if (idxFirstMightBeIntersecting === idxFirstIsAfter) {
      const newRange = new OffsetRange(range2.start, range2.start + newLength);
      if (!newRange.isEmpty) {
        this._ranges.splice(idxFirstMightBeIntersecting, 0, newRange);
      }
    } else {
      const start = Math.min(range2.start, this._ranges[idxFirstMightBeIntersecting].start);
      const endEx = Math.max(range2.endExclusive, this._ranges[idxFirstIsAfter - 1].endExclusive);
      const newRange = new OffsetRange(start, endEx + delta);
      if (!newRange.isEmpty) {
        this._ranges.splice(idxFirstMightBeIntersecting, idxFirstIsAfter - idxFirstMightBeIntersecting, newRange);
      } else {
        this._ranges.splice(idxFirstMightBeIntersecting, idxFirstIsAfter - idxFirstMightBeIntersecting);
      }
    }
  }
  toString() {
    return this._ranges.map((r) => r.toString()).join(" + ");
  }
}
function safeTokenize(languageIdCodec, languageId, tokenizationSupport, text2, hasEOL, state) {
  let r = null;
  if (tokenizationSupport) {
    try {
      r = tokenizationSupport.tokenizeEncoded(text2, hasEOL, state.clone());
    } catch (e) {
      onUnexpectedError(e);
    }
  }
  if (!r) {
    r = nullTokenizeEncoded(languageIdCodec.encodeLanguageId(languageId), state);
  }
  LineTokens.convertToEndOffset(r.tokens, text2.length);
  return r;
}
class DefaultBackgroundTokenizer {
  constructor(_tokenizerWithStateStore, _backgroundTokenStore) {
    this._tokenizerWithStateStore = _tokenizerWithStateStore;
    this._backgroundTokenStore = _backgroundTokenStore;
    this._isDisposed = false;
    this._isScheduled = false;
  }
  dispose() {
    this._isDisposed = true;
  }
  handleChanges() {
    this._beginBackgroundTokenization();
  }
  _beginBackgroundTokenization() {
    if (this._isScheduled || !this._tokenizerWithStateStore._textModel.isAttachedToEditor() || !this._hasLinesToTokenize()) {
      return;
    }
    this._isScheduled = true;
    runWhenIdle((deadline) => {
      this._isScheduled = false;
      this._backgroundTokenizeWithDeadline(deadline);
    });
  }
  /**
   * Tokenize until the deadline occurs, but try to yield every 1-2ms.
   */
  _backgroundTokenizeWithDeadline(deadline) {
    const endTime = Date.now() + deadline.timeRemaining();
    const execute = () => {
      if (this._isDisposed || !this._tokenizerWithStateStore._textModel.isAttachedToEditor() || !this._hasLinesToTokenize()) {
        return;
      }
      this._backgroundTokenizeForAtLeast1ms();
      if (Date.now() < endTime) {
        setTimeout0(execute);
      } else {
        this._beginBackgroundTokenization();
      }
    };
    execute();
  }
  /**
   * Tokenize for at least 1ms.
   */
  _backgroundTokenizeForAtLeast1ms() {
    const lineCount = this._tokenizerWithStateStore._textModel.getLineCount();
    const builder = new ContiguousMultilineTokensBuilder();
    const sw = StopWatch.create(false);
    do {
      if (sw.elapsed() > 1) {
        break;
      }
      const tokenizedLineNumber = this._tokenizeOneInvalidLine(builder);
      if (tokenizedLineNumber >= lineCount) {
        break;
      }
    } while (this._hasLinesToTokenize());
    this._backgroundTokenStore.setTokens(builder.finalize());
    this.checkFinished();
  }
  _hasLinesToTokenize() {
    if (!this._tokenizerWithStateStore) {
      return false;
    }
    return !this._tokenizerWithStateStore.store.allStatesValid();
  }
  _tokenizeOneInvalidLine(builder) {
    var _a2;
    const firstInvalidLine = (_a2 = this._tokenizerWithStateStore) === null || _a2 === void 0 ? void 0 : _a2.getFirstInvalidLine();
    if (!firstInvalidLine) {
      return this._tokenizerWithStateStore._textModel.getLineCount() + 1;
    }
    this._tokenizerWithStateStore.updateTokensUntilLine(builder, firstInvalidLine.lineNumber);
    return firstInvalidLine.lineNumber;
  }
  checkFinished() {
    if (this._isDisposed) {
      return;
    }
    if (this._tokenizerWithStateStore.store.allStatesValid()) {
      this._backgroundTokenStore.backgroundTokenizationFinished();
    }
  }
  requestTokens(startLineNumber, endLineNumberExclusive) {
    this._tokenizerWithStateStore.store.invalidateEndStateRange(new LineRange2(startLineNumber, endLineNumberExclusive));
  }
}
const EMPTY_LINE_TOKENS = new Uint32Array(0).buffer;
class ContiguousTokensEditing {
  static deleteBeginning(lineTokens, toChIndex) {
    if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS) {
      return lineTokens;
    }
    return ContiguousTokensEditing.delete(lineTokens, 0, toChIndex);
  }
  static deleteEnding(lineTokens, fromChIndex) {
    if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS) {
      return lineTokens;
    }
    const tokens = toUint32Array(lineTokens);
    const lineTextLength = tokens[tokens.length - 2];
    return ContiguousTokensEditing.delete(lineTokens, fromChIndex, lineTextLength);
  }
  static delete(lineTokens, fromChIndex, toChIndex) {
    if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS || fromChIndex === toChIndex) {
      return lineTokens;
    }
    const tokens = toUint32Array(lineTokens);
    const tokensCount = tokens.length >>> 1;
    if (fromChIndex === 0 && tokens[tokens.length - 2] === toChIndex) {
      return EMPTY_LINE_TOKENS;
    }
    const fromTokenIndex = LineTokens.findIndexInTokensArray(tokens, fromChIndex);
    const fromTokenStartOffset = fromTokenIndex > 0 ? tokens[fromTokenIndex - 1 << 1] : 0;
    const fromTokenEndOffset = tokens[fromTokenIndex << 1];
    if (toChIndex < fromTokenEndOffset) {
      const delta2 = toChIndex - fromChIndex;
      for (let i = fromTokenIndex; i < tokensCount; i++) {
        tokens[i << 1] -= delta2;
      }
      return lineTokens;
    }
    let dest;
    let lastEnd;
    if (fromTokenStartOffset !== fromChIndex) {
      tokens[fromTokenIndex << 1] = fromChIndex;
      dest = fromTokenIndex + 1 << 1;
      lastEnd = fromChIndex;
    } else {
      dest = fromTokenIndex << 1;
      lastEnd = fromTokenStartOffset;
    }
    const delta = toChIndex - fromChIndex;
    for (let tokenIndex = fromTokenIndex + 1; tokenIndex < tokensCount; tokenIndex++) {
      const tokenEndOffset = tokens[tokenIndex << 1] - delta;
      if (tokenEndOffset > lastEnd) {
        tokens[dest++] = tokenEndOffset;
        tokens[dest++] = tokens[(tokenIndex << 1) + 1];
        lastEnd = tokenEndOffset;
      }
    }
    if (dest === tokens.length) {
      return lineTokens;
    }
    const tmp = new Uint32Array(dest);
    tmp.set(tokens.subarray(0, dest), 0);
    return tmp.buffer;
  }
  static append(lineTokens, _otherTokens) {
    if (_otherTokens === EMPTY_LINE_TOKENS) {
      return lineTokens;
    }
    if (lineTokens === EMPTY_LINE_TOKENS) {
      return _otherTokens;
    }
    if (lineTokens === null) {
      return lineTokens;
    }
    if (_otherTokens === null) {
      return null;
    }
    const myTokens = toUint32Array(lineTokens);
    const otherTokens = toUint32Array(_otherTokens);
    const otherTokensCount = otherTokens.length >>> 1;
    const result2 = new Uint32Array(myTokens.length + otherTokens.length);
    result2.set(myTokens, 0);
    let dest = myTokens.length;
    const delta = myTokens[myTokens.length - 2];
    for (let i = 0; i < otherTokensCount; i++) {
      result2[dest++] = otherTokens[i << 1] + delta;
      result2[dest++] = otherTokens[(i << 1) + 1];
    }
    return result2.buffer;
  }
  static insert(lineTokens, chIndex, textLength) {
    if (lineTokens === null || lineTokens === EMPTY_LINE_TOKENS) {
      return lineTokens;
    }
    const tokens = toUint32Array(lineTokens);
    const tokensCount = tokens.length >>> 1;
    let fromTokenIndex = LineTokens.findIndexInTokensArray(tokens, chIndex);
    if (fromTokenIndex > 0) {
      const fromTokenStartOffset = tokens[fromTokenIndex - 1 << 1];
      if (fromTokenStartOffset === chIndex) {
        fromTokenIndex--;
      }
    }
    for (let tokenIndex = fromTokenIndex; tokenIndex < tokensCount; tokenIndex++) {
      tokens[tokenIndex << 1] += textLength;
    }
    return lineTokens;
  }
}
function toUint32Array(arr) {
  if (arr instanceof Uint32Array) {
    return arr;
  } else {
    return new Uint32Array(arr);
  }
}
class ContiguousTokensStore {
  constructor(languageIdCodec) {
    this._lineTokens = [];
    this._len = 0;
    this._languageIdCodec = languageIdCodec;
  }
  flush() {
    this._lineTokens = [];
    this._len = 0;
  }
  get hasTokens() {
    return this._lineTokens.length > 0;
  }
  getTokens(topLevelLanguageId, lineIndex, lineText) {
    let rawLineTokens = null;
    if (lineIndex < this._len) {
      rawLineTokens = this._lineTokens[lineIndex];
    }
    if (rawLineTokens !== null && rawLineTokens !== EMPTY_LINE_TOKENS) {
      return new LineTokens(toUint32Array(rawLineTokens), lineText, this._languageIdCodec);
    }
    const lineTokens = new Uint32Array(2);
    lineTokens[0] = lineText.length;
    lineTokens[1] = getDefaultMetadata(this._languageIdCodec.encodeLanguageId(topLevelLanguageId));
    return new LineTokens(lineTokens, lineText, this._languageIdCodec);
  }
  static _massageTokens(topLevelLanguageId, lineTextLength, _tokens) {
    const tokens = _tokens ? toUint32Array(_tokens) : null;
    if (lineTextLength === 0) {
      let hasDifferentLanguageId = false;
      if (tokens && tokens.length > 1) {
        hasDifferentLanguageId = TokenMetadata.getLanguageId(tokens[1]) !== topLevelLanguageId;
      }
      if (!hasDifferentLanguageId) {
        return EMPTY_LINE_TOKENS;
      }
    }
    if (!tokens || tokens.length === 0) {
      const tokens2 = new Uint32Array(2);
      tokens2[0] = lineTextLength;
      tokens2[1] = getDefaultMetadata(topLevelLanguageId);
      return tokens2.buffer;
    }
    tokens[tokens.length - 2] = lineTextLength;
    if (tokens.byteOffset === 0 && tokens.byteLength === tokens.buffer.byteLength) {
      return tokens.buffer;
    }
    return tokens;
  }
  _ensureLine(lineIndex) {
    while (lineIndex >= this._len) {
      this._lineTokens[this._len] = null;
      this._len++;
    }
  }
  _deleteLines(start, deleteCount) {
    if (deleteCount === 0) {
      return;
    }
    if (start + deleteCount > this._len) {
      deleteCount = this._len - start;
    }
    this._lineTokens.splice(start, deleteCount);
    this._len -= deleteCount;
  }
  _insertLines(insertIndex, insertCount) {
    if (insertCount === 0) {
      return;
    }
    const lineTokens = [];
    for (let i = 0; i < insertCount; i++) {
      lineTokens[i] = null;
    }
    this._lineTokens = arrayInsert(this._lineTokens, insertIndex, lineTokens);
    this._len += insertCount;
  }
  setTokens(topLevelLanguageId, lineIndex, lineTextLength, _tokens, checkEquality) {
    const tokens = ContiguousTokensStore._massageTokens(this._languageIdCodec.encodeLanguageId(topLevelLanguageId), lineTextLength, _tokens);
    this._ensureLine(lineIndex);
    const oldTokens = this._lineTokens[lineIndex];
    this._lineTokens[lineIndex] = tokens;
    if (checkEquality) {
      return !ContiguousTokensStore._equals(oldTokens, tokens);
    }
    return false;
  }
  static _equals(_a2, _b2) {
    if (!_a2 || !_b2) {
      return !_a2 && !_b2;
    }
    const a = toUint32Array(_a2);
    const b = toUint32Array(_b2);
    if (a.length !== b.length) {
      return false;
    }
    for (let i = 0, len = a.length; i < len; i++) {
      if (a[i] !== b[i]) {
        return false;
      }
    }
    return true;
  }
  //#region Editing
  acceptEdit(range2, eolCount, firstLineLength) {
    this._acceptDeleteRange(range2);
    this._acceptInsertText(new Position$2(range2.startLineNumber, range2.startColumn), eolCount, firstLineLength);
  }
  _acceptDeleteRange(range2) {
    const firstLineIndex = range2.startLineNumber - 1;
    if (firstLineIndex >= this._len) {
      return;
    }
    if (range2.startLineNumber === range2.endLineNumber) {
      if (range2.startColumn === range2.endColumn) {
        return;
      }
      this._lineTokens[firstLineIndex] = ContiguousTokensEditing.delete(this._lineTokens[firstLineIndex], range2.startColumn - 1, range2.endColumn - 1);
      return;
    }
    this._lineTokens[firstLineIndex] = ContiguousTokensEditing.deleteEnding(this._lineTokens[firstLineIndex], range2.startColumn - 1);
    const lastLineIndex = range2.endLineNumber - 1;
    let lastLineTokens = null;
    if (lastLineIndex < this._len) {
      lastLineTokens = ContiguousTokensEditing.deleteBeginning(this._lineTokens[lastLineIndex], range2.endColumn - 1);
    }
    this._lineTokens[firstLineIndex] = ContiguousTokensEditing.append(this._lineTokens[firstLineIndex], lastLineTokens);
    this._deleteLines(range2.startLineNumber, range2.endLineNumber - range2.startLineNumber);
  }
  _acceptInsertText(position, eolCount, firstLineLength) {
    if (eolCount === 0 && firstLineLength === 0) {
      return;
    }
    const lineIndex = position.lineNumber - 1;
    if (lineIndex >= this._len) {
      return;
    }
    if (eolCount === 0) {
      this._lineTokens[lineIndex] = ContiguousTokensEditing.insert(this._lineTokens[lineIndex], position.column - 1, firstLineLength);
      return;
    }
    this._lineTokens[lineIndex] = ContiguousTokensEditing.deleteEnding(this._lineTokens[lineIndex], position.column - 1);
    this._lineTokens[lineIndex] = ContiguousTokensEditing.insert(this._lineTokens[lineIndex], position.column - 1, firstLineLength);
    this._insertLines(position.lineNumber, eolCount);
  }
  //#endregion
  setMultilineTokens(tokens, textModel) {
    if (tokens.length === 0) {
      return { changes: [] };
    }
    const ranges = [];
    for (let i = 0, len = tokens.length; i < len; i++) {
      const element = tokens[i];
      let minChangedLineNumber = 0;
      let maxChangedLineNumber = 0;
      let hasChange = false;
      for (let lineNumber = element.startLineNumber; lineNumber <= element.endLineNumber; lineNumber++) {
        if (hasChange) {
          this.setTokens(textModel.getLanguageId(), lineNumber - 1, textModel.getLineLength(lineNumber), element.getLineTokens(lineNumber), false);
          maxChangedLineNumber = lineNumber;
        } else {
          const lineHasChange = this.setTokens(textModel.getLanguageId(), lineNumber - 1, textModel.getLineLength(lineNumber), element.getLineTokens(lineNumber), true);
          if (lineHasChange) {
            hasChange = true;
            minChangedLineNumber = lineNumber;
            maxChangedLineNumber = lineNumber;
          }
        }
      }
      if (hasChange) {
        ranges.push({ fromLineNumber: minChangedLineNumber, toLineNumber: maxChangedLineNumber });
      }
    }
    return { changes: ranges };
  }
}
function getDefaultMetadata(topLevelLanguageId) {
  return (topLevelLanguageId << 0 | 0 << 8 | 0 << 11 | 1 << 15 | 2 << 24 | 1024) >>> 0;
}
class SparseTokensStore {
  constructor(languageIdCodec) {
    this._pieces = [];
    this._isComplete = false;
    this._languageIdCodec = languageIdCodec;
  }
  flush() {
    this._pieces = [];
    this._isComplete = false;
  }
  isEmpty() {
    return this._pieces.length === 0;
  }
  set(pieces, isComplete) {
    this._pieces = pieces || [];
    this._isComplete = isComplete;
  }
  setPartial(_range, pieces) {
    let range2 = _range;
    if (pieces.length > 0) {
      const _firstRange = pieces[0].getRange();
      const _lastRange = pieces[pieces.length - 1].getRange();
      if (!_firstRange || !_lastRange) {
        return _range;
      }
      range2 = _range.plusRange(_firstRange).plusRange(_lastRange);
    }
    let insertPosition = null;
    for (let i = 0, len = this._pieces.length; i < len; i++) {
      const piece = this._pieces[i];
      if (piece.endLineNumber < range2.startLineNumber) {
        continue;
      }
      if (piece.startLineNumber > range2.endLineNumber) {
        insertPosition = insertPosition || { index: i };
        break;
      }
      piece.removeTokens(range2);
      if (piece.isEmpty()) {
        this._pieces.splice(i, 1);
        i--;
        len--;
        continue;
      }
      if (piece.endLineNumber < range2.startLineNumber) {
        continue;
      }
      if (piece.startLineNumber > range2.endLineNumber) {
        insertPosition = insertPosition || { index: i };
        continue;
      }
      const [a, b] = piece.split(range2);
      if (a.isEmpty()) {
        insertPosition = insertPosition || { index: i };
        continue;
      }
      if (b.isEmpty()) {
        continue;
      }
      this._pieces.splice(i, 1, a, b);
      i++;
      len++;
      insertPosition = insertPosition || { index: i };
    }
    insertPosition = insertPosition || { index: this._pieces.length };
    if (pieces.length > 0) {
      this._pieces = arrayInsert(this._pieces, insertPosition.index, pieces);
    }
    return range2;
  }
  isComplete() {
    return this._isComplete;
  }
  addSparseTokens(lineNumber, aTokens) {
    if (aTokens.getLineContent().length === 0) {
      return aTokens;
    }
    const pieces = this._pieces;
    if (pieces.length === 0) {
      return aTokens;
    }
    const pieceIndex = SparseTokensStore._findFirstPieceWithLine(pieces, lineNumber);
    const bTokens = pieces[pieceIndex].getLineTokens(lineNumber);
    if (!bTokens) {
      return aTokens;
    }
    const aLen = aTokens.getCount();
    const bLen = bTokens.getCount();
    let aIndex = 0;
    const result2 = [];
    let resultLen = 0;
    let lastEndOffset = 0;
    const emitToken = (endOffset, metadata) => {
      if (endOffset === lastEndOffset) {
        return;
      }
      lastEndOffset = endOffset;
      result2[resultLen++] = endOffset;
      result2[resultLen++] = metadata;
    };
    for (let bIndex = 0; bIndex < bLen; bIndex++) {
      const bStartCharacter = bTokens.getStartCharacter(bIndex);
      const bEndCharacter = bTokens.getEndCharacter(bIndex);
      const bMetadata = bTokens.getMetadata(bIndex);
      const bMask = ((bMetadata & 1 ? 2048 : 0) | (bMetadata & 2 ? 4096 : 0) | (bMetadata & 4 ? 8192 : 0) | (bMetadata & 8 ? 16384 : 0) | (bMetadata & 16 ? 16744448 : 0) | (bMetadata & 32 ? 4278190080 : 0)) >>> 0;
      const aMask = ~bMask >>> 0;
      while (aIndex < aLen && aTokens.getEndOffset(aIndex) <= bStartCharacter) {
        emitToken(aTokens.getEndOffset(aIndex), aTokens.getMetadata(aIndex));
        aIndex++;
      }
      if (aIndex < aLen && aTokens.getStartOffset(aIndex) < bStartCharacter) {
        emitToken(bStartCharacter, aTokens.getMetadata(aIndex));
      }
      while (aIndex < aLen && aTokens.getEndOffset(aIndex) < bEndCharacter) {
        emitToken(aTokens.getEndOffset(aIndex), aTokens.getMetadata(aIndex) & aMask | bMetadata & bMask);
        aIndex++;
      }
      if (aIndex < aLen) {
        emitToken(bEndCharacter, aTokens.getMetadata(aIndex) & aMask | bMetadata & bMask);
        if (aTokens.getEndOffset(aIndex) === bEndCharacter) {
          aIndex++;
        }
      } else {
        const aMergeIndex = Math.min(Math.max(0, aIndex - 1), aLen - 1);
        emitToken(bEndCharacter, aTokens.getMetadata(aMergeIndex) & aMask | bMetadata & bMask);
      }
    }
    while (aIndex < aLen) {
      emitToken(aTokens.getEndOffset(aIndex), aTokens.getMetadata(aIndex));
      aIndex++;
    }
    return new LineTokens(new Uint32Array(result2), aTokens.getLineContent(), this._languageIdCodec);
  }
  static _findFirstPieceWithLine(pieces, lineNumber) {
    let low = 0;
    let high = pieces.length - 1;
    while (low < high) {
      let mid = low + Math.floor((high - low) / 2);
      if (pieces[mid].endLineNumber < lineNumber) {
        low = mid + 1;
      } else if (pieces[mid].startLineNumber > lineNumber) {
        high = mid - 1;
      } else {
        while (mid > low && pieces[mid - 1].startLineNumber <= lineNumber && lineNumber <= pieces[mid - 1].endLineNumber) {
          mid--;
        }
        return mid;
      }
    }
    return low;
  }
  acceptEdit(range2, eolCount, firstLineLength, lastLineLength2, firstCharCode) {
    for (const piece of this._pieces) {
      piece.acceptEdit(range2, eolCount, firstLineLength, lastLineLength2, firstCharCode);
    }
  }
}
class TokenizationTextModelPart extends TextModelPart {
  constructor(_languageService, _languageConfigurationService, _textModel, _bracketPairsTextModelPart, _languageId, _attachedViews) {
    super();
    this._languageService = _languageService;
    this._languageConfigurationService = _languageConfigurationService;
    this._textModel = _textModel;
    this._bracketPairsTextModelPart = _bracketPairsTextModelPart;
    this._languageId = _languageId;
    this._attachedViews = _attachedViews;
    this._semanticTokens = new SparseTokensStore(this._languageService.languageIdCodec);
    this._onDidChangeLanguage = this._register(new Emitter$1());
    this.onDidChangeLanguage = this._onDidChangeLanguage.event;
    this._onDidChangeLanguageConfiguration = this._register(new Emitter$1());
    this.onDidChangeLanguageConfiguration = this._onDidChangeLanguageConfiguration.event;
    this._onDidChangeTokens = this._register(new Emitter$1());
    this.onDidChangeTokens = this._onDidChangeTokens.event;
    this.grammarTokens = this._register(new GrammarTokens(this._languageService.languageIdCodec, this._textModel, () => this._languageId, this._attachedViews));
    this._register(this._languageConfigurationService.onDidChange((e) => {
      if (e.affects(this._languageId)) {
        this._onDidChangeLanguageConfiguration.fire({});
      }
    }));
    this._register(this.grammarTokens.onDidChangeTokens((e) => {
      this._emitModelTokensChangedEvent(e);
    }));
    this._register(this.grammarTokens.onDidChangeBackgroundTokenizationState((e) => {
      this._bracketPairsTextModelPart.handleDidChangeBackgroundTokenizationState();
    }));
  }
  handleDidChangeContent(e) {
    if (e.isFlush) {
      this._semanticTokens.flush();
    } else if (!e.isEolChange) {
      for (const c of e.changes) {
        const [eolCount, firstLineLength, lastLineLength2] = countEOL(c.text);
        this._semanticTokens.acceptEdit(
          c.range,
          eolCount,
          firstLineLength,
          lastLineLength2,
          c.text.length > 0 ? c.text.charCodeAt(0) : 0
          /* CharCode.Null */
        );
      }
    }
    this.grammarTokens.handleDidChangeContent(e);
  }
  handleDidChangeAttached() {
    this.grammarTokens.handleDidChangeAttached();
  }
  /**
   * Includes grammar and semantic tokens.
   */
  getLineTokens(lineNumber) {
    this.validateLineNumber(lineNumber);
    const syntacticTokens = this.grammarTokens.getLineTokens(lineNumber);
    return this._semanticTokens.addSparseTokens(lineNumber, syntacticTokens);
  }
  _emitModelTokensChangedEvent(e) {
    if (!this._textModel._isDisposing()) {
      this._bracketPairsTextModelPart.handleDidChangeTokens(e);
      this._onDidChangeTokens.fire(e);
    }
  }
  // #region Grammar Tokens
  validateLineNumber(lineNumber) {
    if (lineNumber < 1 || lineNumber > this._textModel.getLineCount()) {
      throw new BugIndicatingError("Illegal value for lineNumber");
    }
  }
  get hasTokens() {
    return this.grammarTokens.hasTokens;
  }
  resetTokenization() {
    this.grammarTokens.resetTokenization();
  }
  get backgroundTokenizationState() {
    return this.grammarTokens.backgroundTokenizationState;
  }
  forceTokenization(lineNumber) {
    this.validateLineNumber(lineNumber);
    this.grammarTokens.forceTokenization(lineNumber);
  }
  isCheapToTokenize(lineNumber) {
    this.validateLineNumber(lineNumber);
    return this.grammarTokens.isCheapToTokenize(lineNumber);
  }
  tokenizeIfCheap(lineNumber) {
    this.validateLineNumber(lineNumber);
    this.grammarTokens.tokenizeIfCheap(lineNumber);
  }
  getTokenTypeIfInsertingCharacter(lineNumber, column, character) {
    return this.grammarTokens.getTokenTypeIfInsertingCharacter(lineNumber, column, character);
  }
  tokenizeLineWithEdit(position, length2, newText) {
    return this.grammarTokens.tokenizeLineWithEdit(position, length2, newText);
  }
  // #endregion
  // #region Semantic Tokens
  setSemanticTokens(tokens, isComplete) {
    this._semanticTokens.set(tokens, isComplete);
    this._emitModelTokensChangedEvent({
      semanticTokensApplied: tokens !== null,
      ranges: [{ fromLineNumber: 1, toLineNumber: this._textModel.getLineCount() }]
    });
  }
  hasCompleteSemanticTokens() {
    return this._semanticTokens.isComplete();
  }
  hasSomeSemanticTokens() {
    return !this._semanticTokens.isEmpty();
  }
  setPartialSemanticTokens(range2, tokens) {
    if (this.hasCompleteSemanticTokens()) {
      return;
    }
    const changedRange = this._textModel.validateRange(this._semanticTokens.setPartial(range2, tokens));
    this._emitModelTokensChangedEvent({
      semanticTokensApplied: true,
      ranges: [
        {
          fromLineNumber: changedRange.startLineNumber,
          toLineNumber: changedRange.endLineNumber
        }
      ]
    });
  }
  // #endregion
  // #region Utility Methods
  getWordAtPosition(_position) {
    this.assertNotDisposed();
    const position = this._textModel.validatePosition(_position);
    const lineContent = this._textModel.getLineContent(position.lineNumber);
    const lineTokens = this.getLineTokens(position.lineNumber);
    const tokenIndex = lineTokens.findTokenIndexAtOffset(position.column - 1);
    const [rbStartOffset, rbEndOffset] = TokenizationTextModelPart._findLanguageBoundaries(lineTokens, tokenIndex);
    const rightBiasedWord = getWordAtText(position.column, this.getLanguageConfiguration(lineTokens.getLanguageId(tokenIndex)).getWordDefinition(), lineContent.substring(rbStartOffset, rbEndOffset), rbStartOffset);
    if (rightBiasedWord && rightBiasedWord.startColumn <= _position.column && _position.column <= rightBiasedWord.endColumn) {
      return rightBiasedWord;
    }
    if (tokenIndex > 0 && rbStartOffset === position.column - 1) {
      const [lbStartOffset, lbEndOffset] = TokenizationTextModelPart._findLanguageBoundaries(lineTokens, tokenIndex - 1);
      const leftBiasedWord = getWordAtText(position.column, this.getLanguageConfiguration(lineTokens.getLanguageId(tokenIndex - 1)).getWordDefinition(), lineContent.substring(lbStartOffset, lbEndOffset), lbStartOffset);
      if (leftBiasedWord && leftBiasedWord.startColumn <= _position.column && _position.column <= leftBiasedWord.endColumn) {
        return leftBiasedWord;
      }
    }
    return null;
  }
  getLanguageConfiguration(languageId) {
    return this._languageConfigurationService.getLanguageConfiguration(languageId);
  }
  static _findLanguageBoundaries(lineTokens, tokenIndex) {
    const languageId = lineTokens.getLanguageId(tokenIndex);
    let startOffset = 0;
    for (let i = tokenIndex; i >= 0 && lineTokens.getLanguageId(i) === languageId; i--) {
      startOffset = lineTokens.getStartOffset(i);
    }
    let endOffset = lineTokens.getLineContent().length;
    for (let i = tokenIndex, tokenCount = lineTokens.getCount(); i < tokenCount && lineTokens.getLanguageId(i) === languageId; i++) {
      endOffset = lineTokens.getEndOffset(i);
    }
    return [startOffset, endOffset];
  }
  getWordUntilPosition(position) {
    const wordAtPosition = this.getWordAtPosition(position);
    if (!wordAtPosition) {
      return { word: "", startColumn: position.column, endColumn: position.column };
    }
    return {
      word: wordAtPosition.word.substr(0, position.column - wordAtPosition.startColumn),
      startColumn: wordAtPosition.startColumn,
      endColumn: position.column
    };
  }
  // #endregion
  // #region Language Id handling
  getLanguageId() {
    return this._languageId;
  }
  getLanguageIdAtPosition(lineNumber, column) {
    const position = this._textModel.validatePosition(new Position$2(lineNumber, column));
    const lineTokens = this.getLineTokens(position.lineNumber);
    return lineTokens.getLanguageId(lineTokens.findTokenIndexAtOffset(position.column - 1));
  }
  setLanguageId(languageId, source = "api") {
    if (this._languageId === languageId) {
      return;
    }
    const e = {
      oldLanguage: this._languageId,
      newLanguage: languageId,
      source
    };
    this._languageId = languageId;
    this._bracketPairsTextModelPart.handleDidChangeLanguage(e);
    this.grammarTokens.resetTokenization();
    this._onDidChangeLanguage.fire(e);
    this._onDidChangeLanguageConfiguration.fire({});
  }
}
class GrammarTokens extends Disposable {
  get backgroundTokenizationState() {
    return this._backgroundTokenizationState;
  }
  constructor(_languageIdCodec, _textModel, getLanguageId, attachedViews) {
    super();
    this._languageIdCodec = _languageIdCodec;
    this._textModel = _textModel;
    this.getLanguageId = getLanguageId;
    this._tokenizer = null;
    this._defaultBackgroundTokenizer = null;
    this._backgroundTokenizer = this._register(new MutableDisposable());
    this._tokens = new ContiguousTokensStore(this._languageIdCodec);
    this._debugBackgroundTokenizer = this._register(new MutableDisposable());
    this._backgroundTokenizationState = 1;
    this._onDidChangeBackgroundTokenizationState = this._register(new Emitter$1());
    this.onDidChangeBackgroundTokenizationState = this._onDidChangeBackgroundTokenizationState.event;
    this._onDidChangeTokens = this._register(new Emitter$1());
    this.onDidChangeTokens = this._onDidChangeTokens.event;
    this._attachedViewStates = this._register(new DisposableMap());
    this._register(TokenizationRegistry2.onDidChange((e) => {
      const languageId = this.getLanguageId();
      if (e.changedLanguages.indexOf(languageId) === -1) {
        return;
      }
      this.resetTokenization();
    }));
    this.resetTokenization();
    this._register(attachedViews.onDidChangeVisibleRanges(({ view, state }) => {
      if (state) {
        let existing = this._attachedViewStates.get(view);
        if (!existing) {
          existing = new AttachedViewHandler(() => this.refreshRanges(existing.lineRanges));
          this._attachedViewStates.set(view, existing);
        }
        existing.handleStateChange(state);
      } else {
        this._attachedViewStates.deleteAndDispose(view);
      }
    }));
  }
  resetTokenization(fireTokenChangeEvent = true) {
    var _a2;
    this._tokens.flush();
    (_a2 = this._debugBackgroundTokens) === null || _a2 === void 0 ? void 0 : _a2.flush();
    if (this._debugBackgroundStates) {
      this._debugBackgroundStates = new TrackingTokenizationStateStore(this._textModel.getLineCount());
    }
    if (fireTokenChangeEvent) {
      this._onDidChangeTokens.fire({
        semanticTokensApplied: false,
        ranges: [
          {
            fromLineNumber: 1,
            toLineNumber: this._textModel.getLineCount()
          }
        ]
      });
    }
    const initializeTokenization = () => {
      if (this._textModel.isTooLargeForTokenization()) {
        return [null, null];
      }
      const tokenizationSupport2 = TokenizationRegistry2.get(this.getLanguageId());
      if (!tokenizationSupport2) {
        return [null, null];
      }
      let initialState2;
      try {
        initialState2 = tokenizationSupport2.getInitialState();
      } catch (e) {
        onUnexpectedError(e);
        return [null, null];
      }
      return [tokenizationSupport2, initialState2];
    };
    const [tokenizationSupport, initialState] = initializeTokenization();
    if (tokenizationSupport && initialState) {
      this._tokenizer = new TokenizerWithStateStoreAndTextModel(this._textModel.getLineCount(), tokenizationSupport, this._textModel, this._languageIdCodec);
    } else {
      this._tokenizer = null;
    }
    this._backgroundTokenizer.clear();
    this._defaultBackgroundTokenizer = null;
    if (this._tokenizer) {
      const b = {
        setTokens: (tokens) => {
          this.setTokens(tokens);
        },
        backgroundTokenizationFinished: () => {
          if (this._backgroundTokenizationState === 2) {
            return;
          }
          const newState = 2;
          this._backgroundTokenizationState = newState;
          this._onDidChangeBackgroundTokenizationState.fire();
        },
        setEndState: (lineNumber, state) => {
          var _a3;
          if (!this._tokenizer) {
            return;
          }
          const firstInvalidEndStateLineNumber = this._tokenizer.store.getFirstInvalidEndStateLineNumber();
          if (firstInvalidEndStateLineNumber !== null && lineNumber >= firstInvalidEndStateLineNumber) {
            (_a3 = this._tokenizer) === null || _a3 === void 0 ? void 0 : _a3.store.setEndState(lineNumber, state);
          }
        }
      };
      if (tokenizationSupport && tokenizationSupport.createBackgroundTokenizer && !tokenizationSupport.backgroundTokenizerShouldOnlyVerifyTokens) {
        this._backgroundTokenizer.value = tokenizationSupport.createBackgroundTokenizer(this._textModel, b);
      }
      if (!this._backgroundTokenizer.value) {
        this._backgroundTokenizer.value = this._defaultBackgroundTokenizer = new DefaultBackgroundTokenizer(this._tokenizer, b);
        this._defaultBackgroundTokenizer.handleChanges();
      }
      if ((tokenizationSupport === null || tokenizationSupport === void 0 ? void 0 : tokenizationSupport.backgroundTokenizerShouldOnlyVerifyTokens) && tokenizationSupport.createBackgroundTokenizer) {
        this._debugBackgroundTokens = new ContiguousTokensStore(this._languageIdCodec);
        this._debugBackgroundStates = new TrackingTokenizationStateStore(this._textModel.getLineCount());
        this._debugBackgroundTokenizer.clear();
        this._debugBackgroundTokenizer.value = tokenizationSupport.createBackgroundTokenizer(this._textModel, {
          setTokens: (tokens) => {
            var _a3;
            (_a3 = this._debugBackgroundTokens) === null || _a3 === void 0 ? void 0 : _a3.setMultilineTokens(tokens, this._textModel);
          },
          backgroundTokenizationFinished() {
          },
          setEndState: (lineNumber, state) => {
            var _a3;
            (_a3 = this._debugBackgroundStates) === null || _a3 === void 0 ? void 0 : _a3.setEndState(lineNumber, state);
          }
        });
      } else {
        this._debugBackgroundTokens = void 0;
        this._debugBackgroundStates = void 0;
        this._debugBackgroundTokenizer.value = void 0;
      }
    }
    this.refreshAllVisibleLineTokens();
  }
  handleDidChangeAttached() {
    var _a2;
    (_a2 = this._defaultBackgroundTokenizer) === null || _a2 === void 0 ? void 0 : _a2.handleChanges();
  }
  handleDidChangeContent(e) {
    var _a2, _b2, _c2;
    if (e.isFlush) {
      this.resetTokenization(false);
    } else if (!e.isEolChange) {
      for (const c of e.changes) {
        const [eolCount, firstLineLength] = countEOL(c.text);
        this._tokens.acceptEdit(c.range, eolCount, firstLineLength);
        (_a2 = this._debugBackgroundTokens) === null || _a2 === void 0 ? void 0 : _a2.acceptEdit(c.range, eolCount, firstLineLength);
      }
      (_b2 = this._debugBackgroundStates) === null || _b2 === void 0 ? void 0 : _b2.acceptChanges(e.changes);
      if (this._tokenizer) {
        this._tokenizer.store.acceptChanges(e.changes);
      }
      (_c2 = this._defaultBackgroundTokenizer) === null || _c2 === void 0 ? void 0 : _c2.handleChanges();
    }
  }
  setTokens(tokens) {
    const { changes } = this._tokens.setMultilineTokens(tokens, this._textModel);
    if (changes.length > 0) {
      this._onDidChangeTokens.fire({ semanticTokensApplied: false, ranges: changes });
    }
    return { changes };
  }
  refreshAllVisibleLineTokens() {
    const ranges = LineRange2.joinMany([...this._attachedViewStates].map(([_, s]) => s.lineRanges));
    this.refreshRanges(ranges);
  }
  refreshRanges(ranges) {
    for (const range2 of ranges) {
      this.refreshRange(range2.startLineNumber, range2.endLineNumberExclusive - 1);
    }
  }
  refreshRange(startLineNumber, endLineNumber) {
    var _a2, _b2;
    if (!this._tokenizer) {
      return;
    }
    startLineNumber = Math.max(1, Math.min(this._textModel.getLineCount(), startLineNumber));
    endLineNumber = Math.min(this._textModel.getLineCount(), endLineNumber);
    const builder = new ContiguousMultilineTokensBuilder();
    const { heuristicTokens } = this._tokenizer.tokenizeHeuristically(builder, startLineNumber, endLineNumber);
    const changedTokens = this.setTokens(builder.finalize());
    if (heuristicTokens) {
      for (const c of changedTokens.changes) {
        (_a2 = this._backgroundTokenizer.value) === null || _a2 === void 0 ? void 0 : _a2.requestTokens(c.fromLineNumber, c.toLineNumber + 1);
      }
    }
    (_b2 = this._defaultBackgroundTokenizer) === null || _b2 === void 0 ? void 0 : _b2.checkFinished();
  }
  forceTokenization(lineNumber) {
    var _a2, _b2;
    const builder = new ContiguousMultilineTokensBuilder();
    (_a2 = this._tokenizer) === null || _a2 === void 0 ? void 0 : _a2.updateTokensUntilLine(builder, lineNumber);
    this.setTokens(builder.finalize());
    (_b2 = this._defaultBackgroundTokenizer) === null || _b2 === void 0 ? void 0 : _b2.checkFinished();
  }
  isCheapToTokenize(lineNumber) {
    if (!this._tokenizer) {
      return true;
    }
    return this._tokenizer.isCheapToTokenize(lineNumber);
  }
  tokenizeIfCheap(lineNumber) {
    if (this.isCheapToTokenize(lineNumber)) {
      this.forceTokenization(lineNumber);
    }
  }
  getLineTokens(lineNumber) {
    var _a2;
    const lineText = this._textModel.getLineContent(lineNumber);
    const result2 = this._tokens.getTokens(this._textModel.getLanguageId(), lineNumber - 1, lineText);
    if (this._debugBackgroundTokens && this._debugBackgroundStates && this._tokenizer) {
      if (this._debugBackgroundStates.getFirstInvalidEndStateLineNumberOrMax() > lineNumber && this._tokenizer.store.getFirstInvalidEndStateLineNumberOrMax() > lineNumber) {
        const backgroundResult = this._debugBackgroundTokens.getTokens(this._textModel.getLanguageId(), lineNumber - 1, lineText);
        if (!result2.equals(backgroundResult) && ((_a2 = this._debugBackgroundTokenizer.value) === null || _a2 === void 0 ? void 0 : _a2.reportMismatchingTokens)) {
          this._debugBackgroundTokenizer.value.reportMismatchingTokens(lineNumber);
        }
      }
    }
    return result2;
  }
  getTokenTypeIfInsertingCharacter(lineNumber, column, character) {
    if (!this._tokenizer) {
      return 0;
    }
    const position = this._textModel.validatePosition(new Position$2(lineNumber, column));
    this.forceTokenization(position.lineNumber);
    return this._tokenizer.getTokenTypeIfInsertingCharacter(position, character);
  }
  tokenizeLineWithEdit(position, length2, newText) {
    if (!this._tokenizer) {
      return null;
    }
    const validatedPosition = this._textModel.validatePosition(position);
    this.forceTokenization(validatedPosition.lineNumber);
    return this._tokenizer.tokenizeLineWithEdit(validatedPosition, length2, newText);
  }
  get hasTokens() {
    return this._tokens.hasTokens;
  }
}
class AttachedViewHandler extends Disposable {
  get lineRanges() {
    return this._lineRanges;
  }
  constructor(_refreshTokens) {
    super();
    this._refreshTokens = _refreshTokens;
    this.runner = this._register(new RunOnceScheduler(() => this.update(), 50));
    this._computedLineRanges = [];
    this._lineRanges = [];
  }
  update() {
    if (equals$3(this._computedLineRanges, this._lineRanges, (a, b) => a.equals(b))) {
      return;
    }
    this._computedLineRanges = this._lineRanges;
    this._refreshTokens();
  }
  handleStateChange(state) {
    this._lineRanges = state.visibleLineRanges;
    if (state.stabilized) {
      this.runner.cancel();
      this.update();
    } else {
      this.runner.schedule();
    }
  }
}
class ModelRawFlush {
  constructor() {
    this.changeType = 1;
  }
}
class LineInjectedText {
  static applyInjectedText(lineText, injectedTexts) {
    if (!injectedTexts || injectedTexts.length === 0) {
      return lineText;
    }
    let result2 = "";
    let lastOriginalOffset = 0;
    for (const injectedText of injectedTexts) {
      result2 += lineText.substring(lastOriginalOffset, injectedText.column - 1);
      lastOriginalOffset = injectedText.column - 1;
      result2 += injectedText.options.content;
    }
    result2 += lineText.substring(lastOriginalOffset);
    return result2;
  }
  static fromDecorations(decorations2) {
    const result2 = [];
    for (const decoration2 of decorations2) {
      if (decoration2.options.before && decoration2.options.before.content.length > 0) {
        result2.push(new LineInjectedText(decoration2.ownerId, decoration2.range.startLineNumber, decoration2.range.startColumn, decoration2.options.before, 0));
      }
      if (decoration2.options.after && decoration2.options.after.content.length > 0) {
        result2.push(new LineInjectedText(decoration2.ownerId, decoration2.range.endLineNumber, decoration2.range.endColumn, decoration2.options.after, 1));
      }
    }
    result2.sort((a, b) => {
      if (a.lineNumber === b.lineNumber) {
        if (a.column === b.column) {
          return a.order - b.order;
        }
        return a.column - b.column;
      }
      return a.lineNumber - b.lineNumber;
    });
    return result2;
  }
  constructor(ownerId, lineNumber, column, options, order) {
    this.ownerId = ownerId;
    this.lineNumber = lineNumber;
    this.column = column;
    this.options = options;
    this.order = order;
  }
}
class ModelRawLineChanged {
  constructor(lineNumber, detail, injectedText) {
    this.changeType = 2;
    this.lineNumber = lineNumber;
    this.detail = detail;
    this.injectedText = injectedText;
  }
}
class ModelRawLinesDeleted {
  constructor(fromLineNumber, toLineNumber) {
    this.changeType = 3;
    this.fromLineNumber = fromLineNumber;
    this.toLineNumber = toLineNumber;
  }
}
class ModelRawLinesInserted {
  constructor(fromLineNumber, toLineNumber, detail, injectedTexts) {
    this.changeType = 4;
    this.injectedTexts = injectedTexts;
    this.fromLineNumber = fromLineNumber;
    this.toLineNumber = toLineNumber;
    this.detail = detail;
  }
}
class ModelRawEOLChanged {
  constructor() {
    this.changeType = 5;
  }
}
class ModelRawContentChangedEvent {
  constructor(changes, versionId, isUndoing, isRedoing) {
    this.changes = changes;
    this.versionId = versionId;
    this.isUndoing = isUndoing;
    this.isRedoing = isRedoing;
    this.resultingSelection = null;
  }
  containsEvent(type) {
    for (let i = 0, len = this.changes.length; i < len; i++) {
      const change = this.changes[i];
      if (change.changeType === type) {
        return true;
      }
    }
    return false;
  }
  static merge(a, b) {
    const changes = [].concat(a.changes).concat(b.changes);
    const versionId = b.versionId;
    const isUndoing = a.isUndoing || b.isUndoing;
    const isRedoing = a.isRedoing || b.isRedoing;
    return new ModelRawContentChangedEvent(changes, versionId, isUndoing, isRedoing);
  }
}
class ModelInjectedTextChangedEvent {
  constructor(changes) {
    this.changes = changes;
  }
}
class InternalModelContentChangeEvent {
  constructor(rawContentChangedEvent, contentChangedEvent) {
    this.rawContentChangedEvent = rawContentChangedEvent;
    this.contentChangedEvent = contentChangedEvent;
  }
  merge(other) {
    const rawContentChangedEvent = ModelRawContentChangedEvent.merge(this.rawContentChangedEvent, other.rawContentChangedEvent);
    const contentChangedEvent = InternalModelContentChangeEvent._mergeChangeEvents(this.contentChangedEvent, other.contentChangedEvent);
    return new InternalModelContentChangeEvent(rawContentChangedEvent, contentChangedEvent);
  }
  static _mergeChangeEvents(a, b) {
    const changes = [].concat(a.changes).concat(b.changes);
    const eol = b.eol;
    const versionId = b.versionId;
    const isUndoing = a.isUndoing || b.isUndoing;
    const isRedoing = a.isRedoing || b.isRedoing;
    const isFlush = a.isFlush || b.isFlush;
    const isEolChange = a.isEolChange && b.isEolChange;
    return {
      changes,
      eol,
      isEolChange,
      versionId,
      isUndoing,
      isRedoing,
      isFlush
    };
  }
}
const IUndoRedoService = createDecorator("undoRedoService");
class ResourceEditStackSnapshot {
  constructor(resource, elements) {
    this.resource = resource;
    this.elements = elements;
  }
}
class UndoRedoGroup {
  constructor() {
    this.id = UndoRedoGroup._ID++;
    this.order = 1;
  }
  nextOrder() {
    if (this.id === 0) {
      return 0;
    }
    return this.order++;
  }
}
UndoRedoGroup._ID = 0;
UndoRedoGroup.None = new UndoRedoGroup();
class UndoRedoSource {
  constructor() {
    this.id = UndoRedoSource._ID++;
    this.order = 1;
  }
  nextOrder() {
    if (this.id === 0) {
      return 0;
    }
    return this.order++;
  }
}
UndoRedoSource._ID = 0;
UndoRedoSource.None = new UndoRedoSource();
var __decorate$23 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1Z = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
function createTextBufferFactory(text2) {
  const builder = new PieceTreeTextBufferBuilder();
  builder.acceptChunk(text2);
  return builder.finish();
}
function createTextBufferFactoryFromSnapshot(snapshot) {
  const builder = new PieceTreeTextBufferBuilder();
  let chunk;
  while (typeof (chunk = snapshot.read()) === "string") {
    builder.acceptChunk(chunk);
  }
  return builder.finish();
}
function createTextBuffer(value, defaultEOL) {
  let factory;
  if (typeof value === "string") {
    factory = createTextBufferFactory(value);
  } else if (isITextSnapshot(value)) {
    factory = createTextBufferFactoryFromSnapshot(value);
  } else {
    factory = value;
  }
  return factory.create(defaultEOL);
}
let MODEL_ID$1 = 0;
const LIMIT_FIND_COUNT = 999;
const LONG_LINE_BOUNDARY = 1e4;
class TextModelSnapshot {
  constructor(source) {
    this._source = source;
    this._eos = false;
  }
  read() {
    if (this._eos) {
      return null;
    }
    const result2 = [];
    let resultCnt = 0;
    let resultLength = 0;
    do {
      const tmp = this._source.read();
      if (tmp === null) {
        this._eos = true;
        if (resultCnt === 0) {
          return null;
        } else {
          return result2.join("");
        }
      }
      if (tmp.length > 0) {
        result2[resultCnt++] = tmp;
        resultLength += tmp.length;
      }
      if (resultLength >= 64 * 1024) {
        return result2.join("");
      }
    } while (true);
  }
}
const invalidFunc = () => {
  throw new Error(`Invalid change accessor`);
};
let TextModel = class TextModel2 extends Disposable {
  static resolveOptions(textBuffer, options) {
    if (options.detectIndentation) {
      const guessedIndentation = guessIndentation(textBuffer, options.tabSize, options.insertSpaces);
      return new TextModelResolvedOptions({
        tabSize: guessedIndentation.tabSize,
        indentSize: "tabSize",
        insertSpaces: guessedIndentation.insertSpaces,
        trimAutoWhitespace: options.trimAutoWhitespace,
        defaultEOL: options.defaultEOL,
        bracketPairColorizationOptions: options.bracketPairColorizationOptions
      });
    }
    return new TextModelResolvedOptions(options);
  }
  get onDidChangeLanguage() {
    return this._tokenizationTextModelPart.onDidChangeLanguage;
  }
  get onDidChangeLanguageConfiguration() {
    return this._tokenizationTextModelPart.onDidChangeLanguageConfiguration;
  }
  get onDidChangeTokens() {
    return this._tokenizationTextModelPart.onDidChangeTokens;
  }
  onDidChangeContent(listener) {
    return this._eventEmitter.slowEvent((e) => listener(e.contentChangedEvent));
  }
  onDidChangeContentOrInjectedText(listener) {
    return combinedDisposable(this._eventEmitter.fastEvent((e) => listener(e)), this._onDidChangeInjectedText.event((e) => listener(e)));
  }
  _isDisposing() {
    return this.__isDisposing;
  }
  get tokenization() {
    return this._tokenizationTextModelPart;
  }
  get bracketPairs() {
    return this._bracketPairs;
  }
  get guides() {
    return this._guidesTextModelPart;
  }
  constructor(source, languageIdOrSelection, creationOptions, associatedResource = null, _undoRedoService, _languageService, _languageConfigurationService) {
    super();
    this._undoRedoService = _undoRedoService;
    this._languageService = _languageService;
    this._languageConfigurationService = _languageConfigurationService;
    this._onWillDispose = this._register(new Emitter$1());
    this.onWillDispose = this._onWillDispose.event;
    this._onDidChangeDecorations = this._register(new DidChangeDecorationsEmitter((affectedInjectedTextLines) => this.handleBeforeFireDecorationsChangedEvent(affectedInjectedTextLines)));
    this.onDidChangeDecorations = this._onDidChangeDecorations.event;
    this._onDidChangeOptions = this._register(new Emitter$1());
    this.onDidChangeOptions = this._onDidChangeOptions.event;
    this._onDidChangeAttached = this._register(new Emitter$1());
    this.onDidChangeAttached = this._onDidChangeAttached.event;
    this._onDidChangeInjectedText = this._register(new Emitter$1());
    this._eventEmitter = this._register(new DidChangeContentEmitter());
    this._languageSelectionListener = this._register(new MutableDisposable());
    this._deltaDecorationCallCnt = 0;
    this._attachedViews = new AttachedViews();
    MODEL_ID$1++;
    this.id = "$model" + MODEL_ID$1;
    this.isForSimpleWidget = creationOptions.isForSimpleWidget;
    if (typeof associatedResource === "undefined" || associatedResource === null) {
      this._associatedResource = URI.parse("inmemory://model/" + MODEL_ID$1);
    } else {
      this._associatedResource = associatedResource;
    }
    this._attachedEditorCount = 0;
    const { textBuffer, disposable } = createTextBuffer(source, creationOptions.defaultEOL);
    this._buffer = textBuffer;
    this._bufferDisposable = disposable;
    this._options = TextModel2.resolveOptions(this._buffer, creationOptions);
    const languageId = typeof languageIdOrSelection === "string" ? languageIdOrSelection : languageIdOrSelection.languageId;
    if (typeof languageIdOrSelection !== "string") {
      this._languageSelectionListener.value = languageIdOrSelection.onDidChange(() => this._setLanguage(languageIdOrSelection.languageId));
    }
    this._bracketPairs = this._register(new BracketPairsTextModelPart(this, this._languageConfigurationService));
    this._guidesTextModelPart = this._register(new GuidesTextModelPart(this, this._languageConfigurationService));
    this._decorationProvider = this._register(new ColorizedBracketPairsDecorationProvider(this));
    this._tokenizationTextModelPart = new TokenizationTextModelPart(this._languageService, this._languageConfigurationService, this, this._bracketPairs, languageId, this._attachedViews);
    const bufferLineCount = this._buffer.getLineCount();
    const bufferTextLength = this._buffer.getValueLengthInRange(
      new Range$2(1, 1, bufferLineCount, this._buffer.getLineLength(bufferLineCount) + 1),
      0
      /* model.EndOfLinePreference.TextDefined */
    );
    if (creationOptions.largeFileOptimizations) {
      this._isTooLargeForTokenization = bufferTextLength > TextModel2.LARGE_FILE_SIZE_THRESHOLD || bufferLineCount > TextModel2.LARGE_FILE_LINE_COUNT_THRESHOLD;
    } else {
      this._isTooLargeForTokenization = false;
    }
    this._isTooLargeForSyncing = bufferTextLength > TextModel2._MODEL_SYNC_LIMIT;
    this._versionId = 1;
    this._alternativeVersionId = 1;
    this._initialUndoRedoSnapshot = null;
    this._isDisposed = false;
    this.__isDisposing = false;
    this._instanceId = singleLetterHash(MODEL_ID$1);
    this._lastDecorationId = 0;
    this._decorations = /* @__PURE__ */ Object.create(null);
    this._decorationsTree = new DecorationsTrees();
    this._commandManager = new EditStack(this, this._undoRedoService);
    this._isUndoing = false;
    this._isRedoing = false;
    this._trimAutoWhitespaceLines = null;
    this._register(this._decorationProvider.onDidChange(() => {
      this._onDidChangeDecorations.beginDeferredEmit();
      this._onDidChangeDecorations.fire();
      this._onDidChangeDecorations.endDeferredEmit();
    }));
    this._languageService.requestRichLanguageFeatures(languageId);
  }
  dispose() {
    this.__isDisposing = true;
    this._onWillDispose.fire();
    this._tokenizationTextModelPart.dispose();
    this._isDisposed = true;
    super.dispose();
    this._bufferDisposable.dispose();
    this.__isDisposing = false;
    const emptyDisposedTextBuffer = new PieceTreeTextBuffer([], "", "\n", false, false, true, true);
    emptyDisposedTextBuffer.dispose();
    this._buffer = emptyDisposedTextBuffer;
    this._bufferDisposable = Disposable.None;
  }
  _assertNotDisposed() {
    if (this._isDisposed) {
      throw new Error("Model is disposed!");
    }
  }
  _emitContentChangedEvent(rawChange, change) {
    if (this.__isDisposing) {
      return;
    }
    this._tokenizationTextModelPart.handleDidChangeContent(change);
    this._bracketPairs.handleDidChangeContent(change);
    this._eventEmitter.fire(new InternalModelContentChangeEvent(rawChange, change));
  }
  setValue(value) {
    this._assertNotDisposed();
    if (value === null || value === void 0) {
      throw illegalArgument();
    }
    const { textBuffer, disposable } = createTextBuffer(value, this._options.defaultEOL);
    this._setValueFromTextBuffer(textBuffer, disposable);
  }
  _createContentChanged2(range2, rangeOffset, rangeLength, text2, isUndoing, isRedoing, isFlush, isEolChange) {
    return {
      changes: [{
        range: range2,
        rangeOffset,
        rangeLength,
        text: text2
      }],
      eol: this._buffer.getEOL(),
      isEolChange,
      versionId: this.getVersionId(),
      isUndoing,
      isRedoing,
      isFlush
    };
  }
  _setValueFromTextBuffer(textBuffer, textBufferDisposable) {
    this._assertNotDisposed();
    const oldFullModelRange = this.getFullModelRange();
    const oldModelValueLength = this.getValueLengthInRange(oldFullModelRange);
    const endLineNumber = this.getLineCount();
    const endColumn = this.getLineMaxColumn(endLineNumber);
    this._buffer = textBuffer;
    this._bufferDisposable.dispose();
    this._bufferDisposable = textBufferDisposable;
    this._increaseVersionId();
    this._decorations = /* @__PURE__ */ Object.create(null);
    this._decorationsTree = new DecorationsTrees();
    this._commandManager.clear();
    this._trimAutoWhitespaceLines = null;
    this._emitContentChangedEvent(new ModelRawContentChangedEvent([
      new ModelRawFlush()
    ], this._versionId, false, false), this._createContentChanged2(new Range$2(1, 1, endLineNumber, endColumn), 0, oldModelValueLength, this.getValue(), false, false, true, false));
  }
  setEOL(eol) {
    this._assertNotDisposed();
    const newEOL = eol === 1 ? "\r\n" : "\n";
    if (this._buffer.getEOL() === newEOL) {
      return;
    }
    const oldFullModelRange = this.getFullModelRange();
    const oldModelValueLength = this.getValueLengthInRange(oldFullModelRange);
    const endLineNumber = this.getLineCount();
    const endColumn = this.getLineMaxColumn(endLineNumber);
    this._onBeforeEOLChange();
    this._buffer.setEOL(newEOL);
    this._increaseVersionId();
    this._onAfterEOLChange();
    this._emitContentChangedEvent(new ModelRawContentChangedEvent([
      new ModelRawEOLChanged()
    ], this._versionId, false, false), this._createContentChanged2(new Range$2(1, 1, endLineNumber, endColumn), 0, oldModelValueLength, this.getValue(), false, false, false, true));
  }
  _onBeforeEOLChange() {
    this._decorationsTree.ensureAllNodesHaveRanges(this);
  }
  _onAfterEOLChange() {
    const versionId = this.getVersionId();
    const allDecorations = this._decorationsTree.collectNodesPostOrder();
    for (let i = 0, len = allDecorations.length; i < len; i++) {
      const node2 = allDecorations[i];
      const range2 = node2.range;
      const delta = node2.cachedAbsoluteStart - node2.start;
      const startOffset = this._buffer.getOffsetAt(range2.startLineNumber, range2.startColumn);
      const endOffset = this._buffer.getOffsetAt(range2.endLineNumber, range2.endColumn);
      node2.cachedAbsoluteStart = startOffset;
      node2.cachedAbsoluteEnd = endOffset;
      node2.cachedVersionId = versionId;
      node2.start = startOffset - delta;
      node2.end = endOffset - delta;
      recomputeMaxEnd(node2);
    }
  }
  onBeforeAttached() {
    this._attachedEditorCount++;
    if (this._attachedEditorCount === 1) {
      this._tokenizationTextModelPart.handleDidChangeAttached();
      this._onDidChangeAttached.fire(void 0);
    }
    return this._attachedViews.attachView();
  }
  onBeforeDetached(view) {
    this._attachedEditorCount--;
    if (this._attachedEditorCount === 0) {
      this._tokenizationTextModelPart.handleDidChangeAttached();
      this._onDidChangeAttached.fire(void 0);
    }
    this._attachedViews.detachView(view);
  }
  isAttachedToEditor() {
    return this._attachedEditorCount > 0;
  }
  getAttachedEditorCount() {
    return this._attachedEditorCount;
  }
  isTooLargeForSyncing() {
    return this._isTooLargeForSyncing;
  }
  isTooLargeForTokenization() {
    return this._isTooLargeForTokenization;
  }
  isDisposed() {
    return this._isDisposed;
  }
  isDominatedByLongLines() {
    this._assertNotDisposed();
    if (this.isTooLargeForTokenization()) {
      return false;
    }
    let smallLineCharCount = 0;
    let longLineCharCount = 0;
    const lineCount = this._buffer.getLineCount();
    for (let lineNumber = 1; lineNumber <= lineCount; lineNumber++) {
      const lineLength = this._buffer.getLineLength(lineNumber);
      if (lineLength >= LONG_LINE_BOUNDARY) {
        longLineCharCount += lineLength;
      } else {
        smallLineCharCount += lineLength;
      }
    }
    return longLineCharCount > smallLineCharCount;
  }
  get uri() {
    return this._associatedResource;
  }
  //#region Options
  getOptions() {
    this._assertNotDisposed();
    return this._options;
  }
  getFormattingOptions() {
    return {
      tabSize: this._options.indentSize,
      insertSpaces: this._options.insertSpaces
    };
  }
  updateOptions(_newOpts) {
    this._assertNotDisposed();
    const tabSize = typeof _newOpts.tabSize !== "undefined" ? _newOpts.tabSize : this._options.tabSize;
    const indentSize = typeof _newOpts.indentSize !== "undefined" ? _newOpts.indentSize : this._options.originalIndentSize;
    const insertSpaces = typeof _newOpts.insertSpaces !== "undefined" ? _newOpts.insertSpaces : this._options.insertSpaces;
    const trimAutoWhitespace = typeof _newOpts.trimAutoWhitespace !== "undefined" ? _newOpts.trimAutoWhitespace : this._options.trimAutoWhitespace;
    const bracketPairColorizationOptions = typeof _newOpts.bracketColorizationOptions !== "undefined" ? _newOpts.bracketColorizationOptions : this._options.bracketPairColorizationOptions;
    const newOpts = new TextModelResolvedOptions({
      tabSize,
      indentSize,
      insertSpaces,
      defaultEOL: this._options.defaultEOL,
      trimAutoWhitespace,
      bracketPairColorizationOptions
    });
    if (this._options.equals(newOpts)) {
      return;
    }
    const e = this._options.createChangeEvent(newOpts);
    this._options = newOpts;
    this._bracketPairs.handleDidChangeOptions(e);
    this._decorationProvider.handleDidChangeOptions(e);
    this._onDidChangeOptions.fire(e);
  }
  detectIndentation(defaultInsertSpaces, defaultTabSize) {
    this._assertNotDisposed();
    const guessedIndentation = guessIndentation(this._buffer, defaultTabSize, defaultInsertSpaces);
    this.updateOptions({
      insertSpaces: guessedIndentation.insertSpaces,
      tabSize: guessedIndentation.tabSize,
      indentSize: guessedIndentation.tabSize
      // TODO@Alex: guess indentSize independent of tabSize
    });
  }
  normalizeIndentation(str2) {
    this._assertNotDisposed();
    return normalizeIndentation(str2, this._options.indentSize, this._options.insertSpaces);
  }
  //#endregion
  //#region Reading
  getVersionId() {
    this._assertNotDisposed();
    return this._versionId;
  }
  mightContainRTL() {
    return this._buffer.mightContainRTL();
  }
  mightContainUnusualLineTerminators() {
    return this._buffer.mightContainUnusualLineTerminators();
  }
  removeUnusualLineTerminators(selections2 = null) {
    const matches = this.findMatches(
      UNUSUAL_LINE_TERMINATORS.source,
      false,
      true,
      false,
      null,
      false,
      1073741824
      /* Constants.MAX_SAFE_SMALL_INTEGER */
    );
    this._buffer.resetMightContainUnusualLineTerminators();
    this.pushEditOperations(selections2, matches.map((m) => ({ range: m.range, text: null })), () => null);
  }
  mightContainNonBasicASCII() {
    return this._buffer.mightContainNonBasicASCII();
  }
  getAlternativeVersionId() {
    this._assertNotDisposed();
    return this._alternativeVersionId;
  }
  getInitialUndoRedoSnapshot() {
    this._assertNotDisposed();
    return this._initialUndoRedoSnapshot;
  }
  getOffsetAt(rawPosition) {
    this._assertNotDisposed();
    const position = this._validatePosition(
      rawPosition.lineNumber,
      rawPosition.column,
      0
      /* StringOffsetValidationType.Relaxed */
    );
    return this._buffer.getOffsetAt(position.lineNumber, position.column);
  }
  getPositionAt(rawOffset) {
    this._assertNotDisposed();
    const offset = Math.min(this._buffer.getLength(), Math.max(0, rawOffset));
    return this._buffer.getPositionAt(offset);
  }
  _increaseVersionId() {
    this._versionId = this._versionId + 1;
    this._alternativeVersionId = this._versionId;
  }
  _overwriteVersionId(versionId) {
    this._versionId = versionId;
  }
  _overwriteAlternativeVersionId(newAlternativeVersionId) {
    this._alternativeVersionId = newAlternativeVersionId;
  }
  _overwriteInitialUndoRedoSnapshot(newInitialUndoRedoSnapshot) {
    this._initialUndoRedoSnapshot = newInitialUndoRedoSnapshot;
  }
  getValue(eol, preserveBOM = false) {
    this._assertNotDisposed();
    const fullModelRange = this.getFullModelRange();
    const fullModelValue = this.getValueInRange(fullModelRange, eol);
    if (preserveBOM) {
      return this._buffer.getBOM() + fullModelValue;
    }
    return fullModelValue;
  }
  createSnapshot(preserveBOM = false) {
    return new TextModelSnapshot(this._buffer.createSnapshot(preserveBOM));
  }
  getValueLength(eol, preserveBOM = false) {
    this._assertNotDisposed();
    const fullModelRange = this.getFullModelRange();
    const fullModelValue = this.getValueLengthInRange(fullModelRange, eol);
    if (preserveBOM) {
      return this._buffer.getBOM().length + fullModelValue;
    }
    return fullModelValue;
  }
  getValueInRange(rawRange, eol = 0) {
    this._assertNotDisposed();
    return this._buffer.getValueInRange(this.validateRange(rawRange), eol);
  }
  getValueLengthInRange(rawRange, eol = 0) {
    this._assertNotDisposed();
    return this._buffer.getValueLengthInRange(this.validateRange(rawRange), eol);
  }
  getCharacterCountInRange(rawRange, eol = 0) {
    this._assertNotDisposed();
    return this._buffer.getCharacterCountInRange(this.validateRange(rawRange), eol);
  }
  getLineCount() {
    this._assertNotDisposed();
    return this._buffer.getLineCount();
  }
  getLineContent(lineNumber) {
    this._assertNotDisposed();
    if (lineNumber < 1 || lineNumber > this.getLineCount()) {
      throw new BugIndicatingError("Illegal value for lineNumber");
    }
    return this._buffer.getLineContent(lineNumber);
  }
  getLineLength(lineNumber) {
    this._assertNotDisposed();
    if (lineNumber < 1 || lineNumber > this.getLineCount()) {
      throw new BugIndicatingError("Illegal value for lineNumber");
    }
    return this._buffer.getLineLength(lineNumber);
  }
  getLinesContent() {
    this._assertNotDisposed();
    return this._buffer.getLinesContent();
  }
  getEOL() {
    this._assertNotDisposed();
    return this._buffer.getEOL();
  }
  getEndOfLineSequence() {
    this._assertNotDisposed();
    return this._buffer.getEOL() === "\n" ? 0 : 1;
  }
  getLineMinColumn(lineNumber) {
    this._assertNotDisposed();
    return 1;
  }
  getLineMaxColumn(lineNumber) {
    this._assertNotDisposed();
    if (lineNumber < 1 || lineNumber > this.getLineCount()) {
      throw new BugIndicatingError("Illegal value for lineNumber");
    }
    return this._buffer.getLineLength(lineNumber) + 1;
  }
  getLineFirstNonWhitespaceColumn(lineNumber) {
    this._assertNotDisposed();
    if (lineNumber < 1 || lineNumber > this.getLineCount()) {
      throw new BugIndicatingError("Illegal value for lineNumber");
    }
    return this._buffer.getLineFirstNonWhitespaceColumn(lineNumber);
  }
  getLineLastNonWhitespaceColumn(lineNumber) {
    this._assertNotDisposed();
    if (lineNumber < 1 || lineNumber > this.getLineCount()) {
      throw new BugIndicatingError("Illegal value for lineNumber");
    }
    return this._buffer.getLineLastNonWhitespaceColumn(lineNumber);
  }
  /**
   * Validates `range` is within buffer bounds, but allows it to sit in between surrogate pairs, etc.
   * Will try to not allocate if possible.
   */
  _validateRangeRelaxedNoAllocations(range2) {
    const linesCount = this._buffer.getLineCount();
    const initialStartLineNumber = range2.startLineNumber;
    const initialStartColumn = range2.startColumn;
    let startLineNumber = Math.floor(typeof initialStartLineNumber === "number" && !isNaN(initialStartLineNumber) ? initialStartLineNumber : 1);
    let startColumn = Math.floor(typeof initialStartColumn === "number" && !isNaN(initialStartColumn) ? initialStartColumn : 1);
    if (startLineNumber < 1) {
      startLineNumber = 1;
      startColumn = 1;
    } else if (startLineNumber > linesCount) {
      startLineNumber = linesCount;
      startColumn = this.getLineMaxColumn(startLineNumber);
    } else {
      if (startColumn <= 1) {
        startColumn = 1;
      } else {
        const maxColumn = this.getLineMaxColumn(startLineNumber);
        if (startColumn >= maxColumn) {
          startColumn = maxColumn;
        }
      }
    }
    const initialEndLineNumber = range2.endLineNumber;
    const initialEndColumn = range2.endColumn;
    let endLineNumber = Math.floor(typeof initialEndLineNumber === "number" && !isNaN(initialEndLineNumber) ? initialEndLineNumber : 1);
    let endColumn = Math.floor(typeof initialEndColumn === "number" && !isNaN(initialEndColumn) ? initialEndColumn : 1);
    if (endLineNumber < 1) {
      endLineNumber = 1;
      endColumn = 1;
    } else if (endLineNumber > linesCount) {
      endLineNumber = linesCount;
      endColumn = this.getLineMaxColumn(endLineNumber);
    } else {
      if (endColumn <= 1) {
        endColumn = 1;
      } else {
        const maxColumn = this.getLineMaxColumn(endLineNumber);
        if (endColumn >= maxColumn) {
          endColumn = maxColumn;
        }
      }
    }
    if (initialStartLineNumber === startLineNumber && initialStartColumn === startColumn && initialEndLineNumber === endLineNumber && initialEndColumn === endColumn && range2 instanceof Range$2 && !(range2 instanceof Selection$1)) {
      return range2;
    }
    return new Range$2(startLineNumber, startColumn, endLineNumber, endColumn);
  }
  _isValidPosition(lineNumber, column, validationType) {
    if (typeof lineNumber !== "number" || typeof column !== "number") {
      return false;
    }
    if (isNaN(lineNumber) || isNaN(column)) {
      return false;
    }
    if (lineNumber < 1 || column < 1) {
      return false;
    }
    if ((lineNumber | 0) !== lineNumber || (column | 0) !== column) {
      return false;
    }
    const lineCount = this._buffer.getLineCount();
    if (lineNumber > lineCount) {
      return false;
    }
    if (column === 1) {
      return true;
    }
    const maxColumn = this.getLineMaxColumn(lineNumber);
    if (column > maxColumn) {
      return false;
    }
    if (validationType === 1) {
      const charCodeBefore = this._buffer.getLineCharCode(lineNumber, column - 2);
      if (isHighSurrogate(charCodeBefore)) {
        return false;
      }
    }
    return true;
  }
  _validatePosition(_lineNumber, _column, validationType) {
    const lineNumber = Math.floor(typeof _lineNumber === "number" && !isNaN(_lineNumber) ? _lineNumber : 1);
    const column = Math.floor(typeof _column === "number" && !isNaN(_column) ? _column : 1);
    const lineCount = this._buffer.getLineCount();
    if (lineNumber < 1) {
      return new Position$2(1, 1);
    }
    if (lineNumber > lineCount) {
      return new Position$2(lineCount, this.getLineMaxColumn(lineCount));
    }
    if (column <= 1) {
      return new Position$2(lineNumber, 1);
    }
    const maxColumn = this.getLineMaxColumn(lineNumber);
    if (column >= maxColumn) {
      return new Position$2(lineNumber, maxColumn);
    }
    if (validationType === 1) {
      const charCodeBefore = this._buffer.getLineCharCode(lineNumber, column - 2);
      if (isHighSurrogate(charCodeBefore)) {
        return new Position$2(lineNumber, column - 1);
      }
    }
    return new Position$2(lineNumber, column);
  }
  validatePosition(position) {
    const validationType = 1;
    this._assertNotDisposed();
    if (position instanceof Position$2) {
      if (this._isValidPosition(position.lineNumber, position.column, validationType)) {
        return position;
      }
    }
    return this._validatePosition(position.lineNumber, position.column, validationType);
  }
  _isValidRange(range2, validationType) {
    const startLineNumber = range2.startLineNumber;
    const startColumn = range2.startColumn;
    const endLineNumber = range2.endLineNumber;
    const endColumn = range2.endColumn;
    if (!this._isValidPosition(
      startLineNumber,
      startColumn,
      0
      /* StringOffsetValidationType.Relaxed */
    )) {
      return false;
    }
    if (!this._isValidPosition(
      endLineNumber,
      endColumn,
      0
      /* StringOffsetValidationType.Relaxed */
    )) {
      return false;
    }
    if (validationType === 1) {
      const charCodeBeforeStart = startColumn > 1 ? this._buffer.getLineCharCode(startLineNumber, startColumn - 2) : 0;
      const charCodeBeforeEnd = endColumn > 1 && endColumn <= this._buffer.getLineLength(endLineNumber) ? this._buffer.getLineCharCode(endLineNumber, endColumn - 2) : 0;
      const startInsideSurrogatePair = isHighSurrogate(charCodeBeforeStart);
      const endInsideSurrogatePair = isHighSurrogate(charCodeBeforeEnd);
      if (!startInsideSurrogatePair && !endInsideSurrogatePair) {
        return true;
      }
      return false;
    }
    return true;
  }
  validateRange(_range) {
    const validationType = 1;
    this._assertNotDisposed();
    if (_range instanceof Range$2 && !(_range instanceof Selection$1)) {
      if (this._isValidRange(_range, validationType)) {
        return _range;
      }
    }
    const start = this._validatePosition(
      _range.startLineNumber,
      _range.startColumn,
      0
      /* StringOffsetValidationType.Relaxed */
    );
    const end = this._validatePosition(
      _range.endLineNumber,
      _range.endColumn,
      0
      /* StringOffsetValidationType.Relaxed */
    );
    const startLineNumber = start.lineNumber;
    const startColumn = start.column;
    const endLineNumber = end.lineNumber;
    const endColumn = end.column;
    {
      const charCodeBeforeStart = startColumn > 1 ? this._buffer.getLineCharCode(startLineNumber, startColumn - 2) : 0;
      const charCodeBeforeEnd = endColumn > 1 && endColumn <= this._buffer.getLineLength(endLineNumber) ? this._buffer.getLineCharCode(endLineNumber, endColumn - 2) : 0;
      const startInsideSurrogatePair = isHighSurrogate(charCodeBeforeStart);
      const endInsideSurrogatePair = isHighSurrogate(charCodeBeforeEnd);
      if (!startInsideSurrogatePair && !endInsideSurrogatePair) {
        return new Range$2(startLineNumber, startColumn, endLineNumber, endColumn);
      }
      if (startLineNumber === endLineNumber && startColumn === endColumn) {
        return new Range$2(startLineNumber, startColumn - 1, endLineNumber, endColumn - 1);
      }
      if (startInsideSurrogatePair && endInsideSurrogatePair) {
        return new Range$2(startLineNumber, startColumn - 1, endLineNumber, endColumn + 1);
      }
      if (startInsideSurrogatePair) {
        return new Range$2(startLineNumber, startColumn - 1, endLineNumber, endColumn);
      }
      return new Range$2(startLineNumber, startColumn, endLineNumber, endColumn + 1);
    }
  }
  modifyPosition(rawPosition, offset) {
    this._assertNotDisposed();
    const candidate = this.getOffsetAt(rawPosition) + offset;
    return this.getPositionAt(Math.min(this._buffer.getLength(), Math.max(0, candidate)));
  }
  getFullModelRange() {
    this._assertNotDisposed();
    const lineCount = this.getLineCount();
    return new Range$2(1, 1, lineCount, this.getLineMaxColumn(lineCount));
  }
  findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount) {
    return this._buffer.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);
  }
  findMatches(searchString, rawSearchScope, isRegex, matchCase, wordSeparators2, captureMatches, limitResultCount = LIMIT_FIND_COUNT) {
    this._assertNotDisposed();
    let searchRanges = null;
    if (rawSearchScope !== null) {
      if (!Array.isArray(rawSearchScope)) {
        rawSearchScope = [rawSearchScope];
      }
      if (rawSearchScope.every((searchScope) => Range$2.isIRange(searchScope))) {
        searchRanges = rawSearchScope.map((searchScope) => this.validateRange(searchScope));
      }
    }
    if (searchRanges === null) {
      searchRanges = [this.getFullModelRange()];
    }
    searchRanges = searchRanges.sort((d1, d2) => d1.startLineNumber - d2.startLineNumber || d1.startColumn - d2.startColumn);
    const uniqueSearchRanges = [];
    uniqueSearchRanges.push(searchRanges.reduce((prev, curr) => {
      if (Range$2.areIntersecting(prev, curr)) {
        return prev.plusRange(curr);
      }
      uniqueSearchRanges.push(prev);
      return curr;
    }));
    let matchMapper;
    if (!isRegex && searchString.indexOf("\n") < 0) {
      const searchParams = new SearchParams(searchString, isRegex, matchCase, wordSeparators2);
      const searchData = searchParams.parseSearchRequest();
      if (!searchData) {
        return [];
      }
      matchMapper = (searchRange) => this.findMatchesLineByLine(searchRange, searchData, captureMatches, limitResultCount);
    } else {
      matchMapper = (searchRange) => TextModelSearch.findMatches(this, new SearchParams(searchString, isRegex, matchCase, wordSeparators2), searchRange, captureMatches, limitResultCount);
    }
    return uniqueSearchRanges.map(matchMapper).reduce((arr, matches) => arr.concat(matches), []);
  }
  findNextMatch(searchString, rawSearchStart, isRegex, matchCase, wordSeparators2, captureMatches) {
    this._assertNotDisposed();
    const searchStart = this.validatePosition(rawSearchStart);
    if (!isRegex && searchString.indexOf("\n") < 0) {
      const searchParams = new SearchParams(searchString, isRegex, matchCase, wordSeparators2);
      const searchData = searchParams.parseSearchRequest();
      if (!searchData) {
        return null;
      }
      const lineCount = this.getLineCount();
      let searchRange = new Range$2(searchStart.lineNumber, searchStart.column, lineCount, this.getLineMaxColumn(lineCount));
      let ret = this.findMatchesLineByLine(searchRange, searchData, captureMatches, 1);
      TextModelSearch.findNextMatch(this, new SearchParams(searchString, isRegex, matchCase, wordSeparators2), searchStart, captureMatches);
      if (ret.length > 0) {
        return ret[0];
      }
      searchRange = new Range$2(1, 1, searchStart.lineNumber, this.getLineMaxColumn(searchStart.lineNumber));
      ret = this.findMatchesLineByLine(searchRange, searchData, captureMatches, 1);
      if (ret.length > 0) {
        return ret[0];
      }
      return null;
    }
    return TextModelSearch.findNextMatch(this, new SearchParams(searchString, isRegex, matchCase, wordSeparators2), searchStart, captureMatches);
  }
  findPreviousMatch(searchString, rawSearchStart, isRegex, matchCase, wordSeparators2, captureMatches) {
    this._assertNotDisposed();
    const searchStart = this.validatePosition(rawSearchStart);
    return TextModelSearch.findPreviousMatch(this, new SearchParams(searchString, isRegex, matchCase, wordSeparators2), searchStart, captureMatches);
  }
  //#endregion
  //#region Editing
  pushStackElement() {
    this._commandManager.pushStackElement();
  }
  popStackElement() {
    this._commandManager.popStackElement();
  }
  pushEOL(eol) {
    const currentEOL = this.getEOL() === "\n" ? 0 : 1;
    if (currentEOL === eol) {
      return;
    }
    try {
      this._onDidChangeDecorations.beginDeferredEmit();
      this._eventEmitter.beginDeferredEmit();
      if (this._initialUndoRedoSnapshot === null) {
        this._initialUndoRedoSnapshot = this._undoRedoService.createSnapshot(this.uri);
      }
      this._commandManager.pushEOL(eol);
    } finally {
      this._eventEmitter.endDeferredEmit();
      this._onDidChangeDecorations.endDeferredEmit();
    }
  }
  _validateEditOperation(rawOperation) {
    if (rawOperation instanceof ValidAnnotatedEditOperation) {
      return rawOperation;
    }
    return new ValidAnnotatedEditOperation(rawOperation.identifier || null, this.validateRange(rawOperation.range), rawOperation.text, rawOperation.forceMoveMarkers || false, rawOperation.isAutoWhitespaceEdit || false, rawOperation._isTracked || false);
  }
  _validateEditOperations(rawOperations) {
    const result2 = [];
    for (let i = 0, len = rawOperations.length; i < len; i++) {
      result2[i] = this._validateEditOperation(rawOperations[i]);
    }
    return result2;
  }
  pushEditOperations(beforeCursorState, editOperations, cursorStateComputer, group2) {
    try {
      this._onDidChangeDecorations.beginDeferredEmit();
      this._eventEmitter.beginDeferredEmit();
      return this._pushEditOperations(beforeCursorState, this._validateEditOperations(editOperations), cursorStateComputer, group2);
    } finally {
      this._eventEmitter.endDeferredEmit();
      this._onDidChangeDecorations.endDeferredEmit();
    }
  }
  _pushEditOperations(beforeCursorState, editOperations, cursorStateComputer, group2) {
    if (this._options.trimAutoWhitespace && this._trimAutoWhitespaceLines) {
      const incomingEdits = editOperations.map((op) => {
        return {
          range: this.validateRange(op.range),
          text: op.text
        };
      });
      let editsAreNearCursors = true;
      if (beforeCursorState) {
        for (let i = 0, len = beforeCursorState.length; i < len; i++) {
          const sel = beforeCursorState[i];
          let foundEditNearSel = false;
          for (let j = 0, lenJ = incomingEdits.length; j < lenJ; j++) {
            const editRange = incomingEdits[j].range;
            const selIsAbove = editRange.startLineNumber > sel.endLineNumber;
            const selIsBelow = sel.startLineNumber > editRange.endLineNumber;
            if (!selIsAbove && !selIsBelow) {
              foundEditNearSel = true;
              break;
            }
          }
          if (!foundEditNearSel) {
            editsAreNearCursors = false;
            break;
          }
        }
      }
      if (editsAreNearCursors) {
        for (let i = 0, len = this._trimAutoWhitespaceLines.length; i < len; i++) {
          const trimLineNumber = this._trimAutoWhitespaceLines[i];
          const maxLineColumn = this.getLineMaxColumn(trimLineNumber);
          let allowTrimLine = true;
          for (let j = 0, lenJ = incomingEdits.length; j < lenJ; j++) {
            const editRange = incomingEdits[j].range;
            const editText = incomingEdits[j].text;
            if (trimLineNumber < editRange.startLineNumber || trimLineNumber > editRange.endLineNumber) {
              continue;
            }
            if (trimLineNumber === editRange.startLineNumber && editRange.startColumn === maxLineColumn && editRange.isEmpty() && editText && editText.length > 0 && editText.charAt(0) === "\n") {
              continue;
            }
            if (trimLineNumber === editRange.startLineNumber && editRange.startColumn === 1 && editRange.isEmpty() && editText && editText.length > 0 && editText.charAt(editText.length - 1) === "\n") {
              continue;
            }
            allowTrimLine = false;
            break;
          }
          if (allowTrimLine) {
            const trimRange = new Range$2(trimLineNumber, 1, trimLineNumber, maxLineColumn);
            editOperations.push(new ValidAnnotatedEditOperation(null, trimRange, null, false, false, false));
          }
        }
      }
      this._trimAutoWhitespaceLines = null;
    }
    if (this._initialUndoRedoSnapshot === null) {
      this._initialUndoRedoSnapshot = this._undoRedoService.createSnapshot(this.uri);
    }
    return this._commandManager.pushEditOperation(beforeCursorState, editOperations, cursorStateComputer, group2);
  }
  _applyUndo(changes, eol, resultingAlternativeVersionId, resultingSelection) {
    const edits = changes.map((change) => {
      const rangeStart = this.getPositionAt(change.newPosition);
      const rangeEnd = this.getPositionAt(change.newEnd);
      return {
        range: new Range$2(rangeStart.lineNumber, rangeStart.column, rangeEnd.lineNumber, rangeEnd.column),
        text: change.oldText
      };
    });
    this._applyUndoRedoEdits(edits, eol, true, false, resultingAlternativeVersionId, resultingSelection);
  }
  _applyRedo(changes, eol, resultingAlternativeVersionId, resultingSelection) {
    const edits = changes.map((change) => {
      const rangeStart = this.getPositionAt(change.oldPosition);
      const rangeEnd = this.getPositionAt(change.oldEnd);
      return {
        range: new Range$2(rangeStart.lineNumber, rangeStart.column, rangeEnd.lineNumber, rangeEnd.column),
        text: change.newText
      };
    });
    this._applyUndoRedoEdits(edits, eol, false, true, resultingAlternativeVersionId, resultingSelection);
  }
  _applyUndoRedoEdits(edits, eol, isUndoing, isRedoing, resultingAlternativeVersionId, resultingSelection) {
    try {
      this._onDidChangeDecorations.beginDeferredEmit();
      this._eventEmitter.beginDeferredEmit();
      this._isUndoing = isUndoing;
      this._isRedoing = isRedoing;
      this.applyEdits(edits, false);
      this.setEOL(eol);
      this._overwriteAlternativeVersionId(resultingAlternativeVersionId);
    } finally {
      this._isUndoing = false;
      this._isRedoing = false;
      this._eventEmitter.endDeferredEmit(resultingSelection);
      this._onDidChangeDecorations.endDeferredEmit();
    }
  }
  applyEdits(rawOperations, computeUndoEdits = false) {
    try {
      this._onDidChangeDecorations.beginDeferredEmit();
      this._eventEmitter.beginDeferredEmit();
      const operations = this._validateEditOperations(rawOperations);
      return this._doApplyEdits(operations, computeUndoEdits);
    } finally {
      this._eventEmitter.endDeferredEmit();
      this._onDidChangeDecorations.endDeferredEmit();
    }
  }
  _doApplyEdits(rawOperations, computeUndoEdits) {
    const oldLineCount = this._buffer.getLineCount();
    const result2 = this._buffer.applyEdits(rawOperations, this._options.trimAutoWhitespace, computeUndoEdits);
    const newLineCount = this._buffer.getLineCount();
    const contentChanges = result2.changes;
    this._trimAutoWhitespaceLines = result2.trimAutoWhitespaceLineNumbers;
    if (contentChanges.length !== 0) {
      for (let i = 0, len = contentChanges.length; i < len; i++) {
        const change = contentChanges[i];
        this._decorationsTree.acceptReplace(change.rangeOffset, change.rangeLength, change.text.length, change.forceMoveMarkers);
      }
      const rawContentChanges = [];
      this._increaseVersionId();
      let lineCount = oldLineCount;
      for (let i = 0, len = contentChanges.length; i < len; i++) {
        const change = contentChanges[i];
        const [eolCount] = countEOL(change.text);
        this._onDidChangeDecorations.fire();
        const startLineNumber = change.range.startLineNumber;
        const endLineNumber = change.range.endLineNumber;
        const deletingLinesCnt = endLineNumber - startLineNumber;
        const insertingLinesCnt = eolCount;
        const editingLinesCnt = Math.min(deletingLinesCnt, insertingLinesCnt);
        const changeLineCountDelta = insertingLinesCnt - deletingLinesCnt;
        const currentEditStartLineNumber = newLineCount - lineCount - changeLineCountDelta + startLineNumber;
        const firstEditLineNumber = currentEditStartLineNumber;
        const lastInsertedLineNumber = currentEditStartLineNumber + insertingLinesCnt;
        const decorationsWithInjectedTextInEditedRange = this._decorationsTree.getInjectedTextInInterval(this, this.getOffsetAt(new Position$2(firstEditLineNumber, 1)), this.getOffsetAt(new Position$2(lastInsertedLineNumber, this.getLineMaxColumn(lastInsertedLineNumber))), 0);
        const injectedTextInEditedRange = LineInjectedText.fromDecorations(decorationsWithInjectedTextInEditedRange);
        const injectedTextInEditedRangeQueue = new ArrayQueue(injectedTextInEditedRange);
        for (let j = editingLinesCnt; j >= 0; j--) {
          const editLineNumber = startLineNumber + j;
          const currentEditLineNumber = currentEditStartLineNumber + j;
          injectedTextInEditedRangeQueue.takeFromEndWhile((r) => r.lineNumber > currentEditLineNumber);
          const decorationsInCurrentLine = injectedTextInEditedRangeQueue.takeFromEndWhile((r) => r.lineNumber === currentEditLineNumber);
          rawContentChanges.push(new ModelRawLineChanged(editLineNumber, this.getLineContent(currentEditLineNumber), decorationsInCurrentLine));
        }
        if (editingLinesCnt < deletingLinesCnt) {
          const spliceStartLineNumber = startLineNumber + editingLinesCnt;
          rawContentChanges.push(new ModelRawLinesDeleted(spliceStartLineNumber + 1, endLineNumber));
        }
        if (editingLinesCnt < insertingLinesCnt) {
          const injectedTextInEditedRangeQueue2 = new ArrayQueue(injectedTextInEditedRange);
          const spliceLineNumber = startLineNumber + editingLinesCnt;
          const cnt = insertingLinesCnt - editingLinesCnt;
          const fromLineNumber = newLineCount - lineCount - cnt + spliceLineNumber + 1;
          const injectedTexts = [];
          const newLines = [];
          for (let i2 = 0; i2 < cnt; i2++) {
            const lineNumber = fromLineNumber + i2;
            newLines[i2] = this.getLineContent(lineNumber);
            injectedTextInEditedRangeQueue2.takeWhile((r) => r.lineNumber < lineNumber);
            injectedTexts[i2] = injectedTextInEditedRangeQueue2.takeWhile((r) => r.lineNumber === lineNumber);
          }
          rawContentChanges.push(new ModelRawLinesInserted(spliceLineNumber + 1, startLineNumber + insertingLinesCnt, newLines, injectedTexts));
        }
        lineCount += changeLineCountDelta;
      }
      this._emitContentChangedEvent(new ModelRawContentChangedEvent(rawContentChanges, this.getVersionId(), this._isUndoing, this._isRedoing), {
        changes: contentChanges,
        eol: this._buffer.getEOL(),
        isEolChange: false,
        versionId: this.getVersionId(),
        isUndoing: this._isUndoing,
        isRedoing: this._isRedoing,
        isFlush: false
      });
    }
    return result2.reverseEdits === null ? void 0 : result2.reverseEdits;
  }
  undo() {
    return this._undoRedoService.undo(this.uri);
  }
  canUndo() {
    return this._undoRedoService.canUndo(this.uri);
  }
  redo() {
    return this._undoRedoService.redo(this.uri);
  }
  canRedo() {
    return this._undoRedoService.canRedo(this.uri);
  }
  //#endregion
  //#region Decorations
  handleBeforeFireDecorationsChangedEvent(affectedInjectedTextLines) {
    if (affectedInjectedTextLines === null || affectedInjectedTextLines.size === 0) {
      return;
    }
    const affectedLines = Array.from(affectedInjectedTextLines);
    const lineChangeEvents = affectedLines.map((lineNumber) => new ModelRawLineChanged(lineNumber, this.getLineContent(lineNumber), this._getInjectedTextInLine(lineNumber)));
    this._onDidChangeInjectedText.fire(new ModelInjectedTextChangedEvent(lineChangeEvents));
  }
  changeDecorations(callback, ownerId = 0) {
    this._assertNotDisposed();
    try {
      this._onDidChangeDecorations.beginDeferredEmit();
      return this._changeDecorations(ownerId, callback);
    } finally {
      this._onDidChangeDecorations.endDeferredEmit();
    }
  }
  _changeDecorations(ownerId, callback) {
    const changeAccessor = {
      addDecoration: (range2, options) => {
        return this._deltaDecorationsImpl(ownerId, [], [{ range: range2, options }])[0];
      },
      changeDecoration: (id3, newRange) => {
        this._changeDecorationImpl(id3, newRange);
      },
      changeDecorationOptions: (id3, options) => {
        this._changeDecorationOptionsImpl(id3, _normalizeOptions(options));
      },
      removeDecoration: (id3) => {
        this._deltaDecorationsImpl(ownerId, [id3], []);
      },
      deltaDecorations: (oldDecorations, newDecorations) => {
        if (oldDecorations.length === 0 && newDecorations.length === 0) {
          return [];
        }
        return this._deltaDecorationsImpl(ownerId, oldDecorations, newDecorations);
      }
    };
    let result2 = null;
    try {
      result2 = callback(changeAccessor);
    } catch (e) {
      onUnexpectedError(e);
    }
    changeAccessor.addDecoration = invalidFunc;
    changeAccessor.changeDecoration = invalidFunc;
    changeAccessor.changeDecorationOptions = invalidFunc;
    changeAccessor.removeDecoration = invalidFunc;
    changeAccessor.deltaDecorations = invalidFunc;
    return result2;
  }
  deltaDecorations(oldDecorations, newDecorations, ownerId = 0) {
    this._assertNotDisposed();
    if (!oldDecorations) {
      oldDecorations = [];
    }
    if (oldDecorations.length === 0 && newDecorations.length === 0) {
      return [];
    }
    try {
      this._deltaDecorationCallCnt++;
      if (this._deltaDecorationCallCnt > 1) {
        console.warn(`Invoking deltaDecorations recursively could lead to leaking decorations.`);
        onUnexpectedError(new Error(`Invoking deltaDecorations recursively could lead to leaking decorations.`));
      }
      this._onDidChangeDecorations.beginDeferredEmit();
      return this._deltaDecorationsImpl(ownerId, oldDecorations, newDecorations);
    } finally {
      this._onDidChangeDecorations.endDeferredEmit();
      this._deltaDecorationCallCnt--;
    }
  }
  _getTrackedRange(id3) {
    return this.getDecorationRange(id3);
  }
  _setTrackedRange(id3, newRange, newStickiness) {
    const node2 = id3 ? this._decorations[id3] : null;
    if (!node2) {
      if (!newRange) {
        return null;
      }
      return this._deltaDecorationsImpl(0, [], [{ range: newRange, options: TRACKED_RANGE_OPTIONS[newStickiness] }], true)[0];
    }
    if (!newRange) {
      this._decorationsTree.delete(node2);
      delete this._decorations[node2.id];
      return null;
    }
    const range2 = this._validateRangeRelaxedNoAllocations(newRange);
    const startOffset = this._buffer.getOffsetAt(range2.startLineNumber, range2.startColumn);
    const endOffset = this._buffer.getOffsetAt(range2.endLineNumber, range2.endColumn);
    this._decorationsTree.delete(node2);
    node2.reset(this.getVersionId(), startOffset, endOffset, range2);
    node2.setOptions(TRACKED_RANGE_OPTIONS[newStickiness]);
    this._decorationsTree.insert(node2);
    return node2.id;
  }
  removeAllDecorationsWithOwnerId(ownerId) {
    if (this._isDisposed) {
      return;
    }
    const nodes = this._decorationsTree.collectNodesFromOwner(ownerId);
    for (let i = 0, len = nodes.length; i < len; i++) {
      const node2 = nodes[i];
      this._decorationsTree.delete(node2);
      delete this._decorations[node2.id];
    }
  }
  getDecorationOptions(decorationId) {
    const node2 = this._decorations[decorationId];
    if (!node2) {
      return null;
    }
    return node2.options;
  }
  getDecorationRange(decorationId) {
    const node2 = this._decorations[decorationId];
    if (!node2) {
      return null;
    }
    return this._decorationsTree.getNodeRange(this, node2);
  }
  getLineDecorations(lineNumber, ownerId = 0, filterOutValidation = false) {
    if (lineNumber < 1 || lineNumber > this.getLineCount()) {
      return [];
    }
    return this.getLinesDecorations(lineNumber, lineNumber, ownerId, filterOutValidation);
  }
  getLinesDecorations(_startLineNumber, _endLineNumber, ownerId = 0, filterOutValidation = false, onlyMarginDecorations = false) {
    const lineCount = this.getLineCount();
    const startLineNumber = Math.min(lineCount, Math.max(1, _startLineNumber));
    const endLineNumber = Math.min(lineCount, Math.max(1, _endLineNumber));
    const endColumn = this.getLineMaxColumn(endLineNumber);
    const range2 = new Range$2(startLineNumber, 1, endLineNumber, endColumn);
    const decorations2 = this._getDecorationsInRange(range2, ownerId, filterOutValidation, onlyMarginDecorations);
    pushMany(decorations2, this._decorationProvider.getDecorationsInRange(range2, ownerId, filterOutValidation));
    return decorations2;
  }
  getDecorationsInRange(range2, ownerId = 0, filterOutValidation = false, onlyMinimapDecorations = false, onlyMarginDecorations = false) {
    const validatedRange = this.validateRange(range2);
    const decorations2 = this._getDecorationsInRange(validatedRange, ownerId, filterOutValidation, onlyMarginDecorations);
    pushMany(decorations2, this._decorationProvider.getDecorationsInRange(validatedRange, ownerId, filterOutValidation, onlyMinimapDecorations));
    return decorations2;
  }
  getOverviewRulerDecorations(ownerId = 0, filterOutValidation = false) {
    return this._decorationsTree.getAll(this, ownerId, filterOutValidation, true, false);
  }
  getInjectedTextDecorations(ownerId = 0) {
    return this._decorationsTree.getAllInjectedText(this, ownerId);
  }
  _getInjectedTextInLine(lineNumber) {
    const startOffset = this._buffer.getOffsetAt(lineNumber, 1);
    const endOffset = startOffset + this._buffer.getLineLength(lineNumber);
    const result2 = this._decorationsTree.getInjectedTextInInterval(this, startOffset, endOffset, 0);
    return LineInjectedText.fromDecorations(result2).filter((t) => t.lineNumber === lineNumber);
  }
  getAllDecorations(ownerId = 0, filterOutValidation = false) {
    let result2 = this._decorationsTree.getAll(this, ownerId, filterOutValidation, false, false);
    result2 = result2.concat(this._decorationProvider.getAllDecorations(ownerId, filterOutValidation));
    return result2;
  }
  getAllMarginDecorations(ownerId = 0) {
    return this._decorationsTree.getAll(this, ownerId, false, false, true);
  }
  _getDecorationsInRange(filterRange, filterOwnerId, filterOutValidation, onlyMarginDecorations) {
    const startOffset = this._buffer.getOffsetAt(filterRange.startLineNumber, filterRange.startColumn);
    const endOffset = this._buffer.getOffsetAt(filterRange.endLineNumber, filterRange.endColumn);
    return this._decorationsTree.getAllInInterval(this, startOffset, endOffset, filterOwnerId, filterOutValidation, onlyMarginDecorations);
  }
  getRangeAt(start, end) {
    return this._buffer.getRangeAt(start, end - start);
  }
  _changeDecorationImpl(decorationId, _range) {
    const node2 = this._decorations[decorationId];
    if (!node2) {
      return;
    }
    if (node2.options.after) {
      const oldRange = this.getDecorationRange(decorationId);
      this._onDidChangeDecorations.recordLineAffectedByInjectedText(oldRange.endLineNumber);
    }
    if (node2.options.before) {
      const oldRange = this.getDecorationRange(decorationId);
      this._onDidChangeDecorations.recordLineAffectedByInjectedText(oldRange.startLineNumber);
    }
    const range2 = this._validateRangeRelaxedNoAllocations(_range);
    const startOffset = this._buffer.getOffsetAt(range2.startLineNumber, range2.startColumn);
    const endOffset = this._buffer.getOffsetAt(range2.endLineNumber, range2.endColumn);
    this._decorationsTree.delete(node2);
    node2.reset(this.getVersionId(), startOffset, endOffset, range2);
    this._decorationsTree.insert(node2);
    this._onDidChangeDecorations.checkAffectedAndFire(node2.options);
    if (node2.options.after) {
      this._onDidChangeDecorations.recordLineAffectedByInjectedText(range2.endLineNumber);
    }
    if (node2.options.before) {
      this._onDidChangeDecorations.recordLineAffectedByInjectedText(range2.startLineNumber);
    }
  }
  _changeDecorationOptionsImpl(decorationId, options) {
    const node2 = this._decorations[decorationId];
    if (!node2) {
      return;
    }
    const nodeWasInOverviewRuler = node2.options.overviewRuler && node2.options.overviewRuler.color ? true : false;
    const nodeIsInOverviewRuler = options.overviewRuler && options.overviewRuler.color ? true : false;
    this._onDidChangeDecorations.checkAffectedAndFire(node2.options);
    this._onDidChangeDecorations.checkAffectedAndFire(options);
    if (node2.options.after || options.after) {
      const nodeRange = this._decorationsTree.getNodeRange(this, node2);
      this._onDidChangeDecorations.recordLineAffectedByInjectedText(nodeRange.endLineNumber);
    }
    if (node2.options.before || options.before) {
      const nodeRange = this._decorationsTree.getNodeRange(this, node2);
      this._onDidChangeDecorations.recordLineAffectedByInjectedText(nodeRange.startLineNumber);
    }
    if (nodeWasInOverviewRuler !== nodeIsInOverviewRuler) {
      this._decorationsTree.delete(node2);
      node2.setOptions(options);
      this._decorationsTree.insert(node2);
    } else {
      node2.setOptions(options);
    }
  }
  _deltaDecorationsImpl(ownerId, oldDecorationsIds, newDecorations, suppressEvents = false) {
    const versionId = this.getVersionId();
    const oldDecorationsLen = oldDecorationsIds.length;
    let oldDecorationIndex = 0;
    const newDecorationsLen = newDecorations.length;
    let newDecorationIndex = 0;
    this._onDidChangeDecorations.beginDeferredEmit();
    try {
      const result2 = new Array(newDecorationsLen);
      while (oldDecorationIndex < oldDecorationsLen || newDecorationIndex < newDecorationsLen) {
        let node2 = null;
        if (oldDecorationIndex < oldDecorationsLen) {
          do {
            node2 = this._decorations[oldDecorationsIds[oldDecorationIndex++]];
          } while (!node2 && oldDecorationIndex < oldDecorationsLen);
          if (node2) {
            if (node2.options.after) {
              const nodeRange = this._decorationsTree.getNodeRange(this, node2);
              this._onDidChangeDecorations.recordLineAffectedByInjectedText(nodeRange.endLineNumber);
            }
            if (node2.options.before) {
              const nodeRange = this._decorationsTree.getNodeRange(this, node2);
              this._onDidChangeDecorations.recordLineAffectedByInjectedText(nodeRange.startLineNumber);
            }
            this._decorationsTree.delete(node2);
            if (!suppressEvents) {
              this._onDidChangeDecorations.checkAffectedAndFire(node2.options);
            }
          }
        }
        if (newDecorationIndex < newDecorationsLen) {
          if (!node2) {
            const internalDecorationId = ++this._lastDecorationId;
            const decorationId = `${this._instanceId};${internalDecorationId}`;
            node2 = new IntervalNode(decorationId, 0, 0);
            this._decorations[decorationId] = node2;
          }
          const newDecoration = newDecorations[newDecorationIndex];
          const range2 = this._validateRangeRelaxedNoAllocations(newDecoration.range);
          const options = _normalizeOptions(newDecoration.options);
          const startOffset = this._buffer.getOffsetAt(range2.startLineNumber, range2.startColumn);
          const endOffset = this._buffer.getOffsetAt(range2.endLineNumber, range2.endColumn);
          node2.ownerId = ownerId;
          node2.reset(versionId, startOffset, endOffset, range2);
          node2.setOptions(options);
          if (node2.options.after) {
            this._onDidChangeDecorations.recordLineAffectedByInjectedText(range2.endLineNumber);
          }
          if (node2.options.before) {
            this._onDidChangeDecorations.recordLineAffectedByInjectedText(range2.startLineNumber);
          }
          if (!suppressEvents) {
            this._onDidChangeDecorations.checkAffectedAndFire(options);
          }
          this._decorationsTree.insert(node2);
          result2[newDecorationIndex] = node2.id;
          newDecorationIndex++;
        } else {
          if (node2) {
            delete this._decorations[node2.id];
          }
        }
      }
      return result2;
    } finally {
      this._onDidChangeDecorations.endDeferredEmit();
    }
  }
  //#endregion
  //#region Tokenization
  // TODO move them to the tokenization part.
  getLanguageId() {
    return this.tokenization.getLanguageId();
  }
  setLanguage(languageIdOrSelection, source) {
    if (typeof languageIdOrSelection === "string") {
      this._languageSelectionListener.clear();
      this._setLanguage(languageIdOrSelection, source);
    } else {
      this._languageSelectionListener.value = languageIdOrSelection.onDidChange(() => this._setLanguage(languageIdOrSelection.languageId, source));
      this._setLanguage(languageIdOrSelection.languageId, source);
    }
  }
  _setLanguage(languageId, source) {
    this.tokenization.setLanguageId(languageId, source);
    this._languageService.requestRichLanguageFeatures(languageId);
  }
  getLanguageIdAtPosition(lineNumber, column) {
    return this.tokenization.getLanguageIdAtPosition(lineNumber, column);
  }
  getWordAtPosition(position) {
    return this._tokenizationTextModelPart.getWordAtPosition(position);
  }
  getWordUntilPosition(position) {
    return this._tokenizationTextModelPart.getWordUntilPosition(position);
  }
  //#endregion
  normalizePosition(position, affinity) {
    return position;
  }
  /**
   * Gets the column at which indentation stops at a given line.
   * @internal
  */
  getLineIndentColumn(lineNumber) {
    return indentOfLine(this.getLineContent(lineNumber)) + 1;
  }
};
TextModel._MODEL_SYNC_LIMIT = 50 * 1024 * 1024;
TextModel.LARGE_FILE_SIZE_THRESHOLD = 20 * 1024 * 1024;
TextModel.LARGE_FILE_LINE_COUNT_THRESHOLD = 300 * 1e3;
TextModel.DEFAULT_CREATION_OPTIONS = {
  isForSimpleWidget: false,
  tabSize: EDITOR_MODEL_DEFAULTS.tabSize,
  indentSize: EDITOR_MODEL_DEFAULTS.indentSize,
  insertSpaces: EDITOR_MODEL_DEFAULTS.insertSpaces,
  detectIndentation: false,
  defaultEOL: 1,
  trimAutoWhitespace: EDITOR_MODEL_DEFAULTS.trimAutoWhitespace,
  largeFileOptimizations: EDITOR_MODEL_DEFAULTS.largeFileOptimizations,
  bracketPairColorizationOptions: EDITOR_MODEL_DEFAULTS.bracketPairColorizationOptions
};
TextModel = __decorate$23([
  __param$1Z(4, IUndoRedoService),
  __param$1Z(5, ILanguageService),
  __param$1Z(6, ILanguageConfigurationService)
], TextModel);
function indentOfLine(line) {
  let indent = 0;
  for (const c of line) {
    if (c === " " || c === "	") {
      indent++;
    } else {
      break;
    }
  }
  return indent;
}
function isNodeInOverviewRuler(node2) {
  return node2.options.overviewRuler && node2.options.overviewRuler.color ? true : false;
}
function isNodeInjectedText(node2) {
  return !!node2.options.after || !!node2.options.before;
}
class DecorationsTrees {
  constructor() {
    this._decorationsTree0 = new IntervalTree();
    this._decorationsTree1 = new IntervalTree();
    this._injectedTextDecorationsTree = new IntervalTree();
  }
  ensureAllNodesHaveRanges(host) {
    this.getAll(host, 0, false, false, false);
  }
  _ensureNodesHaveRanges(host, nodes) {
    for (const node2 of nodes) {
      if (node2.range === null) {
        node2.range = host.getRangeAt(node2.cachedAbsoluteStart, node2.cachedAbsoluteEnd);
      }
    }
    return nodes;
  }
  getAllInInterval(host, start, end, filterOwnerId, filterOutValidation, onlyMarginDecorations) {
    const versionId = host.getVersionId();
    const result2 = this._intervalSearch(start, end, filterOwnerId, filterOutValidation, versionId, onlyMarginDecorations);
    return this._ensureNodesHaveRanges(host, result2);
  }
  _intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations) {
    const r0 = this._decorationsTree0.intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
    const r1 = this._decorationsTree1.intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
    const r2 = this._injectedTextDecorationsTree.intervalSearch(start, end, filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
    return r0.concat(r1).concat(r2);
  }
  getInjectedTextInInterval(host, start, end, filterOwnerId) {
    const versionId = host.getVersionId();
    const result2 = this._injectedTextDecorationsTree.intervalSearch(start, end, filterOwnerId, false, versionId, false);
    return this._ensureNodesHaveRanges(host, result2).filter((i) => i.options.showIfCollapsed || !i.range.isEmpty());
  }
  getAllInjectedText(host, filterOwnerId) {
    const versionId = host.getVersionId();
    const result2 = this._injectedTextDecorationsTree.search(filterOwnerId, false, versionId, false);
    return this._ensureNodesHaveRanges(host, result2).filter((i) => i.options.showIfCollapsed || !i.range.isEmpty());
  }
  getAll(host, filterOwnerId, filterOutValidation, overviewRulerOnly, onlyMarginDecorations) {
    const versionId = host.getVersionId();
    const result2 = this._search(filterOwnerId, filterOutValidation, overviewRulerOnly, versionId, onlyMarginDecorations);
    return this._ensureNodesHaveRanges(host, result2);
  }
  _search(filterOwnerId, filterOutValidation, overviewRulerOnly, cachedVersionId, onlyMarginDecorations) {
    if (overviewRulerOnly) {
      return this._decorationsTree1.search(filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
    } else {
      const r0 = this._decorationsTree0.search(filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
      const r1 = this._decorationsTree1.search(filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
      const r2 = this._injectedTextDecorationsTree.search(filterOwnerId, filterOutValidation, cachedVersionId, onlyMarginDecorations);
      return r0.concat(r1).concat(r2);
    }
  }
  collectNodesFromOwner(ownerId) {
    const r0 = this._decorationsTree0.collectNodesFromOwner(ownerId);
    const r1 = this._decorationsTree1.collectNodesFromOwner(ownerId);
    const r2 = this._injectedTextDecorationsTree.collectNodesFromOwner(ownerId);
    return r0.concat(r1).concat(r2);
  }
  collectNodesPostOrder() {
    const r0 = this._decorationsTree0.collectNodesPostOrder();
    const r1 = this._decorationsTree1.collectNodesPostOrder();
    const r2 = this._injectedTextDecorationsTree.collectNodesPostOrder();
    return r0.concat(r1).concat(r2);
  }
  insert(node2) {
    if (isNodeInjectedText(node2)) {
      this._injectedTextDecorationsTree.insert(node2);
    } else if (isNodeInOverviewRuler(node2)) {
      this._decorationsTree1.insert(node2);
    } else {
      this._decorationsTree0.insert(node2);
    }
  }
  delete(node2) {
    if (isNodeInjectedText(node2)) {
      this._injectedTextDecorationsTree.delete(node2);
    } else if (isNodeInOverviewRuler(node2)) {
      this._decorationsTree1.delete(node2);
    } else {
      this._decorationsTree0.delete(node2);
    }
  }
  getNodeRange(host, node2) {
    const versionId = host.getVersionId();
    if (node2.cachedVersionId !== versionId) {
      this._resolveNode(node2, versionId);
    }
    if (node2.range === null) {
      node2.range = host.getRangeAt(node2.cachedAbsoluteStart, node2.cachedAbsoluteEnd);
    }
    return node2.range;
  }
  _resolveNode(node2, cachedVersionId) {
    if (isNodeInjectedText(node2)) {
      this._injectedTextDecorationsTree.resolveNode(node2, cachedVersionId);
    } else if (isNodeInOverviewRuler(node2)) {
      this._decorationsTree1.resolveNode(node2, cachedVersionId);
    } else {
      this._decorationsTree0.resolveNode(node2, cachedVersionId);
    }
  }
  acceptReplace(offset, length2, textLength, forceMoveMarkers) {
    this._decorationsTree0.acceptReplace(offset, length2, textLength, forceMoveMarkers);
    this._decorationsTree1.acceptReplace(offset, length2, textLength, forceMoveMarkers);
    this._injectedTextDecorationsTree.acceptReplace(offset, length2, textLength, forceMoveMarkers);
  }
}
function cleanClassName(className3) {
  return className3.replace(/[^a-z0-9\-_]/gi, " ");
}
class DecorationOptions {
  constructor(options) {
    this.color = options.color || "";
    this.darkColor = options.darkColor || "";
  }
}
class ModelDecorationOverviewRulerOptions extends DecorationOptions {
  constructor(options) {
    super(options);
    this._resolvedColor = null;
    this.position = typeof options.position === "number" ? options.position : OverviewRulerLane$1.Center;
  }
  getColor(theme) {
    if (!this._resolvedColor) {
      if (theme.type !== "light" && this.darkColor) {
        this._resolvedColor = this._resolveColor(this.darkColor, theme);
      } else {
        this._resolvedColor = this._resolveColor(this.color, theme);
      }
    }
    return this._resolvedColor;
  }
  invalidateCachedColor() {
    this._resolvedColor = null;
  }
  _resolveColor(color, theme) {
    if (typeof color === "string") {
      return color;
    }
    const c = color ? theme.getColor(color.id) : null;
    if (!c) {
      return "";
    }
    return c.toString();
  }
}
class ModelDecorationGlyphMarginOptions {
  constructor(options) {
    var _a2;
    this.position = (_a2 = options === null || options === void 0 ? void 0 : options.position) !== null && _a2 !== void 0 ? _a2 : GlyphMarginLane$1.Left;
  }
}
class ModelDecorationMinimapOptions extends DecorationOptions {
  constructor(options) {
    super(options);
    this.position = options.position;
  }
  getColor(theme) {
    if (!this._resolvedColor) {
      if (theme.type !== "light" && this.darkColor) {
        this._resolvedColor = this._resolveColor(this.darkColor, theme);
      } else {
        this._resolvedColor = this._resolveColor(this.color, theme);
      }
    }
    return this._resolvedColor;
  }
  invalidateCachedColor() {
    this._resolvedColor = void 0;
  }
  _resolveColor(color, theme) {
    if (typeof color === "string") {
      return Color.fromHex(color);
    }
    return theme.getColor(color.id);
  }
}
class ModelDecorationInjectedTextOptions {
  static from(options) {
    if (options instanceof ModelDecorationInjectedTextOptions) {
      return options;
    }
    return new ModelDecorationInjectedTextOptions(options);
  }
  constructor(options) {
    this.content = options.content || "";
    this.inlineClassName = options.inlineClassName || null;
    this.inlineClassNameAffectsLetterSpacing = options.inlineClassNameAffectsLetterSpacing || false;
    this.attachedData = options.attachedData || null;
    this.cursorStops = options.cursorStops || null;
  }
}
class ModelDecorationOptions {
  static register(options) {
    return new ModelDecorationOptions(options);
  }
  static createDynamic(options) {
    return new ModelDecorationOptions(options);
  }
  constructor(options) {
    var _a2, _b2, _c2, _d2, _e2, _f2;
    this.description = options.description;
    this.blockClassName = options.blockClassName ? cleanClassName(options.blockClassName) : null;
    this.blockDoesNotCollapse = (_a2 = options.blockDoesNotCollapse) !== null && _a2 !== void 0 ? _a2 : null;
    this.blockIsAfterEnd = (_b2 = options.blockIsAfterEnd) !== null && _b2 !== void 0 ? _b2 : null;
    this.blockPadding = (_c2 = options.blockPadding) !== null && _c2 !== void 0 ? _c2 : null;
    this.stickiness = options.stickiness || 0;
    this.zIndex = options.zIndex || 0;
    this.className = options.className ? cleanClassName(options.className) : null;
    this.shouldFillLineOnLineBreak = (_d2 = options.shouldFillLineOnLineBreak) !== null && _d2 !== void 0 ? _d2 : null;
    this.hoverMessage = options.hoverMessage || null;
    this.glyphMarginHoverMessage = options.glyphMarginHoverMessage || null;
    this.isWholeLine = options.isWholeLine || false;
    this.showIfCollapsed = options.showIfCollapsed || false;
    this.collapseOnReplaceEdit = options.collapseOnReplaceEdit || false;
    this.overviewRuler = options.overviewRuler ? new ModelDecorationOverviewRulerOptions(options.overviewRuler) : null;
    this.minimap = options.minimap ? new ModelDecorationMinimapOptions(options.minimap) : null;
    this.glyphMargin = options.glyphMarginClassName ? new ModelDecorationGlyphMarginOptions(options.glyphMargin) : null;
    this.glyphMarginClassName = options.glyphMarginClassName ? cleanClassName(options.glyphMarginClassName) : null;
    this.linesDecorationsClassName = options.linesDecorationsClassName ? cleanClassName(options.linesDecorationsClassName) : null;
    this.firstLineDecorationClassName = options.firstLineDecorationClassName ? cleanClassName(options.firstLineDecorationClassName) : null;
    this.marginClassName = options.marginClassName ? cleanClassName(options.marginClassName) : null;
    this.inlineClassName = options.inlineClassName ? cleanClassName(options.inlineClassName) : null;
    this.inlineClassNameAffectsLetterSpacing = options.inlineClassNameAffectsLetterSpacing || false;
    this.beforeContentClassName = options.beforeContentClassName ? cleanClassName(options.beforeContentClassName) : null;
    this.afterContentClassName = options.afterContentClassName ? cleanClassName(options.afterContentClassName) : null;
    this.after = options.after ? ModelDecorationInjectedTextOptions.from(options.after) : null;
    this.before = options.before ? ModelDecorationInjectedTextOptions.from(options.before) : null;
    this.hideInCommentTokens = (_e2 = options.hideInCommentTokens) !== null && _e2 !== void 0 ? _e2 : false;
    this.hideInStringTokens = (_f2 = options.hideInStringTokens) !== null && _f2 !== void 0 ? _f2 : false;
  }
}
ModelDecorationOptions.EMPTY = ModelDecorationOptions.register({ description: "empty" });
const TRACKED_RANGE_OPTIONS = [
  ModelDecorationOptions.register({
    description: "tracked-range-always-grows-when-typing-at-edges",
    stickiness: 0
    /* model.TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */
  }),
  ModelDecorationOptions.register({
    description: "tracked-range-never-grows-when-typing-at-edges",
    stickiness: 1
    /* model.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
  }),
  ModelDecorationOptions.register({
    description: "tracked-range-grows-only-when-typing-before",
    stickiness: 2
    /* model.TrackedRangeStickiness.GrowsOnlyWhenTypingBefore */
  }),
  ModelDecorationOptions.register({
    description: "tracked-range-grows-only-when-typing-after",
    stickiness: 3
    /* model.TrackedRangeStickiness.GrowsOnlyWhenTypingAfter */
  })
];
function _normalizeOptions(options) {
  if (options instanceof ModelDecorationOptions) {
    return options;
  }
  return ModelDecorationOptions.createDynamic(options);
}
class DidChangeDecorationsEmitter extends Disposable {
  constructor(handleBeforeFire) {
    super();
    this.handleBeforeFire = handleBeforeFire;
    this._actual = this._register(new Emitter$1());
    this.event = this._actual.event;
    this._affectedInjectedTextLines = null;
    this._deferredCnt = 0;
    this._shouldFireDeferred = false;
    this._affectsMinimap = false;
    this._affectsOverviewRuler = false;
    this._affectsGlyphMargin = false;
  }
  beginDeferredEmit() {
    this._deferredCnt++;
  }
  endDeferredEmit() {
    var _a2;
    this._deferredCnt--;
    if (this._deferredCnt === 0) {
      if (this._shouldFireDeferred) {
        this.doFire();
      }
      (_a2 = this._affectedInjectedTextLines) === null || _a2 === void 0 ? void 0 : _a2.clear();
      this._affectedInjectedTextLines = null;
    }
  }
  recordLineAffectedByInjectedText(lineNumber) {
    if (!this._affectedInjectedTextLines) {
      this._affectedInjectedTextLines = /* @__PURE__ */ new Set();
    }
    this._affectedInjectedTextLines.add(lineNumber);
  }
  checkAffectedAndFire(options) {
    if (!this._affectsMinimap) {
      this._affectsMinimap = options.minimap && options.minimap.position ? true : false;
    }
    if (!this._affectsOverviewRuler) {
      this._affectsOverviewRuler = options.overviewRuler && options.overviewRuler.color ? true : false;
    }
    if (!this._affectsGlyphMargin) {
      this._affectsGlyphMargin = options.glyphMarginClassName ? true : false;
    }
    this.tryFire();
  }
  fire() {
    this._affectsMinimap = true;
    this._affectsOverviewRuler = true;
    this._affectsGlyphMargin = true;
    this.tryFire();
  }
  tryFire() {
    if (this._deferredCnt === 0) {
      this.doFire();
    } else {
      this._shouldFireDeferred = true;
    }
  }
  doFire() {
    this.handleBeforeFire(this._affectedInjectedTextLines);
    const event = {
      affectsMinimap: this._affectsMinimap,
      affectsOverviewRuler: this._affectsOverviewRuler,
      affectsGlyphMargin: this._affectsGlyphMargin
    };
    this._shouldFireDeferred = false;
    this._affectsMinimap = false;
    this._affectsOverviewRuler = false;
    this._affectsGlyphMargin = false;
    this._actual.fire(event);
  }
}
class DidChangeContentEmitter extends Disposable {
  constructor() {
    super();
    this._fastEmitter = this._register(new Emitter$1());
    this.fastEvent = this._fastEmitter.event;
    this._slowEmitter = this._register(new Emitter$1());
    this.slowEvent = this._slowEmitter.event;
    this._deferredCnt = 0;
    this._deferredEvent = null;
  }
  beginDeferredEmit() {
    this._deferredCnt++;
  }
  endDeferredEmit(resultingSelection = null) {
    this._deferredCnt--;
    if (this._deferredCnt === 0) {
      if (this._deferredEvent !== null) {
        this._deferredEvent.rawContentChangedEvent.resultingSelection = resultingSelection;
        const e = this._deferredEvent;
        this._deferredEvent = null;
        this._fastEmitter.fire(e);
        this._slowEmitter.fire(e);
      }
    }
  }
  fire(e) {
    if (this._deferredCnt > 0) {
      if (this._deferredEvent) {
        this._deferredEvent = this._deferredEvent.merge(e);
      } else {
        this._deferredEvent = e;
      }
      return;
    }
    this._fastEmitter.fire(e);
    this._slowEmitter.fire(e);
  }
}
class AttachedViews {
  constructor() {
    this._onDidChangeVisibleRanges = new Emitter$1();
    this.onDidChangeVisibleRanges = this._onDidChangeVisibleRanges.event;
    this._views = /* @__PURE__ */ new Set();
  }
  attachView() {
    const view = new AttachedViewImpl((state) => {
      this._onDidChangeVisibleRanges.fire({ view, state });
    });
    this._views.add(view);
    return view;
  }
  detachView(view) {
    this._views.delete(view);
    this._onDidChangeVisibleRanges.fire({ view, state: void 0 });
  }
}
class AttachedViewImpl {
  constructor(handleStateChange) {
    this.handleStateChange = handleStateChange;
  }
  setVisibleLines(visibleLines, stabilized) {
    const visibleLineRanges = visibleLines.map((line) => new LineRange2(line.startLineNumber, line.endLineNumber + 1));
    this.handleStateChange({ visibleLineRanges, stabilized });
  }
}
class Cursor {
  constructor(context) {
    this._selTrackedRange = null;
    this._trackSelection = true;
    this._setState(context, new SingleCursorState(new Range$2(1, 1, 1, 1), 0, 0, new Position$2(1, 1), 0), new SingleCursorState(new Range$2(1, 1, 1, 1), 0, 0, new Position$2(1, 1), 0));
  }
  dispose(context) {
    this._removeTrackedRange(context);
  }
  startTrackingSelection(context) {
    this._trackSelection = true;
    this._updateTrackedRange(context);
  }
  stopTrackingSelection(context) {
    this._trackSelection = false;
    this._removeTrackedRange(context);
  }
  _updateTrackedRange(context) {
    if (!this._trackSelection) {
      return;
    }
    this._selTrackedRange = context.model._setTrackedRange(
      this._selTrackedRange,
      this.modelState.selection,
      0
      /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */
    );
  }
  _removeTrackedRange(context) {
    this._selTrackedRange = context.model._setTrackedRange(
      this._selTrackedRange,
      null,
      0
      /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */
    );
  }
  asCursorState() {
    return new CursorState$1(this.modelState, this.viewState);
  }
  readSelectionFromMarkers(context) {
    const range2 = context.model._getTrackedRange(this._selTrackedRange);
    if (this.modelState.selection.isEmpty() && !range2.isEmpty()) {
      return Selection$1.fromRange(range2.collapseToEnd(), this.modelState.selection.getDirection());
    }
    return Selection$1.fromRange(range2, this.modelState.selection.getDirection());
  }
  ensureValidState(context) {
    this._setState(context, this.modelState, this.viewState);
  }
  setState(context, modelState, viewState) {
    this._setState(context, modelState, viewState);
  }
  static _validatePositionWithCache(viewModel, position, cacheInput, cacheOutput) {
    if (position.equals(cacheInput)) {
      return cacheOutput;
    }
    return viewModel.normalizePosition(
      position,
      2
      /* PositionAffinity.None */
    );
  }
  static _validateViewState(viewModel, viewState) {
    const position = viewState.position;
    const sStartPosition = viewState.selectionStart.getStartPosition();
    const sEndPosition = viewState.selectionStart.getEndPosition();
    const validPosition = viewModel.normalizePosition(
      position,
      2
      /* PositionAffinity.None */
    );
    const validSStartPosition = this._validatePositionWithCache(viewModel, sStartPosition, position, validPosition);
    const validSEndPosition = this._validatePositionWithCache(viewModel, sEndPosition, sStartPosition, validSStartPosition);
    if (position.equals(validPosition) && sStartPosition.equals(validSStartPosition) && sEndPosition.equals(validSEndPosition)) {
      return viewState;
    }
    return new SingleCursorState(Range$2.fromPositions(validSStartPosition, validSEndPosition), viewState.selectionStartKind, viewState.selectionStartLeftoverVisibleColumns + sStartPosition.column - validSStartPosition.column, validPosition, viewState.leftoverVisibleColumns + position.column - validPosition.column);
  }
  _setState(context, modelState, viewState) {
    if (viewState) {
      viewState = Cursor._validateViewState(context.viewModel, viewState);
    }
    if (!modelState) {
      if (!viewState) {
        return;
      }
      const selectionStart = context.model.validateRange(context.coordinatesConverter.convertViewRangeToModelRange(viewState.selectionStart));
      const position = context.model.validatePosition(context.coordinatesConverter.convertViewPositionToModelPosition(viewState.position));
      modelState = new SingleCursorState(selectionStart, viewState.selectionStartKind, viewState.selectionStartLeftoverVisibleColumns, position, viewState.leftoverVisibleColumns);
    } else {
      const selectionStart = context.model.validateRange(modelState.selectionStart);
      const selectionStartLeftoverVisibleColumns = modelState.selectionStart.equalsRange(selectionStart) ? modelState.selectionStartLeftoverVisibleColumns : 0;
      const position = context.model.validatePosition(modelState.position);
      const leftoverVisibleColumns = modelState.position.equals(position) ? modelState.leftoverVisibleColumns : 0;
      modelState = new SingleCursorState(selectionStart, modelState.selectionStartKind, selectionStartLeftoverVisibleColumns, position, leftoverVisibleColumns);
    }
    if (!viewState) {
      const viewSelectionStart1 = context.coordinatesConverter.convertModelPositionToViewPosition(new Position$2(modelState.selectionStart.startLineNumber, modelState.selectionStart.startColumn));
      const viewSelectionStart2 = context.coordinatesConverter.convertModelPositionToViewPosition(new Position$2(modelState.selectionStart.endLineNumber, modelState.selectionStart.endColumn));
      const viewSelectionStart = new Range$2(viewSelectionStart1.lineNumber, viewSelectionStart1.column, viewSelectionStart2.lineNumber, viewSelectionStart2.column);
      const viewPosition = context.coordinatesConverter.convertModelPositionToViewPosition(modelState.position);
      viewState = new SingleCursorState(viewSelectionStart, modelState.selectionStartKind, modelState.selectionStartLeftoverVisibleColumns, viewPosition, modelState.leftoverVisibleColumns);
    } else {
      const viewSelectionStart = context.coordinatesConverter.validateViewRange(viewState.selectionStart, modelState.selectionStart);
      const viewPosition = context.coordinatesConverter.validateViewPosition(viewState.position, modelState.position);
      viewState = new SingleCursorState(viewSelectionStart, modelState.selectionStartKind, modelState.selectionStartLeftoverVisibleColumns, viewPosition, modelState.leftoverVisibleColumns);
    }
    this.modelState = modelState;
    this.viewState = viewState;
    this._updateTrackedRange(context);
  }
}
class CursorCollection {
  constructor(context) {
    this.context = context;
    this.cursors = [new Cursor(context)];
    this.lastAddedCursorIndex = 0;
  }
  dispose() {
    for (const cursor of this.cursors) {
      cursor.dispose(this.context);
    }
  }
  startTrackingSelections() {
    for (const cursor of this.cursors) {
      cursor.startTrackingSelection(this.context);
    }
  }
  stopTrackingSelections() {
    for (const cursor of this.cursors) {
      cursor.stopTrackingSelection(this.context);
    }
  }
  updateContext(context) {
    this.context = context;
  }
  ensureValidState() {
    for (const cursor of this.cursors) {
      cursor.ensureValidState(this.context);
    }
  }
  readSelectionFromMarkers() {
    return this.cursors.map((c) => c.readSelectionFromMarkers(this.context));
  }
  getAll() {
    return this.cursors.map((c) => c.asCursorState());
  }
  getViewPositions() {
    return this.cursors.map((c) => c.viewState.position);
  }
  getTopMostViewPosition() {
    return findMinBy(this.cursors, compareBy((c) => c.viewState.position, Position$2.compare)).viewState.position;
  }
  getBottomMostViewPosition() {
    return findLastMaxBy(this.cursors, compareBy((c) => c.viewState.position, Position$2.compare)).viewState.position;
  }
  getSelections() {
    return this.cursors.map((c) => c.modelState.selection);
  }
  getViewSelections() {
    return this.cursors.map((c) => c.viewState.selection);
  }
  setSelections(selections2) {
    this.setStates(CursorState$1.fromModelSelections(selections2));
  }
  getPrimaryCursor() {
    return this.cursors[0].asCursorState();
  }
  setStates(states) {
    if (states === null) {
      return;
    }
    this.cursors[0].setState(this.context, states[0].modelState, states[0].viewState);
    this._setSecondaryStates(states.slice(1));
  }
  /**
   * Creates or disposes secondary cursors as necessary to match the number of `secondarySelections`.
   */
  _setSecondaryStates(secondaryStates) {
    const secondaryCursorsLength = this.cursors.length - 1;
    const secondaryStatesLength = secondaryStates.length;
    if (secondaryCursorsLength < secondaryStatesLength) {
      const createCnt = secondaryStatesLength - secondaryCursorsLength;
      for (let i = 0; i < createCnt; i++) {
        this._addSecondaryCursor();
      }
    } else if (secondaryCursorsLength > secondaryStatesLength) {
      const removeCnt = secondaryCursorsLength - secondaryStatesLength;
      for (let i = 0; i < removeCnt; i++) {
        this._removeSecondaryCursor(this.cursors.length - 2);
      }
    }
    for (let i = 0; i < secondaryStatesLength; i++) {
      this.cursors[i + 1].setState(this.context, secondaryStates[i].modelState, secondaryStates[i].viewState);
    }
  }
  killSecondaryCursors() {
    this._setSecondaryStates([]);
  }
  _addSecondaryCursor() {
    this.cursors.push(new Cursor(this.context));
    this.lastAddedCursorIndex = this.cursors.length - 1;
  }
  getLastAddedCursorIndex() {
    if (this.cursors.length === 1 || this.lastAddedCursorIndex === 0) {
      return 0;
    }
    return this.lastAddedCursorIndex;
  }
  _removeSecondaryCursor(removeIndex) {
    if (this.lastAddedCursorIndex >= removeIndex + 1) {
      this.lastAddedCursorIndex--;
    }
    this.cursors[removeIndex + 1].dispose(this.context);
    this.cursors.splice(removeIndex + 1, 1);
  }
  normalize() {
    if (this.cursors.length === 1) {
      return;
    }
    const cursors = this.cursors.slice(0);
    const sortedCursors = [];
    for (let i = 0, len = cursors.length; i < len; i++) {
      sortedCursors.push({
        index: i,
        selection: cursors[i].modelState.selection
      });
    }
    sortedCursors.sort(compareBy((s) => s.selection, Range$2.compareRangesUsingStarts));
    for (let sortedCursorIndex = 0; sortedCursorIndex < sortedCursors.length - 1; sortedCursorIndex++) {
      const current = sortedCursors[sortedCursorIndex];
      const next = sortedCursors[sortedCursorIndex + 1];
      const currentSelection = current.selection;
      const nextSelection = next.selection;
      if (!this.context.cursorConfig.multiCursorMergeOverlapping) {
        continue;
      }
      let shouldMergeCursors;
      if (nextSelection.isEmpty() || currentSelection.isEmpty()) {
        shouldMergeCursors = nextSelection.getStartPosition().isBeforeOrEqual(currentSelection.getEndPosition());
      } else {
        shouldMergeCursors = nextSelection.getStartPosition().isBefore(currentSelection.getEndPosition());
      }
      if (shouldMergeCursors) {
        const winnerSortedCursorIndex = current.index < next.index ? sortedCursorIndex : sortedCursorIndex + 1;
        const looserSortedCursorIndex = current.index < next.index ? sortedCursorIndex + 1 : sortedCursorIndex;
        const looserIndex = sortedCursors[looserSortedCursorIndex].index;
        const winnerIndex = sortedCursors[winnerSortedCursorIndex].index;
        const looserSelection = sortedCursors[looserSortedCursorIndex].selection;
        const winnerSelection = sortedCursors[winnerSortedCursorIndex].selection;
        if (!looserSelection.equalsSelection(winnerSelection)) {
          const resultingRange = looserSelection.plusRange(winnerSelection);
          const looserSelectionIsLTR = looserSelection.selectionStartLineNumber === looserSelection.startLineNumber && looserSelection.selectionStartColumn === looserSelection.startColumn;
          const winnerSelectionIsLTR = winnerSelection.selectionStartLineNumber === winnerSelection.startLineNumber && winnerSelection.selectionStartColumn === winnerSelection.startColumn;
          let resultingSelectionIsLTR;
          if (looserIndex === this.lastAddedCursorIndex) {
            resultingSelectionIsLTR = looserSelectionIsLTR;
            this.lastAddedCursorIndex = winnerIndex;
          } else {
            resultingSelectionIsLTR = winnerSelectionIsLTR;
          }
          let resultingSelection;
          if (resultingSelectionIsLTR) {
            resultingSelection = new Selection$1(resultingRange.startLineNumber, resultingRange.startColumn, resultingRange.endLineNumber, resultingRange.endColumn);
          } else {
            resultingSelection = new Selection$1(resultingRange.endLineNumber, resultingRange.endColumn, resultingRange.startLineNumber, resultingRange.startColumn);
          }
          sortedCursors[winnerSortedCursorIndex].selection = resultingSelection;
          const resultingState = CursorState$1.fromModelSelection(resultingSelection);
          cursors[winnerIndex].setState(this.context, resultingState.modelState, resultingState.viewState);
        }
        for (const sortedCursor of sortedCursors) {
          if (sortedCursor.index > looserIndex) {
            sortedCursor.index--;
          }
        }
        cursors.splice(looserIndex, 1);
        sortedCursors.splice(looserSortedCursorIndex, 1);
        this._removeSecondaryCursor(looserIndex - 1);
        sortedCursorIndex--;
      }
    }
  }
}
class CursorContext {
  constructor(model, viewModel, coordinatesConverter, cursorConfig) {
    this._cursorContextBrand = void 0;
    this.model = model;
    this.viewModel = viewModel;
    this.coordinatesConverter = coordinatesConverter;
    this.cursorConfig = cursorConfig;
  }
}
class ViewCompositionStartEvent {
  constructor() {
    this.type = 0;
  }
}
class ViewCompositionEndEvent {
  constructor() {
    this.type = 1;
  }
}
class ViewConfigurationChangedEvent {
  constructor(source) {
    this.type = 2;
    this._source = source;
  }
  hasChanged(id3) {
    return this._source.hasChanged(id3);
  }
}
class ViewCursorStateChangedEvent {
  constructor(selections2, modelSelections, reason) {
    this.selections = selections2;
    this.modelSelections = modelSelections;
    this.reason = reason;
    this.type = 3;
  }
}
class ViewDecorationsChangedEvent {
  constructor(source) {
    this.type = 4;
    if (source) {
      this.affectsMinimap = source.affectsMinimap;
      this.affectsOverviewRuler = source.affectsOverviewRuler;
      this.affectsGlyphMargin = source.affectsGlyphMargin;
    } else {
      this.affectsMinimap = true;
      this.affectsOverviewRuler = true;
      this.affectsGlyphMargin = true;
    }
  }
}
class ViewFlushedEvent {
  constructor() {
    this.type = 5;
  }
}
class ViewFocusChangedEvent {
  constructor(isFocused) {
    this.type = 6;
    this.isFocused = isFocused;
  }
}
class ViewLanguageConfigurationEvent {
  constructor() {
    this.type = 7;
  }
}
class ViewLineMappingChangedEvent {
  constructor() {
    this.type = 8;
  }
}
class ViewLinesChangedEvent {
  constructor(fromLineNumber, count) {
    this.fromLineNumber = fromLineNumber;
    this.count = count;
    this.type = 9;
  }
}
class ViewLinesDeletedEvent {
  constructor(fromLineNumber, toLineNumber) {
    this.type = 10;
    this.fromLineNumber = fromLineNumber;
    this.toLineNumber = toLineNumber;
  }
}
class ViewLinesInsertedEvent {
  constructor(fromLineNumber, toLineNumber) {
    this.type = 11;
    this.fromLineNumber = fromLineNumber;
    this.toLineNumber = toLineNumber;
  }
}
class ViewRevealRangeRequestEvent {
  constructor(source, minimalReveal, range2, selections2, verticalType, revealHorizontal, scrollType) {
    this.source = source;
    this.minimalReveal = minimalReveal;
    this.range = range2;
    this.selections = selections2;
    this.verticalType = verticalType;
    this.revealHorizontal = revealHorizontal;
    this.scrollType = scrollType;
    this.type = 12;
  }
}
class ViewScrollChangedEvent {
  constructor(source) {
    this.type = 13;
    this.scrollWidth = source.scrollWidth;
    this.scrollLeft = source.scrollLeft;
    this.scrollHeight = source.scrollHeight;
    this.scrollTop = source.scrollTop;
    this.scrollWidthChanged = source.scrollWidthChanged;
    this.scrollLeftChanged = source.scrollLeftChanged;
    this.scrollHeightChanged = source.scrollHeightChanged;
    this.scrollTopChanged = source.scrollTopChanged;
  }
}
class ViewThemeChangedEvent {
  constructor(theme) {
    this.theme = theme;
    this.type = 14;
  }
}
class ViewTokensChangedEvent {
  constructor(ranges) {
    this.type = 15;
    this.ranges = ranges;
  }
}
class ViewTokensColorsChangedEvent {
  constructor() {
    this.type = 16;
  }
}
let ViewZonesChangedEvent$1 = class ViewZonesChangedEvent {
  constructor() {
    this.type = 17;
  }
};
class ViewModelEventDispatcher extends Disposable {
  constructor() {
    super();
    this._onEvent = this._register(new Emitter$1());
    this.onEvent = this._onEvent.event;
    this._eventHandlers = [];
    this._viewEventQueue = null;
    this._isConsumingViewEventQueue = false;
    this._collector = null;
    this._collectorCnt = 0;
    this._outgoingEvents = [];
  }
  emitOutgoingEvent(e) {
    this._addOutgoingEvent(e);
    this._emitOutgoingEvents();
  }
  _addOutgoingEvent(e) {
    for (let i = 0, len = this._outgoingEvents.length; i < len; i++) {
      const mergeResult = this._outgoingEvents[i].kind === e.kind ? this._outgoingEvents[i].attemptToMerge(e) : null;
      if (mergeResult) {
        this._outgoingEvents[i] = mergeResult;
        return;
      }
    }
    this._outgoingEvents.push(e);
  }
  _emitOutgoingEvents() {
    while (this._outgoingEvents.length > 0) {
      if (this._collector || this._isConsumingViewEventQueue) {
        return;
      }
      const event = this._outgoingEvents.shift();
      if (event.isNoOp()) {
        continue;
      }
      this._onEvent.fire(event);
    }
  }
  addViewEventHandler(eventHandler) {
    for (let i = 0, len = this._eventHandlers.length; i < len; i++) {
      if (this._eventHandlers[i] === eventHandler) {
        console.warn("Detected duplicate listener in ViewEventDispatcher", eventHandler);
      }
    }
    this._eventHandlers.push(eventHandler);
  }
  removeViewEventHandler(eventHandler) {
    for (let i = 0; i < this._eventHandlers.length; i++) {
      if (this._eventHandlers[i] === eventHandler) {
        this._eventHandlers.splice(i, 1);
        break;
      }
    }
  }
  beginEmitViewEvents() {
    this._collectorCnt++;
    if (this._collectorCnt === 1) {
      this._collector = new ViewModelEventsCollector();
    }
    return this._collector;
  }
  endEmitViewEvents() {
    this._collectorCnt--;
    if (this._collectorCnt === 0) {
      const outgoingEvents = this._collector.outgoingEvents;
      const viewEvents = this._collector.viewEvents;
      this._collector = null;
      for (const outgoingEvent of outgoingEvents) {
        this._addOutgoingEvent(outgoingEvent);
      }
      if (viewEvents.length > 0) {
        this._emitMany(viewEvents);
      }
    }
    this._emitOutgoingEvents();
  }
  emitSingleViewEvent(event) {
    try {
      const eventsCollector = this.beginEmitViewEvents();
      eventsCollector.emitViewEvent(event);
    } finally {
      this.endEmitViewEvents();
    }
  }
  _emitMany(events) {
    if (this._viewEventQueue) {
      this._viewEventQueue = this._viewEventQueue.concat(events);
    } else {
      this._viewEventQueue = events;
    }
    if (!this._isConsumingViewEventQueue) {
      this._consumeViewEventQueue();
    }
  }
  _consumeViewEventQueue() {
    try {
      this._isConsumingViewEventQueue = true;
      this._doConsumeQueue();
    } finally {
      this._isConsumingViewEventQueue = false;
    }
  }
  _doConsumeQueue() {
    while (this._viewEventQueue) {
      const events = this._viewEventQueue;
      this._viewEventQueue = null;
      const eventHandlers = this._eventHandlers.slice(0);
      for (const eventHandler of eventHandlers) {
        eventHandler.handleEvents(events);
      }
    }
  }
}
class ViewModelEventsCollector {
  constructor() {
    this.viewEvents = [];
    this.outgoingEvents = [];
  }
  emitViewEvent(event) {
    this.viewEvents.push(event);
  }
  emitOutgoingEvent(e) {
    this.outgoingEvents.push(e);
  }
}
class ContentSizeChangedEvent {
  constructor(oldContentWidth, oldContentHeight, contentWidth, contentHeight) {
    this.kind = 0;
    this._oldContentWidth = oldContentWidth;
    this._oldContentHeight = oldContentHeight;
    this.contentWidth = contentWidth;
    this.contentHeight = contentHeight;
    this.contentWidthChanged = this._oldContentWidth !== this.contentWidth;
    this.contentHeightChanged = this._oldContentHeight !== this.contentHeight;
  }
  isNoOp() {
    return !this.contentWidthChanged && !this.contentHeightChanged;
  }
  attemptToMerge(other) {
    if (other.kind !== this.kind) {
      return null;
    }
    return new ContentSizeChangedEvent(this._oldContentWidth, this._oldContentHeight, other.contentWidth, other.contentHeight);
  }
}
class FocusChangedEvent {
  constructor(oldHasFocus, hasFocus) {
    this.kind = 1;
    this.oldHasFocus = oldHasFocus;
    this.hasFocus = hasFocus;
  }
  isNoOp() {
    return this.oldHasFocus === this.hasFocus;
  }
  attemptToMerge(other) {
    if (other.kind !== this.kind) {
      return null;
    }
    return new FocusChangedEvent(this.oldHasFocus, other.hasFocus);
  }
}
class ScrollChangedEvent {
  constructor(oldScrollWidth, oldScrollLeft, oldScrollHeight, oldScrollTop, scrollWidth, scrollLeft, scrollHeight, scrollTop) {
    this.kind = 2;
    this._oldScrollWidth = oldScrollWidth;
    this._oldScrollLeft = oldScrollLeft;
    this._oldScrollHeight = oldScrollHeight;
    this._oldScrollTop = oldScrollTop;
    this.scrollWidth = scrollWidth;
    this.scrollLeft = scrollLeft;
    this.scrollHeight = scrollHeight;
    this.scrollTop = scrollTop;
    this.scrollWidthChanged = this._oldScrollWidth !== this.scrollWidth;
    this.scrollLeftChanged = this._oldScrollLeft !== this.scrollLeft;
    this.scrollHeightChanged = this._oldScrollHeight !== this.scrollHeight;
    this.scrollTopChanged = this._oldScrollTop !== this.scrollTop;
  }
  isNoOp() {
    return !this.scrollWidthChanged && !this.scrollLeftChanged && !this.scrollHeightChanged && !this.scrollTopChanged;
  }
  attemptToMerge(other) {
    if (other.kind !== this.kind) {
      return null;
    }
    return new ScrollChangedEvent(this._oldScrollWidth, this._oldScrollLeft, this._oldScrollHeight, this._oldScrollTop, other.scrollWidth, other.scrollLeft, other.scrollHeight, other.scrollTop);
  }
}
class ViewZonesChangedEvent2 {
  constructor() {
    this.kind = 3;
  }
  isNoOp() {
    return false;
  }
  attemptToMerge(other) {
    if (other.kind !== this.kind) {
      return null;
    }
    return this;
  }
}
class HiddenAreasChangedEvent {
  constructor() {
    this.kind = 4;
  }
  isNoOp() {
    return false;
  }
  attemptToMerge(other) {
    if (other.kind !== this.kind) {
      return null;
    }
    return this;
  }
}
class CursorStateChangedEvent {
  constructor(oldSelections, selections2, oldModelVersionId, modelVersionId, source, reason, reachedMaxCursorCount) {
    this.kind = 6;
    this.oldSelections = oldSelections;
    this.selections = selections2;
    this.oldModelVersionId = oldModelVersionId;
    this.modelVersionId = modelVersionId;
    this.source = source;
    this.reason = reason;
    this.reachedMaxCursorCount = reachedMaxCursorCount;
  }
  static _selectionsAreEqual(a, b) {
    if (!a && !b) {
      return true;
    }
    if (!a || !b) {
      return false;
    }
    const aLen = a.length;
    const bLen = b.length;
    if (aLen !== bLen) {
      return false;
    }
    for (let i = 0; i < aLen; i++) {
      if (!a[i].equalsSelection(b[i])) {
        return false;
      }
    }
    return true;
  }
  isNoOp() {
    return CursorStateChangedEvent._selectionsAreEqual(this.oldSelections, this.selections) && this.oldModelVersionId === this.modelVersionId;
  }
  attemptToMerge(other) {
    if (other.kind !== this.kind) {
      return null;
    }
    return new CursorStateChangedEvent(this.oldSelections, other.selections, this.oldModelVersionId, other.modelVersionId, other.source, other.reason, this.reachedMaxCursorCount || other.reachedMaxCursorCount);
  }
}
class ReadOnlyEditAttemptEvent {
  constructor() {
    this.kind = 5;
  }
  isNoOp() {
    return false;
  }
  attemptToMerge(other) {
    if (other.kind !== this.kind) {
      return null;
    }
    return this;
  }
}
class ModelDecorationsChangedEvent {
  constructor(event) {
    this.event = event;
    this.kind = 7;
  }
  isNoOp() {
    return false;
  }
  attemptToMerge(other) {
    return null;
  }
}
class ModelLanguageChangedEvent {
  constructor(event) {
    this.event = event;
    this.kind = 8;
  }
  isNoOp() {
    return false;
  }
  attemptToMerge(other) {
    return null;
  }
}
class ModelLanguageConfigurationChangedEvent {
  constructor(event) {
    this.event = event;
    this.kind = 9;
  }
  isNoOp() {
    return false;
  }
  attemptToMerge(other) {
    return null;
  }
}
class ModelContentChangedEvent {
  constructor(event) {
    this.event = event;
    this.kind = 10;
  }
  isNoOp() {
    return false;
  }
  attemptToMerge(other) {
    return null;
  }
}
class ModelOptionsChangedEvent {
  constructor(event) {
    this.event = event;
    this.kind = 11;
  }
  isNoOp() {
    return false;
  }
  attemptToMerge(other) {
    return null;
  }
}
class ModelTokensChangedEvent {
  constructor(event) {
    this.event = event;
    this.kind = 12;
  }
  isNoOp() {
    return false;
  }
  attemptToMerge(other) {
    return null;
  }
}
class CursorsController extends Disposable {
  constructor(model, viewModel, coordinatesConverter, cursorConfig) {
    super();
    this._model = model;
    this._knownModelVersionId = this._model.getVersionId();
    this._viewModel = viewModel;
    this._coordinatesConverter = coordinatesConverter;
    this.context = new CursorContext(this._model, this._viewModel, this._coordinatesConverter, cursorConfig);
    this._cursors = new CursorCollection(this.context);
    this._hasFocus = false;
    this._isHandling = false;
    this._compositionState = null;
    this._columnSelectData = null;
    this._autoClosedActions = [];
    this._prevEditOperationType = 0;
  }
  dispose() {
    this._cursors.dispose();
    this._autoClosedActions = dispose(this._autoClosedActions);
    super.dispose();
  }
  updateConfiguration(cursorConfig) {
    this.context = new CursorContext(this._model, this._viewModel, this._coordinatesConverter, cursorConfig);
    this._cursors.updateContext(this.context);
  }
  onLineMappingChanged(eventsCollector) {
    if (this._knownModelVersionId !== this._model.getVersionId()) {
      return;
    }
    this.setStates(eventsCollector, "viewModel", 0, this.getCursorStates());
  }
  setHasFocus(hasFocus) {
    this._hasFocus = hasFocus;
  }
  _validateAutoClosedActions() {
    if (this._autoClosedActions.length > 0) {
      const selections2 = this._cursors.getSelections();
      for (let i = 0; i < this._autoClosedActions.length; i++) {
        const autoClosedAction = this._autoClosedActions[i];
        if (!autoClosedAction.isValid(selections2)) {
          autoClosedAction.dispose();
          this._autoClosedActions.splice(i, 1);
          i--;
        }
      }
    }
  }
  // ------ some getters/setters
  getPrimaryCursorState() {
    return this._cursors.getPrimaryCursor();
  }
  getLastAddedCursorIndex() {
    return this._cursors.getLastAddedCursorIndex();
  }
  getCursorStates() {
    return this._cursors.getAll();
  }
  setStates(eventsCollector, source, reason, states) {
    let reachedMaxCursorCount = false;
    const multiCursorLimit = this.context.cursorConfig.multiCursorLimit;
    if (states !== null && states.length > multiCursorLimit) {
      states = states.slice(0, multiCursorLimit);
      reachedMaxCursorCount = true;
    }
    const oldState = CursorModelState.from(this._model, this);
    this._cursors.setStates(states);
    this._cursors.normalize();
    this._columnSelectData = null;
    this._validateAutoClosedActions();
    return this._emitStateChangedIfNecessary(eventsCollector, source, reason, oldState, reachedMaxCursorCount);
  }
  setCursorColumnSelectData(columnSelectData) {
    this._columnSelectData = columnSelectData;
  }
  revealPrimary(eventsCollector, source, minimalReveal, verticalType, revealHorizontal, scrollType) {
    const viewPositions = this._cursors.getViewPositions();
    let revealViewRange = null;
    let revealViewSelections = null;
    if (viewPositions.length > 1) {
      revealViewSelections = this._cursors.getViewSelections();
    } else {
      revealViewRange = Range$2.fromPositions(viewPositions[0], viewPositions[0]);
    }
    eventsCollector.emitViewEvent(new ViewRevealRangeRequestEvent(source, minimalReveal, revealViewRange, revealViewSelections, verticalType, revealHorizontal, scrollType));
  }
  saveState() {
    const result2 = [];
    const selections2 = this._cursors.getSelections();
    for (let i = 0, len = selections2.length; i < len; i++) {
      const selection = selections2[i];
      result2.push({
        inSelectionMode: !selection.isEmpty(),
        selectionStart: {
          lineNumber: selection.selectionStartLineNumber,
          column: selection.selectionStartColumn
        },
        position: {
          lineNumber: selection.positionLineNumber,
          column: selection.positionColumn
        }
      });
    }
    return result2;
  }
  restoreState(eventsCollector, states) {
    const desiredSelections = [];
    for (let i = 0, len = states.length; i < len; i++) {
      const state = states[i];
      let positionLineNumber = 1;
      let positionColumn = 1;
      if (state.position && state.position.lineNumber) {
        positionLineNumber = state.position.lineNumber;
      }
      if (state.position && state.position.column) {
        positionColumn = state.position.column;
      }
      let selectionStartLineNumber = positionLineNumber;
      let selectionStartColumn = positionColumn;
      if (state.selectionStart && state.selectionStart.lineNumber) {
        selectionStartLineNumber = state.selectionStart.lineNumber;
      }
      if (state.selectionStart && state.selectionStart.column) {
        selectionStartColumn = state.selectionStart.column;
      }
      desiredSelections.push({
        selectionStartLineNumber,
        selectionStartColumn,
        positionLineNumber,
        positionColumn
      });
    }
    this.setStates(eventsCollector, "restoreState", 0, CursorState$1.fromModelSelections(desiredSelections));
    this.revealPrimary(
      eventsCollector,
      "restoreState",
      false,
      0,
      true,
      1
      /* editorCommon.ScrollType.Immediate */
    );
  }
  onModelContentChanged(eventsCollector, event) {
    if (event instanceof ModelInjectedTextChangedEvent) {
      if (this._isHandling) {
        return;
      }
      this._isHandling = true;
      try {
        this.setStates(eventsCollector, "modelChange", 0, this.getCursorStates());
      } finally {
        this._isHandling = false;
      }
    } else {
      const e = event.rawContentChangedEvent;
      this._knownModelVersionId = e.versionId;
      if (this._isHandling) {
        return;
      }
      const hadFlushEvent = e.containsEvent(
        1
        /* RawContentChangedType.Flush */
      );
      this._prevEditOperationType = 0;
      if (hadFlushEvent) {
        this._cursors.dispose();
        this._cursors = new CursorCollection(this.context);
        this._validateAutoClosedActions();
        this._emitStateChangedIfNecessary(eventsCollector, "model", 1, null, false);
      } else {
        if (this._hasFocus && e.resultingSelection && e.resultingSelection.length > 0) {
          const cursorState = CursorState$1.fromModelSelections(e.resultingSelection);
          if (this.setStates(eventsCollector, "modelChange", e.isUndoing ? 5 : e.isRedoing ? 6 : 2, cursorState)) {
            this.revealPrimary(
              eventsCollector,
              "modelChange",
              false,
              0,
              true,
              0
              /* editorCommon.ScrollType.Smooth */
            );
          }
        } else {
          const selectionsFromMarkers = this._cursors.readSelectionFromMarkers();
          this.setStates(eventsCollector, "modelChange", 2, CursorState$1.fromModelSelections(selectionsFromMarkers));
        }
      }
    }
  }
  getSelection() {
    return this._cursors.getPrimaryCursor().modelState.selection;
  }
  getTopMostViewPosition() {
    return this._cursors.getTopMostViewPosition();
  }
  getBottomMostViewPosition() {
    return this._cursors.getBottomMostViewPosition();
  }
  getCursorColumnSelectData() {
    if (this._columnSelectData) {
      return this._columnSelectData;
    }
    const primaryCursor = this._cursors.getPrimaryCursor();
    const viewSelectionStart = primaryCursor.viewState.selectionStart.getStartPosition();
    const viewPosition = primaryCursor.viewState.position;
    return {
      isReal: false,
      fromViewLineNumber: viewSelectionStart.lineNumber,
      fromViewVisualColumn: this.context.cursorConfig.visibleColumnFromColumn(this._viewModel, viewSelectionStart),
      toViewLineNumber: viewPosition.lineNumber,
      toViewVisualColumn: this.context.cursorConfig.visibleColumnFromColumn(this._viewModel, viewPosition)
    };
  }
  getSelections() {
    return this._cursors.getSelections();
  }
  setSelections(eventsCollector, source, selections2, reason) {
    this.setStates(eventsCollector, source, reason, CursorState$1.fromModelSelections(selections2));
  }
  getPrevEditOperationType() {
    return this._prevEditOperationType;
  }
  setPrevEditOperationType(type) {
    this._prevEditOperationType = type;
  }
  // ------ auxiliary handling logic
  _pushAutoClosedAction(autoClosedCharactersRanges, autoClosedEnclosingRanges) {
    const autoClosedCharactersDeltaDecorations = [];
    const autoClosedEnclosingDeltaDecorations = [];
    for (let i = 0, len = autoClosedCharactersRanges.length; i < len; i++) {
      autoClosedCharactersDeltaDecorations.push({
        range: autoClosedCharactersRanges[i],
        options: {
          description: "auto-closed-character",
          inlineClassName: "auto-closed-character",
          stickiness: 1
          /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
        }
      });
      autoClosedEnclosingDeltaDecorations.push({
        range: autoClosedEnclosingRanges[i],
        options: {
          description: "auto-closed-enclosing",
          stickiness: 1
          /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
        }
      });
    }
    const autoClosedCharactersDecorations = this._model.deltaDecorations([], autoClosedCharactersDeltaDecorations);
    const autoClosedEnclosingDecorations = this._model.deltaDecorations([], autoClosedEnclosingDeltaDecorations);
    this._autoClosedActions.push(new AutoClosedAction(this._model, autoClosedCharactersDecorations, autoClosedEnclosingDecorations));
  }
  _executeEditOperation(opResult) {
    if (!opResult) {
      return;
    }
    if (opResult.shouldPushStackElementBefore) {
      this._model.pushStackElement();
    }
    const result2 = CommandExecutor.executeCommands(this._model, this._cursors.getSelections(), opResult.commands);
    if (result2) {
      this._interpretCommandResult(result2);
      const autoClosedCharactersRanges = [];
      const autoClosedEnclosingRanges = [];
      for (let i = 0; i < opResult.commands.length; i++) {
        const command = opResult.commands[i];
        if (command instanceof TypeWithAutoClosingCommand && command.enclosingRange && command.closeCharacterRange) {
          autoClosedCharactersRanges.push(command.closeCharacterRange);
          autoClosedEnclosingRanges.push(command.enclosingRange);
        }
      }
      if (autoClosedCharactersRanges.length > 0) {
        this._pushAutoClosedAction(autoClosedCharactersRanges, autoClosedEnclosingRanges);
      }
      this._prevEditOperationType = opResult.type;
    }
    if (opResult.shouldPushStackElementAfter) {
      this._model.pushStackElement();
    }
  }
  _interpretCommandResult(cursorState) {
    if (!cursorState || cursorState.length === 0) {
      cursorState = this._cursors.readSelectionFromMarkers();
    }
    this._columnSelectData = null;
    this._cursors.setSelections(cursorState);
    this._cursors.normalize();
  }
  // -----------------------------------------------------------------------------------------------------------
  // ----- emitting events
  _emitStateChangedIfNecessary(eventsCollector, source, reason, oldState, reachedMaxCursorCount) {
    const newState = CursorModelState.from(this._model, this);
    if (newState.equals(oldState)) {
      return false;
    }
    const selections2 = this._cursors.getSelections();
    const viewSelections = this._cursors.getViewSelections();
    eventsCollector.emitViewEvent(new ViewCursorStateChangedEvent(viewSelections, selections2, reason));
    if (!oldState || oldState.cursorState.length !== newState.cursorState.length || newState.cursorState.some((newCursorState, i) => !newCursorState.modelState.equals(oldState.cursorState[i].modelState))) {
      const oldSelections = oldState ? oldState.cursorState.map((s) => s.modelState.selection) : null;
      const oldModelVersionId = oldState ? oldState.modelVersionId : 0;
      eventsCollector.emitOutgoingEvent(new CursorStateChangedEvent(oldSelections, selections2, oldModelVersionId, newState.modelVersionId, source || "keyboard", reason, reachedMaxCursorCount));
    }
    return true;
  }
  // -----------------------------------------------------------------------------------------------------------
  // ----- handlers beyond this point
  _findAutoClosingPairs(edits) {
    if (!edits.length) {
      return null;
    }
    const indices = [];
    for (let i = 0, len = edits.length; i < len; i++) {
      const edit = edits[i];
      if (!edit.text || edit.text.indexOf("\n") >= 0) {
        return null;
      }
      const m = edit.text.match(/([)\]}>'"`])([^)\]}>'"`]*)$/);
      if (!m) {
        return null;
      }
      const closeChar = m[1];
      const autoClosingPairsCandidates = this.context.cursorConfig.autoClosingPairs.autoClosingPairsCloseSingleChar.get(closeChar);
      if (!autoClosingPairsCandidates || autoClosingPairsCandidates.length !== 1) {
        return null;
      }
      const openChar = autoClosingPairsCandidates[0].open;
      const closeCharIndex = edit.text.length - m[2].length - 1;
      const openCharIndex = edit.text.lastIndexOf(openChar, closeCharIndex - 1);
      if (openCharIndex === -1) {
        return null;
      }
      indices.push([openCharIndex, closeCharIndex]);
    }
    return indices;
  }
  executeEdits(eventsCollector, source, edits, cursorStateComputer) {
    let autoClosingIndices = null;
    if (source === "snippet") {
      autoClosingIndices = this._findAutoClosingPairs(edits);
    }
    if (autoClosingIndices) {
      edits[0]._isTracked = true;
    }
    const autoClosedCharactersRanges = [];
    const autoClosedEnclosingRanges = [];
    const selections2 = this._model.pushEditOperations(this.getSelections(), edits, (undoEdits) => {
      if (autoClosingIndices) {
        for (let i = 0, len = autoClosingIndices.length; i < len; i++) {
          const [openCharInnerIndex, closeCharInnerIndex] = autoClosingIndices[i];
          const undoEdit = undoEdits[i];
          const lineNumber = undoEdit.range.startLineNumber;
          const openCharIndex = undoEdit.range.startColumn - 1 + openCharInnerIndex;
          const closeCharIndex = undoEdit.range.startColumn - 1 + closeCharInnerIndex;
          autoClosedCharactersRanges.push(new Range$2(lineNumber, closeCharIndex + 1, lineNumber, closeCharIndex + 2));
          autoClosedEnclosingRanges.push(new Range$2(lineNumber, openCharIndex + 1, lineNumber, closeCharIndex + 2));
        }
      }
      const selections3 = cursorStateComputer(undoEdits);
      if (selections3) {
        this._isHandling = true;
      }
      return selections3;
    });
    if (selections2) {
      this._isHandling = false;
      this.setSelections(
        eventsCollector,
        source,
        selections2,
        0
        /* CursorChangeReason.NotSet */
      );
    }
    if (autoClosedCharactersRanges.length > 0) {
      this._pushAutoClosedAction(autoClosedCharactersRanges, autoClosedEnclosingRanges);
    }
  }
  _executeEdit(callback, eventsCollector, source, cursorChangeReason = 0) {
    if (this.context.cursorConfig.readOnly) {
      return;
    }
    const oldState = CursorModelState.from(this._model, this);
    this._cursors.stopTrackingSelections();
    this._isHandling = true;
    try {
      this._cursors.ensureValidState();
      callback();
    } catch (err) {
      onUnexpectedError(err);
    }
    this._isHandling = false;
    this._cursors.startTrackingSelections();
    this._validateAutoClosedActions();
    if (this._emitStateChangedIfNecessary(eventsCollector, source, cursorChangeReason, oldState, false)) {
      this.revealPrimary(
        eventsCollector,
        source,
        false,
        0,
        true,
        0
        /* editorCommon.ScrollType.Smooth */
      );
    }
  }
  getAutoClosedCharacters() {
    return AutoClosedAction.getAllAutoClosedCharacters(this._autoClosedActions);
  }
  startComposition(eventsCollector) {
    this._compositionState = new CompositionState(this._model, this.getSelections());
  }
  endComposition(eventsCollector, source) {
    const compositionOutcome = this._compositionState ? this._compositionState.deduceOutcome(this._model, this.getSelections()) : null;
    this._compositionState = null;
    this._executeEdit(() => {
      if (source === "keyboard") {
        this._executeEditOperation(TypeOperations.compositionEndWithInterceptors(this._prevEditOperationType, this.context.cursorConfig, this._model, compositionOutcome, this.getSelections(), this.getAutoClosedCharacters()));
      }
    }, eventsCollector, source);
  }
  type(eventsCollector, text2, source) {
    this._executeEdit(() => {
      if (source === "keyboard") {
        const len = text2.length;
        let offset = 0;
        while (offset < len) {
          const charLength = nextCharLength(text2, offset);
          const chr = text2.substr(offset, charLength);
          this._executeEditOperation(TypeOperations.typeWithInterceptors(!!this._compositionState, this._prevEditOperationType, this.context.cursorConfig, this._model, this.getSelections(), this.getAutoClosedCharacters(), chr));
          offset += charLength;
        }
      } else {
        this._executeEditOperation(TypeOperations.typeWithoutInterceptors(this._prevEditOperationType, this.context.cursorConfig, this._model, this.getSelections(), text2));
      }
    }, eventsCollector, source);
  }
  compositionType(eventsCollector, text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta, source) {
    if (text2.length === 0 && replacePrevCharCnt === 0 && replaceNextCharCnt === 0) {
      if (positionDelta !== 0) {
        const newSelections = this.getSelections().map((selection) => {
          const position = selection.getPosition();
          return new Selection$1(position.lineNumber, position.column + positionDelta, position.lineNumber, position.column + positionDelta);
        });
        this.setSelections(
          eventsCollector,
          source,
          newSelections,
          0
          /* CursorChangeReason.NotSet */
        );
      }
      return;
    }
    this._executeEdit(() => {
      this._executeEditOperation(TypeOperations.compositionType(this._prevEditOperationType, this.context.cursorConfig, this._model, this.getSelections(), text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta));
    }, eventsCollector, source);
  }
  paste(eventsCollector, text2, pasteOnNewLine, multicursorText, source) {
    this._executeEdit(
      () => {
        this._executeEditOperation(TypeOperations.paste(this.context.cursorConfig, this._model, this.getSelections(), text2, pasteOnNewLine, multicursorText || []));
      },
      eventsCollector,
      source,
      4
      /* CursorChangeReason.Paste */
    );
  }
  cut(eventsCollector, source) {
    this._executeEdit(() => {
      this._executeEditOperation(DeleteOperations.cut(this.context.cursorConfig, this._model, this.getSelections()));
    }, eventsCollector, source);
  }
  executeCommand(eventsCollector, command, source) {
    this._executeEdit(() => {
      this._cursors.killSecondaryCursors();
      this._executeEditOperation(new EditOperationResult(0, [command], {
        shouldPushStackElementBefore: false,
        shouldPushStackElementAfter: false
      }));
    }, eventsCollector, source);
  }
  executeCommands(eventsCollector, commands, source) {
    this._executeEdit(() => {
      this._executeEditOperation(new EditOperationResult(0, commands, {
        shouldPushStackElementBefore: false,
        shouldPushStackElementAfter: false
      }));
    }, eventsCollector, source);
  }
}
class CursorModelState {
  static from(model, cursor) {
    return new CursorModelState(model.getVersionId(), cursor.getCursorStates());
  }
  constructor(modelVersionId, cursorState) {
    this.modelVersionId = modelVersionId;
    this.cursorState = cursorState;
  }
  equals(other) {
    if (!other) {
      return false;
    }
    if (this.modelVersionId !== other.modelVersionId) {
      return false;
    }
    if (this.cursorState.length !== other.cursorState.length) {
      return false;
    }
    for (let i = 0, len = this.cursorState.length; i < len; i++) {
      if (!this.cursorState[i].equals(other.cursorState[i])) {
        return false;
      }
    }
    return true;
  }
}
class AutoClosedAction {
  static getAllAutoClosedCharacters(autoClosedActions) {
    let autoClosedCharacters = [];
    for (const autoClosedAction of autoClosedActions) {
      autoClosedCharacters = autoClosedCharacters.concat(autoClosedAction.getAutoClosedCharactersRanges());
    }
    return autoClosedCharacters;
  }
  constructor(model, autoClosedCharactersDecorations, autoClosedEnclosingDecorations) {
    this._model = model;
    this._autoClosedCharactersDecorations = autoClosedCharactersDecorations;
    this._autoClosedEnclosingDecorations = autoClosedEnclosingDecorations;
  }
  dispose() {
    this._autoClosedCharactersDecorations = this._model.deltaDecorations(this._autoClosedCharactersDecorations, []);
    this._autoClosedEnclosingDecorations = this._model.deltaDecorations(this._autoClosedEnclosingDecorations, []);
  }
  getAutoClosedCharactersRanges() {
    const result2 = [];
    for (let i = 0; i < this._autoClosedCharactersDecorations.length; i++) {
      const decorationRange = this._model.getDecorationRange(this._autoClosedCharactersDecorations[i]);
      if (decorationRange) {
        result2.push(decorationRange);
      }
    }
    return result2;
  }
  isValid(selections2) {
    const enclosingRanges = [];
    for (let i = 0; i < this._autoClosedEnclosingDecorations.length; i++) {
      const decorationRange = this._model.getDecorationRange(this._autoClosedEnclosingDecorations[i]);
      if (decorationRange) {
        enclosingRanges.push(decorationRange);
        if (decorationRange.startLineNumber !== decorationRange.endLineNumber) {
          return false;
        }
      }
    }
    enclosingRanges.sort(Range$2.compareRangesUsingStarts);
    selections2.sort(Range$2.compareRangesUsingStarts);
    for (let i = 0; i < selections2.length; i++) {
      if (i >= enclosingRanges.length) {
        return false;
      }
      if (!enclosingRanges[i].strictContainsRange(selections2[i])) {
        return false;
      }
    }
    return true;
  }
}
class CommandExecutor {
  static executeCommands(model, selectionsBefore, commands) {
    const ctx = {
      model,
      selectionsBefore,
      trackedRanges: [],
      trackedRangesDirection: []
    };
    const result2 = this._innerExecuteCommands(ctx, commands);
    for (let i = 0, len = ctx.trackedRanges.length; i < len; i++) {
      ctx.model._setTrackedRange(
        ctx.trackedRanges[i],
        null,
        0
        /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */
      );
    }
    return result2;
  }
  static _innerExecuteCommands(ctx, commands) {
    if (this._arrayIsEmpty(commands)) {
      return null;
    }
    const commandsData = this._getEditOperations(ctx, commands);
    if (commandsData.operations.length === 0) {
      return null;
    }
    const rawOperations = commandsData.operations;
    const loserCursorsMap = this._getLoserCursorMap(rawOperations);
    if (loserCursorsMap.hasOwnProperty("0")) {
      console.warn("Ignoring commands");
      return null;
    }
    const filteredOperations = [];
    for (let i = 0, len = rawOperations.length; i < len; i++) {
      if (!loserCursorsMap.hasOwnProperty(rawOperations[i].identifier.major.toString())) {
        filteredOperations.push(rawOperations[i]);
      }
    }
    if (commandsData.hadTrackedEditOperation && filteredOperations.length > 0) {
      filteredOperations[0]._isTracked = true;
    }
    let selectionsAfter = ctx.model.pushEditOperations(ctx.selectionsBefore, filteredOperations, (inverseEditOperations) => {
      const groupedInverseEditOperations = [];
      for (let i = 0; i < ctx.selectionsBefore.length; i++) {
        groupedInverseEditOperations[i] = [];
      }
      for (const op of inverseEditOperations) {
        if (!op.identifier) {
          continue;
        }
        groupedInverseEditOperations[op.identifier.major].push(op);
      }
      const minorBasedSorter = (a, b) => {
        return a.identifier.minor - b.identifier.minor;
      };
      const cursorSelections = [];
      for (let i = 0; i < ctx.selectionsBefore.length; i++) {
        if (groupedInverseEditOperations[i].length > 0) {
          groupedInverseEditOperations[i].sort(minorBasedSorter);
          cursorSelections[i] = commands[i].computeCursorState(ctx.model, {
            getInverseEditOperations: () => {
              return groupedInverseEditOperations[i];
            },
            getTrackedSelection: (id3) => {
              const idx = parseInt(id3, 10);
              const range2 = ctx.model._getTrackedRange(ctx.trackedRanges[idx]);
              if (ctx.trackedRangesDirection[idx] === 0) {
                return new Selection$1(range2.startLineNumber, range2.startColumn, range2.endLineNumber, range2.endColumn);
              }
              return new Selection$1(range2.endLineNumber, range2.endColumn, range2.startLineNumber, range2.startColumn);
            }
          });
        } else {
          cursorSelections[i] = ctx.selectionsBefore[i];
        }
      }
      return cursorSelections;
    });
    if (!selectionsAfter) {
      selectionsAfter = ctx.selectionsBefore;
    }
    const losingCursors = [];
    for (const losingCursorIndex in loserCursorsMap) {
      if (loserCursorsMap.hasOwnProperty(losingCursorIndex)) {
        losingCursors.push(parseInt(losingCursorIndex, 10));
      }
    }
    losingCursors.sort((a, b) => {
      return b - a;
    });
    for (const losingCursor of losingCursors) {
      selectionsAfter.splice(losingCursor, 1);
    }
    return selectionsAfter;
  }
  static _arrayIsEmpty(commands) {
    for (let i = 0, len = commands.length; i < len; i++) {
      if (commands[i]) {
        return false;
      }
    }
    return true;
  }
  static _getEditOperations(ctx, commands) {
    let operations = [];
    let hadTrackedEditOperation = false;
    for (let i = 0, len = commands.length; i < len; i++) {
      const command = commands[i];
      if (command) {
        const r = this._getEditOperationsFromCommand(ctx, i, command);
        operations = operations.concat(r.operations);
        hadTrackedEditOperation = hadTrackedEditOperation || r.hadTrackedEditOperation;
      }
    }
    return {
      operations,
      hadTrackedEditOperation
    };
  }
  static _getEditOperationsFromCommand(ctx, majorIdentifier, command) {
    const operations = [];
    let operationMinor = 0;
    const addEditOperation = (range2, text2, forceMoveMarkers = false) => {
      if (Range$2.isEmpty(range2) && text2 === "") {
        return;
      }
      operations.push({
        identifier: {
          major: majorIdentifier,
          minor: operationMinor++
        },
        range: range2,
        text: text2,
        forceMoveMarkers,
        isAutoWhitespaceEdit: command.insertsAutoWhitespace
      });
    };
    let hadTrackedEditOperation = false;
    const addTrackedEditOperation = (selection, text2, forceMoveMarkers) => {
      hadTrackedEditOperation = true;
      addEditOperation(selection, text2, forceMoveMarkers);
    };
    const trackSelection = (_selection, trackPreviousOnEmpty) => {
      const selection = Selection$1.liftSelection(_selection);
      let stickiness;
      if (selection.isEmpty()) {
        if (typeof trackPreviousOnEmpty === "boolean") {
          if (trackPreviousOnEmpty) {
            stickiness = 2;
          } else {
            stickiness = 3;
          }
        } else {
          const maxLineColumn = ctx.model.getLineMaxColumn(selection.startLineNumber);
          if (selection.startColumn === maxLineColumn) {
            stickiness = 2;
          } else {
            stickiness = 3;
          }
        }
      } else {
        stickiness = 1;
      }
      const l = ctx.trackedRanges.length;
      const id3 = ctx.model._setTrackedRange(null, selection, stickiness);
      ctx.trackedRanges[l] = id3;
      ctx.trackedRangesDirection[l] = selection.getDirection();
      return l.toString();
    };
    const editOperationBuilder = {
      addEditOperation,
      addTrackedEditOperation,
      trackSelection
    };
    try {
      command.getEditOperations(ctx.model, editOperationBuilder);
    } catch (e) {
      onUnexpectedError(e);
      return {
        operations: [],
        hadTrackedEditOperation: false
      };
    }
    return {
      operations,
      hadTrackedEditOperation
    };
  }
  static _getLoserCursorMap(operations) {
    operations = operations.slice(0);
    operations.sort((a, b) => {
      return -Range$2.compareRangesUsingEnds(a.range, b.range);
    });
    const loserCursorsMap = {};
    for (let i = 1; i < operations.length; i++) {
      const previousOp = operations[i - 1];
      const currentOp = operations[i];
      if (Range$2.getStartPosition(previousOp.range).isBefore(Range$2.getEndPosition(currentOp.range))) {
        let loserMajor;
        if (previousOp.identifier.major > currentOp.identifier.major) {
          loserMajor = previousOp.identifier.major;
        } else {
          loserMajor = currentOp.identifier.major;
        }
        loserCursorsMap[loserMajor.toString()] = true;
        for (let j = 0; j < operations.length; j++) {
          if (operations[j].identifier.major === loserMajor) {
            operations.splice(j, 1);
            if (j < i) {
              i--;
            }
            j--;
          }
        }
        if (i > 0) {
          i--;
        }
      }
    }
    return loserCursorsMap;
  }
}
class CompositionLineState {
  constructor(text2, startSelection, endSelection) {
    this.text = text2;
    this.startSelection = startSelection;
    this.endSelection = endSelection;
  }
}
class CompositionState {
  static _capture(textModel, selections2) {
    const result2 = [];
    for (const selection of selections2) {
      if (selection.startLineNumber !== selection.endLineNumber) {
        return null;
      }
      result2.push(new CompositionLineState(textModel.getLineContent(selection.startLineNumber), selection.startColumn - 1, selection.endColumn - 1));
    }
    return result2;
  }
  constructor(textModel, selections2) {
    this._original = CompositionState._capture(textModel, selections2);
  }
  /**
   * Returns the inserted text during this composition.
   * If the composition resulted in existing text being changed (i.e. not a pure insertion) it returns null.
   */
  deduceOutcome(textModel, selections2) {
    if (!this._original) {
      return null;
    }
    const current = CompositionState._capture(textModel, selections2);
    if (!current) {
      return null;
    }
    if (this._original.length !== current.length) {
      return null;
    }
    const result2 = [];
    for (let i = 0, len = this._original.length; i < len; i++) {
      result2.push(CompositionState._deduceOutcome(this._original[i], current[i]));
    }
    return result2;
  }
  static _deduceOutcome(original, current) {
    const commonPrefix = Math.min(original.startSelection, current.startSelection, commonPrefixLength(original.text, current.text));
    const commonSuffix = Math.min(original.text.length - original.endSelection, current.text.length - current.endSelection, commonSuffixLength(original.text, current.text));
    const deletedText = original.text.substring(commonPrefix, original.text.length - commonSuffix);
    const insertedText = current.text.substring(commonPrefix, current.text.length - commonSuffix);
    return new CompositionOutcome(deletedText, original.startSelection - commonPrefix, original.endSelection - commonPrefix, insertedText, current.startSelection - commonPrefix, current.endSelection - commonPrefix);
  }
}
var __awaiter$1x = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
const fallback = {
  getInitialState: () => NullState,
  tokenizeEncoded: (buffer, hasEOL, state) => nullTokenizeEncoded(0, state)
};
function tokenizeToString(languageService, text2, languageId) {
  return __awaiter$1x(this, void 0, void 0, function* () {
    if (!languageId) {
      return _tokenizeToString(text2, languageService.languageIdCodec, fallback);
    }
    const tokenizationSupport = yield TokenizationRegistry2.getOrCreate(languageId);
    return _tokenizeToString(text2, languageService.languageIdCodec, tokenizationSupport || fallback);
  });
}
function tokenizeLineToHTML(text2, viewLineTokens, colorMap, startOffset, endOffset, tabSize, useNbsp) {
  let result2 = `<div>`;
  let charIndex = startOffset;
  let tabsCharDelta = 0;
  let prevIsSpace = true;
  for (let tokenIndex = 0, tokenCount = viewLineTokens.getCount(); tokenIndex < tokenCount; tokenIndex++) {
    const tokenEndIndex = viewLineTokens.getEndOffset(tokenIndex);
    if (tokenEndIndex <= startOffset) {
      continue;
    }
    let partContent = "";
    for (; charIndex < tokenEndIndex && charIndex < endOffset; charIndex++) {
      const charCode = text2.charCodeAt(charIndex);
      switch (charCode) {
        case 9: {
          let insertSpacesCount = tabSize - (charIndex + tabsCharDelta) % tabSize;
          tabsCharDelta += insertSpacesCount - 1;
          while (insertSpacesCount > 0) {
            if (useNbsp && prevIsSpace) {
              partContent += "&#160;";
              prevIsSpace = false;
            } else {
              partContent += " ";
              prevIsSpace = true;
            }
            insertSpacesCount--;
          }
          break;
        }
        case 60:
          partContent += "&lt;";
          prevIsSpace = false;
          break;
        case 62:
          partContent += "&gt;";
          prevIsSpace = false;
          break;
        case 38:
          partContent += "&amp;";
          prevIsSpace = false;
          break;
        case 0:
          partContent += "&#00;";
          prevIsSpace = false;
          break;
        case 65279:
        case 8232:
        case 8233:
        case 133:
          partContent += "�";
          prevIsSpace = false;
          break;
        case 13:
          partContent += "&#8203";
          prevIsSpace = false;
          break;
        case 32:
          if (useNbsp && prevIsSpace) {
            partContent += "&#160;";
            prevIsSpace = false;
          } else {
            partContent += " ";
            prevIsSpace = true;
          }
          break;
        default:
          partContent += String.fromCharCode(charCode);
          prevIsSpace = false;
      }
    }
    result2 += `<span style="${viewLineTokens.getInlineStyle(tokenIndex, colorMap)}">${partContent}</span>`;
    if (tokenEndIndex > endOffset || charIndex >= endOffset) {
      break;
    }
  }
  result2 += `</div>`;
  return result2;
}
function _tokenizeToString(text2, languageIdCodec, tokenizationSupport) {
  let result2 = `<div class="monaco-tokenized-source">`;
  const lines = splitLines(text2);
  let currentState = tokenizationSupport.getInitialState();
  for (let i = 0, len = lines.length; i < len; i++) {
    const line = lines[i];
    if (i > 0) {
      result2 += `<br/>`;
    }
    const tokenizationResult = tokenizationSupport.tokenizeEncoded(line, true, currentState);
    LineTokens.convertToEndOffset(tokenizationResult.tokens, line.length);
    const lineTokens = new LineTokens(tokenizationResult.tokens, line, languageIdCodec);
    const viewLineTokens = lineTokens.inflate();
    let startOffset = 0;
    for (let j = 0, lenJ = viewLineTokens.getCount(); j < lenJ; j++) {
      const type = viewLineTokens.getClassName(j);
      const endIndex = viewLineTokens.getEndOffset(j);
      result2 += `<span class="${type}">${escape$1(line.substring(startOffset, endIndex))}</span>`;
      startOffset = endIndex;
    }
    currentState = tokenizationResult.endState;
  }
  result2 += `</div>`;
  return result2;
}
class PendingChanges {
  constructor() {
    this._hasPending = false;
    this._inserts = [];
    this._changes = [];
    this._removes = [];
  }
  insert(x) {
    this._hasPending = true;
    this._inserts.push(x);
  }
  change(x) {
    this._hasPending = true;
    this._changes.push(x);
  }
  remove(x) {
    this._hasPending = true;
    this._removes.push(x);
  }
  mustCommit() {
    return this._hasPending;
  }
  commit(linesLayout) {
    if (!this._hasPending) {
      return;
    }
    const inserts = this._inserts;
    const changes = this._changes;
    const removes = this._removes;
    this._hasPending = false;
    this._inserts = [];
    this._changes = [];
    this._removes = [];
    linesLayout._commitPendingChanges(inserts, changes, removes);
  }
}
class EditorWhitespace {
  constructor(id3, afterLineNumber, ordinal, height, minWidth) {
    this.id = id3;
    this.afterLineNumber = afterLineNumber;
    this.ordinal = ordinal;
    this.height = height;
    this.minWidth = minWidth;
    this.prefixSum = 0;
  }
}
class LinesLayout {
  constructor(lineCount, lineHeight, paddingTop, paddingBottom) {
    this._instanceId = singleLetterHash(++LinesLayout.INSTANCE_COUNT);
    this._pendingChanges = new PendingChanges();
    this._lastWhitespaceId = 0;
    this._arr = [];
    this._prefixSumValidIndex = -1;
    this._minWidth = -1;
    this._lineCount = lineCount;
    this._lineHeight = lineHeight;
    this._paddingTop = paddingTop;
    this._paddingBottom = paddingBottom;
  }
  /**
   * Find the insertion index for a new value inside a sorted array of values.
   * If the value is already present in the sorted array, the insertion index will be after the already existing value.
   */
  static findInsertionIndex(arr, afterLineNumber, ordinal) {
    let low = 0;
    let high = arr.length;
    while (low < high) {
      const mid = low + high >>> 1;
      if (afterLineNumber === arr[mid].afterLineNumber) {
        if (ordinal < arr[mid].ordinal) {
          high = mid;
        } else {
          low = mid + 1;
        }
      } else if (afterLineNumber < arr[mid].afterLineNumber) {
        high = mid;
      } else {
        low = mid + 1;
      }
    }
    return low;
  }
  /**
   * Change the height of a line in pixels.
   */
  setLineHeight(lineHeight) {
    this._checkPendingChanges();
    this._lineHeight = lineHeight;
  }
  /**
   * Changes the padding used to calculate vertical offsets.
   */
  setPadding(paddingTop, paddingBottom) {
    this._paddingTop = paddingTop;
    this._paddingBottom = paddingBottom;
  }
  /**
   * Set the number of lines.
   *
   * @param lineCount New number of lines.
   */
  onFlushed(lineCount) {
    this._checkPendingChanges();
    this._lineCount = lineCount;
  }
  changeWhitespace(callback) {
    let hadAChange = false;
    try {
      const accessor = {
        insertWhitespace: (afterLineNumber, ordinal, heightInPx, minWidth) => {
          hadAChange = true;
          afterLineNumber = afterLineNumber | 0;
          ordinal = ordinal | 0;
          heightInPx = heightInPx | 0;
          minWidth = minWidth | 0;
          const id3 = this._instanceId + ++this._lastWhitespaceId;
          this._pendingChanges.insert(new EditorWhitespace(id3, afterLineNumber, ordinal, heightInPx, minWidth));
          return id3;
        },
        changeOneWhitespace: (id3, newAfterLineNumber, newHeight) => {
          hadAChange = true;
          newAfterLineNumber = newAfterLineNumber | 0;
          newHeight = newHeight | 0;
          this._pendingChanges.change({ id: id3, newAfterLineNumber, newHeight });
        },
        removeWhitespace: (id3) => {
          hadAChange = true;
          this._pendingChanges.remove({ id: id3 });
        }
      };
      callback(accessor);
    } finally {
      this._pendingChanges.commit(this);
    }
    return hadAChange;
  }
  _commitPendingChanges(inserts, changes, removes) {
    if (inserts.length > 0 || removes.length > 0) {
      this._minWidth = -1;
    }
    if (inserts.length + changes.length + removes.length <= 1) {
      for (const insert2 of inserts) {
        this._insertWhitespace(insert2);
      }
      for (const change of changes) {
        this._changeOneWhitespace(change.id, change.newAfterLineNumber, change.newHeight);
      }
      for (const remove2 of removes) {
        const index = this._findWhitespaceIndex(remove2.id);
        if (index === -1) {
          continue;
        }
        this._removeWhitespace(index);
      }
      return;
    }
    const toRemove = /* @__PURE__ */ new Set();
    for (const remove2 of removes) {
      toRemove.add(remove2.id);
    }
    const toChange = /* @__PURE__ */ new Map();
    for (const change of changes) {
      toChange.set(change.id, change);
    }
    const applyRemoveAndChange = (whitespaces) => {
      const result3 = [];
      for (const whitespace2 of whitespaces) {
        if (toRemove.has(whitespace2.id)) {
          continue;
        }
        if (toChange.has(whitespace2.id)) {
          const change = toChange.get(whitespace2.id);
          whitespace2.afterLineNumber = change.newAfterLineNumber;
          whitespace2.height = change.newHeight;
        }
        result3.push(whitespace2);
      }
      return result3;
    };
    const result2 = applyRemoveAndChange(this._arr).concat(applyRemoveAndChange(inserts));
    result2.sort((a, b) => {
      if (a.afterLineNumber === b.afterLineNumber) {
        return a.ordinal - b.ordinal;
      }
      return a.afterLineNumber - b.afterLineNumber;
    });
    this._arr = result2;
    this._prefixSumValidIndex = -1;
  }
  _checkPendingChanges() {
    if (this._pendingChanges.mustCommit()) {
      this._pendingChanges.commit(this);
    }
  }
  _insertWhitespace(whitespace2) {
    const insertIndex = LinesLayout.findInsertionIndex(this._arr, whitespace2.afterLineNumber, whitespace2.ordinal);
    this._arr.splice(insertIndex, 0, whitespace2);
    this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, insertIndex - 1);
  }
  _findWhitespaceIndex(id3) {
    const arr = this._arr;
    for (let i = 0, len = arr.length; i < len; i++) {
      if (arr[i].id === id3) {
        return i;
      }
    }
    return -1;
  }
  _changeOneWhitespace(id3, newAfterLineNumber, newHeight) {
    const index = this._findWhitespaceIndex(id3);
    if (index === -1) {
      return;
    }
    if (this._arr[index].height !== newHeight) {
      this._arr[index].height = newHeight;
      this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, index - 1);
    }
    if (this._arr[index].afterLineNumber !== newAfterLineNumber) {
      const whitespace2 = this._arr[index];
      this._removeWhitespace(index);
      whitespace2.afterLineNumber = newAfterLineNumber;
      this._insertWhitespace(whitespace2);
    }
  }
  _removeWhitespace(removeIndex) {
    this._arr.splice(removeIndex, 1);
    this._prefixSumValidIndex = Math.min(this._prefixSumValidIndex, removeIndex - 1);
  }
  /**
   * Notify the layouter that lines have been deleted (a continuous zone of lines).
   *
   * @param fromLineNumber The line number at which the deletion started, inclusive
   * @param toLineNumber The line number at which the deletion ended, inclusive
   */
  onLinesDeleted(fromLineNumber, toLineNumber) {
    this._checkPendingChanges();
    fromLineNumber = fromLineNumber | 0;
    toLineNumber = toLineNumber | 0;
    this._lineCount -= toLineNumber - fromLineNumber + 1;
    for (let i = 0, len = this._arr.length; i < len; i++) {
      const afterLineNumber = this._arr[i].afterLineNumber;
      if (fromLineNumber <= afterLineNumber && afterLineNumber <= toLineNumber) {
        this._arr[i].afterLineNumber = fromLineNumber - 1;
      } else if (afterLineNumber > toLineNumber) {
        this._arr[i].afterLineNumber -= toLineNumber - fromLineNumber + 1;
      }
    }
  }
  /**
   * Notify the layouter that lines have been inserted (a continuous zone of lines).
   *
   * @param fromLineNumber The line number at which the insertion started, inclusive
   * @param toLineNumber The line number at which the insertion ended, inclusive.
   */
  onLinesInserted(fromLineNumber, toLineNumber) {
    this._checkPendingChanges();
    fromLineNumber = fromLineNumber | 0;
    toLineNumber = toLineNumber | 0;
    this._lineCount += toLineNumber - fromLineNumber + 1;
    for (let i = 0, len = this._arr.length; i < len; i++) {
      const afterLineNumber = this._arr[i].afterLineNumber;
      if (fromLineNumber <= afterLineNumber) {
        this._arr[i].afterLineNumber += toLineNumber - fromLineNumber + 1;
      }
    }
  }
  /**
   * Get the sum of all the whitespaces.
   */
  getWhitespacesTotalHeight() {
    this._checkPendingChanges();
    if (this._arr.length === 0) {
      return 0;
    }
    return this.getWhitespacesAccumulatedHeight(this._arr.length - 1);
  }
  /**
   * Return the sum of the heights of the whitespaces at [0..index].
   * This includes the whitespace at `index`.
   *
   * @param index The index of the whitespace.
   * @return The sum of the heights of all whitespaces before the one at `index`, including the one at `index`.
   */
  getWhitespacesAccumulatedHeight(index) {
    this._checkPendingChanges();
    index = index | 0;
    let startIndex = Math.max(0, this._prefixSumValidIndex + 1);
    if (startIndex === 0) {
      this._arr[0].prefixSum = this._arr[0].height;
      startIndex++;
    }
    for (let i = startIndex; i <= index; i++) {
      this._arr[i].prefixSum = this._arr[i - 1].prefixSum + this._arr[i].height;
    }
    this._prefixSumValidIndex = Math.max(this._prefixSumValidIndex, index);
    return this._arr[index].prefixSum;
  }
  /**
   * Get the sum of heights for all objects.
   *
   * @return The sum of heights for all objects.
   */
  getLinesTotalHeight() {
    this._checkPendingChanges();
    const linesHeight = this._lineHeight * this._lineCount;
    const whitespacesHeight = this.getWhitespacesTotalHeight();
    return linesHeight + whitespacesHeight + this._paddingTop + this._paddingBottom;
  }
  /**
   * Returns the accumulated height of whitespaces before the given line number.
   *
   * @param lineNumber The line number
   */
  getWhitespaceAccumulatedHeightBeforeLineNumber(lineNumber) {
    this._checkPendingChanges();
    lineNumber = lineNumber | 0;
    const lastWhitespaceBeforeLineNumber = this._findLastWhitespaceBeforeLineNumber(lineNumber);
    if (lastWhitespaceBeforeLineNumber === -1) {
      return 0;
    }
    return this.getWhitespacesAccumulatedHeight(lastWhitespaceBeforeLineNumber);
  }
  _findLastWhitespaceBeforeLineNumber(lineNumber) {
    lineNumber = lineNumber | 0;
    const arr = this._arr;
    let low = 0;
    let high = arr.length - 1;
    while (low <= high) {
      const delta = high - low | 0;
      const halfDelta = delta / 2 | 0;
      const mid = low + halfDelta | 0;
      if (arr[mid].afterLineNumber < lineNumber) {
        if (mid + 1 >= arr.length || arr[mid + 1].afterLineNumber >= lineNumber) {
          return mid;
        } else {
          low = mid + 1 | 0;
        }
      } else {
        high = mid - 1 | 0;
      }
    }
    return -1;
  }
  _findFirstWhitespaceAfterLineNumber(lineNumber) {
    lineNumber = lineNumber | 0;
    const lastWhitespaceBeforeLineNumber = this._findLastWhitespaceBeforeLineNumber(lineNumber);
    const firstWhitespaceAfterLineNumber = lastWhitespaceBeforeLineNumber + 1;
    if (firstWhitespaceAfterLineNumber < this._arr.length) {
      return firstWhitespaceAfterLineNumber;
    }
    return -1;
  }
  /**
   * Find the index of the first whitespace which has `afterLineNumber` >= `lineNumber`.
   * @return The index of the first whitespace with `afterLineNumber` >= `lineNumber` or -1 if no whitespace is found.
   */
  getFirstWhitespaceIndexAfterLineNumber(lineNumber) {
    this._checkPendingChanges();
    lineNumber = lineNumber | 0;
    return this._findFirstWhitespaceAfterLineNumber(lineNumber);
  }
  /**
   * Get the vertical offset (the sum of heights for all objects above) a certain line number.
   *
   * @param lineNumber The line number
   * @return The sum of heights for all objects above `lineNumber`.
   */
  getVerticalOffsetForLineNumber(lineNumber, includeViewZones = false) {
    this._checkPendingChanges();
    lineNumber = lineNumber | 0;
    let previousLinesHeight;
    if (lineNumber > 1) {
      previousLinesHeight = this._lineHeight * (lineNumber - 1);
    } else {
      previousLinesHeight = 0;
    }
    const previousWhitespacesHeight = this.getWhitespaceAccumulatedHeightBeforeLineNumber(lineNumber - (includeViewZones ? 1 : 0));
    return previousLinesHeight + previousWhitespacesHeight + this._paddingTop;
  }
  /**
   * Get the vertical offset (the sum of heights for all objects above) a certain line number.
   *
   * @param lineNumber The line number
   * @return The sum of heights for all objects above `lineNumber`.
   */
  getVerticalOffsetAfterLineNumber(lineNumber, includeViewZones = false) {
    this._checkPendingChanges();
    lineNumber = lineNumber | 0;
    const previousLinesHeight = this._lineHeight * lineNumber;
    const previousWhitespacesHeight = this.getWhitespaceAccumulatedHeightBeforeLineNumber(lineNumber + (includeViewZones ? 1 : 0));
    return previousLinesHeight + previousWhitespacesHeight + this._paddingTop;
  }
  /**
   * The maximum min width for all whitespaces.
   */
  getWhitespaceMinWidth() {
    this._checkPendingChanges();
    if (this._minWidth === -1) {
      let minWidth = 0;
      for (let i = 0, len = this._arr.length; i < len; i++) {
        minWidth = Math.max(minWidth, this._arr[i].minWidth);
      }
      this._minWidth = minWidth;
    }
    return this._minWidth;
  }
  /**
   * Check if `verticalOffset` is below all lines.
   */
  isAfterLines(verticalOffset) {
    this._checkPendingChanges();
    const totalHeight = this.getLinesTotalHeight();
    return verticalOffset > totalHeight;
  }
  isInTopPadding(verticalOffset) {
    if (this._paddingTop === 0) {
      return false;
    }
    this._checkPendingChanges();
    return verticalOffset < this._paddingTop;
  }
  isInBottomPadding(verticalOffset) {
    if (this._paddingBottom === 0) {
      return false;
    }
    this._checkPendingChanges();
    const totalHeight = this.getLinesTotalHeight();
    return verticalOffset >= totalHeight - this._paddingBottom;
  }
  /**
   * Find the first line number that is at or after vertical offset `verticalOffset`.
   * i.e. if getVerticalOffsetForLine(line) is x and getVerticalOffsetForLine(line + 1) is y, then
   * getLineNumberAtOrAfterVerticalOffset(i) = line, x <= i < y.
   *
   * @param verticalOffset The vertical offset to search at.
   * @return The line number at or after vertical offset `verticalOffset`.
   */
  getLineNumberAtOrAfterVerticalOffset(verticalOffset) {
    this._checkPendingChanges();
    verticalOffset = verticalOffset | 0;
    if (verticalOffset < 0) {
      return 1;
    }
    const linesCount = this._lineCount | 0;
    const lineHeight = this._lineHeight;
    let minLineNumber = 1;
    let maxLineNumber = linesCount;
    while (minLineNumber < maxLineNumber) {
      const midLineNumber = (minLineNumber + maxLineNumber) / 2 | 0;
      const midLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(midLineNumber) | 0;
      if (verticalOffset >= midLineNumberVerticalOffset + lineHeight) {
        minLineNumber = midLineNumber + 1;
      } else if (verticalOffset >= midLineNumberVerticalOffset) {
        return midLineNumber;
      } else {
        maxLineNumber = midLineNumber;
      }
    }
    if (minLineNumber > linesCount) {
      return linesCount;
    }
    return minLineNumber;
  }
  /**
   * Get all the lines and their relative vertical offsets that are positioned between `verticalOffset1` and `verticalOffset2`.
   *
   * @param verticalOffset1 The beginning of the viewport.
   * @param verticalOffset2 The end of the viewport.
   * @return A structure describing the lines positioned between `verticalOffset1` and `verticalOffset2`.
   */
  getLinesViewportData(verticalOffset1, verticalOffset2) {
    this._checkPendingChanges();
    verticalOffset1 = verticalOffset1 | 0;
    verticalOffset2 = verticalOffset2 | 0;
    const lineHeight = this._lineHeight;
    const startLineNumber = this.getLineNumberAtOrAfterVerticalOffset(verticalOffset1) | 0;
    const startLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(startLineNumber) | 0;
    let endLineNumber = this._lineCount | 0;
    let whitespaceIndex = this.getFirstWhitespaceIndexAfterLineNumber(startLineNumber) | 0;
    const whitespaceCount = this.getWhitespacesCount() | 0;
    let currentWhitespaceHeight;
    let currentWhitespaceAfterLineNumber;
    if (whitespaceIndex === -1) {
      whitespaceIndex = whitespaceCount;
      currentWhitespaceAfterLineNumber = endLineNumber + 1;
      currentWhitespaceHeight = 0;
    } else {
      currentWhitespaceAfterLineNumber = this.getAfterLineNumberForWhitespaceIndex(whitespaceIndex) | 0;
      currentWhitespaceHeight = this.getHeightForWhitespaceIndex(whitespaceIndex) | 0;
    }
    let currentVerticalOffset = startLineNumberVerticalOffset;
    let currentLineRelativeOffset = currentVerticalOffset;
    const STEP_SIZE = 5e5;
    let bigNumbersDelta = 0;
    if (startLineNumberVerticalOffset >= STEP_SIZE) {
      bigNumbersDelta = Math.floor(startLineNumberVerticalOffset / STEP_SIZE) * STEP_SIZE;
      bigNumbersDelta = Math.floor(bigNumbersDelta / lineHeight) * lineHeight;
      currentLineRelativeOffset -= bigNumbersDelta;
    }
    const linesOffsets = [];
    const verticalCenter = verticalOffset1 + (verticalOffset2 - verticalOffset1) / 2;
    let centeredLineNumber = -1;
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      if (centeredLineNumber === -1) {
        const currentLineTop = currentVerticalOffset;
        const currentLineBottom = currentVerticalOffset + lineHeight;
        if (currentLineTop <= verticalCenter && verticalCenter < currentLineBottom || currentLineTop > verticalCenter) {
          centeredLineNumber = lineNumber;
        }
      }
      currentVerticalOffset += lineHeight;
      linesOffsets[lineNumber - startLineNumber] = currentLineRelativeOffset;
      currentLineRelativeOffset += lineHeight;
      while (currentWhitespaceAfterLineNumber === lineNumber) {
        currentLineRelativeOffset += currentWhitespaceHeight;
        currentVerticalOffset += currentWhitespaceHeight;
        whitespaceIndex++;
        if (whitespaceIndex >= whitespaceCount) {
          currentWhitespaceAfterLineNumber = endLineNumber + 1;
        } else {
          currentWhitespaceAfterLineNumber = this.getAfterLineNumberForWhitespaceIndex(whitespaceIndex) | 0;
          currentWhitespaceHeight = this.getHeightForWhitespaceIndex(whitespaceIndex) | 0;
        }
      }
      if (currentVerticalOffset >= verticalOffset2) {
        endLineNumber = lineNumber;
        break;
      }
    }
    if (centeredLineNumber === -1) {
      centeredLineNumber = endLineNumber;
    }
    const endLineNumberVerticalOffset = this.getVerticalOffsetForLineNumber(endLineNumber) | 0;
    let completelyVisibleStartLineNumber = startLineNumber;
    let completelyVisibleEndLineNumber = endLineNumber;
    if (completelyVisibleStartLineNumber < completelyVisibleEndLineNumber) {
      if (startLineNumberVerticalOffset < verticalOffset1) {
        completelyVisibleStartLineNumber++;
      }
    }
    if (completelyVisibleStartLineNumber < completelyVisibleEndLineNumber) {
      if (endLineNumberVerticalOffset + lineHeight > verticalOffset2) {
        completelyVisibleEndLineNumber--;
      }
    }
    return {
      bigNumbersDelta,
      startLineNumber,
      endLineNumber,
      relativeVerticalOffset: linesOffsets,
      centeredLineNumber,
      completelyVisibleStartLineNumber,
      completelyVisibleEndLineNumber
    };
  }
  getVerticalOffsetForWhitespaceIndex(whitespaceIndex) {
    this._checkPendingChanges();
    whitespaceIndex = whitespaceIndex | 0;
    const afterLineNumber = this.getAfterLineNumberForWhitespaceIndex(whitespaceIndex);
    let previousLinesHeight;
    if (afterLineNumber >= 1) {
      previousLinesHeight = this._lineHeight * afterLineNumber;
    } else {
      previousLinesHeight = 0;
    }
    let previousWhitespacesHeight;
    if (whitespaceIndex > 0) {
      previousWhitespacesHeight = this.getWhitespacesAccumulatedHeight(whitespaceIndex - 1);
    } else {
      previousWhitespacesHeight = 0;
    }
    return previousLinesHeight + previousWhitespacesHeight + this._paddingTop;
  }
  getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset) {
    this._checkPendingChanges();
    verticalOffset = verticalOffset | 0;
    let minWhitespaceIndex = 0;
    let maxWhitespaceIndex = this.getWhitespacesCount() - 1;
    if (maxWhitespaceIndex < 0) {
      return -1;
    }
    const maxWhitespaceVerticalOffset = this.getVerticalOffsetForWhitespaceIndex(maxWhitespaceIndex);
    const maxWhitespaceHeight = this.getHeightForWhitespaceIndex(maxWhitespaceIndex);
    if (verticalOffset >= maxWhitespaceVerticalOffset + maxWhitespaceHeight) {
      return -1;
    }
    while (minWhitespaceIndex < maxWhitespaceIndex) {
      const midWhitespaceIndex = Math.floor((minWhitespaceIndex + maxWhitespaceIndex) / 2);
      const midWhitespaceVerticalOffset = this.getVerticalOffsetForWhitespaceIndex(midWhitespaceIndex);
      const midWhitespaceHeight = this.getHeightForWhitespaceIndex(midWhitespaceIndex);
      if (verticalOffset >= midWhitespaceVerticalOffset + midWhitespaceHeight) {
        minWhitespaceIndex = midWhitespaceIndex + 1;
      } else if (verticalOffset >= midWhitespaceVerticalOffset) {
        return midWhitespaceIndex;
      } else {
        maxWhitespaceIndex = midWhitespaceIndex;
      }
    }
    return minWhitespaceIndex;
  }
  /**
   * Get exactly the whitespace that is layouted at `verticalOffset`.
   *
   * @param verticalOffset The vertical offset.
   * @return Precisely the whitespace that is layouted at `verticaloffset` or null.
   */
  getWhitespaceAtVerticalOffset(verticalOffset) {
    this._checkPendingChanges();
    verticalOffset = verticalOffset | 0;
    const candidateIndex = this.getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset);
    if (candidateIndex < 0) {
      return null;
    }
    if (candidateIndex >= this.getWhitespacesCount()) {
      return null;
    }
    const candidateTop = this.getVerticalOffsetForWhitespaceIndex(candidateIndex);
    if (candidateTop > verticalOffset) {
      return null;
    }
    const candidateHeight = this.getHeightForWhitespaceIndex(candidateIndex);
    const candidateId = this.getIdForWhitespaceIndex(candidateIndex);
    const candidateAfterLineNumber = this.getAfterLineNumberForWhitespaceIndex(candidateIndex);
    return {
      id: candidateId,
      afterLineNumber: candidateAfterLineNumber,
      verticalOffset: candidateTop,
      height: candidateHeight
    };
  }
  /**
   * Get a list of whitespaces that are positioned between `verticalOffset1` and `verticalOffset2`.
   *
   * @param verticalOffset1 The beginning of the viewport.
   * @param verticalOffset2 The end of the viewport.
   * @return An array with all the whitespaces in the viewport. If no whitespace is in viewport, the array is empty.
   */
  getWhitespaceViewportData(verticalOffset1, verticalOffset2) {
    this._checkPendingChanges();
    verticalOffset1 = verticalOffset1 | 0;
    verticalOffset2 = verticalOffset2 | 0;
    const startIndex = this.getWhitespaceIndexAtOrAfterVerticallOffset(verticalOffset1);
    const endIndex = this.getWhitespacesCount() - 1;
    if (startIndex < 0) {
      return [];
    }
    const result2 = [];
    for (let i = startIndex; i <= endIndex; i++) {
      const top = this.getVerticalOffsetForWhitespaceIndex(i);
      const height = this.getHeightForWhitespaceIndex(i);
      if (top >= verticalOffset2) {
        break;
      }
      result2.push({
        id: this.getIdForWhitespaceIndex(i),
        afterLineNumber: this.getAfterLineNumberForWhitespaceIndex(i),
        verticalOffset: top,
        height
      });
    }
    return result2;
  }
  /**
   * Get all whitespaces.
   */
  getWhitespaces() {
    this._checkPendingChanges();
    return this._arr.slice(0);
  }
  /**
   * The number of whitespaces.
   */
  getWhitespacesCount() {
    this._checkPendingChanges();
    return this._arr.length;
  }
  /**
   * Get the `id` for whitespace at index `index`.
   *
   * @param index The index of the whitespace.
   * @return `id` of whitespace at `index`.
   */
  getIdForWhitespaceIndex(index) {
    this._checkPendingChanges();
    index = index | 0;
    return this._arr[index].id;
  }
  /**
   * Get the `afterLineNumber` for whitespace at index `index`.
   *
   * @param index The index of the whitespace.
   * @return `afterLineNumber` of whitespace at `index`.
   */
  getAfterLineNumberForWhitespaceIndex(index) {
    this._checkPendingChanges();
    index = index | 0;
    return this._arr[index].afterLineNumber;
  }
  /**
   * Get the `height` for whitespace at index `index`.
   *
   * @param index The index of the whitespace.
   * @return `height` of whitespace at `index`.
   */
  getHeightForWhitespaceIndex(index) {
    this._checkPendingChanges();
    index = index | 0;
    return this._arr[index].height;
  }
}
LinesLayout.INSTANCE_COUNT = 0;
const SMOOTH_SCROLLING_TIME = 125;
class EditorScrollDimensions {
  constructor(width, contentWidth, height, contentHeight) {
    width = width | 0;
    contentWidth = contentWidth | 0;
    height = height | 0;
    contentHeight = contentHeight | 0;
    if (width < 0) {
      width = 0;
    }
    if (contentWidth < 0) {
      contentWidth = 0;
    }
    if (height < 0) {
      height = 0;
    }
    if (contentHeight < 0) {
      contentHeight = 0;
    }
    this.width = width;
    this.contentWidth = contentWidth;
    this.scrollWidth = Math.max(width, contentWidth);
    this.height = height;
    this.contentHeight = contentHeight;
    this.scrollHeight = Math.max(height, contentHeight);
  }
  equals(other) {
    return this.width === other.width && this.contentWidth === other.contentWidth && this.height === other.height && this.contentHeight === other.contentHeight;
  }
}
class EditorScrollable extends Disposable {
  constructor(smoothScrollDuration, scheduleAtNextAnimationFrame2) {
    super();
    this._onDidContentSizeChange = this._register(new Emitter$1());
    this.onDidContentSizeChange = this._onDidContentSizeChange.event;
    this._dimensions = new EditorScrollDimensions(0, 0, 0, 0);
    this._scrollable = this._register(new Scrollable({
      forceIntegerValues: true,
      smoothScrollDuration,
      scheduleAtNextAnimationFrame: scheduleAtNextAnimationFrame2
    }));
    this.onDidScroll = this._scrollable.onScroll;
  }
  getScrollable() {
    return this._scrollable;
  }
  setSmoothScrollDuration(smoothScrollDuration) {
    this._scrollable.setSmoothScrollDuration(smoothScrollDuration);
  }
  validateScrollPosition(scrollPosition) {
    return this._scrollable.validateScrollPosition(scrollPosition);
  }
  getScrollDimensions() {
    return this._dimensions;
  }
  setScrollDimensions(dimensions) {
    if (this._dimensions.equals(dimensions)) {
      return;
    }
    const oldDimensions = this._dimensions;
    this._dimensions = dimensions;
    this._scrollable.setScrollDimensions({
      width: dimensions.width,
      scrollWidth: dimensions.scrollWidth,
      height: dimensions.height,
      scrollHeight: dimensions.scrollHeight
    }, true);
    const contentWidthChanged = oldDimensions.contentWidth !== dimensions.contentWidth;
    const contentHeightChanged = oldDimensions.contentHeight !== dimensions.contentHeight;
    if (contentWidthChanged || contentHeightChanged) {
      this._onDidContentSizeChange.fire(new ContentSizeChangedEvent(oldDimensions.contentWidth, oldDimensions.contentHeight, dimensions.contentWidth, dimensions.contentHeight));
    }
  }
  getFutureScrollPosition() {
    return this._scrollable.getFutureScrollPosition();
  }
  getCurrentScrollPosition() {
    return this._scrollable.getCurrentScrollPosition();
  }
  setScrollPositionNow(update) {
    this._scrollable.setScrollPositionNow(update);
  }
  setScrollPositionSmooth(update) {
    this._scrollable.setScrollPositionSmooth(update);
  }
  hasPendingScrollAnimation() {
    return this._scrollable.hasPendingScrollAnimation();
  }
}
class ViewLayout extends Disposable {
  constructor(configuration, lineCount, scheduleAtNextAnimationFrame2) {
    super();
    this._configuration = configuration;
    const options = this._configuration.options;
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    const padding = options.get(
      82
      /* EditorOption.padding */
    );
    this._linesLayout = new LinesLayout(lineCount, options.get(
      65
      /* EditorOption.lineHeight */
    ), padding.top, padding.bottom);
    this._scrollable = this._register(new EditorScrollable(0, scheduleAtNextAnimationFrame2));
    this._configureSmoothScrollDuration();
    this._scrollable.setScrollDimensions(new EditorScrollDimensions(layoutInfo.contentWidth, 0, layoutInfo.height, 0));
    this.onDidScroll = this._scrollable.onDidScroll;
    this.onDidContentSizeChange = this._scrollable.onDidContentSizeChange;
    this._updateHeight();
  }
  dispose() {
    super.dispose();
  }
  getScrollable() {
    return this._scrollable.getScrollable();
  }
  onHeightMaybeChanged() {
    this._updateHeight();
  }
  _configureSmoothScrollDuration() {
    this._scrollable.setSmoothScrollDuration(this._configuration.options.get(
      112
      /* EditorOption.smoothScrolling */
    ) ? SMOOTH_SCROLLING_TIME : 0);
  }
  // ---- begin view event handlers
  onConfigurationChanged(e) {
    const options = this._configuration.options;
    if (e.hasChanged(
      65
      /* EditorOption.lineHeight */
    )) {
      this._linesLayout.setLineHeight(options.get(
        65
        /* EditorOption.lineHeight */
      ));
    }
    if (e.hasChanged(
      82
      /* EditorOption.padding */
    )) {
      const padding = options.get(
        82
        /* EditorOption.padding */
      );
      this._linesLayout.setPadding(padding.top, padding.bottom);
    }
    if (e.hasChanged(
      142
      /* EditorOption.layoutInfo */
    )) {
      const layoutInfo = options.get(
        142
        /* EditorOption.layoutInfo */
      );
      const width = layoutInfo.contentWidth;
      const height = layoutInfo.height;
      const scrollDimensions = this._scrollable.getScrollDimensions();
      const contentWidth = scrollDimensions.contentWidth;
      this._scrollable.setScrollDimensions(new EditorScrollDimensions(width, scrollDimensions.contentWidth, height, this._getContentHeight(width, height, contentWidth)));
    } else {
      this._updateHeight();
    }
    if (e.hasChanged(
      112
      /* EditorOption.smoothScrolling */
    )) {
      this._configureSmoothScrollDuration();
    }
  }
  onFlushed(lineCount) {
    this._linesLayout.onFlushed(lineCount);
  }
  onLinesDeleted(fromLineNumber, toLineNumber) {
    this._linesLayout.onLinesDeleted(fromLineNumber, toLineNumber);
  }
  onLinesInserted(fromLineNumber, toLineNumber) {
    this._linesLayout.onLinesInserted(fromLineNumber, toLineNumber);
  }
  // ---- end view event handlers
  _getHorizontalScrollbarHeight(width, scrollWidth) {
    const options = this._configuration.options;
    const scrollbar = options.get(
      101
      /* EditorOption.scrollbar */
    );
    if (scrollbar.horizontal === 2) {
      return 0;
    }
    if (width >= scrollWidth) {
      return 0;
    }
    return scrollbar.horizontalScrollbarSize;
  }
  _getContentHeight(width, height, contentWidth) {
    const options = this._configuration.options;
    let result2 = this._linesLayout.getLinesTotalHeight();
    if (options.get(
      103
      /* EditorOption.scrollBeyondLastLine */
    )) {
      result2 += Math.max(0, height - options.get(
        65
        /* EditorOption.lineHeight */
      ) - options.get(
        82
        /* EditorOption.padding */
      ).bottom);
    } else {
      result2 += this._getHorizontalScrollbarHeight(width, contentWidth);
    }
    return result2;
  }
  _updateHeight() {
    const scrollDimensions = this._scrollable.getScrollDimensions();
    const width = scrollDimensions.width;
    const height = scrollDimensions.height;
    const contentWidth = scrollDimensions.contentWidth;
    this._scrollable.setScrollDimensions(new EditorScrollDimensions(width, scrollDimensions.contentWidth, height, this._getContentHeight(width, height, contentWidth)));
  }
  // ---- Layouting logic
  getCurrentViewport() {
    const scrollDimensions = this._scrollable.getScrollDimensions();
    const currentScrollPosition = this._scrollable.getCurrentScrollPosition();
    return new Viewport(currentScrollPosition.scrollTop, currentScrollPosition.scrollLeft, scrollDimensions.width, scrollDimensions.height);
  }
  getFutureViewport() {
    const scrollDimensions = this._scrollable.getScrollDimensions();
    const currentScrollPosition = this._scrollable.getFutureScrollPosition();
    return new Viewport(currentScrollPosition.scrollTop, currentScrollPosition.scrollLeft, scrollDimensions.width, scrollDimensions.height);
  }
  _computeContentWidth(maxLineWidth) {
    const options = this._configuration.options;
    const wrappingInfo = options.get(
      143
      /* EditorOption.wrappingInfo */
    );
    const fontInfo = options.get(
      49
      /* EditorOption.fontInfo */
    );
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    if (wrappingInfo.isViewportWrapping) {
      const minimap2 = options.get(
        71
        /* EditorOption.minimap */
      );
      if (maxLineWidth > layoutInfo.contentWidth + fontInfo.typicalHalfwidthCharacterWidth) {
        if (minimap2.enabled && minimap2.side === "right") {
          return maxLineWidth + layoutInfo.verticalScrollbarWidth;
        }
      }
      return maxLineWidth;
    } else {
      const extraHorizontalSpace = options.get(
        102
        /* EditorOption.scrollBeyondLastColumn */
      ) * fontInfo.typicalHalfwidthCharacterWidth;
      const whitespaceMinWidth = this._linesLayout.getWhitespaceMinWidth();
      return Math.max(maxLineWidth + extraHorizontalSpace + layoutInfo.verticalScrollbarWidth, whitespaceMinWidth);
    }
  }
  setMaxLineWidth(maxLineWidth) {
    const scrollDimensions = this._scrollable.getScrollDimensions();
    this._scrollable.setScrollDimensions(new EditorScrollDimensions(scrollDimensions.width, this._computeContentWidth(maxLineWidth), scrollDimensions.height, scrollDimensions.contentHeight));
    this._updateHeight();
  }
  // ---- view state
  saveState() {
    const currentScrollPosition = this._scrollable.getFutureScrollPosition();
    const scrollTop = currentScrollPosition.scrollTop;
    const firstLineNumberInViewport = this._linesLayout.getLineNumberAtOrAfterVerticalOffset(scrollTop);
    const whitespaceAboveFirstLine = this._linesLayout.getWhitespaceAccumulatedHeightBeforeLineNumber(firstLineNumberInViewport);
    return {
      scrollTop,
      scrollTopWithoutViewZones: scrollTop - whitespaceAboveFirstLine,
      scrollLeft: currentScrollPosition.scrollLeft
    };
  }
  // ----
  changeWhitespace(callback) {
    const hadAChange = this._linesLayout.changeWhitespace(callback);
    if (hadAChange) {
      this.onHeightMaybeChanged();
    }
    return hadAChange;
  }
  getVerticalOffsetForLineNumber(lineNumber, includeViewZones = false) {
    return this._linesLayout.getVerticalOffsetForLineNumber(lineNumber, includeViewZones);
  }
  getVerticalOffsetAfterLineNumber(lineNumber, includeViewZones = false) {
    return this._linesLayout.getVerticalOffsetAfterLineNumber(lineNumber, includeViewZones);
  }
  isAfterLines(verticalOffset) {
    return this._linesLayout.isAfterLines(verticalOffset);
  }
  isInTopPadding(verticalOffset) {
    return this._linesLayout.isInTopPadding(verticalOffset);
  }
  isInBottomPadding(verticalOffset) {
    return this._linesLayout.isInBottomPadding(verticalOffset);
  }
  getLineNumberAtVerticalOffset(verticalOffset) {
    return this._linesLayout.getLineNumberAtOrAfterVerticalOffset(verticalOffset);
  }
  getWhitespaceAtVerticalOffset(verticalOffset) {
    return this._linesLayout.getWhitespaceAtVerticalOffset(verticalOffset);
  }
  getLinesViewportData() {
    const visibleBox = this.getCurrentViewport();
    return this._linesLayout.getLinesViewportData(visibleBox.top, visibleBox.top + visibleBox.height);
  }
  getLinesViewportDataAtScrollTop(scrollTop) {
    const scrollDimensions = this._scrollable.getScrollDimensions();
    if (scrollTop + scrollDimensions.height > scrollDimensions.scrollHeight) {
      scrollTop = scrollDimensions.scrollHeight - scrollDimensions.height;
    }
    if (scrollTop < 0) {
      scrollTop = 0;
    }
    return this._linesLayout.getLinesViewportData(scrollTop, scrollTop + scrollDimensions.height);
  }
  getWhitespaceViewportData() {
    const visibleBox = this.getCurrentViewport();
    return this._linesLayout.getWhitespaceViewportData(visibleBox.top, visibleBox.top + visibleBox.height);
  }
  getWhitespaces() {
    return this._linesLayout.getWhitespaces();
  }
  // ----
  getContentWidth() {
    const scrollDimensions = this._scrollable.getScrollDimensions();
    return scrollDimensions.contentWidth;
  }
  getScrollWidth() {
    const scrollDimensions = this._scrollable.getScrollDimensions();
    return scrollDimensions.scrollWidth;
  }
  getContentHeight() {
    const scrollDimensions = this._scrollable.getScrollDimensions();
    return scrollDimensions.contentHeight;
  }
  getScrollHeight() {
    const scrollDimensions = this._scrollable.getScrollDimensions();
    return scrollDimensions.scrollHeight;
  }
  getCurrentScrollLeft() {
    const currentScrollPosition = this._scrollable.getCurrentScrollPosition();
    return currentScrollPosition.scrollLeft;
  }
  getCurrentScrollTop() {
    const currentScrollPosition = this._scrollable.getCurrentScrollPosition();
    return currentScrollPosition.scrollTop;
  }
  validateScrollPosition(scrollPosition) {
    return this._scrollable.validateScrollPosition(scrollPosition);
  }
  setScrollPosition(position, type) {
    if (type === 1) {
      this._scrollable.setScrollPositionNow(position);
    } else {
      this._scrollable.setScrollPositionSmooth(position);
    }
  }
  hasPendingScrollAnimation() {
    return this._scrollable.hasPendingScrollAnimation();
  }
  deltaScrollNow(deltaScrollLeft, deltaScrollTop) {
    const currentScrollPosition = this._scrollable.getCurrentScrollPosition();
    this._scrollable.setScrollPositionNow({
      scrollLeft: currentScrollPosition.scrollLeft + deltaScrollLeft,
      scrollTop: currentScrollPosition.scrollTop + deltaScrollTop
    });
  }
}
class ViewModelDecorations {
  constructor(editorId, model, configuration, linesCollection, coordinatesConverter) {
    this.editorId = editorId;
    this.model = model;
    this.configuration = configuration;
    this._linesCollection = linesCollection;
    this._coordinatesConverter = coordinatesConverter;
    this._decorationsCache = /* @__PURE__ */ Object.create(null);
    this._cachedModelDecorationsResolver = null;
    this._cachedModelDecorationsResolverViewRange = null;
  }
  _clearCachedModelDecorationsResolver() {
    this._cachedModelDecorationsResolver = null;
    this._cachedModelDecorationsResolverViewRange = null;
  }
  dispose() {
    this._decorationsCache = /* @__PURE__ */ Object.create(null);
    this._clearCachedModelDecorationsResolver();
  }
  reset() {
    this._decorationsCache = /* @__PURE__ */ Object.create(null);
    this._clearCachedModelDecorationsResolver();
  }
  onModelDecorationsChanged() {
    this._decorationsCache = /* @__PURE__ */ Object.create(null);
    this._clearCachedModelDecorationsResolver();
  }
  onLineMappingChanged() {
    this._decorationsCache = /* @__PURE__ */ Object.create(null);
    this._clearCachedModelDecorationsResolver();
  }
  _getOrCreateViewModelDecoration(modelDecoration) {
    const id3 = modelDecoration.id;
    let r = this._decorationsCache[id3];
    if (!r) {
      const modelRange = modelDecoration.range;
      const options = modelDecoration.options;
      let viewRange;
      if (options.isWholeLine) {
        const start = this._coordinatesConverter.convertModelPositionToViewPosition(new Position$2(modelRange.startLineNumber, 1), 0, false, true);
        const end = this._coordinatesConverter.convertModelPositionToViewPosition(
          new Position$2(modelRange.endLineNumber, this.model.getLineMaxColumn(modelRange.endLineNumber)),
          1
          /* PositionAffinity.Right */
        );
        viewRange = new Range$2(start.lineNumber, start.column, end.lineNumber, end.column);
      } else {
        viewRange = this._coordinatesConverter.convertModelRangeToViewRange(
          modelRange,
          1
          /* PositionAffinity.Right */
        );
      }
      r = new ViewModelDecoration(viewRange, options);
      this._decorationsCache[id3] = r;
    }
    return r;
  }
  getMinimapDecorationsInRange(range2) {
    return this._getDecorationsInRange(range2, true, false).decorations;
  }
  getDecorationsViewportData(viewRange) {
    let cacheIsValid = this._cachedModelDecorationsResolver !== null;
    cacheIsValid = cacheIsValid && viewRange.equalsRange(this._cachedModelDecorationsResolverViewRange);
    if (!cacheIsValid) {
      this._cachedModelDecorationsResolver = this._getDecorationsInRange(viewRange, false, false);
      this._cachedModelDecorationsResolverViewRange = viewRange;
    }
    return this._cachedModelDecorationsResolver;
  }
  getInlineDecorationsOnLine(lineNumber, onlyMinimapDecorations = false, onlyMarginDecorations = false) {
    const range2 = new Range$2(lineNumber, this._linesCollection.getViewLineMinColumn(lineNumber), lineNumber, this._linesCollection.getViewLineMaxColumn(lineNumber));
    return this._getDecorationsInRange(range2, onlyMinimapDecorations, onlyMarginDecorations).inlineDecorations[0];
  }
  _getDecorationsInRange(viewRange, onlyMinimapDecorations, onlyMarginDecorations) {
    const modelDecorations = this._linesCollection.getDecorationsInRange(viewRange, this.editorId, filterValidationDecorations(this.configuration.options), onlyMinimapDecorations, onlyMarginDecorations);
    const startLineNumber = viewRange.startLineNumber;
    const endLineNumber = viewRange.endLineNumber;
    const decorationsInViewport = [];
    let decorationsInViewportLen = 0;
    const inlineDecorations = [];
    for (let j = startLineNumber; j <= endLineNumber; j++) {
      inlineDecorations[j - startLineNumber] = [];
    }
    for (let i = 0, len = modelDecorations.length; i < len; i++) {
      const modelDecoration = modelDecorations[i];
      const decorationOptions = modelDecoration.options;
      if (!isModelDecorationVisible(this.model, modelDecoration)) {
        continue;
      }
      const viewModelDecoration = this._getOrCreateViewModelDecoration(modelDecoration);
      const viewRange2 = viewModelDecoration.range;
      decorationsInViewport[decorationsInViewportLen++] = viewModelDecoration;
      if (decorationOptions.inlineClassName) {
        const inlineDecoration = new InlineDecoration(
          viewRange2,
          decorationOptions.inlineClassName,
          decorationOptions.inlineClassNameAffectsLetterSpacing ? 3 : 0
          /* InlineDecorationType.Regular */
        );
        const intersectedStartLineNumber = Math.max(startLineNumber, viewRange2.startLineNumber);
        const intersectedEndLineNumber = Math.min(endLineNumber, viewRange2.endLineNumber);
        for (let j = intersectedStartLineNumber; j <= intersectedEndLineNumber; j++) {
          inlineDecorations[j - startLineNumber].push(inlineDecoration);
        }
      }
      if (decorationOptions.beforeContentClassName) {
        if (startLineNumber <= viewRange2.startLineNumber && viewRange2.startLineNumber <= endLineNumber) {
          const inlineDecoration = new InlineDecoration(
            new Range$2(viewRange2.startLineNumber, viewRange2.startColumn, viewRange2.startLineNumber, viewRange2.startColumn),
            decorationOptions.beforeContentClassName,
            1
            /* InlineDecorationType.Before */
          );
          inlineDecorations[viewRange2.startLineNumber - startLineNumber].push(inlineDecoration);
        }
      }
      if (decorationOptions.afterContentClassName) {
        if (startLineNumber <= viewRange2.endLineNumber && viewRange2.endLineNumber <= endLineNumber) {
          const inlineDecoration = new InlineDecoration(
            new Range$2(viewRange2.endLineNumber, viewRange2.endColumn, viewRange2.endLineNumber, viewRange2.endColumn),
            decorationOptions.afterContentClassName,
            2
            /* InlineDecorationType.After */
          );
          inlineDecorations[viewRange2.endLineNumber - startLineNumber].push(inlineDecoration);
        }
      }
    }
    return {
      decorations: decorationsInViewport,
      inlineDecorations
    };
  }
}
function isModelDecorationVisible(model, decoration2) {
  if (decoration2.options.hideInCommentTokens && isModelDecorationInComment(model, decoration2)) {
    return false;
  }
  if (decoration2.options.hideInStringTokens && isModelDecorationInString(model, decoration2)) {
    return false;
  }
  return true;
}
function isModelDecorationInComment(model, decoration2) {
  return testTokensInRange(
    model,
    decoration2.range,
    (tokenType) => tokenType === 1
    /* StandardTokenType.Comment */
  );
}
function isModelDecorationInString(model, decoration2) {
  return testTokensInRange(
    model,
    decoration2.range,
    (tokenType) => tokenType === 2
    /* StandardTokenType.String */
  );
}
function testTokensInRange(model, range2, callback) {
  for (let lineNumber = range2.startLineNumber; lineNumber <= range2.endLineNumber; lineNumber++) {
    const lineTokens = model.tokenization.getLineTokens(lineNumber);
    const isFirstLine = lineNumber === range2.startLineNumber;
    const isEndLine = lineNumber === range2.endLineNumber;
    let tokenIdx = isFirstLine ? lineTokens.findTokenIndexAtOffset(range2.startColumn - 1) : 0;
    while (tokenIdx < lineTokens.getCount()) {
      if (isEndLine) {
        const startOffset = lineTokens.getStartOffset(tokenIdx);
        if (startOffset > range2.endColumn - 1) {
          break;
        }
      }
      const callbackResult = callback(lineTokens.getStandardTokenType(tokenIdx));
      if (!callbackResult) {
        return false;
      }
      tokenIdx++;
    }
  }
  return true;
}
function createModelLineProjection(lineBreakData, isVisible) {
  if (lineBreakData === null) {
    if (isVisible) {
      return IdentityModelLineProjection.INSTANCE;
    }
    return HiddenModelLineProjection.INSTANCE;
  } else {
    return new ModelLineProjection(lineBreakData, isVisible);
  }
}
class ModelLineProjection {
  constructor(lineBreakData, isVisible) {
    this._projectionData = lineBreakData;
    this._isVisible = isVisible;
  }
  isVisible() {
    return this._isVisible;
  }
  setVisible(isVisible) {
    this._isVisible = isVisible;
    return this;
  }
  getProjectionData() {
    return this._projectionData;
  }
  getViewLineCount() {
    if (!this._isVisible) {
      return 0;
    }
    return this._projectionData.getOutputLineCount();
  }
  getViewLineContent(model, modelLineNumber, outputLineIndex) {
    this._assertVisible();
    const startOffsetInInputWithInjections = outputLineIndex > 0 ? this._projectionData.breakOffsets[outputLineIndex - 1] : 0;
    const endOffsetInInputWithInjections = this._projectionData.breakOffsets[outputLineIndex];
    let r;
    if (this._projectionData.injectionOffsets !== null) {
      const injectedTexts = this._projectionData.injectionOffsets.map((offset, idx) => new LineInjectedText(0, 0, offset + 1, this._projectionData.injectionOptions[idx], 0));
      const lineWithInjections = LineInjectedText.applyInjectedText(model.getLineContent(modelLineNumber), injectedTexts);
      r = lineWithInjections.substring(startOffsetInInputWithInjections, endOffsetInInputWithInjections);
    } else {
      r = model.getValueInRange({
        startLineNumber: modelLineNumber,
        startColumn: startOffsetInInputWithInjections + 1,
        endLineNumber: modelLineNumber,
        endColumn: endOffsetInInputWithInjections + 1
      });
    }
    if (outputLineIndex > 0) {
      r = spaces(this._projectionData.wrappedTextIndentLength) + r;
    }
    return r;
  }
  getViewLineLength(model, modelLineNumber, outputLineIndex) {
    this._assertVisible();
    return this._projectionData.getLineLength(outputLineIndex);
  }
  getViewLineMinColumn(_model, _modelLineNumber, outputLineIndex) {
    this._assertVisible();
    return this._projectionData.getMinOutputOffset(outputLineIndex) + 1;
  }
  getViewLineMaxColumn(model, modelLineNumber, outputLineIndex) {
    this._assertVisible();
    return this._projectionData.getMaxOutputOffset(outputLineIndex) + 1;
  }
  /**
   * Try using {@link getViewLinesData} instead.
  */
  getViewLineData(model, modelLineNumber, outputLineIndex) {
    const arr = new Array();
    this.getViewLinesData(model, modelLineNumber, outputLineIndex, 1, 0, [true], arr);
    return arr[0];
  }
  getViewLinesData(model, modelLineNumber, outputLineIdx, lineCount, globalStartIndex, needed, result2) {
    this._assertVisible();
    const lineBreakData = this._projectionData;
    const injectionOffsets = lineBreakData.injectionOffsets;
    const injectionOptions = lineBreakData.injectionOptions;
    let inlineDecorationsPerOutputLine = null;
    if (injectionOffsets) {
      inlineDecorationsPerOutputLine = [];
      let totalInjectedTextLengthBefore = 0;
      let currentInjectedOffset = 0;
      for (let outputLineIndex = 0; outputLineIndex < lineBreakData.getOutputLineCount(); outputLineIndex++) {
        const inlineDecorations = new Array();
        inlineDecorationsPerOutputLine[outputLineIndex] = inlineDecorations;
        const lineStartOffsetInInputWithInjections = outputLineIndex > 0 ? lineBreakData.breakOffsets[outputLineIndex - 1] : 0;
        const lineEndOffsetInInputWithInjections = lineBreakData.breakOffsets[outputLineIndex];
        while (currentInjectedOffset < injectionOffsets.length) {
          const length2 = injectionOptions[currentInjectedOffset].content.length;
          const injectedTextStartOffsetInInputWithInjections = injectionOffsets[currentInjectedOffset] + totalInjectedTextLengthBefore;
          const injectedTextEndOffsetInInputWithInjections = injectedTextStartOffsetInInputWithInjections + length2;
          if (injectedTextStartOffsetInInputWithInjections > lineEndOffsetInInputWithInjections) {
            break;
          }
          if (lineStartOffsetInInputWithInjections < injectedTextEndOffsetInInputWithInjections) {
            const options = injectionOptions[currentInjectedOffset];
            if (options.inlineClassName) {
              const offset = outputLineIndex > 0 ? lineBreakData.wrappedTextIndentLength : 0;
              const start = offset + Math.max(injectedTextStartOffsetInInputWithInjections - lineStartOffsetInInputWithInjections, 0);
              const end = offset + Math.min(injectedTextEndOffsetInInputWithInjections - lineStartOffsetInInputWithInjections, lineEndOffsetInInputWithInjections - lineStartOffsetInInputWithInjections);
              if (start !== end) {
                inlineDecorations.push(new SingleLineInlineDecoration(start, end, options.inlineClassName, options.inlineClassNameAffectsLetterSpacing));
              }
            }
          }
          if (injectedTextEndOffsetInInputWithInjections <= lineEndOffsetInInputWithInjections) {
            totalInjectedTextLengthBefore += length2;
            currentInjectedOffset++;
          } else {
            break;
          }
        }
      }
    }
    let lineWithInjections;
    if (injectionOffsets) {
      lineWithInjections = model.tokenization.getLineTokens(modelLineNumber).withInserted(injectionOffsets.map((offset, idx) => ({
        offset,
        text: injectionOptions[idx].content,
        tokenMetadata: LineTokens.defaultTokenMetadata
      })));
    } else {
      lineWithInjections = model.tokenization.getLineTokens(modelLineNumber);
    }
    for (let outputLineIndex = outputLineIdx; outputLineIndex < outputLineIdx + lineCount; outputLineIndex++) {
      const globalIndex = globalStartIndex + outputLineIndex - outputLineIdx;
      if (!needed[globalIndex]) {
        result2[globalIndex] = null;
        continue;
      }
      result2[globalIndex] = this._getViewLineData(lineWithInjections, inlineDecorationsPerOutputLine ? inlineDecorationsPerOutputLine[outputLineIndex] : null, outputLineIndex);
    }
  }
  _getViewLineData(lineWithInjections, inlineDecorations, outputLineIndex) {
    this._assertVisible();
    const lineBreakData = this._projectionData;
    const deltaStartIndex = outputLineIndex > 0 ? lineBreakData.wrappedTextIndentLength : 0;
    const lineStartOffsetInInputWithInjections = outputLineIndex > 0 ? lineBreakData.breakOffsets[outputLineIndex - 1] : 0;
    const lineEndOffsetInInputWithInjections = lineBreakData.breakOffsets[outputLineIndex];
    const tokens = lineWithInjections.sliceAndInflate(lineStartOffsetInInputWithInjections, lineEndOffsetInInputWithInjections, deltaStartIndex);
    let lineContent = tokens.getLineContent();
    if (outputLineIndex > 0) {
      lineContent = spaces(lineBreakData.wrappedTextIndentLength) + lineContent;
    }
    const minColumn = this._projectionData.getMinOutputOffset(outputLineIndex) + 1;
    const maxColumn = lineContent.length + 1;
    const continuesWithWrappedLine = outputLineIndex + 1 < this.getViewLineCount();
    const startVisibleColumn = outputLineIndex === 0 ? 0 : lineBreakData.breakOffsetsVisibleColumn[outputLineIndex - 1];
    return new ViewLineData(lineContent, continuesWithWrappedLine, minColumn, maxColumn, startVisibleColumn, tokens, inlineDecorations);
  }
  getModelColumnOfViewPosition(outputLineIndex, outputColumn) {
    this._assertVisible();
    return this._projectionData.translateToInputOffset(outputLineIndex, outputColumn - 1) + 1;
  }
  getViewPositionOfModelPosition(deltaLineNumber, inputColumn, affinity = 2) {
    this._assertVisible();
    const r = this._projectionData.translateToOutputPosition(inputColumn - 1, affinity);
    return r.toPosition(deltaLineNumber);
  }
  getViewLineNumberOfModelPosition(deltaLineNumber, inputColumn) {
    this._assertVisible();
    const r = this._projectionData.translateToOutputPosition(inputColumn - 1);
    return deltaLineNumber + r.outputLineIndex;
  }
  normalizePosition(outputLineIndex, outputPosition, affinity) {
    const baseViewLineNumber = outputPosition.lineNumber - outputLineIndex;
    const normalizedOutputPosition = this._projectionData.normalizeOutputPosition(outputLineIndex, outputPosition.column - 1, affinity);
    const result2 = normalizedOutputPosition.toPosition(baseViewLineNumber);
    return result2;
  }
  getInjectedTextAt(outputLineIndex, outputColumn) {
    return this._projectionData.getInjectedText(outputLineIndex, outputColumn - 1);
  }
  _assertVisible() {
    if (!this._isVisible) {
      throw new Error("Not supported");
    }
  }
}
class IdentityModelLineProjection {
  constructor() {
  }
  isVisible() {
    return true;
  }
  setVisible(isVisible) {
    if (isVisible) {
      return this;
    }
    return HiddenModelLineProjection.INSTANCE;
  }
  getProjectionData() {
    return null;
  }
  getViewLineCount() {
    return 1;
  }
  getViewLineContent(model, modelLineNumber, _outputLineIndex) {
    return model.getLineContent(modelLineNumber);
  }
  getViewLineLength(model, modelLineNumber, _outputLineIndex) {
    return model.getLineLength(modelLineNumber);
  }
  getViewLineMinColumn(model, modelLineNumber, _outputLineIndex) {
    return model.getLineMinColumn(modelLineNumber);
  }
  getViewLineMaxColumn(model, modelLineNumber, _outputLineIndex) {
    return model.getLineMaxColumn(modelLineNumber);
  }
  getViewLineData(model, modelLineNumber, _outputLineIndex) {
    const lineTokens = model.tokenization.getLineTokens(modelLineNumber);
    const lineContent = lineTokens.getLineContent();
    return new ViewLineData(lineContent, false, 1, lineContent.length + 1, 0, lineTokens.inflate(), null);
  }
  getViewLinesData(model, modelLineNumber, _fromOuputLineIndex, _toOutputLineIndex, globalStartIndex, needed, result2) {
    if (!needed[globalStartIndex]) {
      result2[globalStartIndex] = null;
      return;
    }
    result2[globalStartIndex] = this.getViewLineData(model, modelLineNumber, 0);
  }
  getModelColumnOfViewPosition(_outputLineIndex, outputColumn) {
    return outputColumn;
  }
  getViewPositionOfModelPosition(deltaLineNumber, inputColumn) {
    return new Position$2(deltaLineNumber, inputColumn);
  }
  getViewLineNumberOfModelPosition(deltaLineNumber, _inputColumn) {
    return deltaLineNumber;
  }
  normalizePosition(outputLineIndex, outputPosition, affinity) {
    return outputPosition;
  }
  getInjectedTextAt(_outputLineIndex, _outputColumn) {
    return null;
  }
}
IdentityModelLineProjection.INSTANCE = new IdentityModelLineProjection();
class HiddenModelLineProjection {
  constructor() {
  }
  isVisible() {
    return false;
  }
  setVisible(isVisible) {
    if (!isVisible) {
      return this;
    }
    return IdentityModelLineProjection.INSTANCE;
  }
  getProjectionData() {
    return null;
  }
  getViewLineCount() {
    return 0;
  }
  getViewLineContent(_model, _modelLineNumber, _outputLineIndex) {
    throw new Error("Not supported");
  }
  getViewLineLength(_model, _modelLineNumber, _outputLineIndex) {
    throw new Error("Not supported");
  }
  getViewLineMinColumn(_model, _modelLineNumber, _outputLineIndex) {
    throw new Error("Not supported");
  }
  getViewLineMaxColumn(_model, _modelLineNumber, _outputLineIndex) {
    throw new Error("Not supported");
  }
  getViewLineData(_model, _modelLineNumber, _outputLineIndex) {
    throw new Error("Not supported");
  }
  getViewLinesData(_model, _modelLineNumber, _fromOuputLineIndex, _toOutputLineIndex, _globalStartIndex, _needed, _result) {
    throw new Error("Not supported");
  }
  getModelColumnOfViewPosition(_outputLineIndex, _outputColumn) {
    throw new Error("Not supported");
  }
  getViewPositionOfModelPosition(_deltaLineNumber, _inputColumn) {
    throw new Error("Not supported");
  }
  getViewLineNumberOfModelPosition(_deltaLineNumber, _inputColumn) {
    throw new Error("Not supported");
  }
  normalizePosition(outputLineIndex, outputPosition, affinity) {
    throw new Error("Not supported");
  }
  getInjectedTextAt(_outputLineIndex, _outputColumn) {
    throw new Error("Not supported");
  }
}
HiddenModelLineProjection.INSTANCE = new HiddenModelLineProjection();
const _spaces = [""];
function spaces(count) {
  if (count >= _spaces.length) {
    for (let i = 1; i <= count; i++) {
      _spaces[i] = _makeSpaces(i);
    }
  }
  return _spaces[count];
}
function _makeSpaces(count) {
  return new Array(count + 1).join(" ");
}
class PrefixSumComputer {
  constructor(values) {
    this.values = values;
    this.prefixSum = new Uint32Array(values.length);
    this.prefixSumValidIndex = new Int32Array(1);
    this.prefixSumValidIndex[0] = -1;
  }
  insertValues(insertIndex, insertValues) {
    insertIndex = toUint32(insertIndex);
    const oldValues = this.values;
    const oldPrefixSum = this.prefixSum;
    const insertValuesLen = insertValues.length;
    if (insertValuesLen === 0) {
      return false;
    }
    this.values = new Uint32Array(oldValues.length + insertValuesLen);
    this.values.set(oldValues.subarray(0, insertIndex), 0);
    this.values.set(oldValues.subarray(insertIndex), insertIndex + insertValuesLen);
    this.values.set(insertValues, insertIndex);
    if (insertIndex - 1 < this.prefixSumValidIndex[0]) {
      this.prefixSumValidIndex[0] = insertIndex - 1;
    }
    this.prefixSum = new Uint32Array(this.values.length);
    if (this.prefixSumValidIndex[0] >= 0) {
      this.prefixSum.set(oldPrefixSum.subarray(0, this.prefixSumValidIndex[0] + 1));
    }
    return true;
  }
  setValue(index, value) {
    index = toUint32(index);
    value = toUint32(value);
    if (this.values[index] === value) {
      return false;
    }
    this.values[index] = value;
    if (index - 1 < this.prefixSumValidIndex[0]) {
      this.prefixSumValidIndex[0] = index - 1;
    }
    return true;
  }
  removeValues(startIndex, count) {
    startIndex = toUint32(startIndex);
    count = toUint32(count);
    const oldValues = this.values;
    const oldPrefixSum = this.prefixSum;
    if (startIndex >= oldValues.length) {
      return false;
    }
    const maxCount = oldValues.length - startIndex;
    if (count >= maxCount) {
      count = maxCount;
    }
    if (count === 0) {
      return false;
    }
    this.values = new Uint32Array(oldValues.length - count);
    this.values.set(oldValues.subarray(0, startIndex), 0);
    this.values.set(oldValues.subarray(startIndex + count), startIndex);
    this.prefixSum = new Uint32Array(this.values.length);
    if (startIndex - 1 < this.prefixSumValidIndex[0]) {
      this.prefixSumValidIndex[0] = startIndex - 1;
    }
    if (this.prefixSumValidIndex[0] >= 0) {
      this.prefixSum.set(oldPrefixSum.subarray(0, this.prefixSumValidIndex[0] + 1));
    }
    return true;
  }
  getTotalSum() {
    if (this.values.length === 0) {
      return 0;
    }
    return this._getPrefixSum(this.values.length - 1);
  }
  /**
   * Returns the sum of the first `index + 1` many items.
   * @returns `SUM(0 <= j <= index, values[j])`.
   */
  getPrefixSum(index) {
    if (index < 0) {
      return 0;
    }
    index = toUint32(index);
    return this._getPrefixSum(index);
  }
  _getPrefixSum(index) {
    if (index <= this.prefixSumValidIndex[0]) {
      return this.prefixSum[index];
    }
    let startIndex = this.prefixSumValidIndex[0] + 1;
    if (startIndex === 0) {
      this.prefixSum[0] = this.values[0];
      startIndex++;
    }
    if (index >= this.values.length) {
      index = this.values.length - 1;
    }
    for (let i = startIndex; i <= index; i++) {
      this.prefixSum[i] = this.prefixSum[i - 1] + this.values[i];
    }
    this.prefixSumValidIndex[0] = Math.max(this.prefixSumValidIndex[0], index);
    return this.prefixSum[index];
  }
  getIndexOf(sum) {
    sum = Math.floor(sum);
    this.getTotalSum();
    let low = 0;
    let high = this.values.length - 1;
    let mid = 0;
    let midStop = 0;
    let midStart = 0;
    while (low <= high) {
      mid = low + (high - low) / 2 | 0;
      midStop = this.prefixSum[mid];
      midStart = midStop - this.values[mid];
      if (sum < midStart) {
        high = mid - 1;
      } else if (sum >= midStop) {
        low = mid + 1;
      } else {
        break;
      }
    }
    return new PrefixSumIndexOfResult(mid, sum - midStart);
  }
}
class ConstantTimePrefixSumComputer {
  constructor(values) {
    this._values = values;
    this._isValid = false;
    this._validEndIndex = -1;
    this._prefixSum = [];
    this._indexBySum = [];
  }
  /**
   * @returns SUM(0 <= j < values.length, values[j])
   */
  getTotalSum() {
    this._ensureValid();
    return this._indexBySum.length;
  }
  /**
   * Returns the sum of the first `count` many items.
   * @returns `SUM(0 <= j < count, values[j])`.
   */
  getPrefixSum(count) {
    this._ensureValid();
    if (count === 0) {
      return 0;
    }
    return this._prefixSum[count - 1];
  }
  /**
   * @returns `result`, such that `getPrefixSum(result.index) + result.remainder = sum`
   */
  getIndexOf(sum) {
    this._ensureValid();
    const idx = this._indexBySum[sum];
    const viewLinesAbove = idx > 0 ? this._prefixSum[idx - 1] : 0;
    return new PrefixSumIndexOfResult(idx, sum - viewLinesAbove);
  }
  removeValues(start, deleteCount) {
    this._values.splice(start, deleteCount);
    this._invalidate(start);
  }
  insertValues(insertIndex, insertArr) {
    this._values = arrayInsert(this._values, insertIndex, insertArr);
    this._invalidate(insertIndex);
  }
  _invalidate(index) {
    this._isValid = false;
    this._validEndIndex = Math.min(this._validEndIndex, index - 1);
  }
  _ensureValid() {
    if (this._isValid) {
      return;
    }
    for (let i = this._validEndIndex + 1, len = this._values.length; i < len; i++) {
      const value = this._values[i];
      const sumAbove = i > 0 ? this._prefixSum[i - 1] : 0;
      this._prefixSum[i] = sumAbove + value;
      for (let j = 0; j < value; j++) {
        this._indexBySum[sumAbove + j] = i;
      }
    }
    this._prefixSum.length = this._values.length;
    this._indexBySum.length = this._prefixSum[this._prefixSum.length - 1];
    this._isValid = true;
    this._validEndIndex = this._values.length - 1;
  }
  setValue(index, value) {
    if (this._values[index] === value) {
      return;
    }
    this._values[index] = value;
    this._invalidate(index);
  }
}
class PrefixSumIndexOfResult {
  constructor(index, remainder) {
    this.index = index;
    this.remainder = remainder;
    this._prefixSumIndexOfResultBrand = void 0;
    this.index = index;
    this.remainder = remainder;
  }
}
class ViewModelLinesFromProjectedModel {
  constructor(editorId, model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, fontInfo, tabSize, wrappingStrategy, wrappingColumn, wrappingIndent, wordBreak) {
    this._editorId = editorId;
    this.model = model;
    this._validModelVersionId = -1;
    this._domLineBreaksComputerFactory = domLineBreaksComputerFactory;
    this._monospaceLineBreaksComputerFactory = monospaceLineBreaksComputerFactory;
    this.fontInfo = fontInfo;
    this.tabSize = tabSize;
    this.wrappingStrategy = wrappingStrategy;
    this.wrappingColumn = wrappingColumn;
    this.wrappingIndent = wrappingIndent;
    this.wordBreak = wordBreak;
    this._constructLines(
      /*resetHiddenAreas*/
      true,
      null
    );
  }
  dispose() {
    this.hiddenAreasDecorationIds = this.model.deltaDecorations(this.hiddenAreasDecorationIds, []);
  }
  createCoordinatesConverter() {
    return new CoordinatesConverter(this);
  }
  _constructLines(resetHiddenAreas, previousLineBreaks) {
    this.modelLineProjections = [];
    if (resetHiddenAreas) {
      this.hiddenAreasDecorationIds = this.model.deltaDecorations(this.hiddenAreasDecorationIds, []);
    }
    const linesContent = this.model.getLinesContent();
    const injectedTextDecorations = this.model.getInjectedTextDecorations(this._editorId);
    const lineCount = linesContent.length;
    const lineBreaksComputer = this.createLineBreaksComputer();
    const injectedTextQueue = new ArrayQueue(LineInjectedText.fromDecorations(injectedTextDecorations));
    for (let i = 0; i < lineCount; i++) {
      const lineInjectedText = injectedTextQueue.takeWhile((t) => t.lineNumber === i + 1);
      lineBreaksComputer.addRequest(linesContent[i], lineInjectedText, previousLineBreaks ? previousLineBreaks[i] : null);
    }
    const linesBreaks = lineBreaksComputer.finalize();
    const values = [];
    const hiddenAreas = this.hiddenAreasDecorationIds.map((areaId) => this.model.getDecorationRange(areaId)).sort(Range$2.compareRangesUsingStarts);
    let hiddenAreaStart = 1, hiddenAreaEnd = 0;
    let hiddenAreaIdx = -1;
    let nextLineNumberToUpdateHiddenArea = hiddenAreaIdx + 1 < hiddenAreas.length ? hiddenAreaEnd + 1 : lineCount + 2;
    for (let i = 0; i < lineCount; i++) {
      const lineNumber = i + 1;
      if (lineNumber === nextLineNumberToUpdateHiddenArea) {
        hiddenAreaIdx++;
        hiddenAreaStart = hiddenAreas[hiddenAreaIdx].startLineNumber;
        hiddenAreaEnd = hiddenAreas[hiddenAreaIdx].endLineNumber;
        nextLineNumberToUpdateHiddenArea = hiddenAreaIdx + 1 < hiddenAreas.length ? hiddenAreaEnd + 1 : lineCount + 2;
      }
      const isInHiddenArea = lineNumber >= hiddenAreaStart && lineNumber <= hiddenAreaEnd;
      const line = createModelLineProjection(linesBreaks[i], !isInHiddenArea);
      values[i] = line.getViewLineCount();
      this.modelLineProjections[i] = line;
    }
    this._validModelVersionId = this.model.getVersionId();
    this.projectedModelLineLineCounts = new ConstantTimePrefixSumComputer(values);
  }
  getHiddenAreas() {
    return this.hiddenAreasDecorationIds.map((decId) => this.model.getDecorationRange(decId));
  }
  setHiddenAreas(_ranges) {
    const validatedRanges = _ranges.map((r) => this.model.validateRange(r));
    const newRanges = normalizeLineRanges(validatedRanges);
    const oldRanges = this.hiddenAreasDecorationIds.map((areaId) => this.model.getDecorationRange(areaId)).sort(Range$2.compareRangesUsingStarts);
    if (newRanges.length === oldRanges.length) {
      let hasDifference = false;
      for (let i = 0; i < newRanges.length; i++) {
        if (!newRanges[i].equalsRange(oldRanges[i])) {
          hasDifference = true;
          break;
        }
      }
      if (!hasDifference) {
        return false;
      }
    }
    const newDecorations = newRanges.map((r) => ({
      range: r,
      options: ModelDecorationOptions.EMPTY
    }));
    this.hiddenAreasDecorationIds = this.model.deltaDecorations(this.hiddenAreasDecorationIds, newDecorations);
    const hiddenAreas = newRanges;
    let hiddenAreaStart = 1, hiddenAreaEnd = 0;
    let hiddenAreaIdx = -1;
    let nextLineNumberToUpdateHiddenArea = hiddenAreaIdx + 1 < hiddenAreas.length ? hiddenAreaEnd + 1 : this.modelLineProjections.length + 2;
    let hasVisibleLine = false;
    for (let i = 0; i < this.modelLineProjections.length; i++) {
      const lineNumber = i + 1;
      if (lineNumber === nextLineNumberToUpdateHiddenArea) {
        hiddenAreaIdx++;
        hiddenAreaStart = hiddenAreas[hiddenAreaIdx].startLineNumber;
        hiddenAreaEnd = hiddenAreas[hiddenAreaIdx].endLineNumber;
        nextLineNumberToUpdateHiddenArea = hiddenAreaIdx + 1 < hiddenAreas.length ? hiddenAreaEnd + 1 : this.modelLineProjections.length + 2;
      }
      let lineChanged = false;
      if (lineNumber >= hiddenAreaStart && lineNumber <= hiddenAreaEnd) {
        if (this.modelLineProjections[i].isVisible()) {
          this.modelLineProjections[i] = this.modelLineProjections[i].setVisible(false);
          lineChanged = true;
        }
      } else {
        hasVisibleLine = true;
        if (!this.modelLineProjections[i].isVisible()) {
          this.modelLineProjections[i] = this.modelLineProjections[i].setVisible(true);
          lineChanged = true;
        }
      }
      if (lineChanged) {
        const newOutputLineCount = this.modelLineProjections[i].getViewLineCount();
        this.projectedModelLineLineCounts.setValue(i, newOutputLineCount);
      }
    }
    if (!hasVisibleLine) {
      this.setHiddenAreas([]);
    }
    return true;
  }
  modelPositionIsVisible(modelLineNumber, _modelColumn) {
    if (modelLineNumber < 1 || modelLineNumber > this.modelLineProjections.length) {
      return false;
    }
    return this.modelLineProjections[modelLineNumber - 1].isVisible();
  }
  getModelLineViewLineCount(modelLineNumber) {
    if (modelLineNumber < 1 || modelLineNumber > this.modelLineProjections.length) {
      return 1;
    }
    return this.modelLineProjections[modelLineNumber - 1].getViewLineCount();
  }
  setTabSize(newTabSize) {
    if (this.tabSize === newTabSize) {
      return false;
    }
    this.tabSize = newTabSize;
    this._constructLines(
      /*resetHiddenAreas*/
      false,
      null
    );
    return true;
  }
  setWrappingSettings(fontInfo, wrappingStrategy, wrappingColumn, wrappingIndent, wordBreak) {
    const equalFontInfo = this.fontInfo.equals(fontInfo);
    const equalWrappingStrategy = this.wrappingStrategy === wrappingStrategy;
    const equalWrappingColumn = this.wrappingColumn === wrappingColumn;
    const equalWrappingIndent = this.wrappingIndent === wrappingIndent;
    const equalWordBreak = this.wordBreak === wordBreak;
    if (equalFontInfo && equalWrappingStrategy && equalWrappingColumn && equalWrappingIndent && equalWordBreak) {
      return false;
    }
    const onlyWrappingColumnChanged = equalFontInfo && equalWrappingStrategy && !equalWrappingColumn && equalWrappingIndent && equalWordBreak;
    this.fontInfo = fontInfo;
    this.wrappingStrategy = wrappingStrategy;
    this.wrappingColumn = wrappingColumn;
    this.wrappingIndent = wrappingIndent;
    this.wordBreak = wordBreak;
    let previousLineBreaks = null;
    if (onlyWrappingColumnChanged) {
      previousLineBreaks = [];
      for (let i = 0, len = this.modelLineProjections.length; i < len; i++) {
        previousLineBreaks[i] = this.modelLineProjections[i].getProjectionData();
      }
    }
    this._constructLines(
      /*resetHiddenAreas*/
      false,
      previousLineBreaks
    );
    return true;
  }
  createLineBreaksComputer() {
    const lineBreaksComputerFactory = this.wrappingStrategy === "advanced" ? this._domLineBreaksComputerFactory : this._monospaceLineBreaksComputerFactory;
    return lineBreaksComputerFactory.createLineBreaksComputer(this.fontInfo, this.tabSize, this.wrappingColumn, this.wrappingIndent, this.wordBreak);
  }
  onModelFlushed() {
    this._constructLines(
      /*resetHiddenAreas*/
      true,
      null
    );
  }
  onModelLinesDeleted(versionId, fromLineNumber, toLineNumber) {
    if (!versionId || versionId <= this._validModelVersionId) {
      return null;
    }
    const outputFromLineNumber = fromLineNumber === 1 ? 1 : this.projectedModelLineLineCounts.getPrefixSum(fromLineNumber - 1) + 1;
    const outputToLineNumber = this.projectedModelLineLineCounts.getPrefixSum(toLineNumber);
    this.modelLineProjections.splice(fromLineNumber - 1, toLineNumber - fromLineNumber + 1);
    this.projectedModelLineLineCounts.removeValues(fromLineNumber - 1, toLineNumber - fromLineNumber + 1);
    return new ViewLinesDeletedEvent(outputFromLineNumber, outputToLineNumber);
  }
  onModelLinesInserted(versionId, fromLineNumber, _toLineNumber, lineBreaks) {
    if (!versionId || versionId <= this._validModelVersionId) {
      return null;
    }
    const isInHiddenArea = fromLineNumber > 2 && !this.modelLineProjections[fromLineNumber - 2].isVisible();
    const outputFromLineNumber = fromLineNumber === 1 ? 1 : this.projectedModelLineLineCounts.getPrefixSum(fromLineNumber - 1) + 1;
    let totalOutputLineCount = 0;
    const insertLines = [];
    const insertPrefixSumValues = [];
    for (let i = 0, len = lineBreaks.length; i < len; i++) {
      const line = createModelLineProjection(lineBreaks[i], !isInHiddenArea);
      insertLines.push(line);
      const outputLineCount = line.getViewLineCount();
      totalOutputLineCount += outputLineCount;
      insertPrefixSumValues[i] = outputLineCount;
    }
    this.modelLineProjections = this.modelLineProjections.slice(0, fromLineNumber - 1).concat(insertLines).concat(this.modelLineProjections.slice(fromLineNumber - 1));
    this.projectedModelLineLineCounts.insertValues(fromLineNumber - 1, insertPrefixSumValues);
    return new ViewLinesInsertedEvent(outputFromLineNumber, outputFromLineNumber + totalOutputLineCount - 1);
  }
  onModelLineChanged(versionId, lineNumber, lineBreakData) {
    if (versionId !== null && versionId <= this._validModelVersionId) {
      return [false, null, null, null];
    }
    const lineIndex = lineNumber - 1;
    const oldOutputLineCount = this.modelLineProjections[lineIndex].getViewLineCount();
    const isVisible = this.modelLineProjections[lineIndex].isVisible();
    const line = createModelLineProjection(lineBreakData, isVisible);
    this.modelLineProjections[lineIndex] = line;
    const newOutputLineCount = this.modelLineProjections[lineIndex].getViewLineCount();
    let lineMappingChanged = false;
    let changeFrom = 0;
    let changeTo = -1;
    let insertFrom = 0;
    let insertTo = -1;
    let deleteFrom = 0;
    let deleteTo = -1;
    if (oldOutputLineCount > newOutputLineCount) {
      changeFrom = this.projectedModelLineLineCounts.getPrefixSum(lineNumber - 1) + 1;
      changeTo = changeFrom + newOutputLineCount - 1;
      deleteFrom = changeTo + 1;
      deleteTo = deleteFrom + (oldOutputLineCount - newOutputLineCount) - 1;
      lineMappingChanged = true;
    } else if (oldOutputLineCount < newOutputLineCount) {
      changeFrom = this.projectedModelLineLineCounts.getPrefixSum(lineNumber - 1) + 1;
      changeTo = changeFrom + oldOutputLineCount - 1;
      insertFrom = changeTo + 1;
      insertTo = insertFrom + (newOutputLineCount - oldOutputLineCount) - 1;
      lineMappingChanged = true;
    } else {
      changeFrom = this.projectedModelLineLineCounts.getPrefixSum(lineNumber - 1) + 1;
      changeTo = changeFrom + newOutputLineCount - 1;
    }
    this.projectedModelLineLineCounts.setValue(lineIndex, newOutputLineCount);
    const viewLinesChangedEvent = changeFrom <= changeTo ? new ViewLinesChangedEvent(changeFrom, changeTo - changeFrom + 1) : null;
    const viewLinesInsertedEvent = insertFrom <= insertTo ? new ViewLinesInsertedEvent(insertFrom, insertTo) : null;
    const viewLinesDeletedEvent = deleteFrom <= deleteTo ? new ViewLinesDeletedEvent(deleteFrom, deleteTo) : null;
    return [lineMappingChanged, viewLinesChangedEvent, viewLinesInsertedEvent, viewLinesDeletedEvent];
  }
  acceptVersionId(versionId) {
    this._validModelVersionId = versionId;
    if (this.modelLineProjections.length === 1 && !this.modelLineProjections[0].isVisible()) {
      this.setHiddenAreas([]);
    }
  }
  getViewLineCount() {
    return this.projectedModelLineLineCounts.getTotalSum();
  }
  _toValidViewLineNumber(viewLineNumber) {
    if (viewLineNumber < 1) {
      return 1;
    }
    const viewLineCount = this.getViewLineCount();
    if (viewLineNumber > viewLineCount) {
      return viewLineCount;
    }
    return viewLineNumber | 0;
  }
  getActiveIndentGuide(viewLineNumber, minLineNumber, maxLineNumber) {
    viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
    minLineNumber = this._toValidViewLineNumber(minLineNumber);
    maxLineNumber = this._toValidViewLineNumber(maxLineNumber);
    const modelPosition = this.convertViewPositionToModelPosition(viewLineNumber, this.getViewLineMinColumn(viewLineNumber));
    const modelMinPosition = this.convertViewPositionToModelPosition(minLineNumber, this.getViewLineMinColumn(minLineNumber));
    const modelMaxPosition = this.convertViewPositionToModelPosition(maxLineNumber, this.getViewLineMinColumn(maxLineNumber));
    const result2 = this.model.guides.getActiveIndentGuide(modelPosition.lineNumber, modelMinPosition.lineNumber, modelMaxPosition.lineNumber);
    const viewStartPosition = this.convertModelPositionToViewPosition(result2.startLineNumber, 1);
    const viewEndPosition = this.convertModelPositionToViewPosition(result2.endLineNumber, this.model.getLineMaxColumn(result2.endLineNumber));
    return {
      startLineNumber: viewStartPosition.lineNumber,
      endLineNumber: viewEndPosition.lineNumber,
      indent: result2.indent
    };
  }
  // #region ViewLineInfo
  getViewLineInfo(viewLineNumber) {
    viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
    const r = this.projectedModelLineLineCounts.getIndexOf(viewLineNumber - 1);
    const lineIndex = r.index;
    const remainder = r.remainder;
    return new ViewLineInfo(lineIndex + 1, remainder);
  }
  getMinColumnOfViewLine(viewLineInfo) {
    return this.modelLineProjections[viewLineInfo.modelLineNumber - 1].getViewLineMinColumn(this.model, viewLineInfo.modelLineNumber, viewLineInfo.modelLineWrappedLineIdx);
  }
  getMaxColumnOfViewLine(viewLineInfo) {
    return this.modelLineProjections[viewLineInfo.modelLineNumber - 1].getViewLineMaxColumn(this.model, viewLineInfo.modelLineNumber, viewLineInfo.modelLineWrappedLineIdx);
  }
  getModelStartPositionOfViewLine(viewLineInfo) {
    const line = this.modelLineProjections[viewLineInfo.modelLineNumber - 1];
    const minViewColumn = line.getViewLineMinColumn(this.model, viewLineInfo.modelLineNumber, viewLineInfo.modelLineWrappedLineIdx);
    const column = line.getModelColumnOfViewPosition(viewLineInfo.modelLineWrappedLineIdx, minViewColumn);
    return new Position$2(viewLineInfo.modelLineNumber, column);
  }
  getModelEndPositionOfViewLine(viewLineInfo) {
    const line = this.modelLineProjections[viewLineInfo.modelLineNumber - 1];
    const maxViewColumn = line.getViewLineMaxColumn(this.model, viewLineInfo.modelLineNumber, viewLineInfo.modelLineWrappedLineIdx);
    const column = line.getModelColumnOfViewPosition(viewLineInfo.modelLineWrappedLineIdx, maxViewColumn);
    return new Position$2(viewLineInfo.modelLineNumber, column);
  }
  getViewLineInfosGroupedByModelRanges(viewStartLineNumber, viewEndLineNumber) {
    const startViewLine = this.getViewLineInfo(viewStartLineNumber);
    const endViewLine = this.getViewLineInfo(viewEndLineNumber);
    const result2 = new Array();
    let lastVisibleModelPos = this.getModelStartPositionOfViewLine(startViewLine);
    let viewLines2 = new Array();
    for (let curModelLine = startViewLine.modelLineNumber; curModelLine <= endViewLine.modelLineNumber; curModelLine++) {
      const line = this.modelLineProjections[curModelLine - 1];
      if (line.isVisible()) {
        const startOffset = curModelLine === startViewLine.modelLineNumber ? startViewLine.modelLineWrappedLineIdx : 0;
        const endOffset = curModelLine === endViewLine.modelLineNumber ? endViewLine.modelLineWrappedLineIdx + 1 : line.getViewLineCount();
        for (let i = startOffset; i < endOffset; i++) {
          viewLines2.push(new ViewLineInfo(curModelLine, i));
        }
      }
      if (!line.isVisible() && lastVisibleModelPos) {
        const lastVisibleModelPos2 = new Position$2(curModelLine - 1, this.model.getLineMaxColumn(curModelLine - 1) + 1);
        const modelRange = Range$2.fromPositions(lastVisibleModelPos, lastVisibleModelPos2);
        result2.push(new ViewLineInfoGroupedByModelRange(modelRange, viewLines2));
        viewLines2 = [];
        lastVisibleModelPos = null;
      } else if (line.isVisible() && !lastVisibleModelPos) {
        lastVisibleModelPos = new Position$2(curModelLine, 1);
      }
    }
    if (lastVisibleModelPos) {
      const modelRange = Range$2.fromPositions(lastVisibleModelPos, this.getModelEndPositionOfViewLine(endViewLine));
      result2.push(new ViewLineInfoGroupedByModelRange(modelRange, viewLines2));
    }
    return result2;
  }
  // #endregion
  getViewLinesBracketGuides(viewStartLineNumber, viewEndLineNumber, activeViewPosition, options) {
    const modelActivePosition = activeViewPosition ? this.convertViewPositionToModelPosition(activeViewPosition.lineNumber, activeViewPosition.column) : null;
    const resultPerViewLine = [];
    for (const group2 of this.getViewLineInfosGroupedByModelRanges(viewStartLineNumber, viewEndLineNumber)) {
      const modelRangeStartLineNumber = group2.modelRange.startLineNumber;
      const bracketGuidesPerModelLine = this.model.guides.getLinesBracketGuides(modelRangeStartLineNumber, group2.modelRange.endLineNumber, modelActivePosition, options);
      for (const viewLineInfo of group2.viewLines) {
        const bracketGuides = bracketGuidesPerModelLine[viewLineInfo.modelLineNumber - modelRangeStartLineNumber];
        const result2 = bracketGuides.map((g) => {
          if (g.forWrappedLinesAfterColumn !== -1) {
            const p3 = this.modelLineProjections[viewLineInfo.modelLineNumber - 1].getViewPositionOfModelPosition(0, g.forWrappedLinesAfterColumn);
            if (p3.lineNumber >= viewLineInfo.modelLineWrappedLineIdx) {
              return void 0;
            }
          }
          if (g.forWrappedLinesBeforeOrAtColumn !== -1) {
            const p3 = this.modelLineProjections[viewLineInfo.modelLineNumber - 1].getViewPositionOfModelPosition(0, g.forWrappedLinesBeforeOrAtColumn);
            if (p3.lineNumber < viewLineInfo.modelLineWrappedLineIdx) {
              return void 0;
            }
          }
          if (!g.horizontalLine) {
            return g;
          }
          let column = -1;
          if (g.column !== -1) {
            const p3 = this.modelLineProjections[viewLineInfo.modelLineNumber - 1].getViewPositionOfModelPosition(0, g.column);
            if (p3.lineNumber === viewLineInfo.modelLineWrappedLineIdx) {
              column = p3.column;
            } else if (p3.lineNumber < viewLineInfo.modelLineWrappedLineIdx) {
              column = this.getMinColumnOfViewLine(viewLineInfo);
            } else if (p3.lineNumber > viewLineInfo.modelLineWrappedLineIdx) {
              return void 0;
            }
          }
          const viewPosition = this.convertModelPositionToViewPosition(viewLineInfo.modelLineNumber, g.horizontalLine.endColumn);
          const p2 = this.modelLineProjections[viewLineInfo.modelLineNumber - 1].getViewPositionOfModelPosition(0, g.horizontalLine.endColumn);
          if (p2.lineNumber === viewLineInfo.modelLineWrappedLineIdx) {
            return new IndentGuide(g.visibleColumn, column, g.className, new IndentGuideHorizontalLine(g.horizontalLine.top, viewPosition.column), -1, -1);
          } else if (p2.lineNumber < viewLineInfo.modelLineWrappedLineIdx) {
            return void 0;
          } else {
            if (g.visibleColumn !== -1) {
              return void 0;
            }
            return new IndentGuide(g.visibleColumn, column, g.className, new IndentGuideHorizontalLine(g.horizontalLine.top, this.getMaxColumnOfViewLine(viewLineInfo)), -1, -1);
          }
        });
        resultPerViewLine.push(result2.filter((r) => !!r));
      }
    }
    return resultPerViewLine;
  }
  getViewLinesIndentGuides(viewStartLineNumber, viewEndLineNumber) {
    viewStartLineNumber = this._toValidViewLineNumber(viewStartLineNumber);
    viewEndLineNumber = this._toValidViewLineNumber(viewEndLineNumber);
    const modelStart = this.convertViewPositionToModelPosition(viewStartLineNumber, this.getViewLineMinColumn(viewStartLineNumber));
    const modelEnd = this.convertViewPositionToModelPosition(viewEndLineNumber, this.getViewLineMaxColumn(viewEndLineNumber));
    let result2 = [];
    const resultRepeatCount = [];
    const resultRepeatOption = [];
    const modelStartLineIndex = modelStart.lineNumber - 1;
    const modelEndLineIndex = modelEnd.lineNumber - 1;
    let reqStart = null;
    for (let modelLineIndex = modelStartLineIndex; modelLineIndex <= modelEndLineIndex; modelLineIndex++) {
      const line = this.modelLineProjections[modelLineIndex];
      if (line.isVisible()) {
        const viewLineStartIndex = line.getViewLineNumberOfModelPosition(0, modelLineIndex === modelStartLineIndex ? modelStart.column : 1);
        const viewLineEndIndex = line.getViewLineNumberOfModelPosition(0, this.model.getLineMaxColumn(modelLineIndex + 1));
        const count = viewLineEndIndex - viewLineStartIndex + 1;
        let option = 0;
        if (count > 1 && line.getViewLineMinColumn(this.model, modelLineIndex + 1, viewLineEndIndex) === 1) {
          option = viewLineStartIndex === 0 ? 1 : 2;
        }
        resultRepeatCount.push(count);
        resultRepeatOption.push(option);
        if (reqStart === null) {
          reqStart = new Position$2(modelLineIndex + 1, 0);
        }
      } else {
        if (reqStart !== null) {
          result2 = result2.concat(this.model.guides.getLinesIndentGuides(reqStart.lineNumber, modelLineIndex));
          reqStart = null;
        }
      }
    }
    if (reqStart !== null) {
      result2 = result2.concat(this.model.guides.getLinesIndentGuides(reqStart.lineNumber, modelEnd.lineNumber));
      reqStart = null;
    }
    const viewLineCount = viewEndLineNumber - viewStartLineNumber + 1;
    const viewIndents = new Array(viewLineCount);
    let currIndex = 0;
    for (let i = 0, len = result2.length; i < len; i++) {
      let value = result2[i];
      const count = Math.min(viewLineCount - currIndex, resultRepeatCount[i]);
      const option = resultRepeatOption[i];
      let blockAtIndex;
      if (option === 2) {
        blockAtIndex = 0;
      } else if (option === 1) {
        blockAtIndex = 1;
      } else {
        blockAtIndex = count;
      }
      for (let j = 0; j < count; j++) {
        if (j === blockAtIndex) {
          value = 0;
        }
        viewIndents[currIndex++] = value;
      }
    }
    return viewIndents;
  }
  getViewLineContent(viewLineNumber) {
    const info = this.getViewLineInfo(viewLineNumber);
    return this.modelLineProjections[info.modelLineNumber - 1].getViewLineContent(this.model, info.modelLineNumber, info.modelLineWrappedLineIdx);
  }
  getViewLineLength(viewLineNumber) {
    const info = this.getViewLineInfo(viewLineNumber);
    return this.modelLineProjections[info.modelLineNumber - 1].getViewLineLength(this.model, info.modelLineNumber, info.modelLineWrappedLineIdx);
  }
  getViewLineMinColumn(viewLineNumber) {
    const info = this.getViewLineInfo(viewLineNumber);
    return this.modelLineProjections[info.modelLineNumber - 1].getViewLineMinColumn(this.model, info.modelLineNumber, info.modelLineWrappedLineIdx);
  }
  getViewLineMaxColumn(viewLineNumber) {
    const info = this.getViewLineInfo(viewLineNumber);
    return this.modelLineProjections[info.modelLineNumber - 1].getViewLineMaxColumn(this.model, info.modelLineNumber, info.modelLineWrappedLineIdx);
  }
  getViewLineData(viewLineNumber) {
    const info = this.getViewLineInfo(viewLineNumber);
    return this.modelLineProjections[info.modelLineNumber - 1].getViewLineData(this.model, info.modelLineNumber, info.modelLineWrappedLineIdx);
  }
  getViewLinesData(viewStartLineNumber, viewEndLineNumber, needed) {
    viewStartLineNumber = this._toValidViewLineNumber(viewStartLineNumber);
    viewEndLineNumber = this._toValidViewLineNumber(viewEndLineNumber);
    const start = this.projectedModelLineLineCounts.getIndexOf(viewStartLineNumber - 1);
    let viewLineNumber = viewStartLineNumber;
    const startModelLineIndex = start.index;
    const startRemainder = start.remainder;
    const result2 = [];
    for (let modelLineIndex = startModelLineIndex, len = this.model.getLineCount(); modelLineIndex < len; modelLineIndex++) {
      const line = this.modelLineProjections[modelLineIndex];
      if (!line.isVisible()) {
        continue;
      }
      const fromViewLineIndex = modelLineIndex === startModelLineIndex ? startRemainder : 0;
      let remainingViewLineCount = line.getViewLineCount() - fromViewLineIndex;
      let lastLine = false;
      if (viewLineNumber + remainingViewLineCount > viewEndLineNumber) {
        lastLine = true;
        remainingViewLineCount = viewEndLineNumber - viewLineNumber + 1;
      }
      line.getViewLinesData(this.model, modelLineIndex + 1, fromViewLineIndex, remainingViewLineCount, viewLineNumber - viewStartLineNumber, needed, result2);
      viewLineNumber += remainingViewLineCount;
      if (lastLine) {
        break;
      }
    }
    return result2;
  }
  validateViewPosition(viewLineNumber, viewColumn, expectedModelPosition) {
    viewLineNumber = this._toValidViewLineNumber(viewLineNumber);
    const r = this.projectedModelLineLineCounts.getIndexOf(viewLineNumber - 1);
    const lineIndex = r.index;
    const remainder = r.remainder;
    const line = this.modelLineProjections[lineIndex];
    const minColumn = line.getViewLineMinColumn(this.model, lineIndex + 1, remainder);
    const maxColumn = line.getViewLineMaxColumn(this.model, lineIndex + 1, remainder);
    if (viewColumn < minColumn) {
      viewColumn = minColumn;
    }
    if (viewColumn > maxColumn) {
      viewColumn = maxColumn;
    }
    const computedModelColumn = line.getModelColumnOfViewPosition(remainder, viewColumn);
    const computedModelPosition = this.model.validatePosition(new Position$2(lineIndex + 1, computedModelColumn));
    if (computedModelPosition.equals(expectedModelPosition)) {
      return new Position$2(viewLineNumber, viewColumn);
    }
    return this.convertModelPositionToViewPosition(expectedModelPosition.lineNumber, expectedModelPosition.column);
  }
  validateViewRange(viewRange, expectedModelRange) {
    const validViewStart = this.validateViewPosition(viewRange.startLineNumber, viewRange.startColumn, expectedModelRange.getStartPosition());
    const validViewEnd = this.validateViewPosition(viewRange.endLineNumber, viewRange.endColumn, expectedModelRange.getEndPosition());
    return new Range$2(validViewStart.lineNumber, validViewStart.column, validViewEnd.lineNumber, validViewEnd.column);
  }
  convertViewPositionToModelPosition(viewLineNumber, viewColumn) {
    const info = this.getViewLineInfo(viewLineNumber);
    const inputColumn = this.modelLineProjections[info.modelLineNumber - 1].getModelColumnOfViewPosition(info.modelLineWrappedLineIdx, viewColumn);
    return this.model.validatePosition(new Position$2(info.modelLineNumber, inputColumn));
  }
  convertViewRangeToModelRange(viewRange) {
    const start = this.convertViewPositionToModelPosition(viewRange.startLineNumber, viewRange.startColumn);
    const end = this.convertViewPositionToModelPosition(viewRange.endLineNumber, viewRange.endColumn);
    return new Range$2(start.lineNumber, start.column, end.lineNumber, end.column);
  }
  convertModelPositionToViewPosition(_modelLineNumber, _modelColumn, affinity = 2, allowZeroLineNumber = false, belowHiddenRanges = false) {
    const validPosition = this.model.validatePosition(new Position$2(_modelLineNumber, _modelColumn));
    const inputLineNumber = validPosition.lineNumber;
    const inputColumn = validPosition.column;
    let lineIndex = inputLineNumber - 1, lineIndexChanged = false;
    if (belowHiddenRanges) {
      while (lineIndex < this.modelLineProjections.length && !this.modelLineProjections[lineIndex].isVisible()) {
        lineIndex++;
        lineIndexChanged = true;
      }
    } else {
      while (lineIndex > 0 && !this.modelLineProjections[lineIndex].isVisible()) {
        lineIndex--;
        lineIndexChanged = true;
      }
    }
    if (lineIndex === 0 && !this.modelLineProjections[lineIndex].isVisible()) {
      return new Position$2(allowZeroLineNumber ? 0 : 1, 1);
    }
    const deltaLineNumber = 1 + this.projectedModelLineLineCounts.getPrefixSum(lineIndex);
    let r;
    if (lineIndexChanged) {
      if (belowHiddenRanges) {
        r = this.modelLineProjections[lineIndex].getViewPositionOfModelPosition(deltaLineNumber, 1, affinity);
      } else {
        r = this.modelLineProjections[lineIndex].getViewPositionOfModelPosition(deltaLineNumber, this.model.getLineMaxColumn(lineIndex + 1), affinity);
      }
    } else {
      r = this.modelLineProjections[inputLineNumber - 1].getViewPositionOfModelPosition(deltaLineNumber, inputColumn, affinity);
    }
    return r;
  }
  /**
   * @param affinity The affinity in case of an empty range. Has no effect for non-empty ranges.
  */
  convertModelRangeToViewRange(modelRange, affinity = 0) {
    if (modelRange.isEmpty()) {
      const start = this.convertModelPositionToViewPosition(modelRange.startLineNumber, modelRange.startColumn, affinity);
      return Range$2.fromPositions(start);
    } else {
      const start = this.convertModelPositionToViewPosition(
        modelRange.startLineNumber,
        modelRange.startColumn,
        1
        /* PositionAffinity.Right */
      );
      const end = this.convertModelPositionToViewPosition(
        modelRange.endLineNumber,
        modelRange.endColumn,
        0
        /* PositionAffinity.Left */
      );
      return new Range$2(start.lineNumber, start.column, end.lineNumber, end.column);
    }
  }
  getViewLineNumberOfModelPosition(modelLineNumber, modelColumn) {
    let lineIndex = modelLineNumber - 1;
    if (this.modelLineProjections[lineIndex].isVisible()) {
      const deltaLineNumber2 = 1 + this.projectedModelLineLineCounts.getPrefixSum(lineIndex);
      return this.modelLineProjections[lineIndex].getViewLineNumberOfModelPosition(deltaLineNumber2, modelColumn);
    }
    while (lineIndex > 0 && !this.modelLineProjections[lineIndex].isVisible()) {
      lineIndex--;
    }
    if (lineIndex === 0 && !this.modelLineProjections[lineIndex].isVisible()) {
      return 1;
    }
    const deltaLineNumber = 1 + this.projectedModelLineLineCounts.getPrefixSum(lineIndex);
    return this.modelLineProjections[lineIndex].getViewLineNumberOfModelPosition(deltaLineNumber, this.model.getLineMaxColumn(lineIndex + 1));
  }
  getDecorationsInRange(range2, ownerId, filterOutValidation, onlyMinimapDecorations, onlyMarginDecorations) {
    const modelStart = this.convertViewPositionToModelPosition(range2.startLineNumber, range2.startColumn);
    const modelEnd = this.convertViewPositionToModelPosition(range2.endLineNumber, range2.endColumn);
    if (modelEnd.lineNumber - modelStart.lineNumber <= range2.endLineNumber - range2.startLineNumber) {
      return this.model.getDecorationsInRange(new Range$2(modelStart.lineNumber, 1, modelEnd.lineNumber, modelEnd.column), ownerId, filterOutValidation, onlyMinimapDecorations, onlyMarginDecorations);
    }
    let result2 = [];
    const modelStartLineIndex = modelStart.lineNumber - 1;
    const modelEndLineIndex = modelEnd.lineNumber - 1;
    let reqStart = null;
    for (let modelLineIndex = modelStartLineIndex; modelLineIndex <= modelEndLineIndex; modelLineIndex++) {
      const line = this.modelLineProjections[modelLineIndex];
      if (line.isVisible()) {
        if (reqStart === null) {
          reqStart = new Position$2(modelLineIndex + 1, modelLineIndex === modelStartLineIndex ? modelStart.column : 1);
        }
      } else {
        if (reqStart !== null) {
          const maxLineColumn = this.model.getLineMaxColumn(modelLineIndex);
          result2 = result2.concat(this.model.getDecorationsInRange(new Range$2(reqStart.lineNumber, reqStart.column, modelLineIndex, maxLineColumn), ownerId, filterOutValidation, onlyMinimapDecorations));
          reqStart = null;
        }
      }
    }
    if (reqStart !== null) {
      result2 = result2.concat(this.model.getDecorationsInRange(new Range$2(reqStart.lineNumber, reqStart.column, modelEnd.lineNumber, modelEnd.column), ownerId, filterOutValidation, onlyMinimapDecorations));
      reqStart = null;
    }
    result2.sort((a, b) => {
      const res = Range$2.compareRangesUsingStarts(a.range, b.range);
      if (res === 0) {
        if (a.id < b.id) {
          return -1;
        }
        if (a.id > b.id) {
          return 1;
        }
        return 0;
      }
      return res;
    });
    const finalResult = [];
    let finalResultLen = 0;
    let prevDecId = null;
    for (const dec of result2) {
      const decId = dec.id;
      if (prevDecId === decId) {
        continue;
      }
      prevDecId = decId;
      finalResult[finalResultLen++] = dec;
    }
    return finalResult;
  }
  getInjectedTextAt(position) {
    const info = this.getViewLineInfo(position.lineNumber);
    return this.modelLineProjections[info.modelLineNumber - 1].getInjectedTextAt(info.modelLineWrappedLineIdx, position.column);
  }
  normalizePosition(position, affinity) {
    const info = this.getViewLineInfo(position.lineNumber);
    return this.modelLineProjections[info.modelLineNumber - 1].normalizePosition(info.modelLineWrappedLineIdx, position, affinity);
  }
  getLineIndentColumn(lineNumber) {
    const info = this.getViewLineInfo(lineNumber);
    if (info.modelLineWrappedLineIdx === 0) {
      return this.model.getLineIndentColumn(info.modelLineNumber);
    }
    return 0;
  }
}
function normalizeLineRanges(ranges) {
  if (ranges.length === 0) {
    return [];
  }
  const sortedRanges = ranges.slice();
  sortedRanges.sort(Range$2.compareRangesUsingStarts);
  const result2 = [];
  let currentRangeStart = sortedRanges[0].startLineNumber;
  let currentRangeEnd = sortedRanges[0].endLineNumber;
  for (let i = 1, len = sortedRanges.length; i < len; i++) {
    const range2 = sortedRanges[i];
    if (range2.startLineNumber > currentRangeEnd + 1) {
      result2.push(new Range$2(currentRangeStart, 1, currentRangeEnd, 1));
      currentRangeStart = range2.startLineNumber;
      currentRangeEnd = range2.endLineNumber;
    } else if (range2.endLineNumber > currentRangeEnd) {
      currentRangeEnd = range2.endLineNumber;
    }
  }
  result2.push(new Range$2(currentRangeStart, 1, currentRangeEnd, 1));
  return result2;
}
class ViewLineInfo {
  constructor(modelLineNumber, modelLineWrappedLineIdx) {
    this.modelLineNumber = modelLineNumber;
    this.modelLineWrappedLineIdx = modelLineWrappedLineIdx;
  }
}
class ViewLineInfoGroupedByModelRange {
  constructor(modelRange, viewLines2) {
    this.modelRange = modelRange;
    this.viewLines = viewLines2;
  }
}
class CoordinatesConverter {
  constructor(lines) {
    this._lines = lines;
  }
  // View -> Model conversion and related methods
  convertViewPositionToModelPosition(viewPosition) {
    return this._lines.convertViewPositionToModelPosition(viewPosition.lineNumber, viewPosition.column);
  }
  convertViewRangeToModelRange(viewRange) {
    return this._lines.convertViewRangeToModelRange(viewRange);
  }
  validateViewPosition(viewPosition, expectedModelPosition) {
    return this._lines.validateViewPosition(viewPosition.lineNumber, viewPosition.column, expectedModelPosition);
  }
  validateViewRange(viewRange, expectedModelRange) {
    return this._lines.validateViewRange(viewRange, expectedModelRange);
  }
  // Model -> View conversion and related methods
  convertModelPositionToViewPosition(modelPosition, affinity, allowZero, belowHiddenRanges) {
    return this._lines.convertModelPositionToViewPosition(modelPosition.lineNumber, modelPosition.column, affinity, allowZero, belowHiddenRanges);
  }
  convertModelRangeToViewRange(modelRange, affinity) {
    return this._lines.convertModelRangeToViewRange(modelRange, affinity);
  }
  modelPositionIsVisible(modelPosition) {
    return this._lines.modelPositionIsVisible(modelPosition.lineNumber, modelPosition.column);
  }
  getModelLineViewLineCount(modelLineNumber) {
    return this._lines.getModelLineViewLineCount(modelLineNumber);
  }
  getViewLineNumberOfModelPosition(modelLineNumber, modelColumn) {
    return this._lines.getViewLineNumberOfModelPosition(modelLineNumber, modelColumn);
  }
}
class ViewModelLinesFromModelAsIs {
  constructor(model) {
    this.model = model;
  }
  dispose() {
  }
  createCoordinatesConverter() {
    return new IdentityCoordinatesConverter(this);
  }
  getHiddenAreas() {
    return [];
  }
  setHiddenAreas(_ranges) {
    return false;
  }
  setTabSize(_newTabSize) {
    return false;
  }
  setWrappingSettings(_fontInfo, _wrappingStrategy, _wrappingColumn, _wrappingIndent) {
    return false;
  }
  createLineBreaksComputer() {
    const result2 = [];
    return {
      addRequest: (lineText, injectedText, previousLineBreakData) => {
        result2.push(null);
      },
      finalize: () => {
        return result2;
      }
    };
  }
  onModelFlushed() {
  }
  onModelLinesDeleted(_versionId, fromLineNumber, toLineNumber) {
    return new ViewLinesDeletedEvent(fromLineNumber, toLineNumber);
  }
  onModelLinesInserted(_versionId, fromLineNumber, toLineNumber, lineBreaks) {
    return new ViewLinesInsertedEvent(fromLineNumber, toLineNumber);
  }
  onModelLineChanged(_versionId, lineNumber, lineBreakData) {
    return [false, new ViewLinesChangedEvent(lineNumber, 1), null, null];
  }
  acceptVersionId(_versionId) {
  }
  getViewLineCount() {
    return this.model.getLineCount();
  }
  getActiveIndentGuide(viewLineNumber, _minLineNumber, _maxLineNumber) {
    return {
      startLineNumber: viewLineNumber,
      endLineNumber: viewLineNumber,
      indent: 0
    };
  }
  getViewLinesBracketGuides(startLineNumber, endLineNumber, activePosition) {
    return new Array(endLineNumber - startLineNumber + 1).fill([]);
  }
  getViewLinesIndentGuides(viewStartLineNumber, viewEndLineNumber) {
    const viewLineCount = viewEndLineNumber - viewStartLineNumber + 1;
    const result2 = new Array(viewLineCount);
    for (let i = 0; i < viewLineCount; i++) {
      result2[i] = 0;
    }
    return result2;
  }
  getViewLineContent(viewLineNumber) {
    return this.model.getLineContent(viewLineNumber);
  }
  getViewLineLength(viewLineNumber) {
    return this.model.getLineLength(viewLineNumber);
  }
  getViewLineMinColumn(viewLineNumber) {
    return this.model.getLineMinColumn(viewLineNumber);
  }
  getViewLineMaxColumn(viewLineNumber) {
    return this.model.getLineMaxColumn(viewLineNumber);
  }
  getViewLineData(viewLineNumber) {
    const lineTokens = this.model.tokenization.getLineTokens(viewLineNumber);
    const lineContent = lineTokens.getLineContent();
    return new ViewLineData(lineContent, false, 1, lineContent.length + 1, 0, lineTokens.inflate(), null);
  }
  getViewLinesData(viewStartLineNumber, viewEndLineNumber, needed) {
    const lineCount = this.model.getLineCount();
    viewStartLineNumber = Math.min(Math.max(1, viewStartLineNumber), lineCount);
    viewEndLineNumber = Math.min(Math.max(1, viewEndLineNumber), lineCount);
    const result2 = [];
    for (let lineNumber = viewStartLineNumber; lineNumber <= viewEndLineNumber; lineNumber++) {
      const idx = lineNumber - viewStartLineNumber;
      result2[idx] = needed[idx] ? this.getViewLineData(lineNumber) : null;
    }
    return result2;
  }
  getDecorationsInRange(range2, ownerId, filterOutValidation, onlyMinimapDecorations, onlyMarginDecorations) {
    return this.model.getDecorationsInRange(range2, ownerId, filterOutValidation, onlyMinimapDecorations, onlyMarginDecorations);
  }
  normalizePosition(position, affinity) {
    return this.model.normalizePosition(position, affinity);
  }
  getLineIndentColumn(lineNumber) {
    return this.model.getLineIndentColumn(lineNumber);
  }
  getInjectedTextAt(position) {
    return null;
  }
}
class IdentityCoordinatesConverter {
  constructor(lines) {
    this._lines = lines;
  }
  _validPosition(pos) {
    return this._lines.model.validatePosition(pos);
  }
  _validRange(range2) {
    return this._lines.model.validateRange(range2);
  }
  // View -> Model conversion and related methods
  convertViewPositionToModelPosition(viewPosition) {
    return this._validPosition(viewPosition);
  }
  convertViewRangeToModelRange(viewRange) {
    return this._validRange(viewRange);
  }
  validateViewPosition(_viewPosition, expectedModelPosition) {
    return this._validPosition(expectedModelPosition);
  }
  validateViewRange(_viewRange, expectedModelRange) {
    return this._validRange(expectedModelRange);
  }
  // Model -> View conversion and related methods
  convertModelPositionToViewPosition(modelPosition) {
    return this._validPosition(modelPosition);
  }
  convertModelRangeToViewRange(modelRange) {
    return this._validRange(modelRange);
  }
  modelPositionIsVisible(modelPosition) {
    const lineCount = this._lines.model.getLineCount();
    if (modelPosition.lineNumber < 1 || modelPosition.lineNumber > lineCount) {
      return false;
    }
    return true;
  }
  getModelLineViewLineCount(modelLineNumber) {
    return 1;
  }
  getViewLineNumberOfModelPosition(modelLineNumber, modelColumn) {
    return modelLineNumber;
  }
}
let ViewModel$1 = class ViewModel extends Disposable {
  constructor(editorId, configuration, model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, scheduleAtNextAnimationFrame2, languageConfigurationService, _themeService, _attachedView) {
    super();
    this.languageConfigurationService = languageConfigurationService;
    this._themeService = _themeService;
    this._attachedView = _attachedView;
    this.hiddenAreasModel = new HiddenAreasModel();
    this.previousHiddenAreas = [];
    this._editorId = editorId;
    this._configuration = configuration;
    this.model = model;
    this._eventDispatcher = new ViewModelEventDispatcher();
    this.onEvent = this._eventDispatcher.onEvent;
    this.cursorConfig = new CursorConfiguration(this.model.getLanguageId(), this.model.getOptions(), this._configuration, this.languageConfigurationService);
    this._updateConfigurationViewLineCount = this._register(new RunOnceScheduler(() => this._updateConfigurationViewLineCountNow(), 0));
    this._hasFocus = false;
    this._viewportStart = ViewportStart.create(this.model);
    if (this.model.isTooLargeForTokenization()) {
      this._lines = new ViewModelLinesFromModelAsIs(this.model);
    } else {
      const options = this._configuration.options;
      const fontInfo = options.get(
        49
        /* EditorOption.fontInfo */
      );
      const wrappingStrategy = options.get(
        136
        /* EditorOption.wrappingStrategy */
      );
      const wrappingInfo = options.get(
        143
        /* EditorOption.wrappingInfo */
      );
      const wrappingIndent = options.get(
        135
        /* EditorOption.wrappingIndent */
      );
      const wordBreak = options.get(
        127
        /* EditorOption.wordBreak */
      );
      this._lines = new ViewModelLinesFromProjectedModel(this._editorId, this.model, domLineBreaksComputerFactory, monospaceLineBreaksComputerFactory, fontInfo, this.model.getOptions().tabSize, wrappingStrategy, wrappingInfo.wrappingColumn, wrappingIndent, wordBreak);
    }
    this.coordinatesConverter = this._lines.createCoordinatesConverter();
    this._cursor = this._register(new CursorsController(model, this, this.coordinatesConverter, this.cursorConfig));
    this.viewLayout = this._register(new ViewLayout(this._configuration, this.getLineCount(), scheduleAtNextAnimationFrame2));
    this._register(this.viewLayout.onDidScroll((e) => {
      if (e.scrollTopChanged) {
        this._handleVisibleLinesChanged();
      }
      if (e.scrollTopChanged) {
        this._viewportStart.invalidate();
      }
      this._eventDispatcher.emitSingleViewEvent(new ViewScrollChangedEvent(e));
      this._eventDispatcher.emitOutgoingEvent(new ScrollChangedEvent(e.oldScrollWidth, e.oldScrollLeft, e.oldScrollHeight, e.oldScrollTop, e.scrollWidth, e.scrollLeft, e.scrollHeight, e.scrollTop));
    }));
    this._register(this.viewLayout.onDidContentSizeChange((e) => {
      this._eventDispatcher.emitOutgoingEvent(e);
    }));
    this._decorations = new ViewModelDecorations(this._editorId, this.model, this._configuration, this._lines, this.coordinatesConverter);
    this._registerModelEvents();
    this._register(this._configuration.onDidChangeFast((e) => {
      try {
        const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
        this._onConfigurationChanged(eventsCollector, e);
      } finally {
        this._eventDispatcher.endEmitViewEvents();
      }
    }));
    this._register(MinimapTokensColorTracker.getInstance().onDidChange(() => {
      this._eventDispatcher.emitSingleViewEvent(new ViewTokensColorsChangedEvent());
    }));
    this._register(this._themeService.onDidColorThemeChange((theme) => {
      this._invalidateDecorationsColorCache();
      this._eventDispatcher.emitSingleViewEvent(new ViewThemeChangedEvent(theme));
    }));
    this._updateConfigurationViewLineCountNow();
  }
  dispose() {
    super.dispose();
    this._decorations.dispose();
    this._lines.dispose();
    this._viewportStart.dispose();
    this._eventDispatcher.dispose();
  }
  createLineBreaksComputer() {
    return this._lines.createLineBreaksComputer();
  }
  addViewEventHandler(eventHandler) {
    this._eventDispatcher.addViewEventHandler(eventHandler);
  }
  removeViewEventHandler(eventHandler) {
    this._eventDispatcher.removeViewEventHandler(eventHandler);
  }
  _updateConfigurationViewLineCountNow() {
    this._configuration.setViewLineCount(this._lines.getViewLineCount());
  }
  getModelVisibleRanges() {
    const linesViewportData = this.viewLayout.getLinesViewportData();
    const viewVisibleRange = new Range$2(linesViewportData.startLineNumber, this.getLineMinColumn(linesViewportData.startLineNumber), linesViewportData.endLineNumber, this.getLineMaxColumn(linesViewportData.endLineNumber));
    const modelVisibleRanges = this._toModelVisibleRanges(viewVisibleRange);
    return modelVisibleRanges;
  }
  visibleLinesStabilized() {
    const modelVisibleRanges = this.getModelVisibleRanges();
    this._attachedView.setVisibleLines(modelVisibleRanges, true);
  }
  _handleVisibleLinesChanged() {
    const modelVisibleRanges = this.getModelVisibleRanges();
    this._attachedView.setVisibleLines(modelVisibleRanges, false);
  }
  setHasFocus(hasFocus) {
    this._hasFocus = hasFocus;
    this._cursor.setHasFocus(hasFocus);
    this._eventDispatcher.emitSingleViewEvent(new ViewFocusChangedEvent(hasFocus));
    this._eventDispatcher.emitOutgoingEvent(new FocusChangedEvent(!hasFocus, hasFocus));
  }
  onCompositionStart() {
    this._eventDispatcher.emitSingleViewEvent(new ViewCompositionStartEvent());
  }
  onCompositionEnd() {
    this._eventDispatcher.emitSingleViewEvent(new ViewCompositionEndEvent());
  }
  _captureStableViewport() {
    if (this._viewportStart.isValid && this.viewLayout.getCurrentScrollTop() > 0) {
      const previousViewportStartViewPosition = new Position$2(this._viewportStart.viewLineNumber, this.getLineMinColumn(this._viewportStart.viewLineNumber));
      const previousViewportStartModelPosition = this.coordinatesConverter.convertViewPositionToModelPosition(previousViewportStartViewPosition);
      return new StableViewport(previousViewportStartModelPosition, this._viewportStart.startLineDelta);
    }
    return new StableViewport(null, 0);
  }
  _onConfigurationChanged(eventsCollector, e) {
    const stableViewport = this._captureStableViewport();
    const options = this._configuration.options;
    const fontInfo = options.get(
      49
      /* EditorOption.fontInfo */
    );
    const wrappingStrategy = options.get(
      136
      /* EditorOption.wrappingStrategy */
    );
    const wrappingInfo = options.get(
      143
      /* EditorOption.wrappingInfo */
    );
    const wrappingIndent = options.get(
      135
      /* EditorOption.wrappingIndent */
    );
    const wordBreak = options.get(
      127
      /* EditorOption.wordBreak */
    );
    if (this._lines.setWrappingSettings(fontInfo, wrappingStrategy, wrappingInfo.wrappingColumn, wrappingIndent, wordBreak)) {
      eventsCollector.emitViewEvent(new ViewFlushedEvent());
      eventsCollector.emitViewEvent(new ViewLineMappingChangedEvent());
      eventsCollector.emitViewEvent(new ViewDecorationsChangedEvent(null));
      this._cursor.onLineMappingChanged(eventsCollector);
      this._decorations.onLineMappingChanged();
      this.viewLayout.onFlushed(this.getLineCount());
      this._updateConfigurationViewLineCount.schedule();
    }
    if (e.hasChanged(
      89
      /* EditorOption.readOnly */
    )) {
      this._decorations.reset();
      eventsCollector.emitViewEvent(new ViewDecorationsChangedEvent(null));
    }
    eventsCollector.emitViewEvent(new ViewConfigurationChangedEvent(e));
    this.viewLayout.onConfigurationChanged(e);
    stableViewport.recoverViewportStart(this.coordinatesConverter, this.viewLayout);
    if (CursorConfiguration.shouldRecreate(e)) {
      this.cursorConfig = new CursorConfiguration(this.model.getLanguageId(), this.model.getOptions(), this._configuration, this.languageConfigurationService);
      this._cursor.updateConfiguration(this.cursorConfig);
    }
  }
  _registerModelEvents() {
    this._register(this.model.onDidChangeContentOrInjectedText((e) => {
      try {
        const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
        let hadOtherModelChange = false;
        let hadModelLineChangeThatChangedLineMapping = false;
        const changes = e instanceof InternalModelContentChangeEvent ? e.rawContentChangedEvent.changes : e.changes;
        const versionId = e instanceof InternalModelContentChangeEvent ? e.rawContentChangedEvent.versionId : null;
        const lineBreaksComputer = this._lines.createLineBreaksComputer();
        for (const change of changes) {
          switch (change.changeType) {
            case 4: {
              for (let lineIdx = 0; lineIdx < change.detail.length; lineIdx++) {
                const line = change.detail[lineIdx];
                let injectedText = change.injectedTexts[lineIdx];
                if (injectedText) {
                  injectedText = injectedText.filter((element) => !element.ownerId || element.ownerId === this._editorId);
                }
                lineBreaksComputer.addRequest(line, injectedText, null);
              }
              break;
            }
            case 2: {
              let injectedText = null;
              if (change.injectedText) {
                injectedText = change.injectedText.filter((element) => !element.ownerId || element.ownerId === this._editorId);
              }
              lineBreaksComputer.addRequest(change.detail, injectedText, null);
              break;
            }
          }
        }
        const lineBreaks = lineBreaksComputer.finalize();
        const lineBreakQueue = new ArrayQueue(lineBreaks);
        for (const change of changes) {
          switch (change.changeType) {
            case 1: {
              this._lines.onModelFlushed();
              eventsCollector.emitViewEvent(new ViewFlushedEvent());
              this._decorations.reset();
              this.viewLayout.onFlushed(this.getLineCount());
              hadOtherModelChange = true;
              break;
            }
            case 3: {
              const linesDeletedEvent = this._lines.onModelLinesDeleted(versionId, change.fromLineNumber, change.toLineNumber);
              if (linesDeletedEvent !== null) {
                eventsCollector.emitViewEvent(linesDeletedEvent);
                this.viewLayout.onLinesDeleted(linesDeletedEvent.fromLineNumber, linesDeletedEvent.toLineNumber);
              }
              hadOtherModelChange = true;
              break;
            }
            case 4: {
              const insertedLineBreaks = lineBreakQueue.takeCount(change.detail.length);
              const linesInsertedEvent = this._lines.onModelLinesInserted(versionId, change.fromLineNumber, change.toLineNumber, insertedLineBreaks);
              if (linesInsertedEvent !== null) {
                eventsCollector.emitViewEvent(linesInsertedEvent);
                this.viewLayout.onLinesInserted(linesInsertedEvent.fromLineNumber, linesInsertedEvent.toLineNumber);
              }
              hadOtherModelChange = true;
              break;
            }
            case 2: {
              const changedLineBreakData = lineBreakQueue.dequeue();
              const [lineMappingChanged, linesChangedEvent, linesInsertedEvent, linesDeletedEvent] = this._lines.onModelLineChanged(versionId, change.lineNumber, changedLineBreakData);
              hadModelLineChangeThatChangedLineMapping = lineMappingChanged;
              if (linesChangedEvent) {
                eventsCollector.emitViewEvent(linesChangedEvent);
              }
              if (linesInsertedEvent) {
                eventsCollector.emitViewEvent(linesInsertedEvent);
                this.viewLayout.onLinesInserted(linesInsertedEvent.fromLineNumber, linesInsertedEvent.toLineNumber);
              }
              if (linesDeletedEvent) {
                eventsCollector.emitViewEvent(linesDeletedEvent);
                this.viewLayout.onLinesDeleted(linesDeletedEvent.fromLineNumber, linesDeletedEvent.toLineNumber);
              }
              break;
            }
            case 5: {
              break;
            }
          }
        }
        if (versionId !== null) {
          this._lines.acceptVersionId(versionId);
        }
        this.viewLayout.onHeightMaybeChanged();
        if (!hadOtherModelChange && hadModelLineChangeThatChangedLineMapping) {
          eventsCollector.emitViewEvent(new ViewLineMappingChangedEvent());
          eventsCollector.emitViewEvent(new ViewDecorationsChangedEvent(null));
          this._cursor.onLineMappingChanged(eventsCollector);
          this._decorations.onLineMappingChanged();
        }
      } finally {
        this._eventDispatcher.endEmitViewEvents();
      }
      const viewportStartWasValid = this._viewportStart.isValid;
      this._viewportStart.invalidate();
      this._configuration.setModelLineCount(this.model.getLineCount());
      this._updateConfigurationViewLineCountNow();
      if (!this._hasFocus && this.model.getAttachedEditorCount() >= 2 && viewportStartWasValid) {
        const modelRange = this.model._getTrackedRange(this._viewportStart.modelTrackedRange);
        if (modelRange) {
          const viewPosition = this.coordinatesConverter.convertModelPositionToViewPosition(modelRange.getStartPosition());
          const viewPositionTop = this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber);
          this.viewLayout.setScrollPosition(
            { scrollTop: viewPositionTop + this._viewportStart.startLineDelta },
            1
            /* ScrollType.Immediate */
          );
        }
      }
      try {
        const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
        if (e instanceof InternalModelContentChangeEvent) {
          eventsCollector.emitOutgoingEvent(new ModelContentChangedEvent(e.contentChangedEvent));
        }
        this._cursor.onModelContentChanged(eventsCollector, e);
      } finally {
        this._eventDispatcher.endEmitViewEvents();
      }
      this._handleVisibleLinesChanged();
    }));
    this._register(this.model.onDidChangeTokens((e) => {
      const viewRanges = [];
      for (let j = 0, lenJ = e.ranges.length; j < lenJ; j++) {
        const modelRange = e.ranges[j];
        const viewStartLineNumber = this.coordinatesConverter.convertModelPositionToViewPosition(new Position$2(modelRange.fromLineNumber, 1)).lineNumber;
        const viewEndLineNumber = this.coordinatesConverter.convertModelPositionToViewPosition(new Position$2(modelRange.toLineNumber, this.model.getLineMaxColumn(modelRange.toLineNumber))).lineNumber;
        viewRanges[j] = {
          fromLineNumber: viewStartLineNumber,
          toLineNumber: viewEndLineNumber
        };
      }
      this._eventDispatcher.emitSingleViewEvent(new ViewTokensChangedEvent(viewRanges));
      this._eventDispatcher.emitOutgoingEvent(new ModelTokensChangedEvent(e));
    }));
    this._register(this.model.onDidChangeLanguageConfiguration((e) => {
      this._eventDispatcher.emitSingleViewEvent(new ViewLanguageConfigurationEvent());
      this.cursorConfig = new CursorConfiguration(this.model.getLanguageId(), this.model.getOptions(), this._configuration, this.languageConfigurationService);
      this._cursor.updateConfiguration(this.cursorConfig);
      this._eventDispatcher.emitOutgoingEvent(new ModelLanguageConfigurationChangedEvent(e));
    }));
    this._register(this.model.onDidChangeLanguage((e) => {
      this.cursorConfig = new CursorConfiguration(this.model.getLanguageId(), this.model.getOptions(), this._configuration, this.languageConfigurationService);
      this._cursor.updateConfiguration(this.cursorConfig);
      this._eventDispatcher.emitOutgoingEvent(new ModelLanguageChangedEvent(e));
    }));
    this._register(this.model.onDidChangeOptions((e) => {
      if (this._lines.setTabSize(this.model.getOptions().tabSize)) {
        try {
          const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
          eventsCollector.emitViewEvent(new ViewFlushedEvent());
          eventsCollector.emitViewEvent(new ViewLineMappingChangedEvent());
          eventsCollector.emitViewEvent(new ViewDecorationsChangedEvent(null));
          this._cursor.onLineMappingChanged(eventsCollector);
          this._decorations.onLineMappingChanged();
          this.viewLayout.onFlushed(this.getLineCount());
        } finally {
          this._eventDispatcher.endEmitViewEvents();
        }
        this._updateConfigurationViewLineCount.schedule();
      }
      this.cursorConfig = new CursorConfiguration(this.model.getLanguageId(), this.model.getOptions(), this._configuration, this.languageConfigurationService);
      this._cursor.updateConfiguration(this.cursorConfig);
      this._eventDispatcher.emitOutgoingEvent(new ModelOptionsChangedEvent(e));
    }));
    this._register(this.model.onDidChangeDecorations((e) => {
      this._decorations.onModelDecorationsChanged();
      this._eventDispatcher.emitSingleViewEvent(new ViewDecorationsChangedEvent(e));
      this._eventDispatcher.emitOutgoingEvent(new ModelDecorationsChangedEvent(e));
    }));
  }
  setHiddenAreas(ranges, source) {
    this.hiddenAreasModel.setHiddenAreas(source, ranges);
    const mergedRanges = this.hiddenAreasModel.getMergedRanges();
    if (mergedRanges === this.previousHiddenAreas) {
      return;
    }
    this.previousHiddenAreas = mergedRanges;
    const stableViewport = this._captureStableViewport();
    let lineMappingChanged = false;
    try {
      const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
      lineMappingChanged = this._lines.setHiddenAreas(mergedRanges);
      if (lineMappingChanged) {
        eventsCollector.emitViewEvent(new ViewFlushedEvent());
        eventsCollector.emitViewEvent(new ViewLineMappingChangedEvent());
        eventsCollector.emitViewEvent(new ViewDecorationsChangedEvent(null));
        this._cursor.onLineMappingChanged(eventsCollector);
        this._decorations.onLineMappingChanged();
        this.viewLayout.onFlushed(this.getLineCount());
        this.viewLayout.onHeightMaybeChanged();
      }
      stableViewport.recoverViewportStart(this.coordinatesConverter, this.viewLayout);
    } finally {
      this._eventDispatcher.endEmitViewEvents();
    }
    this._updateConfigurationViewLineCount.schedule();
    if (lineMappingChanged) {
      this._eventDispatcher.emitOutgoingEvent(new HiddenAreasChangedEvent());
    }
  }
  getVisibleRangesPlusViewportAboveBelow() {
    const layoutInfo = this._configuration.options.get(
      142
      /* EditorOption.layoutInfo */
    );
    const lineHeight = this._configuration.options.get(
      65
      /* EditorOption.lineHeight */
    );
    const linesAround = Math.max(20, Math.round(layoutInfo.height / lineHeight));
    const partialData = this.viewLayout.getLinesViewportData();
    const startViewLineNumber = Math.max(1, partialData.completelyVisibleStartLineNumber - linesAround);
    const endViewLineNumber = Math.min(this.getLineCount(), partialData.completelyVisibleEndLineNumber + linesAround);
    return this._toModelVisibleRanges(new Range$2(startViewLineNumber, this.getLineMinColumn(startViewLineNumber), endViewLineNumber, this.getLineMaxColumn(endViewLineNumber)));
  }
  getVisibleRanges() {
    const visibleViewRange = this.getCompletelyVisibleViewRange();
    return this._toModelVisibleRanges(visibleViewRange);
  }
  getHiddenAreas() {
    return this._lines.getHiddenAreas();
  }
  _toModelVisibleRanges(visibleViewRange) {
    const visibleRange = this.coordinatesConverter.convertViewRangeToModelRange(visibleViewRange);
    const hiddenAreas = this._lines.getHiddenAreas();
    if (hiddenAreas.length === 0) {
      return [visibleRange];
    }
    const result2 = [];
    let resultLen = 0;
    let startLineNumber = visibleRange.startLineNumber;
    let startColumn = visibleRange.startColumn;
    const endLineNumber = visibleRange.endLineNumber;
    const endColumn = visibleRange.endColumn;
    for (let i = 0, len = hiddenAreas.length; i < len; i++) {
      const hiddenStartLineNumber = hiddenAreas[i].startLineNumber;
      const hiddenEndLineNumber = hiddenAreas[i].endLineNumber;
      if (hiddenEndLineNumber < startLineNumber) {
        continue;
      }
      if (hiddenStartLineNumber > endLineNumber) {
        continue;
      }
      if (startLineNumber < hiddenStartLineNumber) {
        result2[resultLen++] = new Range$2(startLineNumber, startColumn, hiddenStartLineNumber - 1, this.model.getLineMaxColumn(hiddenStartLineNumber - 1));
      }
      startLineNumber = hiddenEndLineNumber + 1;
      startColumn = 1;
    }
    if (startLineNumber < endLineNumber || startLineNumber === endLineNumber && startColumn < endColumn) {
      result2[resultLen++] = new Range$2(startLineNumber, startColumn, endLineNumber, endColumn);
    }
    return result2;
  }
  getCompletelyVisibleViewRange() {
    const partialData = this.viewLayout.getLinesViewportData();
    const startViewLineNumber = partialData.completelyVisibleStartLineNumber;
    const endViewLineNumber = partialData.completelyVisibleEndLineNumber;
    return new Range$2(startViewLineNumber, this.getLineMinColumn(startViewLineNumber), endViewLineNumber, this.getLineMaxColumn(endViewLineNumber));
  }
  getCompletelyVisibleViewRangeAtScrollTop(scrollTop) {
    const partialData = this.viewLayout.getLinesViewportDataAtScrollTop(scrollTop);
    const startViewLineNumber = partialData.completelyVisibleStartLineNumber;
    const endViewLineNumber = partialData.completelyVisibleEndLineNumber;
    return new Range$2(startViewLineNumber, this.getLineMinColumn(startViewLineNumber), endViewLineNumber, this.getLineMaxColumn(endViewLineNumber));
  }
  saveState() {
    const compatViewState = this.viewLayout.saveState();
    const scrollTop = compatViewState.scrollTop;
    const firstViewLineNumber = this.viewLayout.getLineNumberAtVerticalOffset(scrollTop);
    const firstPosition = this.coordinatesConverter.convertViewPositionToModelPosition(new Position$2(firstViewLineNumber, this.getLineMinColumn(firstViewLineNumber)));
    const firstPositionDeltaTop = this.viewLayout.getVerticalOffsetForLineNumber(firstViewLineNumber) - scrollTop;
    return {
      scrollLeft: compatViewState.scrollLeft,
      firstPosition,
      firstPositionDeltaTop
    };
  }
  reduceRestoreState(state) {
    if (typeof state.firstPosition === "undefined") {
      return this._reduceRestoreStateCompatibility(state);
    }
    const modelPosition = this.model.validatePosition(state.firstPosition);
    const viewPosition = this.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);
    const scrollTop = this.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber) - state.firstPositionDeltaTop;
    return {
      scrollLeft: state.scrollLeft,
      scrollTop
    };
  }
  _reduceRestoreStateCompatibility(state) {
    return {
      scrollLeft: state.scrollLeft,
      scrollTop: state.scrollTopWithoutViewZones
    };
  }
  getTabSize() {
    return this.model.getOptions().tabSize;
  }
  getLineCount() {
    return this._lines.getViewLineCount();
  }
  /**
   * Gives a hint that a lot of requests are about to come in for these line numbers.
   */
  setViewport(startLineNumber, endLineNumber, centeredLineNumber) {
    this._viewportStart.update(this, startLineNumber);
  }
  getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber) {
    return this._lines.getActiveIndentGuide(lineNumber, minLineNumber, maxLineNumber);
  }
  getLinesIndentGuides(startLineNumber, endLineNumber) {
    return this._lines.getViewLinesIndentGuides(startLineNumber, endLineNumber);
  }
  getBracketGuidesInRangeByLine(startLineNumber, endLineNumber, activePosition, options) {
    return this._lines.getViewLinesBracketGuides(startLineNumber, endLineNumber, activePosition, options);
  }
  getLineContent(lineNumber) {
    return this._lines.getViewLineContent(lineNumber);
  }
  getLineLength(lineNumber) {
    return this._lines.getViewLineLength(lineNumber);
  }
  getLineMinColumn(lineNumber) {
    return this._lines.getViewLineMinColumn(lineNumber);
  }
  getLineMaxColumn(lineNumber) {
    return this._lines.getViewLineMaxColumn(lineNumber);
  }
  getLineFirstNonWhitespaceColumn(lineNumber) {
    const result2 = firstNonWhitespaceIndex(this.getLineContent(lineNumber));
    if (result2 === -1) {
      return 0;
    }
    return result2 + 1;
  }
  getLineLastNonWhitespaceColumn(lineNumber) {
    const result2 = lastNonWhitespaceIndex(this.getLineContent(lineNumber));
    if (result2 === -1) {
      return 0;
    }
    return result2 + 2;
  }
  getMinimapDecorationsInRange(range2) {
    return this._decorations.getMinimapDecorationsInRange(range2);
  }
  getDecorationsInViewport(visibleRange) {
    return this._decorations.getDecorationsViewportData(visibleRange).decorations;
  }
  getInjectedTextAt(viewPosition) {
    return this._lines.getInjectedTextAt(viewPosition);
  }
  getViewportViewLineRenderingData(visibleRange, lineNumber) {
    const allInlineDecorations = this._decorations.getDecorationsViewportData(visibleRange).inlineDecorations;
    const inlineDecorations = allInlineDecorations[lineNumber - visibleRange.startLineNumber];
    return this._getViewLineRenderingData(lineNumber, inlineDecorations);
  }
  getViewLineRenderingData(lineNumber) {
    const inlineDecorations = this._decorations.getInlineDecorationsOnLine(lineNumber);
    return this._getViewLineRenderingData(lineNumber, inlineDecorations);
  }
  _getViewLineRenderingData(lineNumber, inlineDecorations) {
    const mightContainRTL = this.model.mightContainRTL();
    const mightContainNonBasicASCII = this.model.mightContainNonBasicASCII();
    const tabSize = this.getTabSize();
    const lineData = this._lines.getViewLineData(lineNumber);
    if (lineData.inlineDecorations) {
      inlineDecorations = [
        ...inlineDecorations,
        ...lineData.inlineDecorations.map((d) => d.toInlineDecoration(lineNumber))
      ];
    }
    return new ViewLineRenderingData(lineData.minColumn, lineData.maxColumn, lineData.content, lineData.continuesWithWrappedLine, mightContainRTL, mightContainNonBasicASCII, lineData.tokens, inlineDecorations, tabSize, lineData.startVisibleColumn);
  }
  getViewLineData(lineNumber) {
    return this._lines.getViewLineData(lineNumber);
  }
  getMinimapLinesRenderingData(startLineNumber, endLineNumber, needed) {
    const result2 = this._lines.getViewLinesData(startLineNumber, endLineNumber, needed);
    return new MinimapLinesRenderingData(this.getTabSize(), result2);
  }
  getAllOverviewRulerDecorations(theme) {
    const decorations2 = this.model.getOverviewRulerDecorations(this._editorId, filterValidationDecorations(this._configuration.options));
    const result2 = new OverviewRulerDecorations();
    for (const decoration2 of decorations2) {
      const decorationOptions = decoration2.options;
      const opts = decorationOptions.overviewRuler;
      if (!opts) {
        continue;
      }
      const lane = opts.position;
      if (lane === 0) {
        continue;
      }
      const color = opts.getColor(theme.value);
      const viewStartLineNumber = this.coordinatesConverter.getViewLineNumberOfModelPosition(decoration2.range.startLineNumber, decoration2.range.startColumn);
      const viewEndLineNumber = this.coordinatesConverter.getViewLineNumberOfModelPosition(decoration2.range.endLineNumber, decoration2.range.endColumn);
      result2.accept(color, decorationOptions.zIndex, viewStartLineNumber, viewEndLineNumber, lane);
    }
    return result2.asArray;
  }
  _invalidateDecorationsColorCache() {
    const decorations2 = this.model.getOverviewRulerDecorations();
    for (const decoration2 of decorations2) {
      const opts1 = decoration2.options.overviewRuler;
      opts1 === null || opts1 === void 0 ? void 0 : opts1.invalidateCachedColor();
      const opts2 = decoration2.options.minimap;
      opts2 === null || opts2 === void 0 ? void 0 : opts2.invalidateCachedColor();
    }
  }
  getValueInRange(range2, eol) {
    const modelRange = this.coordinatesConverter.convertViewRangeToModelRange(range2);
    return this.model.getValueInRange(modelRange, eol);
  }
  getValueLengthInRange(range2, eol) {
    const modelRange = this.coordinatesConverter.convertViewRangeToModelRange(range2);
    return this.model.getValueLengthInRange(modelRange, eol);
  }
  modifyPosition(position, offset) {
    const modelPosition = this.coordinatesConverter.convertViewPositionToModelPosition(position);
    return this.model.modifyPosition(modelPosition, offset);
  }
  deduceModelPositionRelativeToViewPosition(viewAnchorPosition, deltaOffset, lineFeedCnt) {
    const modelAnchor = this.coordinatesConverter.convertViewPositionToModelPosition(viewAnchorPosition);
    if (this.model.getEOL().length === 2) {
      if (deltaOffset < 0) {
        deltaOffset -= lineFeedCnt;
      } else {
        deltaOffset += lineFeedCnt;
      }
    }
    const modelAnchorOffset = this.model.getOffsetAt(modelAnchor);
    const resultOffset = modelAnchorOffset + deltaOffset;
    return this.model.getPositionAt(resultOffset);
  }
  getPlainTextToCopy(modelRanges, emptySelectionClipboard, forceCRLF) {
    const newLineCharacter = forceCRLF ? "\r\n" : this.model.getEOL();
    modelRanges = modelRanges.slice(0);
    modelRanges.sort(Range$2.compareRangesUsingStarts);
    let hasEmptyRange = false;
    let hasNonEmptyRange = false;
    for (const range2 of modelRanges) {
      if (range2.isEmpty()) {
        hasEmptyRange = true;
      } else {
        hasNonEmptyRange = true;
      }
    }
    if (!hasNonEmptyRange) {
      if (!emptySelectionClipboard) {
        return "";
      }
      const modelLineNumbers = modelRanges.map((r) => r.startLineNumber);
      let result3 = "";
      for (let i = 0; i < modelLineNumbers.length; i++) {
        if (i > 0 && modelLineNumbers[i - 1] === modelLineNumbers[i]) {
          continue;
        }
        result3 += this.model.getLineContent(modelLineNumbers[i]) + newLineCharacter;
      }
      return result3;
    }
    if (hasEmptyRange && emptySelectionClipboard) {
      const result3 = [];
      let prevModelLineNumber = 0;
      for (const modelRange of modelRanges) {
        const modelLineNumber = modelRange.startLineNumber;
        if (modelRange.isEmpty()) {
          if (modelLineNumber !== prevModelLineNumber) {
            result3.push(this.model.getLineContent(modelLineNumber));
          }
        } else {
          result3.push(this.model.getValueInRange(
            modelRange,
            forceCRLF ? 2 : 0
            /* EndOfLinePreference.TextDefined */
          ));
        }
        prevModelLineNumber = modelLineNumber;
      }
      return result3.length === 1 ? result3[0] : result3;
    }
    const result2 = [];
    for (const modelRange of modelRanges) {
      if (!modelRange.isEmpty()) {
        result2.push(this.model.getValueInRange(
          modelRange,
          forceCRLF ? 2 : 0
          /* EndOfLinePreference.TextDefined */
        ));
      }
    }
    return result2.length === 1 ? result2[0] : result2;
  }
  getRichTextToCopy(modelRanges, emptySelectionClipboard) {
    const languageId = this.model.getLanguageId();
    if (languageId === PLAINTEXT_LANGUAGE_ID) {
      return null;
    }
    if (modelRanges.length !== 1) {
      return null;
    }
    let range2 = modelRanges[0];
    if (range2.isEmpty()) {
      if (!emptySelectionClipboard) {
        return null;
      }
      const lineNumber = range2.startLineNumber;
      range2 = new Range$2(lineNumber, this.model.getLineMinColumn(lineNumber), lineNumber, this.model.getLineMaxColumn(lineNumber));
    }
    const fontInfo = this._configuration.options.get(
      49
      /* EditorOption.fontInfo */
    );
    const colorMap = this._getColorMap();
    const hasBadChars = /[:;\\\/<>]/.test(fontInfo.fontFamily);
    const useDefaultFontFamily = hasBadChars || fontInfo.fontFamily === EDITOR_FONT_DEFAULTS.fontFamily;
    let fontFamily;
    if (useDefaultFontFamily) {
      fontFamily = EDITOR_FONT_DEFAULTS.fontFamily;
    } else {
      fontFamily = fontInfo.fontFamily;
      fontFamily = fontFamily.replace(/"/g, "'");
      const hasQuotesOrIsList = /[,']/.test(fontFamily);
      if (!hasQuotesOrIsList) {
        const needsQuotes = /[+ ]/.test(fontFamily);
        if (needsQuotes) {
          fontFamily = `'${fontFamily}'`;
        }
      }
      fontFamily = `${fontFamily}, ${EDITOR_FONT_DEFAULTS.fontFamily}`;
    }
    return {
      mode: languageId,
      html: `<div style="color: ${colorMap[
        1
        /* ColorId.DefaultForeground */
      ]};background-color: ${colorMap[
        2
        /* ColorId.DefaultBackground */
      ]};font-family: ${fontFamily};font-weight: ${fontInfo.fontWeight};font-size: ${fontInfo.fontSize}px;line-height: ${fontInfo.lineHeight}px;white-space: pre;">` + this._getHTMLToCopy(range2, colorMap) + "</div>"
    };
  }
  _getHTMLToCopy(modelRange, colorMap) {
    const startLineNumber = modelRange.startLineNumber;
    const startColumn = modelRange.startColumn;
    const endLineNumber = modelRange.endLineNumber;
    const endColumn = modelRange.endColumn;
    const tabSize = this.getTabSize();
    let result2 = "";
    for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
      const lineTokens = this.model.tokenization.getLineTokens(lineNumber);
      const lineContent = lineTokens.getLineContent();
      const startOffset = lineNumber === startLineNumber ? startColumn - 1 : 0;
      const endOffset = lineNumber === endLineNumber ? endColumn - 1 : lineContent.length;
      if (lineContent === "") {
        result2 += "<br>";
      } else {
        result2 += tokenizeLineToHTML(lineContent, lineTokens.inflate(), colorMap, startOffset, endOffset, tabSize, isWindows);
      }
    }
    return result2;
  }
  _getColorMap() {
    const colorMap = TokenizationRegistry2.getColorMap();
    const result2 = ["#000000"];
    if (colorMap) {
      for (let i = 1, len = colorMap.length; i < len; i++) {
        result2[i] = Color.Format.CSS.formatHex(colorMap[i]);
      }
    }
    return result2;
  }
  //#region cursor operations
  getPrimaryCursorState() {
    return this._cursor.getPrimaryCursorState();
  }
  getLastAddedCursorIndex() {
    return this._cursor.getLastAddedCursorIndex();
  }
  getCursorStates() {
    return this._cursor.getCursorStates();
  }
  setCursorStates(source, reason, states) {
    return this._withViewEventsCollector((eventsCollector) => this._cursor.setStates(eventsCollector, source, reason, states));
  }
  getCursorColumnSelectData() {
    return this._cursor.getCursorColumnSelectData();
  }
  getCursorAutoClosedCharacters() {
    return this._cursor.getAutoClosedCharacters();
  }
  setCursorColumnSelectData(columnSelectData) {
    this._cursor.setCursorColumnSelectData(columnSelectData);
  }
  getPrevEditOperationType() {
    return this._cursor.getPrevEditOperationType();
  }
  setPrevEditOperationType(type) {
    this._cursor.setPrevEditOperationType(type);
  }
  getSelection() {
    return this._cursor.getSelection();
  }
  getSelections() {
    return this._cursor.getSelections();
  }
  getPosition() {
    return this._cursor.getPrimaryCursorState().modelState.position;
  }
  setSelections(source, selections2, reason = 0) {
    this._withViewEventsCollector((eventsCollector) => this._cursor.setSelections(eventsCollector, source, selections2, reason));
  }
  saveCursorState() {
    return this._cursor.saveState();
  }
  restoreCursorState(states) {
    this._withViewEventsCollector((eventsCollector) => this._cursor.restoreState(eventsCollector, states));
  }
  _executeCursorEdit(callback) {
    if (this._cursor.context.cursorConfig.readOnly) {
      this._eventDispatcher.emitOutgoingEvent(new ReadOnlyEditAttemptEvent());
      return;
    }
    this._withViewEventsCollector(callback);
  }
  executeEdits(source, edits, cursorStateComputer) {
    this._executeCursorEdit((eventsCollector) => this._cursor.executeEdits(eventsCollector, source, edits, cursorStateComputer));
  }
  startComposition() {
    this._executeCursorEdit((eventsCollector) => this._cursor.startComposition(eventsCollector));
  }
  endComposition(source) {
    this._executeCursorEdit((eventsCollector) => this._cursor.endComposition(eventsCollector, source));
  }
  type(text2, source) {
    this._executeCursorEdit((eventsCollector) => this._cursor.type(eventsCollector, text2, source));
  }
  compositionType(text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta, source) {
    this._executeCursorEdit((eventsCollector) => this._cursor.compositionType(eventsCollector, text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta, source));
  }
  paste(text2, pasteOnNewLine, multicursorText, source) {
    this._executeCursorEdit((eventsCollector) => this._cursor.paste(eventsCollector, text2, pasteOnNewLine, multicursorText, source));
  }
  cut(source) {
    this._executeCursorEdit((eventsCollector) => this._cursor.cut(eventsCollector, source));
  }
  executeCommand(command, source) {
    this._executeCursorEdit((eventsCollector) => this._cursor.executeCommand(eventsCollector, command, source));
  }
  executeCommands(commands, source) {
    this._executeCursorEdit((eventsCollector) => this._cursor.executeCommands(eventsCollector, commands, source));
  }
  revealPrimaryCursor(source, revealHorizontal, minimalReveal = false) {
    this._withViewEventsCollector((eventsCollector) => this._cursor.revealPrimary(
      eventsCollector,
      source,
      minimalReveal,
      0,
      revealHorizontal,
      0
      /* ScrollType.Smooth */
    ));
  }
  revealTopMostCursor(source) {
    const viewPosition = this._cursor.getTopMostViewPosition();
    const viewRange = new Range$2(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column);
    this._withViewEventsCollector((eventsCollector) => eventsCollector.emitViewEvent(new ViewRevealRangeRequestEvent(
      source,
      false,
      viewRange,
      null,
      0,
      true,
      0
      /* ScrollType.Smooth */
    )));
  }
  revealBottomMostCursor(source) {
    const viewPosition = this._cursor.getBottomMostViewPosition();
    const viewRange = new Range$2(viewPosition.lineNumber, viewPosition.column, viewPosition.lineNumber, viewPosition.column);
    this._withViewEventsCollector((eventsCollector) => eventsCollector.emitViewEvent(new ViewRevealRangeRequestEvent(
      source,
      false,
      viewRange,
      null,
      0,
      true,
      0
      /* ScrollType.Smooth */
    )));
  }
  revealRange(source, revealHorizontal, viewRange, verticalType, scrollType) {
    this._withViewEventsCollector((eventsCollector) => eventsCollector.emitViewEvent(new ViewRevealRangeRequestEvent(source, false, viewRange, null, verticalType, revealHorizontal, scrollType)));
  }
  //#endregion
  //#region viewLayout
  changeWhitespace(callback) {
    const hadAChange = this.viewLayout.changeWhitespace(callback);
    if (hadAChange) {
      this._eventDispatcher.emitSingleViewEvent(new ViewZonesChangedEvent$1());
      this._eventDispatcher.emitOutgoingEvent(new ViewZonesChangedEvent2());
    }
  }
  //#endregion
  _withViewEventsCollector(callback) {
    try {
      const eventsCollector = this._eventDispatcher.beginEmitViewEvents();
      return callback(eventsCollector);
    } finally {
      this._eventDispatcher.endEmitViewEvents();
    }
  }
  normalizePosition(position, affinity) {
    return this._lines.normalizePosition(position, affinity);
  }
  /**
   * Gets the column at which indentation stops at a given line.
   * @internal
  */
  getLineIndentColumn(lineNumber) {
    return this._lines.getLineIndentColumn(lineNumber);
  }
};
class ViewportStart {
  static create(model) {
    const viewportStartLineTrackedRange = model._setTrackedRange(
      null,
      new Range$2(1, 1, 1, 1),
      1
      /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
    );
    return new ViewportStart(model, 1, false, viewportStartLineTrackedRange, 0);
  }
  get viewLineNumber() {
    return this._viewLineNumber;
  }
  get isValid() {
    return this._isValid;
  }
  get modelTrackedRange() {
    return this._modelTrackedRange;
  }
  get startLineDelta() {
    return this._startLineDelta;
  }
  constructor(_model, _viewLineNumber, _isValid, _modelTrackedRange, _startLineDelta) {
    this._model = _model;
    this._viewLineNumber = _viewLineNumber;
    this._isValid = _isValid;
    this._modelTrackedRange = _modelTrackedRange;
    this._startLineDelta = _startLineDelta;
  }
  dispose() {
    this._model._setTrackedRange(
      this._modelTrackedRange,
      null,
      1
      /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
    );
  }
  update(viewModel, startLineNumber) {
    const position = viewModel.coordinatesConverter.convertViewPositionToModelPosition(new Position$2(startLineNumber, viewModel.getLineMinColumn(startLineNumber)));
    const viewportStartLineTrackedRange = viewModel.model._setTrackedRange(
      this._modelTrackedRange,
      new Range$2(position.lineNumber, position.column, position.lineNumber, position.column),
      1
      /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
    );
    const viewportStartLineTop = viewModel.viewLayout.getVerticalOffsetForLineNumber(startLineNumber);
    const scrollTop = viewModel.viewLayout.getCurrentScrollTop();
    this._viewLineNumber = startLineNumber;
    this._isValid = true;
    this._modelTrackedRange = viewportStartLineTrackedRange;
    this._startLineDelta = scrollTop - viewportStartLineTop;
  }
  invalidate() {
    this._isValid = false;
  }
}
class OverviewRulerDecorations {
  constructor() {
    this._asMap = /* @__PURE__ */ Object.create(null);
    this.asArray = [];
  }
  accept(color, zIndex, startLineNumber, endLineNumber, lane) {
    const prevGroup = this._asMap[color];
    if (prevGroup) {
      const prevData = prevGroup.data;
      const prevLane = prevData[prevData.length - 3];
      const prevEndLineNumber = prevData[prevData.length - 1];
      if (prevLane === lane && prevEndLineNumber + 1 >= startLineNumber) {
        if (endLineNumber > prevEndLineNumber) {
          prevData[prevData.length - 1] = endLineNumber;
        }
        return;
      }
      prevData.push(lane, startLineNumber, endLineNumber);
    } else {
      const group2 = new OverviewRulerDecorationsGroup(color, zIndex, [lane, startLineNumber, endLineNumber]);
      this._asMap[color] = group2;
      this.asArray.push(group2);
    }
  }
}
class HiddenAreasModel {
  constructor() {
    this.hiddenAreas = /* @__PURE__ */ new Map();
    this.shouldRecompute = false;
    this.ranges = [];
  }
  setHiddenAreas(source, ranges) {
    const existing = this.hiddenAreas.get(source);
    if (existing && rangeArraysEqual(existing, ranges)) {
      return;
    }
    this.hiddenAreas.set(source, ranges);
    this.shouldRecompute = true;
  }
  /**
   * The returned array is immutable.
  */
  getMergedRanges() {
    if (!this.shouldRecompute) {
      return this.ranges;
    }
    this.shouldRecompute = false;
    const newRanges = Array.from(this.hiddenAreas.values()).reduce((r, hiddenAreas) => mergeLineRangeArray(r, hiddenAreas), []);
    if (rangeArraysEqual(this.ranges, newRanges)) {
      return this.ranges;
    }
    this.ranges = newRanges;
    return this.ranges;
  }
}
function mergeLineRangeArray(arr1, arr2) {
  const result2 = [];
  let i = 0;
  let j = 0;
  while (i < arr1.length && j < arr2.length) {
    const item1 = arr1[i];
    const item2 = arr2[j];
    if (item1.endLineNumber < item2.startLineNumber - 1) {
      result2.push(arr1[i++]);
    } else if (item2.endLineNumber < item1.startLineNumber - 1) {
      result2.push(arr2[j++]);
    } else {
      const startLineNumber = Math.min(item1.startLineNumber, item2.startLineNumber);
      const endLineNumber = Math.max(item1.endLineNumber, item2.endLineNumber);
      result2.push(new Range$2(startLineNumber, 1, endLineNumber, 1));
      i++;
      j++;
    }
  }
  while (i < arr1.length) {
    result2.push(arr1[i++]);
  }
  while (j < arr2.length) {
    result2.push(arr2[j++]);
  }
  return result2;
}
function rangeArraysEqual(arr1, arr2) {
  if (arr1.length !== arr2.length) {
    return false;
  }
  for (let i = 0; i < arr1.length; i++) {
    if (!arr1[i].equalsRange(arr2[i])) {
      return false;
    }
  }
  return true;
}
class StableViewport {
  constructor(viewportStartModelPosition, startLineDelta) {
    this.viewportStartModelPosition = viewportStartModelPosition;
    this.startLineDelta = startLineDelta;
  }
  recoverViewportStart(coordinatesConverter, viewLayout) {
    if (!this.viewportStartModelPosition) {
      return;
    }
    const viewPosition = coordinatesConverter.convertModelPositionToViewPosition(this.viewportStartModelPosition);
    const viewPositionTop = viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber);
    viewLayout.setScrollPosition(
      { scrollTop: viewPositionTop + this.startLineDelta },
      1
      /* ScrollType.Immediate */
    );
  }
}
class ServiceCollection {
  constructor(...entries) {
    this._entries = /* @__PURE__ */ new Map();
    for (const [id3, service] of entries) {
      this.set(id3, service);
    }
  }
  set(id3, instanceOrDescriptor) {
    const result2 = this._entries.get(id3);
    this._entries.set(id3, instanceOrDescriptor);
    return result2;
  }
  get(id3) {
    return this._entries.get(id3);
  }
}
var Severity$1;
(function(Severity2) {
  Severity2[Severity2["Ignore"] = 0] = "Ignore";
  Severity2[Severity2["Info"] = 1] = "Info";
  Severity2[Severity2["Warning"] = 2] = "Warning";
  Severity2[Severity2["Error"] = 3] = "Error";
})(Severity$1 || (Severity$1 = {}));
(function(Severity2) {
  const _error = "error";
  const _warning = "warning";
  const _warn = "warn";
  const _info = "info";
  const _ignore = "ignore";
  function fromValue(value) {
    if (!value) {
      return Severity2.Ignore;
    }
    if (equalsIgnoreCase(_error, value)) {
      return Severity2.Error;
    }
    if (equalsIgnoreCase(_warning, value) || equalsIgnoreCase(_warn, value)) {
      return Severity2.Warning;
    }
    if (equalsIgnoreCase(_info, value)) {
      return Severity2.Info;
    }
    return Severity2.Ignore;
  }
  Severity2.fromValue = fromValue;
  function toString3(severity) {
    switch (severity) {
      case Severity2.Error:
        return _error;
      case Severity2.Warning:
        return _warning;
      case Severity2.Info:
        return _info;
      default:
        return _ignore;
    }
  }
  Severity2.toString = toString3;
})(Severity$1 || (Severity$1 = {}));
const Severity$2 = Severity$1;
var Severity = Severity$2;
const INotificationService = createDecorator("notificationService");
class NoOpNotification {
}
class ModelLineProjectionData {
  constructor(injectionOffsets, injectionOptions, breakOffsets, breakOffsetsVisibleColumn, wrappedTextIndentLength) {
    this.injectionOffsets = injectionOffsets;
    this.injectionOptions = injectionOptions;
    this.breakOffsets = breakOffsets;
    this.breakOffsetsVisibleColumn = breakOffsetsVisibleColumn;
    this.wrappedTextIndentLength = wrappedTextIndentLength;
  }
  getOutputLineCount() {
    return this.breakOffsets.length;
  }
  getMinOutputOffset(outputLineIndex) {
    if (outputLineIndex > 0) {
      return this.wrappedTextIndentLength;
    }
    return 0;
  }
  getLineLength(outputLineIndex) {
    const startOffset = outputLineIndex > 0 ? this.breakOffsets[outputLineIndex - 1] : 0;
    const endOffset = this.breakOffsets[outputLineIndex];
    let lineLength = endOffset - startOffset;
    if (outputLineIndex > 0) {
      lineLength += this.wrappedTextIndentLength;
    }
    return lineLength;
  }
  getMaxOutputOffset(outputLineIndex) {
    return this.getLineLength(outputLineIndex);
  }
  translateToInputOffset(outputLineIndex, outputOffset) {
    if (outputLineIndex > 0) {
      outputOffset = Math.max(0, outputOffset - this.wrappedTextIndentLength);
    }
    const offsetInInputWithInjection = outputLineIndex === 0 ? outputOffset : this.breakOffsets[outputLineIndex - 1] + outputOffset;
    let offsetInInput = offsetInInputWithInjection;
    if (this.injectionOffsets !== null) {
      for (let i = 0; i < this.injectionOffsets.length; i++) {
        if (offsetInInput > this.injectionOffsets[i]) {
          if (offsetInInput < this.injectionOffsets[i] + this.injectionOptions[i].content.length) {
            offsetInInput = this.injectionOffsets[i];
          } else {
            offsetInInput -= this.injectionOptions[i].content.length;
          }
        } else {
          break;
        }
      }
    }
    return offsetInInput;
  }
  translateToOutputPosition(inputOffset, affinity = 2) {
    let inputOffsetInInputWithInjection = inputOffset;
    if (this.injectionOffsets !== null) {
      for (let i = 0; i < this.injectionOffsets.length; i++) {
        if (inputOffset < this.injectionOffsets[i]) {
          break;
        }
        if (affinity !== 1 && inputOffset === this.injectionOffsets[i]) {
          break;
        }
        inputOffsetInInputWithInjection += this.injectionOptions[i].content.length;
      }
    }
    return this.offsetInInputWithInjectionsToOutputPosition(inputOffsetInInputWithInjection, affinity);
  }
  offsetInInputWithInjectionsToOutputPosition(offsetInInputWithInjections, affinity = 2) {
    let low = 0;
    let high = this.breakOffsets.length - 1;
    let mid = 0;
    let midStart = 0;
    while (low <= high) {
      mid = low + (high - low) / 2 | 0;
      const midStop = this.breakOffsets[mid];
      midStart = mid > 0 ? this.breakOffsets[mid - 1] : 0;
      if (affinity === 0) {
        if (offsetInInputWithInjections <= midStart) {
          high = mid - 1;
        } else if (offsetInInputWithInjections > midStop) {
          low = mid + 1;
        } else {
          break;
        }
      } else {
        if (offsetInInputWithInjections < midStart) {
          high = mid - 1;
        } else if (offsetInInputWithInjections >= midStop) {
          low = mid + 1;
        } else {
          break;
        }
      }
    }
    let outputOffset = offsetInInputWithInjections - midStart;
    if (mid > 0) {
      outputOffset += this.wrappedTextIndentLength;
    }
    return new OutputPosition(mid, outputOffset);
  }
  normalizeOutputPosition(outputLineIndex, outputOffset, affinity) {
    if (this.injectionOffsets !== null) {
      const offsetInInputWithInjections = this.outputPositionToOffsetInInputWithInjections(outputLineIndex, outputOffset);
      const normalizedOffsetInUnwrappedLine = this.normalizeOffsetInInputWithInjectionsAroundInjections(offsetInInputWithInjections, affinity);
      if (normalizedOffsetInUnwrappedLine !== offsetInInputWithInjections) {
        return this.offsetInInputWithInjectionsToOutputPosition(normalizedOffsetInUnwrappedLine, affinity);
      }
    }
    if (affinity === 0) {
      if (outputLineIndex > 0 && outputOffset === this.getMinOutputOffset(outputLineIndex)) {
        return new OutputPosition(outputLineIndex - 1, this.getMaxOutputOffset(outputLineIndex - 1));
      }
    } else if (affinity === 1) {
      const maxOutputLineIndex = this.getOutputLineCount() - 1;
      if (outputLineIndex < maxOutputLineIndex && outputOffset === this.getMaxOutputOffset(outputLineIndex)) {
        return new OutputPosition(outputLineIndex + 1, this.getMinOutputOffset(outputLineIndex + 1));
      }
    }
    return new OutputPosition(outputLineIndex, outputOffset);
  }
  outputPositionToOffsetInInputWithInjections(outputLineIndex, outputOffset) {
    if (outputLineIndex > 0) {
      outputOffset = Math.max(0, outputOffset - this.wrappedTextIndentLength);
    }
    const result2 = (outputLineIndex > 0 ? this.breakOffsets[outputLineIndex - 1] : 0) + outputOffset;
    return result2;
  }
  normalizeOffsetInInputWithInjectionsAroundInjections(offsetInInputWithInjections, affinity) {
    const injectedText = this.getInjectedTextAtOffset(offsetInInputWithInjections);
    if (!injectedText) {
      return offsetInInputWithInjections;
    }
    if (affinity === 2) {
      if (offsetInInputWithInjections === injectedText.offsetInInputWithInjections + injectedText.length && hasRightCursorStop(this.injectionOptions[injectedText.injectedTextIndex].cursorStops)) {
        return injectedText.offsetInInputWithInjections + injectedText.length;
      } else {
        let result2 = injectedText.offsetInInputWithInjections;
        if (hasLeftCursorStop(this.injectionOptions[injectedText.injectedTextIndex].cursorStops)) {
          return result2;
        }
        let index = injectedText.injectedTextIndex - 1;
        while (index >= 0 && this.injectionOffsets[index] === this.injectionOffsets[injectedText.injectedTextIndex]) {
          if (hasRightCursorStop(this.injectionOptions[index].cursorStops)) {
            break;
          }
          result2 -= this.injectionOptions[index].content.length;
          if (hasLeftCursorStop(this.injectionOptions[index].cursorStops)) {
            break;
          }
          index--;
        }
        return result2;
      }
    } else if (affinity === 1 || affinity === 4) {
      let result2 = injectedText.offsetInInputWithInjections + injectedText.length;
      let index = injectedText.injectedTextIndex;
      while (index + 1 < this.injectionOffsets.length && this.injectionOffsets[index + 1] === this.injectionOffsets[index]) {
        result2 += this.injectionOptions[index + 1].content.length;
        index++;
      }
      return result2;
    } else if (affinity === 0 || affinity === 3) {
      let result2 = injectedText.offsetInInputWithInjections;
      let index = injectedText.injectedTextIndex;
      while (index - 1 >= 0 && this.injectionOffsets[index - 1] === this.injectionOffsets[index]) {
        result2 -= this.injectionOptions[index - 1].content.length;
        index--;
      }
      return result2;
    }
    assertNever();
  }
  getInjectedText(outputLineIndex, outputOffset) {
    const offset = this.outputPositionToOffsetInInputWithInjections(outputLineIndex, outputOffset);
    const injectedText = this.getInjectedTextAtOffset(offset);
    if (!injectedText) {
      return null;
    }
    return {
      options: this.injectionOptions[injectedText.injectedTextIndex]
    };
  }
  getInjectedTextAtOffset(offsetInInputWithInjections) {
    const injectionOffsets = this.injectionOffsets;
    const injectionOptions = this.injectionOptions;
    if (injectionOffsets !== null) {
      let totalInjectedTextLengthBefore = 0;
      for (let i = 0; i < injectionOffsets.length; i++) {
        const length2 = injectionOptions[i].content.length;
        const injectedTextStartOffsetInInputWithInjections = injectionOffsets[i] + totalInjectedTextLengthBefore;
        const injectedTextEndOffsetInInputWithInjections = injectionOffsets[i] + totalInjectedTextLengthBefore + length2;
        if (injectedTextStartOffsetInInputWithInjections > offsetInInputWithInjections) {
          break;
        }
        if (offsetInInputWithInjections <= injectedTextEndOffsetInInputWithInjections) {
          return {
            injectedTextIndex: i,
            offsetInInputWithInjections: injectedTextStartOffsetInInputWithInjections,
            length: length2
          };
        }
        totalInjectedTextLengthBefore += length2;
      }
    }
    return void 0;
  }
}
function hasRightCursorStop(cursorStop) {
  if (cursorStop === null || cursorStop === void 0) {
    return true;
  }
  return cursorStop === InjectedTextCursorStops$1.Right || cursorStop === InjectedTextCursorStops$1.Both;
}
function hasLeftCursorStop(cursorStop) {
  if (cursorStop === null || cursorStop === void 0) {
    return true;
  }
  return cursorStop === InjectedTextCursorStops$1.Left || cursorStop === InjectedTextCursorStops$1.Both;
}
class OutputPosition {
  constructor(outputLineIndex, outputOffset) {
    this.outputLineIndex = outputLineIndex;
    this.outputOffset = outputOffset;
  }
  toString() {
    return `${this.outputLineIndex}:${this.outputOffset}`;
  }
  toPosition(baseLineNumber) {
    return new Position$2(baseLineNumber + this.outputLineIndex, this.outputOffset + 1);
  }
}
class MonospaceLineBreaksComputerFactory {
  static create(options) {
    return new MonospaceLineBreaksComputerFactory(options.get(
      131
      /* EditorOption.wordWrapBreakBeforeCharacters */
    ), options.get(
      130
      /* EditorOption.wordWrapBreakAfterCharacters */
    ));
  }
  constructor(breakBeforeChars, breakAfterChars) {
    this.classifier = new WrappingCharacterClassifier(breakBeforeChars, breakAfterChars);
  }
  createLineBreaksComputer(fontInfo, tabSize, wrappingColumn, wrappingIndent, wordBreak) {
    const requests = [];
    const injectedTexts = [];
    const previousBreakingData = [];
    return {
      addRequest: (lineText, injectedText, previousLineBreakData) => {
        requests.push(lineText);
        injectedTexts.push(injectedText);
        previousBreakingData.push(previousLineBreakData);
      },
      finalize: () => {
        const columnsForFullWidthChar = fontInfo.typicalFullwidthCharacterWidth / fontInfo.typicalHalfwidthCharacterWidth;
        const result2 = [];
        for (let i = 0, len = requests.length; i < len; i++) {
          const injectedText = injectedTexts[i];
          const previousLineBreakData = previousBreakingData[i];
          if (previousLineBreakData && !previousLineBreakData.injectionOptions && !injectedText) {
            result2[i] = createLineBreaksFromPreviousLineBreaks(this.classifier, previousLineBreakData, requests[i], tabSize, wrappingColumn, columnsForFullWidthChar, wrappingIndent, wordBreak);
          } else {
            result2[i] = createLineBreaks$1(this.classifier, requests[i], injectedText, tabSize, wrappingColumn, columnsForFullWidthChar, wrappingIndent, wordBreak);
          }
        }
        arrPool1.length = 0;
        arrPool2.length = 0;
        return result2;
      }
    };
  }
}
class WrappingCharacterClassifier extends CharacterClassifier {
  constructor(BREAK_BEFORE, BREAK_AFTER) {
    super(
      0
      /* CharacterClass.NONE */
    );
    for (let i = 0; i < BREAK_BEFORE.length; i++) {
      this.set(
        BREAK_BEFORE.charCodeAt(i),
        1
        /* CharacterClass.BREAK_BEFORE */
      );
    }
    for (let i = 0; i < BREAK_AFTER.length; i++) {
      this.set(
        BREAK_AFTER.charCodeAt(i),
        2
        /* CharacterClass.BREAK_AFTER */
      );
    }
  }
  get(charCode) {
    if (charCode >= 0 && charCode < 256) {
      return this._asciiMap[charCode];
    } else {
      if (charCode >= 12352 && charCode <= 12543 || charCode >= 13312 && charCode <= 19903 || charCode >= 19968 && charCode <= 40959) {
        return 3;
      }
      return this._map.get(charCode) || this._defaultValue;
    }
  }
}
let arrPool1 = [];
let arrPool2 = [];
function createLineBreaksFromPreviousLineBreaks(classifier, previousBreakingData, lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent, wordBreak) {
  if (firstLineBreakColumn === -1) {
    return null;
  }
  const len = lineText.length;
  if (len <= 1) {
    return null;
  }
  const isKeepAll = wordBreak === "keepAll";
  const prevBreakingOffsets = previousBreakingData.breakOffsets;
  const prevBreakingOffsetsVisibleColumn = previousBreakingData.breakOffsetsVisibleColumn;
  const wrappedTextIndentLength = computeWrappedTextIndentLength(lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent);
  const wrappedLineBreakColumn = firstLineBreakColumn - wrappedTextIndentLength;
  const breakingOffsets = arrPool1;
  const breakingOffsetsVisibleColumn = arrPool2;
  let breakingOffsetsCount = 0;
  let lastBreakingOffset = 0;
  let lastBreakingOffsetVisibleColumn = 0;
  let breakingColumn = firstLineBreakColumn;
  const prevLen = prevBreakingOffsets.length;
  let prevIndex = 0;
  if (prevIndex >= 0) {
    let bestDistance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex] - breakingColumn);
    while (prevIndex + 1 < prevLen) {
      const distance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex + 1] - breakingColumn);
      if (distance >= bestDistance) {
        break;
      }
      bestDistance = distance;
      prevIndex++;
    }
  }
  while (prevIndex < prevLen) {
    let prevBreakOffset = prevIndex < 0 ? 0 : prevBreakingOffsets[prevIndex];
    let prevBreakOffsetVisibleColumn = prevIndex < 0 ? 0 : prevBreakingOffsetsVisibleColumn[prevIndex];
    if (lastBreakingOffset > prevBreakOffset) {
      prevBreakOffset = lastBreakingOffset;
      prevBreakOffsetVisibleColumn = lastBreakingOffsetVisibleColumn;
    }
    let breakOffset = 0;
    let breakOffsetVisibleColumn = 0;
    let forcedBreakOffset = 0;
    let forcedBreakOffsetVisibleColumn = 0;
    if (prevBreakOffsetVisibleColumn <= breakingColumn) {
      let visibleColumn = prevBreakOffsetVisibleColumn;
      let prevCharCode = prevBreakOffset === 0 ? 0 : lineText.charCodeAt(prevBreakOffset - 1);
      let prevCharCodeClass = prevBreakOffset === 0 ? 0 : classifier.get(prevCharCode);
      let entireLineFits = true;
      for (let i = prevBreakOffset; i < len; i++) {
        const charStartOffset = i;
        const charCode = lineText.charCodeAt(i);
        let charCodeClass;
        let charWidth;
        if (isHighSurrogate(charCode)) {
          i++;
          charCodeClass = 0;
          charWidth = 2;
        } else {
          charCodeClass = classifier.get(charCode);
          charWidth = computeCharWidth(charCode, visibleColumn, tabSize, columnsForFullWidthChar);
        }
        if (charStartOffset > lastBreakingOffset && canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass, isKeepAll)) {
          breakOffset = charStartOffset;
          breakOffsetVisibleColumn = visibleColumn;
        }
        visibleColumn += charWidth;
        if (visibleColumn > breakingColumn) {
          if (charStartOffset > lastBreakingOffset) {
            forcedBreakOffset = charStartOffset;
            forcedBreakOffsetVisibleColumn = visibleColumn - charWidth;
          } else {
            forcedBreakOffset = i + 1;
            forcedBreakOffsetVisibleColumn = visibleColumn;
          }
          if (visibleColumn - breakOffsetVisibleColumn > wrappedLineBreakColumn) {
            breakOffset = 0;
          }
          entireLineFits = false;
          break;
        }
        prevCharCode = charCode;
        prevCharCodeClass = charCodeClass;
      }
      if (entireLineFits) {
        if (breakingOffsetsCount > 0) {
          breakingOffsets[breakingOffsetsCount] = prevBreakingOffsets[prevBreakingOffsets.length - 1];
          breakingOffsetsVisibleColumn[breakingOffsetsCount] = prevBreakingOffsetsVisibleColumn[prevBreakingOffsets.length - 1];
          breakingOffsetsCount++;
        }
        break;
      }
    }
    if (breakOffset === 0) {
      let visibleColumn = prevBreakOffsetVisibleColumn;
      let charCode = lineText.charCodeAt(prevBreakOffset);
      let charCodeClass = classifier.get(charCode);
      let hitATabCharacter = false;
      for (let i = prevBreakOffset - 1; i >= lastBreakingOffset; i--) {
        const charStartOffset = i + 1;
        const prevCharCode = lineText.charCodeAt(i);
        if (prevCharCode === 9) {
          hitATabCharacter = true;
          break;
        }
        let prevCharCodeClass;
        let prevCharWidth;
        if (isLowSurrogate(prevCharCode)) {
          i--;
          prevCharCodeClass = 0;
          prevCharWidth = 2;
        } else {
          prevCharCodeClass = classifier.get(prevCharCode);
          prevCharWidth = isFullWidthCharacter(prevCharCode) ? columnsForFullWidthChar : 1;
        }
        if (visibleColumn <= breakingColumn) {
          if (forcedBreakOffset === 0) {
            forcedBreakOffset = charStartOffset;
            forcedBreakOffsetVisibleColumn = visibleColumn;
          }
          if (visibleColumn <= breakingColumn - wrappedLineBreakColumn) {
            break;
          }
          if (canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass, isKeepAll)) {
            breakOffset = charStartOffset;
            breakOffsetVisibleColumn = visibleColumn;
            break;
          }
        }
        visibleColumn -= prevCharWidth;
        charCode = prevCharCode;
        charCodeClass = prevCharCodeClass;
      }
      if (breakOffset !== 0) {
        const remainingWidthOfNextLine = wrappedLineBreakColumn - (forcedBreakOffsetVisibleColumn - breakOffsetVisibleColumn);
        if (remainingWidthOfNextLine <= tabSize) {
          const charCodeAtForcedBreakOffset = lineText.charCodeAt(forcedBreakOffset);
          let charWidth;
          if (isHighSurrogate(charCodeAtForcedBreakOffset)) {
            charWidth = 2;
          } else {
            charWidth = computeCharWidth(charCodeAtForcedBreakOffset, forcedBreakOffsetVisibleColumn, tabSize, columnsForFullWidthChar);
          }
          if (remainingWidthOfNextLine - charWidth < 0) {
            breakOffset = 0;
          }
        }
      }
      if (hitATabCharacter) {
        prevIndex--;
        continue;
      }
    }
    if (breakOffset === 0) {
      breakOffset = forcedBreakOffset;
      breakOffsetVisibleColumn = forcedBreakOffsetVisibleColumn;
    }
    if (breakOffset <= lastBreakingOffset) {
      const charCode = lineText.charCodeAt(lastBreakingOffset);
      if (isHighSurrogate(charCode)) {
        breakOffset = lastBreakingOffset + 2;
        breakOffsetVisibleColumn = lastBreakingOffsetVisibleColumn + 2;
      } else {
        breakOffset = lastBreakingOffset + 1;
        breakOffsetVisibleColumn = lastBreakingOffsetVisibleColumn + computeCharWidth(charCode, lastBreakingOffsetVisibleColumn, tabSize, columnsForFullWidthChar);
      }
    }
    lastBreakingOffset = breakOffset;
    breakingOffsets[breakingOffsetsCount] = breakOffset;
    lastBreakingOffsetVisibleColumn = breakOffsetVisibleColumn;
    breakingOffsetsVisibleColumn[breakingOffsetsCount] = breakOffsetVisibleColumn;
    breakingOffsetsCount++;
    breakingColumn = breakOffsetVisibleColumn + wrappedLineBreakColumn;
    while (prevIndex < 0 || prevIndex < prevLen && prevBreakingOffsetsVisibleColumn[prevIndex] < breakOffsetVisibleColumn) {
      prevIndex++;
    }
    let bestDistance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex] - breakingColumn);
    while (prevIndex + 1 < prevLen) {
      const distance = Math.abs(prevBreakingOffsetsVisibleColumn[prevIndex + 1] - breakingColumn);
      if (distance >= bestDistance) {
        break;
      }
      bestDistance = distance;
      prevIndex++;
    }
  }
  if (breakingOffsetsCount === 0) {
    return null;
  }
  breakingOffsets.length = breakingOffsetsCount;
  breakingOffsetsVisibleColumn.length = breakingOffsetsCount;
  arrPool1 = previousBreakingData.breakOffsets;
  arrPool2 = previousBreakingData.breakOffsetsVisibleColumn;
  previousBreakingData.breakOffsets = breakingOffsets;
  previousBreakingData.breakOffsetsVisibleColumn = breakingOffsetsVisibleColumn;
  previousBreakingData.wrappedTextIndentLength = wrappedTextIndentLength;
  return previousBreakingData;
}
function createLineBreaks$1(classifier, _lineText, injectedTexts, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent, wordBreak) {
  const lineText = LineInjectedText.applyInjectedText(_lineText, injectedTexts);
  let injectionOptions;
  let injectionOffsets;
  if (injectedTexts && injectedTexts.length > 0) {
    injectionOptions = injectedTexts.map((t) => t.options);
    injectionOffsets = injectedTexts.map((text2) => text2.column - 1);
  } else {
    injectionOptions = null;
    injectionOffsets = null;
  }
  if (firstLineBreakColumn === -1) {
    if (!injectionOptions) {
      return null;
    }
    return new ModelLineProjectionData(injectionOffsets, injectionOptions, [lineText.length], [], 0);
  }
  const len = lineText.length;
  if (len <= 1) {
    if (!injectionOptions) {
      return null;
    }
    return new ModelLineProjectionData(injectionOffsets, injectionOptions, [lineText.length], [], 0);
  }
  const isKeepAll = wordBreak === "keepAll";
  const wrappedTextIndentLength = computeWrappedTextIndentLength(lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent);
  const wrappedLineBreakColumn = firstLineBreakColumn - wrappedTextIndentLength;
  const breakingOffsets = [];
  const breakingOffsetsVisibleColumn = [];
  let breakingOffsetsCount = 0;
  let breakOffset = 0;
  let breakOffsetVisibleColumn = 0;
  let breakingColumn = firstLineBreakColumn;
  let prevCharCode = lineText.charCodeAt(0);
  let prevCharCodeClass = classifier.get(prevCharCode);
  let visibleColumn = computeCharWidth(prevCharCode, 0, tabSize, columnsForFullWidthChar);
  let startOffset = 1;
  if (isHighSurrogate(prevCharCode)) {
    visibleColumn += 1;
    prevCharCode = lineText.charCodeAt(1);
    prevCharCodeClass = classifier.get(prevCharCode);
    startOffset++;
  }
  for (let i = startOffset; i < len; i++) {
    const charStartOffset = i;
    const charCode = lineText.charCodeAt(i);
    let charCodeClass;
    let charWidth;
    if (isHighSurrogate(charCode)) {
      i++;
      charCodeClass = 0;
      charWidth = 2;
    } else {
      charCodeClass = classifier.get(charCode);
      charWidth = computeCharWidth(charCode, visibleColumn, tabSize, columnsForFullWidthChar);
    }
    if (canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass, isKeepAll)) {
      breakOffset = charStartOffset;
      breakOffsetVisibleColumn = visibleColumn;
    }
    visibleColumn += charWidth;
    if (visibleColumn > breakingColumn) {
      if (breakOffset === 0 || visibleColumn - breakOffsetVisibleColumn > wrappedLineBreakColumn) {
        breakOffset = charStartOffset;
        breakOffsetVisibleColumn = visibleColumn - charWidth;
      }
      breakingOffsets[breakingOffsetsCount] = breakOffset;
      breakingOffsetsVisibleColumn[breakingOffsetsCount] = breakOffsetVisibleColumn;
      breakingOffsetsCount++;
      breakingColumn = breakOffsetVisibleColumn + wrappedLineBreakColumn;
      breakOffset = 0;
    }
    prevCharCode = charCode;
    prevCharCodeClass = charCodeClass;
  }
  if (breakingOffsetsCount === 0 && (!injectedTexts || injectedTexts.length === 0)) {
    return null;
  }
  breakingOffsets[breakingOffsetsCount] = len;
  breakingOffsetsVisibleColumn[breakingOffsetsCount] = visibleColumn;
  return new ModelLineProjectionData(injectionOffsets, injectionOptions, breakingOffsets, breakingOffsetsVisibleColumn, wrappedTextIndentLength);
}
function computeCharWidth(charCode, visibleColumn, tabSize, columnsForFullWidthChar) {
  if (charCode === 9) {
    return tabSize - visibleColumn % tabSize;
  }
  if (isFullWidthCharacter(charCode)) {
    return columnsForFullWidthChar;
  }
  if (charCode < 32) {
    return columnsForFullWidthChar;
  }
  return 1;
}
function tabCharacterWidth(visibleColumn, tabSize) {
  return tabSize - visibleColumn % tabSize;
}
function canBreak(prevCharCode, prevCharCodeClass, charCode, charCodeClass, isKeepAll) {
  return charCode !== 32 && (prevCharCodeClass === 2 && charCodeClass !== 2 || prevCharCodeClass !== 1 && charCodeClass === 1 || !isKeepAll && prevCharCodeClass === 3 && charCodeClass !== 2 || !isKeepAll && charCodeClass === 3 && prevCharCodeClass !== 1);
}
function computeWrappedTextIndentLength(lineText, tabSize, firstLineBreakColumn, columnsForFullWidthChar, wrappingIndent) {
  let wrappedTextIndentLength = 0;
  if (wrappingIndent !== 0) {
    const firstNonWhitespaceIndex$1 = firstNonWhitespaceIndex(lineText);
    if (firstNonWhitespaceIndex$1 !== -1) {
      for (let i = 0; i < firstNonWhitespaceIndex$1; i++) {
        const charWidth = lineText.charCodeAt(i) === 9 ? tabCharacterWidth(wrappedTextIndentLength, tabSize) : 1;
        wrappedTextIndentLength += charWidth;
      }
      const numberOfAdditionalTabs = wrappingIndent === 3 ? 2 : wrappingIndent === 2 ? 1 : 0;
      for (let i = 0; i < numberOfAdditionalTabs; i++) {
        const charWidth = tabCharacterWidth(wrappedTextIndentLength, tabSize);
        wrappedTextIndentLength += charWidth;
      }
      if (wrappedTextIndentLength + columnsForFullWidthChar > firstLineBreakColumn) {
        wrappedTextIndentLength = 0;
      }
    }
  }
  return wrappedTextIndentLength;
}
const ttPolicy$4 = createTrustedTypesPolicy("domLineBreaksComputer", { createHTML: (value) => value });
class DOMLineBreaksComputerFactory {
  static create() {
    return new DOMLineBreaksComputerFactory();
  }
  constructor() {
  }
  createLineBreaksComputer(fontInfo, tabSize, wrappingColumn, wrappingIndent, wordBreak) {
    const requests = [];
    const injectedTexts = [];
    return {
      addRequest: (lineText, injectedText, previousLineBreakData) => {
        requests.push(lineText);
        injectedTexts.push(injectedText);
      },
      finalize: () => {
        return createLineBreaks(requests, fontInfo, tabSize, wrappingColumn, wrappingIndent, wordBreak, injectedTexts);
      }
    };
  }
}
function createLineBreaks(requests, fontInfo, tabSize, firstLineBreakColumn, wrappingIndent, wordBreak, injectedTextsPerLine) {
  var _a2;
  function createEmptyLineBreakWithPossiblyInjectedText(requestIdx) {
    const injectedTexts = injectedTextsPerLine[requestIdx];
    if (injectedTexts) {
      const lineText = LineInjectedText.applyInjectedText(requests[requestIdx], injectedTexts);
      const injectionOptions = injectedTexts.map((t) => t.options);
      const injectionOffsets = injectedTexts.map((text2) => text2.column - 1);
      return new ModelLineProjectionData(injectionOffsets, injectionOptions, [lineText.length], [], 0);
    } else {
      return null;
    }
  }
  if (firstLineBreakColumn === -1) {
    const result3 = [];
    for (let i = 0, len = requests.length; i < len; i++) {
      result3[i] = createEmptyLineBreakWithPossiblyInjectedText(i);
    }
    return result3;
  }
  const overallWidth = Math.round(firstLineBreakColumn * fontInfo.typicalHalfwidthCharacterWidth);
  const additionalIndent = wrappingIndent === 3 ? 2 : wrappingIndent === 2 ? 1 : 0;
  const additionalIndentSize = Math.round(tabSize * additionalIndent);
  const additionalIndentLength = Math.ceil(fontInfo.spaceWidth * additionalIndentSize);
  const containerDomNode = document.createElement("div");
  applyFontInfo(containerDomNode, fontInfo);
  const sb = new StringBuilder(1e4);
  const firstNonWhitespaceIndices = [];
  const wrappedTextIndentLengths = [];
  const renderLineContents = [];
  const allCharOffsets = [];
  const allVisibleColumns = [];
  for (let i = 0; i < requests.length; i++) {
    const lineContent = LineInjectedText.applyInjectedText(requests[i], injectedTextsPerLine[i]);
    let firstNonWhitespaceIndex$1 = 0;
    let wrappedTextIndentLength = 0;
    let width = overallWidth;
    if (wrappingIndent !== 0) {
      firstNonWhitespaceIndex$1 = firstNonWhitespaceIndex(lineContent);
      if (firstNonWhitespaceIndex$1 === -1) {
        firstNonWhitespaceIndex$1 = 0;
      } else {
        for (let i2 = 0; i2 < firstNonWhitespaceIndex$1; i2++) {
          const charWidth = lineContent.charCodeAt(i2) === 9 ? tabSize - wrappedTextIndentLength % tabSize : 1;
          wrappedTextIndentLength += charWidth;
        }
        const indentWidth = Math.ceil(fontInfo.spaceWidth * wrappedTextIndentLength);
        if (indentWidth + fontInfo.typicalFullwidthCharacterWidth > overallWidth) {
          firstNonWhitespaceIndex$1 = 0;
          wrappedTextIndentLength = 0;
        } else {
          width = overallWidth - indentWidth;
        }
      }
    }
    const renderLineContent = lineContent.substr(firstNonWhitespaceIndex$1);
    const tmp = renderLine(renderLineContent, wrappedTextIndentLength, tabSize, width, sb, additionalIndentLength);
    firstNonWhitespaceIndices[i] = firstNonWhitespaceIndex$1;
    wrappedTextIndentLengths[i] = wrappedTextIndentLength;
    renderLineContents[i] = renderLineContent;
    allCharOffsets[i] = tmp[0];
    allVisibleColumns[i] = tmp[1];
  }
  const html2 = sb.build();
  const trustedhtml = (_a2 = ttPolicy$4 === null || ttPolicy$4 === void 0 ? void 0 : ttPolicy$4.createHTML(html2)) !== null && _a2 !== void 0 ? _a2 : html2;
  containerDomNode.innerHTML = trustedhtml;
  containerDomNode.style.position = "absolute";
  containerDomNode.style.top = "10000";
  if (wordBreak === "keepAll") {
    containerDomNode.style.wordBreak = "keep-all";
    containerDomNode.style.overflowWrap = "anywhere";
  } else {
    containerDomNode.style.wordBreak = "inherit";
    containerDomNode.style.overflowWrap = "break-word";
  }
  document.body.appendChild(containerDomNode);
  const range2 = document.createRange();
  const lineDomNodes = Array.prototype.slice.call(containerDomNode.children, 0);
  const result2 = [];
  for (let i = 0; i < requests.length; i++) {
    const lineDomNode = lineDomNodes[i];
    const breakOffsets = readLineBreaks(range2, lineDomNode, renderLineContents[i], allCharOffsets[i]);
    if (breakOffsets === null) {
      result2[i] = createEmptyLineBreakWithPossiblyInjectedText(i);
      continue;
    }
    const firstNonWhitespaceIndex2 = firstNonWhitespaceIndices[i];
    const wrappedTextIndentLength = wrappedTextIndentLengths[i] + additionalIndentSize;
    const visibleColumns = allVisibleColumns[i];
    const breakOffsetsVisibleColumn = [];
    for (let j = 0, len = breakOffsets.length; j < len; j++) {
      breakOffsetsVisibleColumn[j] = visibleColumns[breakOffsets[j]];
    }
    if (firstNonWhitespaceIndex2 !== 0) {
      for (let j = 0, len = breakOffsets.length; j < len; j++) {
        breakOffsets[j] += firstNonWhitespaceIndex2;
      }
    }
    let injectionOptions;
    let injectionOffsets;
    const curInjectedTexts = injectedTextsPerLine[i];
    if (curInjectedTexts) {
      injectionOptions = curInjectedTexts.map((t) => t.options);
      injectionOffsets = curInjectedTexts.map((text2) => text2.column - 1);
    } else {
      injectionOptions = null;
      injectionOffsets = null;
    }
    result2[i] = new ModelLineProjectionData(injectionOffsets, injectionOptions, breakOffsets, breakOffsetsVisibleColumn, wrappedTextIndentLength);
  }
  document.body.removeChild(containerDomNode);
  return result2;
}
function renderLine(lineContent, initialVisibleColumn, tabSize, width, sb, wrappingIndentLength) {
  if (wrappingIndentLength !== 0) {
    const hangingOffset = String(wrappingIndentLength);
    sb.appendString('<div style="text-indent: -');
    sb.appendString(hangingOffset);
    sb.appendString("px; padding-left: ");
    sb.appendString(hangingOffset);
    sb.appendString("px; box-sizing: border-box; width:");
  } else {
    sb.appendString('<div style="width:');
  }
  sb.appendString(String(width));
  sb.appendString('px;">');
  const len = lineContent.length;
  let visibleColumn = initialVisibleColumn;
  let charOffset = 0;
  const charOffsets = [];
  const visibleColumns = [];
  let nextCharCode = 0 < len ? lineContent.charCodeAt(0) : 0;
  sb.appendString("<span>");
  for (let charIndex = 0; charIndex < len; charIndex++) {
    if (charIndex !== 0 && charIndex % 16384 === 0) {
      sb.appendString("</span><span>");
    }
    charOffsets[charIndex] = charOffset;
    visibleColumns[charIndex] = visibleColumn;
    const charCode = nextCharCode;
    nextCharCode = charIndex + 1 < len ? lineContent.charCodeAt(charIndex + 1) : 0;
    let producedCharacters = 1;
    let charWidth = 1;
    switch (charCode) {
      case 9:
        producedCharacters = tabSize - visibleColumn % tabSize;
        charWidth = producedCharacters;
        for (let space2 = 1; space2 <= producedCharacters; space2++) {
          if (space2 < producedCharacters) {
            sb.appendCharCode(160);
          } else {
            sb.appendASCIICharCode(
              32
              /* CharCode.Space */
            );
          }
        }
        break;
      case 32:
        if (nextCharCode === 32) {
          sb.appendCharCode(160);
        } else {
          sb.appendASCIICharCode(
            32
            /* CharCode.Space */
          );
        }
        break;
      case 60:
        sb.appendString("&lt;");
        break;
      case 62:
        sb.appendString("&gt;");
        break;
      case 38:
        sb.appendString("&amp;");
        break;
      case 0:
        sb.appendString("&#00;");
        break;
      case 65279:
      case 8232:
      case 8233:
      case 133:
        sb.appendCharCode(65533);
        break;
      default:
        if (isFullWidthCharacter(charCode)) {
          charWidth++;
        }
        if (charCode < 32) {
          sb.appendCharCode(9216 + charCode);
        } else {
          sb.appendCharCode(charCode);
        }
    }
    charOffset += producedCharacters;
    visibleColumn += charWidth;
  }
  sb.appendString("</span>");
  charOffsets[lineContent.length] = charOffset;
  visibleColumns[lineContent.length] = visibleColumn;
  sb.appendString("</div>");
  return [charOffsets, visibleColumns];
}
function readLineBreaks(range2, lineDomNode, lineContent, charOffsets) {
  if (lineContent.length <= 1) {
    return null;
  }
  const spans = Array.prototype.slice.call(lineDomNode.children, 0);
  const breakOffsets = [];
  try {
    discoverBreaks(range2, spans, charOffsets, 0, null, lineContent.length - 1, null, breakOffsets);
  } catch (err) {
    console.log(err);
    return null;
  }
  if (breakOffsets.length === 0) {
    return null;
  }
  breakOffsets.push(lineContent.length);
  return breakOffsets;
}
function discoverBreaks(range2, spans, charOffsets, low, lowRects, high, highRects, result2) {
  if (low === high) {
    return;
  }
  lowRects = lowRects || readClientRect(range2, spans, charOffsets[low], charOffsets[low + 1]);
  highRects = highRects || readClientRect(range2, spans, charOffsets[high], charOffsets[high + 1]);
  if (Math.abs(lowRects[0].top - highRects[0].top) <= 0.1) {
    return;
  }
  if (low + 1 === high) {
    result2.push(high);
    return;
  }
  const mid = low + (high - low) / 2 | 0;
  const midRects = readClientRect(range2, spans, charOffsets[mid], charOffsets[mid + 1]);
  discoverBreaks(range2, spans, charOffsets, low, lowRects, mid, midRects, result2);
  discoverBreaks(range2, spans, charOffsets, mid, midRects, high, highRects, result2);
}
function readClientRect(range2, spans, startOffset, endOffset) {
  range2.setStart(
    spans[startOffset / 16384 | 0].firstChild,
    startOffset % 16384
    /* Constants.SPAN_MODULO_LIMIT */
  );
  range2.setEnd(
    spans[endOffset / 16384 | 0].firstChild,
    endOffset % 16384
    /* Constants.SPAN_MODULO_LIMIT */
  );
  return range2.getClientRects();
}
const ILanguageFeaturesService = createDecorator("ILanguageFeaturesService");
const accessibleDiffViewerCategory = {
  value: localize("accessibleDiffViewer", "Accessible Diff Viewer"),
  original: "Accessible Diff Viewer"
};
class AccessibleDiffViewerNext extends Action2 {
  constructor() {
    super({
      id: AccessibleDiffViewerNext.id,
      title: { value: localize("editor.action.accessibleDiffViewer.next", "Go to Next Difference"), original: "Go to Next Difference" },
      category: accessibleDiffViewerCategory,
      precondition: ContextKeyExpr.has("isInDiffEditor"),
      keybinding: {
        primary: 65,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      f1: true
    });
  }
  run(accessor) {
    const diffEditor2 = findFocusedDiffEditor(accessor);
    diffEditor2 === null || diffEditor2 === void 0 ? void 0 : diffEditor2.accessibleDiffViewerNext();
  }
}
AccessibleDiffViewerNext.id = "editor.action.accessibleDiffViewer.next";
MenuRegistry.appendMenuItem(MenuId.EditorTitle, {
  command: {
    id: AccessibleDiffViewerNext.id,
    title: localize("Open Accessible Diff Viewer", "Open Accessible Diff Viewer")
  },
  order: 10,
  group: "2_diff",
  when: ContextKeyExpr.and(EditorContextKeys.accessibleDiffViewerVisible.negate(), ContextKeyExpr.has("isInDiffEditor"))
});
class AccessibleDiffViewerPrev extends Action2 {
  constructor() {
    super({
      id: AccessibleDiffViewerPrev.id,
      title: { value: localize("editor.action.accessibleDiffViewer.prev", "Go to Previous Difference"), original: "Go to Previous Difference" },
      category: accessibleDiffViewerCategory,
      precondition: ContextKeyExpr.has("isInDiffEditor"),
      keybinding: {
        primary: 1024 | 65,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      f1: true
    });
  }
  run(accessor) {
    const diffEditor2 = findFocusedDiffEditor(accessor);
    diffEditor2 === null || diffEditor2 === void 0 ? void 0 : diffEditor2.accessibleDiffViewerPrev();
  }
}
AccessibleDiffViewerPrev.id = "editor.action.accessibleDiffViewer.prev";
function findFocusedDiffEditor(accessor) {
  var _a2;
  const codeEditorService = accessor.get(ICodeEditorService);
  const diffEditors = codeEditorService.listDiffEditors();
  const activeCodeEditor = (_a2 = codeEditorService.getFocusedCodeEditor()) !== null && _a2 !== void 0 ? _a2 : codeEditorService.getActiveCodeEditor();
  if (!activeCodeEditor) {
    return null;
  }
  for (let i = 0, len = diffEditors.length; i < len; i++) {
    const diffEditor2 = diffEditors[i];
    if (diffEditor2.getModifiedEditor().getId() === activeCodeEditor.getId() || diffEditor2.getOriginalEditor().getId() === activeCodeEditor.getId()) {
      return diffEditor2;
    }
  }
  if (document.activeElement) {
    for (const d of diffEditors) {
      const container2 = d.getContainerDomNode();
      if (isElementOrParentOf(container2, document.activeElement)) {
        return d;
      }
    }
  }
  return null;
}
function isElementOrParentOf(elementOrParent, element) {
  let e = element;
  while (e) {
    if (e === elementOrParent) {
      return true;
    }
    e = e.parentElement;
  }
  return false;
}
CommandsRegistry.registerCommandAlias("editor.action.diffReview.next", AccessibleDiffViewerNext.id);
registerAction2(AccessibleDiffViewerNext);
CommandsRegistry.registerCommandAlias("editor.action.diffReview.prev", AccessibleDiffViewerPrev.id);
registerAction2(AccessibleDiffViewerPrev);
class CodeEditorContributions extends Disposable {
  constructor() {
    super();
    this._editor = null;
    this._instantiationService = null;
    this._instances = this._register(new DisposableMap());
    this._pending = /* @__PURE__ */ new Map();
    this._finishedInstantiation = [];
    this._finishedInstantiation[
      0
      /* EditorContributionInstantiation.Eager */
    ] = false;
    this._finishedInstantiation[
      1
      /* EditorContributionInstantiation.AfterFirstRender */
    ] = false;
    this._finishedInstantiation[
      2
      /* EditorContributionInstantiation.BeforeFirstInteraction */
    ] = false;
    this._finishedInstantiation[
      3
      /* EditorContributionInstantiation.Eventually */
    ] = false;
  }
  initialize(editor2, contributions, instantiationService) {
    this._editor = editor2;
    this._instantiationService = instantiationService;
    for (const desc of contributions) {
      if (this._pending.has(desc.id)) {
        onUnexpectedError(new Error(`Cannot have two contributions with the same id ${desc.id}`));
        continue;
      }
      this._pending.set(desc.id, desc);
    }
    this._instantiateSome(
      0
      /* EditorContributionInstantiation.Eager */
    );
    this._register(runWhenIdle(() => {
      this._instantiateSome(
        1
        /* EditorContributionInstantiation.AfterFirstRender */
      );
    }));
    this._register(runWhenIdle(() => {
      this._instantiateSome(
        2
        /* EditorContributionInstantiation.BeforeFirstInteraction */
      );
    }));
    this._register(runWhenIdle(() => {
      this._instantiateSome(
        3
        /* EditorContributionInstantiation.Eventually */
      );
    }, 5e3));
  }
  saveViewState() {
    const contributionsState = {};
    for (const [id3, contribution] of this._instances) {
      if (typeof contribution.saveViewState === "function") {
        contributionsState[id3] = contribution.saveViewState();
      }
    }
    return contributionsState;
  }
  restoreViewState(contributionsState) {
    for (const [id3, contribution] of this._instances) {
      if (typeof contribution.restoreViewState === "function") {
        contribution.restoreViewState(contributionsState[id3]);
      }
    }
  }
  get(id3) {
    this._instantiateById(id3);
    return this._instances.get(id3) || null;
  }
  onBeforeInteractionEvent() {
    this._instantiateSome(
      2
      /* EditorContributionInstantiation.BeforeFirstInteraction */
    );
  }
  onAfterModelAttached() {
    this._register(runWhenIdle(() => {
      this._instantiateSome(
        1
        /* EditorContributionInstantiation.AfterFirstRender */
      );
    }, 50));
  }
  _instantiateSome(instantiation) {
    if (this._finishedInstantiation[instantiation]) {
      return;
    }
    this._finishedInstantiation[instantiation] = true;
    const contribs = this._findPendingContributionsByInstantiation(instantiation);
    for (const contrib of contribs) {
      this._instantiateById(contrib.id);
    }
  }
  _findPendingContributionsByInstantiation(instantiation) {
    const result2 = [];
    for (const [, desc] of this._pending) {
      if (desc.instantiation === instantiation) {
        result2.push(desc);
      }
    }
    return result2;
  }
  _instantiateById(id3) {
    const desc = this._pending.get(id3);
    if (!desc) {
      return;
    }
    this._pending.delete(id3);
    if (!this._instantiationService || !this._editor) {
      throw new Error(`Cannot instantiate contributions before being initialized!`);
    }
    try {
      const instance = this._instantiationService.createInstance(desc.ctor, this._editor);
      this._instances.set(desc.id, instance);
      if (typeof instance.restoreViewState === "function" && desc.instantiation !== 0) {
        console.warn(`Editor contribution '${desc.id}' should be eager instantiated because it uses saveViewState / restoreViewState.`);
      }
    } catch (err) {
      onUnexpectedError(err);
    }
  }
}
var __decorate$22 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1Y = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$1w = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
let EDITOR_ID = 0;
let ModelData$1 = class ModelData {
  constructor(model, viewModel, view, hasRealView, listenersToRemove, attachedView) {
    this.model = model;
    this.viewModel = viewModel;
    this.view = view;
    this.hasRealView = hasRealView;
    this.listenersToRemove = listenersToRemove;
    this.attachedView = attachedView;
  }
  dispose() {
    dispose(this.listenersToRemove);
    this.model.onBeforeDetached(this.attachedView);
    if (this.hasRealView) {
      this.view.dispose();
    }
    this.viewModel.dispose();
  }
};
let CodeEditorWidget = class CodeEditorWidget2 extends Disposable {
  //#endregion
  get isSimpleWidget() {
    return this._configuration.isSimpleWidget;
  }
  constructor(domElement, _options, codeEditorWidgetOptions, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService, languageConfigurationService, languageFeaturesService) {
    super();
    this.languageConfigurationService = languageConfigurationService;
    this._deliveryQueue = createEventDeliveryQueue();
    this._contributions = this._register(new CodeEditorContributions());
    this._onDidDispose = this._register(new Emitter$1());
    this.onDidDispose = this._onDidDispose.event;
    this._onDidChangeModelContent = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
    this.onDidChangeModelContent = this._onDidChangeModelContent.event;
    this._onDidChangeModelLanguage = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
    this.onDidChangeModelLanguage = this._onDidChangeModelLanguage.event;
    this._onDidChangeModelLanguageConfiguration = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
    this.onDidChangeModelLanguageConfiguration = this._onDidChangeModelLanguageConfiguration.event;
    this._onDidChangeModelOptions = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
    this.onDidChangeModelOptions = this._onDidChangeModelOptions.event;
    this._onDidChangeModelDecorations = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
    this.onDidChangeModelDecorations = this._onDidChangeModelDecorations.event;
    this._onDidChangeModelTokens = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
    this.onDidChangeModelTokens = this._onDidChangeModelTokens.event;
    this._onDidChangeConfiguration = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
    this.onDidChangeConfiguration = this._onDidChangeConfiguration.event;
    this._onDidChangeModel = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
    this.onDidChangeModel = this._onDidChangeModel.event;
    this._onDidChangeCursorPosition = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
    this.onDidChangeCursorPosition = this._onDidChangeCursorPosition.event;
    this._onDidChangeCursorSelection = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
    this.onDidChangeCursorSelection = this._onDidChangeCursorSelection.event;
    this._onDidAttemptReadOnlyEdit = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
    this.onDidAttemptReadOnlyEdit = this._onDidAttemptReadOnlyEdit.event;
    this._onDidLayoutChange = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
    this.onDidLayoutChange = this._onDidLayoutChange.event;
    this._editorTextFocus = this._register(new BooleanEventEmitter({ deliveryQueue: this._deliveryQueue }));
    this.onDidFocusEditorText = this._editorTextFocus.onDidChangeToTrue;
    this.onDidBlurEditorText = this._editorTextFocus.onDidChangeToFalse;
    this._editorWidgetFocus = this._register(new BooleanEventEmitter({ deliveryQueue: this._deliveryQueue }));
    this.onDidFocusEditorWidget = this._editorWidgetFocus.onDidChangeToTrue;
    this.onDidBlurEditorWidget = this._editorWidgetFocus.onDidChangeToFalse;
    this._onWillType = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
    this.onWillType = this._onWillType.event;
    this._onDidType = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
    this.onDidType = this._onDidType.event;
    this._onDidCompositionStart = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
    this.onDidCompositionStart = this._onDidCompositionStart.event;
    this._onDidCompositionEnd = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
    this.onDidCompositionEnd = this._onDidCompositionEnd.event;
    this._onDidPaste = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
    this.onDidPaste = this._onDidPaste.event;
    this._onMouseUp = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
    this.onMouseUp = this._onMouseUp.event;
    this._onMouseDown = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
    this.onMouseDown = this._onMouseDown.event;
    this._onMouseDrag = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
    this.onMouseDrag = this._onMouseDrag.event;
    this._onMouseDrop = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
    this.onMouseDrop = this._onMouseDrop.event;
    this._onMouseDropCanceled = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
    this.onMouseDropCanceled = this._onMouseDropCanceled.event;
    this._onDropIntoEditor = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
    this.onDropIntoEditor = this._onDropIntoEditor.event;
    this._onContextMenu = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
    this.onContextMenu = this._onContextMenu.event;
    this._onMouseMove = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
    this.onMouseMove = this._onMouseMove.event;
    this._onMouseLeave = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
    this.onMouseLeave = this._onMouseLeave.event;
    this._onMouseWheel = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
    this.onMouseWheel = this._onMouseWheel.event;
    this._onKeyUp = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
    this.onKeyUp = this._onKeyUp.event;
    this._onKeyDown = this._register(new InteractionEmitter(this._contributions, this._deliveryQueue));
    this.onKeyDown = this._onKeyDown.event;
    this._onDidContentSizeChange = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
    this.onDidContentSizeChange = this._onDidContentSizeChange.event;
    this._onDidScrollChange = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
    this.onDidScrollChange = this._onDidScrollChange.event;
    this._onDidChangeViewZones = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
    this.onDidChangeViewZones = this._onDidChangeViewZones.event;
    this._onDidChangeHiddenAreas = this._register(new Emitter$1({ deliveryQueue: this._deliveryQueue }));
    this.onDidChangeHiddenAreas = this._onDidChangeHiddenAreas.event;
    this._actions = /* @__PURE__ */ new Map();
    this._bannerDomNode = null;
    this._dropIntoEditorDecorations = this.createDecorationsCollection();
    codeEditorService.willCreateCodeEditor();
    const options = Object.assign({}, _options);
    this._domElement = domElement;
    this._overflowWidgetsDomNode = options.overflowWidgetsDomNode;
    delete options.overflowWidgetsDomNode;
    this._id = ++EDITOR_ID;
    this._decorationTypeKeysToIds = {};
    this._decorationTypeSubtypes = {};
    this._telemetryData = codeEditorWidgetOptions.telemetryData;
    this._configuration = this._register(this._createConfiguration(codeEditorWidgetOptions.isSimpleWidget || false, options, accessibilityService));
    this._register(this._configuration.onDidChange((e) => {
      this._onDidChangeConfiguration.fire(e);
      const options2 = this._configuration.options;
      if (e.hasChanged(
        142
        /* EditorOption.layoutInfo */
      )) {
        const layoutInfo = options2.get(
          142
          /* EditorOption.layoutInfo */
        );
        this._onDidLayoutChange.fire(layoutInfo);
      }
    }));
    this._contextKeyService = this._register(contextKeyService.createScoped(this._domElement));
    this._notificationService = notificationService;
    this._codeEditorService = codeEditorService;
    this._commandService = commandService;
    this._themeService = themeService;
    this._register(new EditorContextKeysManager(this, this._contextKeyService));
    this._register(new EditorModeContext(this, this._contextKeyService, languageFeaturesService));
    this._instantiationService = instantiationService.createChild(new ServiceCollection([IContextKeyService, this._contextKeyService]));
    this._modelData = null;
    this._focusTracker = new CodeEditorWidgetFocusTracker(domElement);
    this._register(this._focusTracker.onChange(() => {
      this._editorWidgetFocus.setValue(this._focusTracker.hasFocus());
    }));
    this._contentWidgets = {};
    this._overlayWidgets = {};
    this._glyphMarginWidgets = {};
    let contributions;
    if (Array.isArray(codeEditorWidgetOptions.contributions)) {
      contributions = codeEditorWidgetOptions.contributions;
    } else {
      contributions = EditorExtensionsRegistry.getEditorContributions();
    }
    this._contributions.initialize(this, contributions, this._instantiationService);
    for (const action of EditorExtensionsRegistry.getEditorActions()) {
      if (this._actions.has(action.id)) {
        onUnexpectedError(new Error(`Cannot have two actions with the same id ${action.id}`));
        continue;
      }
      const internalAction = new InternalEditorAction(action.id, action.label, action.alias, withNullAsUndefined(action.precondition), () => {
        return this._instantiationService.invokeFunction((accessor) => {
          return Promise.resolve(action.runEditorCommand(accessor, this, null));
        });
      }, this._contextKeyService);
      this._actions.set(internalAction.id, internalAction);
    }
    const isDropIntoEnabled = () => {
      return !this._configuration.options.get(
        89
        /* EditorOption.readOnly */
      ) && this._configuration.options.get(
        35
        /* EditorOption.dropIntoEditor */
      ).enabled;
    };
    this._register(new DragAndDropObserver(this._domElement, {
      onDragEnter: () => void 0,
      onDragOver: (e) => {
        if (!isDropIntoEnabled()) {
          return;
        }
        const target = this.getTargetAtClientPoint(e.clientX, e.clientY);
        if (target === null || target === void 0 ? void 0 : target.position) {
          this.showDropIndicatorAt(target.position);
        }
      },
      onDrop: (e) => __awaiter$1w(this, void 0, void 0, function* () {
        if (!isDropIntoEnabled()) {
          return;
        }
        this.removeDropIndicator();
        if (!e.dataTransfer) {
          return;
        }
        const target = this.getTargetAtClientPoint(e.clientX, e.clientY);
        if (target === null || target === void 0 ? void 0 : target.position) {
          this._onDropIntoEditor.fire({ position: target.position, event: e });
        }
      }),
      onDragLeave: () => {
        this.removeDropIndicator();
      },
      onDragEnd: () => {
        this.removeDropIndicator();
      }
    }));
    this._codeEditorService.addCodeEditor(this);
  }
  writeScreenReaderContent(reason) {
    var _a2;
    (_a2 = this._modelData) === null || _a2 === void 0 ? void 0 : _a2.view.writeScreenReaderContent(reason);
  }
  _createConfiguration(isSimpleWidget, options, accessibilityService) {
    return new EditorConfiguration(isSimpleWidget, options, this._domElement, accessibilityService);
  }
  getId() {
    return this.getEditorType() + ":" + this._id;
  }
  getEditorType() {
    return EditorType.ICodeEditor;
  }
  dispose() {
    this._codeEditorService.removeCodeEditor(this);
    this._focusTracker.dispose();
    this._actions.clear();
    this._contentWidgets = {};
    this._overlayWidgets = {};
    this._removeDecorationTypes();
    this._postDetachModelCleanup(this._detachModel());
    this._onDidDispose.fire();
    super.dispose();
  }
  invokeWithinContext(fn) {
    return this._instantiationService.invokeFunction(fn);
  }
  updateOptions(newOptions) {
    this._configuration.updateOptions(newOptions || {});
  }
  getOptions() {
    return this._configuration.options;
  }
  getOption(id3) {
    return this._configuration.options.get(id3);
  }
  getRawOptions() {
    return this._configuration.getRawOptions();
  }
  getOverflowWidgetsDomNode() {
    return this._overflowWidgetsDomNode;
  }
  getConfiguredWordAtPosition(position) {
    if (!this._modelData) {
      return null;
    }
    return WordOperations.getWordAtPosition(this._modelData.model, this._configuration.options.get(
      128
      /* EditorOption.wordSeparators */
    ), position);
  }
  getValue(options = null) {
    if (!this._modelData) {
      return "";
    }
    const preserveBOM = options && options.preserveBOM ? true : false;
    let eolPreference = 0;
    if (options && options.lineEnding && options.lineEnding === "\n") {
      eolPreference = 1;
    } else if (options && options.lineEnding && options.lineEnding === "\r\n") {
      eolPreference = 2;
    }
    return this._modelData.model.getValue(eolPreference, preserveBOM);
  }
  setValue(newValue) {
    if (!this._modelData) {
      return;
    }
    this._modelData.model.setValue(newValue);
  }
  getModel() {
    if (!this._modelData) {
      return null;
    }
    return this._modelData.model;
  }
  setModel(_model = null) {
    const model = _model;
    if (this._modelData === null && model === null) {
      return;
    }
    if (this._modelData && this._modelData.model === model) {
      return;
    }
    const hasTextFocus = this.hasTextFocus();
    const detachedModel = this._detachModel();
    this._attachModel(model);
    if (hasTextFocus && this.hasModel()) {
      this.focus();
    }
    const e = {
      oldModelUrl: detachedModel ? detachedModel.uri : null,
      newModelUrl: model ? model.uri : null
    };
    this._removeDecorationTypes();
    this._onDidChangeModel.fire(e);
    this._postDetachModelCleanup(detachedModel);
    this._contributions.onAfterModelAttached();
  }
  _removeDecorationTypes() {
    this._decorationTypeKeysToIds = {};
    if (this._decorationTypeSubtypes) {
      for (const decorationType in this._decorationTypeSubtypes) {
        const subTypes = this._decorationTypeSubtypes[decorationType];
        for (const subType in subTypes) {
          this._removeDecorationType(decorationType + "-" + subType);
        }
      }
      this._decorationTypeSubtypes = {};
    }
  }
  getVisibleRanges() {
    if (!this._modelData) {
      return [];
    }
    return this._modelData.viewModel.getVisibleRanges();
  }
  getVisibleRangesPlusViewportAboveBelow() {
    if (!this._modelData) {
      return [];
    }
    return this._modelData.viewModel.getVisibleRangesPlusViewportAboveBelow();
  }
  getWhitespaces() {
    if (!this._modelData) {
      return [];
    }
    return this._modelData.viewModel.viewLayout.getWhitespaces();
  }
  static _getVerticalOffsetAfterPosition(modelData, modelLineNumber, modelColumn, includeViewZones) {
    const modelPosition = modelData.model.validatePosition({
      lineNumber: modelLineNumber,
      column: modelColumn
    });
    const viewPosition = modelData.viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);
    return modelData.viewModel.viewLayout.getVerticalOffsetAfterLineNumber(viewPosition.lineNumber, includeViewZones);
  }
  getTopForLineNumber(lineNumber, includeViewZones = false) {
    if (!this._modelData) {
      return -1;
    }
    return CodeEditorWidget2._getVerticalOffsetForPosition(this._modelData, lineNumber, 1, includeViewZones);
  }
  getTopForPosition(lineNumber, column) {
    if (!this._modelData) {
      return -1;
    }
    return CodeEditorWidget2._getVerticalOffsetForPosition(this._modelData, lineNumber, column, false);
  }
  static _getVerticalOffsetForPosition(modelData, modelLineNumber, modelColumn, includeViewZones = false) {
    const modelPosition = modelData.model.validatePosition({
      lineNumber: modelLineNumber,
      column: modelColumn
    });
    const viewPosition = modelData.viewModel.coordinatesConverter.convertModelPositionToViewPosition(modelPosition);
    return modelData.viewModel.viewLayout.getVerticalOffsetForLineNumber(viewPosition.lineNumber, includeViewZones);
  }
  getBottomForLineNumber(lineNumber, includeViewZones = false) {
    if (!this._modelData) {
      return -1;
    }
    return CodeEditorWidget2._getVerticalOffsetAfterPosition(this._modelData, lineNumber, 1, includeViewZones);
  }
  setHiddenAreas(ranges, source) {
    var _a2;
    (_a2 = this._modelData) === null || _a2 === void 0 ? void 0 : _a2.viewModel.setHiddenAreas(ranges.map((r) => Range$2.lift(r)), source);
  }
  getVisibleColumnFromPosition(rawPosition) {
    if (!this._modelData) {
      return rawPosition.column;
    }
    const position = this._modelData.model.validatePosition(rawPosition);
    const tabSize = this._modelData.model.getOptions().tabSize;
    return CursorColumns.visibleColumnFromColumn(this._modelData.model.getLineContent(position.lineNumber), position.column, tabSize) + 1;
  }
  getPosition() {
    if (!this._modelData) {
      return null;
    }
    return this._modelData.viewModel.getPosition();
  }
  setPosition(position, source = "api") {
    if (!this._modelData) {
      return;
    }
    if (!Position$2.isIPosition(position)) {
      throw new Error("Invalid arguments");
    }
    this._modelData.viewModel.setSelections(source, [{
      selectionStartLineNumber: position.lineNumber,
      selectionStartColumn: position.column,
      positionLineNumber: position.lineNumber,
      positionColumn: position.column
    }]);
  }
  _sendRevealRange(modelRange, verticalType, revealHorizontal, scrollType) {
    if (!this._modelData) {
      return;
    }
    if (!Range$2.isIRange(modelRange)) {
      throw new Error("Invalid arguments");
    }
    const validatedModelRange = this._modelData.model.validateRange(modelRange);
    const viewRange = this._modelData.viewModel.coordinatesConverter.convertModelRangeToViewRange(validatedModelRange);
    this._modelData.viewModel.revealRange("api", revealHorizontal, viewRange, verticalType, scrollType);
  }
  revealLine(lineNumber, scrollType = 0) {
    this._revealLine(lineNumber, 0, scrollType);
  }
  revealLineInCenter(lineNumber, scrollType = 0) {
    this._revealLine(lineNumber, 1, scrollType);
  }
  revealLineInCenterIfOutsideViewport(lineNumber, scrollType = 0) {
    this._revealLine(lineNumber, 2, scrollType);
  }
  revealLineNearTop(lineNumber, scrollType = 0) {
    this._revealLine(lineNumber, 5, scrollType);
  }
  _revealLine(lineNumber, revealType, scrollType) {
    if (typeof lineNumber !== "number") {
      throw new Error("Invalid arguments");
    }
    this._sendRevealRange(new Range$2(lineNumber, 1, lineNumber, 1), revealType, false, scrollType);
  }
  revealPosition(position, scrollType = 0) {
    this._revealPosition(position, 0, true, scrollType);
  }
  revealPositionInCenter(position, scrollType = 0) {
    this._revealPosition(position, 1, true, scrollType);
  }
  revealPositionInCenterIfOutsideViewport(position, scrollType = 0) {
    this._revealPosition(position, 2, true, scrollType);
  }
  revealPositionNearTop(position, scrollType = 0) {
    this._revealPosition(position, 5, true, scrollType);
  }
  _revealPosition(position, verticalType, revealHorizontal, scrollType) {
    if (!Position$2.isIPosition(position)) {
      throw new Error("Invalid arguments");
    }
    this._sendRevealRange(new Range$2(position.lineNumber, position.column, position.lineNumber, position.column), verticalType, revealHorizontal, scrollType);
  }
  getSelection() {
    if (!this._modelData) {
      return null;
    }
    return this._modelData.viewModel.getSelection();
  }
  getSelections() {
    if (!this._modelData) {
      return null;
    }
    return this._modelData.viewModel.getSelections();
  }
  setSelection(something, source = "api") {
    const isSelection = Selection$1.isISelection(something);
    const isRange = Range$2.isIRange(something);
    if (!isSelection && !isRange) {
      throw new Error("Invalid arguments");
    }
    if (isSelection) {
      this._setSelectionImpl(something, source);
    } else if (isRange) {
      const selection = {
        selectionStartLineNumber: something.startLineNumber,
        selectionStartColumn: something.startColumn,
        positionLineNumber: something.endLineNumber,
        positionColumn: something.endColumn
      };
      this._setSelectionImpl(selection, source);
    }
  }
  _setSelectionImpl(sel, source) {
    if (!this._modelData) {
      return;
    }
    const selection = new Selection$1(sel.selectionStartLineNumber, sel.selectionStartColumn, sel.positionLineNumber, sel.positionColumn);
    this._modelData.viewModel.setSelections(source, [selection]);
  }
  revealLines(startLineNumber, endLineNumber, scrollType = 0) {
    this._revealLines(startLineNumber, endLineNumber, 0, scrollType);
  }
  revealLinesInCenter(startLineNumber, endLineNumber, scrollType = 0) {
    this._revealLines(startLineNumber, endLineNumber, 1, scrollType);
  }
  revealLinesInCenterIfOutsideViewport(startLineNumber, endLineNumber, scrollType = 0) {
    this._revealLines(startLineNumber, endLineNumber, 2, scrollType);
  }
  revealLinesNearTop(startLineNumber, endLineNumber, scrollType = 0) {
    this._revealLines(startLineNumber, endLineNumber, 5, scrollType);
  }
  _revealLines(startLineNumber, endLineNumber, verticalType, scrollType) {
    if (typeof startLineNumber !== "number" || typeof endLineNumber !== "number") {
      throw new Error("Invalid arguments");
    }
    this._sendRevealRange(new Range$2(startLineNumber, 1, endLineNumber, 1), verticalType, false, scrollType);
  }
  revealRange(range2, scrollType = 0, revealVerticalInCenter = false, revealHorizontal = true) {
    this._revealRange(range2, revealVerticalInCenter ? 1 : 0, revealHorizontal, scrollType);
  }
  revealRangeInCenter(range2, scrollType = 0) {
    this._revealRange(range2, 1, true, scrollType);
  }
  revealRangeInCenterIfOutsideViewport(range2, scrollType = 0) {
    this._revealRange(range2, 2, true, scrollType);
  }
  revealRangeNearTop(range2, scrollType = 0) {
    this._revealRange(range2, 5, true, scrollType);
  }
  revealRangeNearTopIfOutsideViewport(range2, scrollType = 0) {
    this._revealRange(range2, 6, true, scrollType);
  }
  revealRangeAtTop(range2, scrollType = 0) {
    this._revealRange(range2, 3, true, scrollType);
  }
  _revealRange(range2, verticalType, revealHorizontal, scrollType) {
    if (!Range$2.isIRange(range2)) {
      throw new Error("Invalid arguments");
    }
    this._sendRevealRange(Range$2.lift(range2), verticalType, revealHorizontal, scrollType);
  }
  setSelections(ranges, source = "api", reason = 0) {
    if (!this._modelData) {
      return;
    }
    if (!ranges || ranges.length === 0) {
      throw new Error("Invalid arguments");
    }
    for (let i = 0, len = ranges.length; i < len; i++) {
      if (!Selection$1.isISelection(ranges[i])) {
        throw new Error("Invalid arguments");
      }
    }
    this._modelData.viewModel.setSelections(source, ranges, reason);
  }
  getContentWidth() {
    if (!this._modelData) {
      return -1;
    }
    return this._modelData.viewModel.viewLayout.getContentWidth();
  }
  getScrollWidth() {
    if (!this._modelData) {
      return -1;
    }
    return this._modelData.viewModel.viewLayout.getScrollWidth();
  }
  getScrollLeft() {
    if (!this._modelData) {
      return -1;
    }
    return this._modelData.viewModel.viewLayout.getCurrentScrollLeft();
  }
  getContentHeight() {
    if (!this._modelData) {
      return -1;
    }
    return this._modelData.viewModel.viewLayout.getContentHeight();
  }
  getScrollHeight() {
    if (!this._modelData) {
      return -1;
    }
    return this._modelData.viewModel.viewLayout.getScrollHeight();
  }
  getScrollTop() {
    if (!this._modelData) {
      return -1;
    }
    return this._modelData.viewModel.viewLayout.getCurrentScrollTop();
  }
  setScrollLeft(newScrollLeft, scrollType = 1) {
    if (!this._modelData) {
      return;
    }
    if (typeof newScrollLeft !== "number") {
      throw new Error("Invalid arguments");
    }
    this._modelData.viewModel.viewLayout.setScrollPosition({
      scrollLeft: newScrollLeft
    }, scrollType);
  }
  setScrollTop(newScrollTop, scrollType = 1) {
    if (!this._modelData) {
      return;
    }
    if (typeof newScrollTop !== "number") {
      throw new Error("Invalid arguments");
    }
    this._modelData.viewModel.viewLayout.setScrollPosition({
      scrollTop: newScrollTop
    }, scrollType);
  }
  setScrollPosition(position, scrollType = 1) {
    if (!this._modelData) {
      return;
    }
    this._modelData.viewModel.viewLayout.setScrollPosition(position, scrollType);
  }
  hasPendingScrollAnimation() {
    if (!this._modelData) {
      return false;
    }
    return this._modelData.viewModel.viewLayout.hasPendingScrollAnimation();
  }
  saveViewState() {
    if (!this._modelData) {
      return null;
    }
    const contributionsState = this._contributions.saveViewState();
    const cursorState = this._modelData.viewModel.saveCursorState();
    const viewState = this._modelData.viewModel.saveState();
    return {
      cursorState,
      viewState,
      contributionsState
    };
  }
  restoreViewState(s) {
    if (!this._modelData || !this._modelData.hasRealView) {
      return;
    }
    const codeEditorState = s;
    if (codeEditorState && codeEditorState.cursorState && codeEditorState.viewState) {
      const cursorState = codeEditorState.cursorState;
      if (Array.isArray(cursorState)) {
        if (cursorState.length > 0) {
          this._modelData.viewModel.restoreCursorState(cursorState);
        }
      } else {
        this._modelData.viewModel.restoreCursorState([cursorState]);
      }
      this._contributions.restoreViewState(codeEditorState.contributionsState || {});
      const reducedState = this._modelData.viewModel.reduceRestoreState(codeEditorState.viewState);
      this._modelData.view.restoreState(reducedState);
    }
  }
  handleInitialized() {
    var _a2;
    (_a2 = this._getViewModel()) === null || _a2 === void 0 ? void 0 : _a2.visibleLinesStabilized();
  }
  getContribution(id3) {
    return this._contributions.get(id3);
  }
  getActions() {
    return Array.from(this._actions.values());
  }
  getSupportedActions() {
    let result2 = this.getActions();
    result2 = result2.filter((action) => action.isSupported());
    return result2;
  }
  getAction(id3) {
    return this._actions.get(id3) || null;
  }
  trigger(source, handlerId, payload) {
    payload = payload || {};
    switch (handlerId) {
      case "compositionStart":
        this._startComposition();
        return;
      case "compositionEnd":
        this._endComposition(source);
        return;
      case "type": {
        const args = payload;
        this._type(source, args.text || "");
        return;
      }
      case "replacePreviousChar": {
        const args = payload;
        this._compositionType(source, args.text || "", args.replaceCharCnt || 0, 0, 0);
        return;
      }
      case "compositionType": {
        const args = payload;
        this._compositionType(source, args.text || "", args.replacePrevCharCnt || 0, args.replaceNextCharCnt || 0, args.positionDelta || 0);
        return;
      }
      case "paste": {
        const args = payload;
        this._paste(source, args.text || "", args.pasteOnNewLine || false, args.multicursorText || null, args.mode || null);
        return;
      }
      case "cut":
        this._cut(source);
        return;
    }
    const action = this.getAction(handlerId);
    if (action) {
      Promise.resolve(action.run(payload)).then(void 0, onUnexpectedError);
      return;
    }
    if (!this._modelData) {
      return;
    }
    if (this._triggerEditorCommand(source, handlerId, payload)) {
      return;
    }
    this._triggerCommand(handlerId, payload);
  }
  _triggerCommand(handlerId, payload) {
    this._commandService.executeCommand(handlerId, payload);
  }
  _startComposition() {
    if (!this._modelData) {
      return;
    }
    this._modelData.viewModel.startComposition();
    this._onDidCompositionStart.fire();
  }
  _endComposition(source) {
    if (!this._modelData) {
      return;
    }
    this._modelData.viewModel.endComposition(source);
    this._onDidCompositionEnd.fire();
  }
  _type(source, text2) {
    if (!this._modelData || text2.length === 0) {
      return;
    }
    if (source === "keyboard") {
      this._onWillType.fire(text2);
    }
    this._modelData.viewModel.type(text2, source);
    if (source === "keyboard") {
      this._onDidType.fire(text2);
    }
  }
  _compositionType(source, text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta) {
    if (!this._modelData) {
      return;
    }
    this._modelData.viewModel.compositionType(text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta, source);
  }
  _paste(source, text2, pasteOnNewLine, multicursorText, mode) {
    if (!this._modelData || text2.length === 0) {
      return;
    }
    const viewModel = this._modelData.viewModel;
    const startPosition = viewModel.getSelection().getStartPosition();
    viewModel.paste(text2, pasteOnNewLine, multicursorText, source);
    const endPosition = viewModel.getSelection().getStartPosition();
    if (source === "keyboard") {
      this._onDidPaste.fire({
        range: new Range$2(startPosition.lineNumber, startPosition.column, endPosition.lineNumber, endPosition.column),
        languageId: mode
      });
    }
  }
  _cut(source) {
    if (!this._modelData) {
      return;
    }
    this._modelData.viewModel.cut(source);
  }
  _triggerEditorCommand(source, handlerId, payload) {
    const command = EditorExtensionsRegistry.getEditorCommand(handlerId);
    if (command) {
      payload = payload || {};
      payload.source = source;
      this._instantiationService.invokeFunction((accessor) => {
        Promise.resolve(command.runEditorCommand(accessor, this, payload)).then(void 0, onUnexpectedError);
      });
      return true;
    }
    return false;
  }
  _getViewModel() {
    if (!this._modelData) {
      return null;
    }
    return this._modelData.viewModel;
  }
  pushUndoStop() {
    if (!this._modelData) {
      return false;
    }
    if (this._configuration.options.get(
      89
      /* EditorOption.readOnly */
    )) {
      return false;
    }
    this._modelData.model.pushStackElement();
    return true;
  }
  popUndoStop() {
    if (!this._modelData) {
      return false;
    }
    if (this._configuration.options.get(
      89
      /* EditorOption.readOnly */
    )) {
      return false;
    }
    this._modelData.model.popStackElement();
    return true;
  }
  executeEdits(source, edits, endCursorState) {
    if (!this._modelData) {
      return false;
    }
    if (this._configuration.options.get(
      89
      /* EditorOption.readOnly */
    )) {
      return false;
    }
    let cursorStateComputer;
    if (!endCursorState) {
      cursorStateComputer = () => null;
    } else if (Array.isArray(endCursorState)) {
      cursorStateComputer = () => endCursorState;
    } else {
      cursorStateComputer = endCursorState;
    }
    this._modelData.viewModel.executeEdits(source, edits, cursorStateComputer);
    return true;
  }
  executeCommand(source, command) {
    if (!this._modelData) {
      return;
    }
    this._modelData.viewModel.executeCommand(command, source);
  }
  executeCommands(source, commands) {
    if (!this._modelData) {
      return;
    }
    this._modelData.viewModel.executeCommands(commands, source);
  }
  createDecorationsCollection(decorations2) {
    return new EditorDecorationsCollection(this, decorations2);
  }
  changeDecorations(callback) {
    if (!this._modelData) {
      return null;
    }
    return this._modelData.model.changeDecorations(callback, this._id);
  }
  getLineDecorations(lineNumber) {
    if (!this._modelData) {
      return null;
    }
    return this._modelData.model.getLineDecorations(lineNumber, this._id, filterValidationDecorations(this._configuration.options));
  }
  getDecorationsInRange(range2) {
    if (!this._modelData) {
      return null;
    }
    return this._modelData.model.getDecorationsInRange(range2, this._id, filterValidationDecorations(this._configuration.options));
  }
  /**
   * @deprecated
   */
  deltaDecorations(oldDecorations, newDecorations) {
    if (!this._modelData) {
      return [];
    }
    if (oldDecorations.length === 0 && newDecorations.length === 0) {
      return oldDecorations;
    }
    return this._modelData.model.deltaDecorations(oldDecorations, newDecorations, this._id);
  }
  removeDecorations(decorationIds) {
    if (!this._modelData || decorationIds.length === 0) {
      return;
    }
    this._modelData.model.changeDecorations((changeAccessor) => {
      changeAccessor.deltaDecorations(decorationIds, []);
    });
  }
  removeDecorationsByType(decorationTypeKey) {
    const oldDecorationsIds = this._decorationTypeKeysToIds[decorationTypeKey];
    if (oldDecorationsIds) {
      this.deltaDecorations(oldDecorationsIds, []);
    }
    if (this._decorationTypeKeysToIds.hasOwnProperty(decorationTypeKey)) {
      delete this._decorationTypeKeysToIds[decorationTypeKey];
    }
    if (this._decorationTypeSubtypes.hasOwnProperty(decorationTypeKey)) {
      delete this._decorationTypeSubtypes[decorationTypeKey];
    }
  }
  getLayoutInfo() {
    const options = this._configuration.options;
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    return layoutInfo;
  }
  createOverviewRuler(cssClassName) {
    if (!this._modelData || !this._modelData.hasRealView) {
      return null;
    }
    return this._modelData.view.createOverviewRuler(cssClassName);
  }
  getContainerDomNode() {
    return this._domElement;
  }
  getDomNode() {
    if (!this._modelData || !this._modelData.hasRealView) {
      return null;
    }
    return this._modelData.view.domNode.domNode;
  }
  delegateVerticalScrollbarPointerDown(browserEvent) {
    if (!this._modelData || !this._modelData.hasRealView) {
      return;
    }
    this._modelData.view.delegateVerticalScrollbarPointerDown(browserEvent);
  }
  delegateScrollFromMouseWheelEvent(browserEvent) {
    if (!this._modelData || !this._modelData.hasRealView) {
      return;
    }
    this._modelData.view.delegateScrollFromMouseWheelEvent(browserEvent);
  }
  layout(dimension) {
    this._configuration.observeContainer(dimension);
    this.render();
  }
  focus() {
    if (!this._modelData || !this._modelData.hasRealView) {
      return;
    }
    this._modelData.view.focus();
  }
  hasTextFocus() {
    if (!this._modelData || !this._modelData.hasRealView) {
      return false;
    }
    return this._modelData.view.isFocused();
  }
  hasWidgetFocus() {
    return this._focusTracker && this._focusTracker.hasFocus();
  }
  addContentWidget(widget) {
    const widgetData = {
      widget,
      position: widget.getPosition()
    };
    if (this._contentWidgets.hasOwnProperty(widget.getId())) {
      console.warn("Overwriting a content widget with the same id.");
    }
    this._contentWidgets[widget.getId()] = widgetData;
    if (this._modelData && this._modelData.hasRealView) {
      this._modelData.view.addContentWidget(widgetData);
    }
  }
  layoutContentWidget(widget) {
    const widgetId = widget.getId();
    if (this._contentWidgets.hasOwnProperty(widgetId)) {
      const widgetData = this._contentWidgets[widgetId];
      widgetData.position = widget.getPosition();
      if (this._modelData && this._modelData.hasRealView) {
        this._modelData.view.layoutContentWidget(widgetData);
      }
    }
  }
  removeContentWidget(widget) {
    const widgetId = widget.getId();
    if (this._contentWidgets.hasOwnProperty(widgetId)) {
      const widgetData = this._contentWidgets[widgetId];
      delete this._contentWidgets[widgetId];
      if (this._modelData && this._modelData.hasRealView) {
        this._modelData.view.removeContentWidget(widgetData);
      }
    }
  }
  addOverlayWidget(widget) {
    const widgetData = {
      widget,
      position: widget.getPosition()
    };
    if (this._overlayWidgets.hasOwnProperty(widget.getId())) {
      console.warn("Overwriting an overlay widget with the same id.");
    }
    this._overlayWidgets[widget.getId()] = widgetData;
    if (this._modelData && this._modelData.hasRealView) {
      this._modelData.view.addOverlayWidget(widgetData);
    }
  }
  layoutOverlayWidget(widget) {
    const widgetId = widget.getId();
    if (this._overlayWidgets.hasOwnProperty(widgetId)) {
      const widgetData = this._overlayWidgets[widgetId];
      widgetData.position = widget.getPosition();
      if (this._modelData && this._modelData.hasRealView) {
        this._modelData.view.layoutOverlayWidget(widgetData);
      }
    }
  }
  removeOverlayWidget(widget) {
    const widgetId = widget.getId();
    if (this._overlayWidgets.hasOwnProperty(widgetId)) {
      const widgetData = this._overlayWidgets[widgetId];
      delete this._overlayWidgets[widgetId];
      if (this._modelData && this._modelData.hasRealView) {
        this._modelData.view.removeOverlayWidget(widgetData);
      }
    }
  }
  addGlyphMarginWidget(widget) {
    const widgetData = {
      widget,
      position: widget.getPosition()
    };
    if (this._glyphMarginWidgets.hasOwnProperty(widget.getId())) {
      console.warn("Overwriting a glyph margin widget with the same id.");
    }
    this._glyphMarginWidgets[widget.getId()] = widgetData;
    if (this._modelData && this._modelData.hasRealView) {
      this._modelData.view.addGlyphMarginWidget(widgetData);
    }
  }
  layoutGlyphMarginWidget(widget) {
    const widgetId = widget.getId();
    if (this._glyphMarginWidgets.hasOwnProperty(widgetId)) {
      const widgetData = this._glyphMarginWidgets[widgetId];
      widgetData.position = widget.getPosition();
      if (this._modelData && this._modelData.hasRealView) {
        this._modelData.view.layoutGlyphMarginWidget(widgetData);
      }
    }
  }
  removeGlyphMarginWidget(widget) {
    const widgetId = widget.getId();
    if (this._glyphMarginWidgets.hasOwnProperty(widgetId)) {
      const widgetData = this._glyphMarginWidgets[widgetId];
      delete this._glyphMarginWidgets[widgetId];
      if (this._modelData && this._modelData.hasRealView) {
        this._modelData.view.removeGlyphMarginWidget(widgetData);
      }
    }
  }
  changeViewZones(callback) {
    if (!this._modelData || !this._modelData.hasRealView) {
      return;
    }
    this._modelData.view.change(callback);
  }
  getTargetAtClientPoint(clientX, clientY) {
    if (!this._modelData || !this._modelData.hasRealView) {
      return null;
    }
    return this._modelData.view.getTargetAtClientPoint(clientX, clientY);
  }
  getScrolledVisiblePosition(rawPosition) {
    if (!this._modelData || !this._modelData.hasRealView) {
      return null;
    }
    const position = this._modelData.model.validatePosition(rawPosition);
    const options = this._configuration.options;
    const layoutInfo = options.get(
      142
      /* EditorOption.layoutInfo */
    );
    const top = CodeEditorWidget2._getVerticalOffsetForPosition(this._modelData, position.lineNumber, position.column) - this.getScrollTop();
    const left = this._modelData.view.getOffsetForColumn(position.lineNumber, position.column) + layoutInfo.glyphMarginWidth + layoutInfo.lineNumbersWidth + layoutInfo.decorationsWidth - this.getScrollLeft();
    return {
      top,
      left,
      height: options.get(
        65
        /* EditorOption.lineHeight */
      )
    };
  }
  getOffsetForColumn(lineNumber, column) {
    if (!this._modelData || !this._modelData.hasRealView) {
      return -1;
    }
    return this._modelData.view.getOffsetForColumn(lineNumber, column);
  }
  render(forceRedraw = false) {
    if (!this._modelData || !this._modelData.hasRealView) {
      return;
    }
    this._modelData.view.render(true, forceRedraw);
  }
  setAriaOptions(options) {
    if (!this._modelData || !this._modelData.hasRealView) {
      return;
    }
    this._modelData.view.setAriaOptions(options);
  }
  applyFontInfo(target) {
    applyFontInfo(target, this._configuration.options.get(
      49
      /* EditorOption.fontInfo */
    ));
  }
  setBanner(domNode, domNodeHeight) {
    if (this._bannerDomNode && this._domElement.contains(this._bannerDomNode)) {
      this._domElement.removeChild(this._bannerDomNode);
    }
    this._bannerDomNode = domNode;
    this._configuration.setReservedHeight(domNode ? domNodeHeight : 0);
    if (this._bannerDomNode) {
      this._domElement.prepend(this._bannerDomNode);
    }
  }
  _attachModel(model) {
    if (!model) {
      this._modelData = null;
      return;
    }
    const listenersToRemove = [];
    this._domElement.setAttribute("data-mode-id", model.getLanguageId());
    this._configuration.setIsDominatedByLongLines(model.isDominatedByLongLines());
    this._configuration.setModelLineCount(model.getLineCount());
    const attachedView = model.onBeforeAttached();
    const viewModel = new ViewModel$1(this._id, this._configuration, model, DOMLineBreaksComputerFactory.create(), MonospaceLineBreaksComputerFactory.create(this._configuration.options), (callback) => scheduleAtNextAnimationFrame(callback), this.languageConfigurationService, this._themeService, attachedView);
    listenersToRemove.push(model.onWillDispose(() => this.setModel(null)));
    listenersToRemove.push(viewModel.onEvent((e) => {
      switch (e.kind) {
        case 0:
          this._onDidContentSizeChange.fire(e);
          break;
        case 1:
          this._editorTextFocus.setValue(e.hasFocus);
          break;
        case 2:
          this._onDidScrollChange.fire(e);
          break;
        case 3:
          this._onDidChangeViewZones.fire();
          break;
        case 4:
          this._onDidChangeHiddenAreas.fire();
          break;
        case 5:
          this._onDidAttemptReadOnlyEdit.fire();
          break;
        case 6: {
          if (e.reachedMaxCursorCount) {
            const multiCursorLimit = this.getOption(
              78
              /* EditorOption.multiCursorLimit */
            );
            const message = localize("cursors.maximum", "The number of cursors has been limited to {0}. Consider using [find and replace](https://code.visualstudio.com/docs/editor/codebasics#_find-and-replace) for larger changes or increase the editor multi cursor limit setting.", multiCursorLimit);
            this._notificationService.prompt(Severity.Warning, message, [
              {
                label: "Find and Replace",
                run: () => {
                  this._commandService.executeCommand("editor.action.startFindReplaceAction");
                }
              },
              {
                label: localize("goToSetting", "Increase Multi Cursor Limit"),
                run: () => {
                  this._commandService.executeCommand("workbench.action.openSettings2", {
                    query: "editor.multiCursorLimit"
                  });
                }
              }
            ]);
          }
          const positions = [];
          for (let i = 0, len = e.selections.length; i < len; i++) {
            positions[i] = e.selections[i].getPosition();
          }
          const e1 = {
            position: positions[0],
            secondaryPositions: positions.slice(1),
            reason: e.reason,
            source: e.source
          };
          this._onDidChangeCursorPosition.fire(e1);
          const e2 = {
            selection: e.selections[0],
            secondarySelections: e.selections.slice(1),
            modelVersionId: e.modelVersionId,
            oldSelections: e.oldSelections,
            oldModelVersionId: e.oldModelVersionId,
            source: e.source,
            reason: e.reason
          };
          this._onDidChangeCursorSelection.fire(e2);
          break;
        }
        case 7:
          this._onDidChangeModelDecorations.fire(e.event);
          break;
        case 8:
          this._domElement.setAttribute("data-mode-id", model.getLanguageId());
          this._onDidChangeModelLanguage.fire(e.event);
          break;
        case 9:
          this._onDidChangeModelLanguageConfiguration.fire(e.event);
          break;
        case 10:
          this._onDidChangeModelContent.fire(e.event);
          break;
        case 11:
          this._onDidChangeModelOptions.fire(e.event);
          break;
        case 12:
          this._onDidChangeModelTokens.fire(e.event);
          break;
      }
    }));
    const [view, hasRealView] = this._createView(viewModel);
    if (hasRealView) {
      this._domElement.appendChild(view.domNode.domNode);
      let keys = Object.keys(this._contentWidgets);
      for (let i = 0, len = keys.length; i < len; i++) {
        const widgetId = keys[i];
        view.addContentWidget(this._contentWidgets[widgetId]);
      }
      keys = Object.keys(this._overlayWidgets);
      for (let i = 0, len = keys.length; i < len; i++) {
        const widgetId = keys[i];
        view.addOverlayWidget(this._overlayWidgets[widgetId]);
      }
      keys = Object.keys(this._glyphMarginWidgets);
      for (let i = 0, len = keys.length; i < len; i++) {
        const widgetId = keys[i];
        view.addGlyphMarginWidget(this._glyphMarginWidgets[widgetId]);
      }
      view.render(false, true);
      view.domNode.domNode.setAttribute("data-uri", model.uri.toString());
    }
    this._modelData = new ModelData$1(model, viewModel, view, hasRealView, listenersToRemove, attachedView);
  }
  _createView(viewModel) {
    let commandDelegate;
    if (this.isSimpleWidget) {
      commandDelegate = {
        paste: (text2, pasteOnNewLine, multicursorText, mode) => {
          this._paste("keyboard", text2, pasteOnNewLine, multicursorText, mode);
        },
        type: (text2) => {
          this._type("keyboard", text2);
        },
        compositionType: (text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta) => {
          this._compositionType("keyboard", text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta);
        },
        startComposition: () => {
          this._startComposition();
        },
        endComposition: () => {
          this._endComposition("keyboard");
        },
        cut: () => {
          this._cut("keyboard");
        }
      };
    } else {
      commandDelegate = {
        paste: (text2, pasteOnNewLine, multicursorText, mode) => {
          const payload = { text: text2, pasteOnNewLine, multicursorText, mode };
          this._commandService.executeCommand("paste", payload);
        },
        type: (text2) => {
          const payload = { text: text2 };
          this._commandService.executeCommand("type", payload);
        },
        compositionType: (text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta) => {
          if (replaceNextCharCnt || positionDelta) {
            const payload = { text: text2, replacePrevCharCnt, replaceNextCharCnt, positionDelta };
            this._commandService.executeCommand("compositionType", payload);
          } else {
            const payload = { text: text2, replaceCharCnt: replacePrevCharCnt };
            this._commandService.executeCommand("replacePreviousChar", payload);
          }
        },
        startComposition: () => {
          this._commandService.executeCommand("compositionStart", {});
        },
        endComposition: () => {
          this._commandService.executeCommand("compositionEnd", {});
        },
        cut: () => {
          this._commandService.executeCommand("cut", {});
        }
      };
    }
    const viewUserInputEvents = new ViewUserInputEvents(viewModel.coordinatesConverter);
    viewUserInputEvents.onKeyDown = (e) => this._onKeyDown.fire(e);
    viewUserInputEvents.onKeyUp = (e) => this._onKeyUp.fire(e);
    viewUserInputEvents.onContextMenu = (e) => this._onContextMenu.fire(e);
    viewUserInputEvents.onMouseMove = (e) => this._onMouseMove.fire(e);
    viewUserInputEvents.onMouseLeave = (e) => this._onMouseLeave.fire(e);
    viewUserInputEvents.onMouseDown = (e) => this._onMouseDown.fire(e);
    viewUserInputEvents.onMouseUp = (e) => this._onMouseUp.fire(e);
    viewUserInputEvents.onMouseDrag = (e) => this._onMouseDrag.fire(e);
    viewUserInputEvents.onMouseDrop = (e) => this._onMouseDrop.fire(e);
    viewUserInputEvents.onMouseDropCanceled = (e) => this._onMouseDropCanceled.fire(e);
    viewUserInputEvents.onMouseWheel = (e) => this._onMouseWheel.fire(e);
    const view = new View$1(commandDelegate, this._configuration, this._themeService.getColorTheme(), viewModel, viewUserInputEvents, this._overflowWidgetsDomNode, this._instantiationService);
    return [view, true];
  }
  _postDetachModelCleanup(detachedModel) {
    detachedModel === null || detachedModel === void 0 ? void 0 : detachedModel.removeAllDecorationsWithOwnerId(this._id);
  }
  _detachModel() {
    if (!this._modelData) {
      return null;
    }
    const model = this._modelData.model;
    const removeDomNode = this._modelData.hasRealView ? this._modelData.view.domNode.domNode : null;
    this._modelData.dispose();
    this._modelData = null;
    this._domElement.removeAttribute("data-mode-id");
    if (removeDomNode && this._domElement.contains(removeDomNode)) {
      this._domElement.removeChild(removeDomNode);
    }
    if (this._bannerDomNode && this._domElement.contains(this._bannerDomNode)) {
      this._domElement.removeChild(this._bannerDomNode);
    }
    return model;
  }
  _removeDecorationType(key) {
    this._codeEditorService.removeDecorationType(key);
  }
  hasModel() {
    return this._modelData !== null;
  }
  showDropIndicatorAt(position) {
    const newDecorations = [{
      range: new Range$2(position.lineNumber, position.column, position.lineNumber, position.column),
      options: CodeEditorWidget2.dropIntoEditorDecorationOptions
    }];
    this._dropIntoEditorDecorations.set(newDecorations);
    this.revealPosition(
      position,
      1
      /* editorCommon.ScrollType.Immediate */
    );
  }
  removeDropIndicator() {
    this._dropIntoEditorDecorations.clear();
  }
  setContextValue(key, value) {
    this._contextKeyService.createKey(key, value);
  }
};
CodeEditorWidget.dropIntoEditorDecorationOptions = ModelDecorationOptions.register({
  description: "workbench-dnd-target",
  className: "dnd-target"
});
CodeEditorWidget = __decorate$22([
  __param$1Y(3, IInstantiationService),
  __param$1Y(4, ICodeEditorService),
  __param$1Y(5, ICommandService),
  __param$1Y(6, IContextKeyService),
  __param$1Y(7, IThemeService),
  __param$1Y(8, INotificationService),
  __param$1Y(9, IAccessibilityService),
  __param$1Y(10, ILanguageConfigurationService),
  __param$1Y(11, ILanguageFeaturesService)
], CodeEditorWidget);
class BooleanEventEmitter extends Disposable {
  constructor(_emitterOptions) {
    super();
    this._emitterOptions = _emitterOptions;
    this._onDidChangeToTrue = this._register(new Emitter$1(this._emitterOptions));
    this.onDidChangeToTrue = this._onDidChangeToTrue.event;
    this._onDidChangeToFalse = this._register(new Emitter$1(this._emitterOptions));
    this.onDidChangeToFalse = this._onDidChangeToFalse.event;
    this._value = 0;
  }
  setValue(_value) {
    const value = _value ? 2 : 1;
    if (this._value === value) {
      return;
    }
    this._value = value;
    if (this._value === 2) {
      this._onDidChangeToTrue.fire();
    } else if (this._value === 1) {
      this._onDidChangeToFalse.fire();
    }
  }
}
class InteractionEmitter extends Emitter$1 {
  constructor(_contributions, deliveryQueue) {
    super({ deliveryQueue });
    this._contributions = _contributions;
  }
  fire(event) {
    this._contributions.onBeforeInteractionEvent();
    super.fire(event);
  }
}
class EditorContextKeysManager extends Disposable {
  constructor(editor2, contextKeyService) {
    super();
    this._editor = editor2;
    contextKeyService.createKey("editorId", editor2.getId());
    this._editorSimpleInput = EditorContextKeys.editorSimpleInput.bindTo(contextKeyService);
    this._editorFocus = EditorContextKeys.focus.bindTo(contextKeyService);
    this._textInputFocus = EditorContextKeys.textInputFocus.bindTo(contextKeyService);
    this._editorTextFocus = EditorContextKeys.editorTextFocus.bindTo(contextKeyService);
    this._editorTabMovesFocus = EditorContextKeys.tabMovesFocus.bindTo(contextKeyService);
    this._editorReadonly = EditorContextKeys.readOnly.bindTo(contextKeyService);
    this._inDiffEditor = EditorContextKeys.inDiffEditor.bindTo(contextKeyService);
    this._editorColumnSelection = EditorContextKeys.columnSelection.bindTo(contextKeyService);
    this._hasMultipleSelections = EditorContextKeys.hasMultipleSelections.bindTo(contextKeyService);
    this._hasNonEmptySelection = EditorContextKeys.hasNonEmptySelection.bindTo(contextKeyService);
    this._canUndo = EditorContextKeys.canUndo.bindTo(contextKeyService);
    this._canRedo = EditorContextKeys.canRedo.bindTo(contextKeyService);
    this._register(this._editor.onDidChangeConfiguration(() => this._updateFromConfig()));
    this._register(this._editor.onDidChangeCursorSelection(() => this._updateFromSelection()));
    this._register(this._editor.onDidFocusEditorWidget(() => this._updateFromFocus()));
    this._register(this._editor.onDidBlurEditorWidget(() => this._updateFromFocus()));
    this._register(this._editor.onDidFocusEditorText(() => this._updateFromFocus()));
    this._register(this._editor.onDidBlurEditorText(() => this._updateFromFocus()));
    this._register(this._editor.onDidChangeModel(() => this._updateFromModel()));
    this._register(this._editor.onDidChangeConfiguration(() => this._updateFromModel()));
    this._register(TabFocus.onDidChangeTabFocus(() => this._editorTabMovesFocus.set(TabFocus.getTabFocusMode(
      "editorFocus"
      /* TabFocusContext.Editor */
    ))));
    this._updateFromConfig();
    this._updateFromSelection();
    this._updateFromFocus();
    this._updateFromModel();
    this._editorSimpleInput.set(this._editor.isSimpleWidget);
  }
  _updateFromConfig() {
    const options = this._editor.getOptions();
    this._editorTabMovesFocus.set(TabFocus.getTabFocusMode(
      "editorFocus"
      /* TabFocusContext.Editor */
    ));
    this._editorReadonly.set(options.get(
      89
      /* EditorOption.readOnly */
    ));
    this._inDiffEditor.set(options.get(
      60
      /* EditorOption.inDiffEditor */
    ));
    this._editorColumnSelection.set(options.get(
      21
      /* EditorOption.columnSelection */
    ));
  }
  _updateFromSelection() {
    const selections2 = this._editor.getSelections();
    if (!selections2) {
      this._hasMultipleSelections.reset();
      this._hasNonEmptySelection.reset();
    } else {
      this._hasMultipleSelections.set(selections2.length > 1);
      this._hasNonEmptySelection.set(selections2.some((s) => !s.isEmpty()));
    }
  }
  _updateFromFocus() {
    this._editorFocus.set(this._editor.hasWidgetFocus() && !this._editor.isSimpleWidget);
    this._editorTextFocus.set(this._editor.hasTextFocus() && !this._editor.isSimpleWidget);
    this._textInputFocus.set(this._editor.hasTextFocus());
  }
  _updateFromModel() {
    const model = this._editor.getModel();
    this._canUndo.set(Boolean(model && model.canUndo()));
    this._canRedo.set(Boolean(model && model.canRedo()));
  }
}
class EditorModeContext extends Disposable {
  constructor(_editor, _contextKeyService, _languageFeaturesService) {
    super();
    this._editor = _editor;
    this._contextKeyService = _contextKeyService;
    this._languageFeaturesService = _languageFeaturesService;
    this._langId = EditorContextKeys.languageId.bindTo(_contextKeyService);
    this._hasCompletionItemProvider = EditorContextKeys.hasCompletionItemProvider.bindTo(_contextKeyService);
    this._hasCodeActionsProvider = EditorContextKeys.hasCodeActionsProvider.bindTo(_contextKeyService);
    this._hasCodeLensProvider = EditorContextKeys.hasCodeLensProvider.bindTo(_contextKeyService);
    this._hasDefinitionProvider = EditorContextKeys.hasDefinitionProvider.bindTo(_contextKeyService);
    this._hasDeclarationProvider = EditorContextKeys.hasDeclarationProvider.bindTo(_contextKeyService);
    this._hasImplementationProvider = EditorContextKeys.hasImplementationProvider.bindTo(_contextKeyService);
    this._hasTypeDefinitionProvider = EditorContextKeys.hasTypeDefinitionProvider.bindTo(_contextKeyService);
    this._hasHoverProvider = EditorContextKeys.hasHoverProvider.bindTo(_contextKeyService);
    this._hasDocumentHighlightProvider = EditorContextKeys.hasDocumentHighlightProvider.bindTo(_contextKeyService);
    this._hasDocumentSymbolProvider = EditorContextKeys.hasDocumentSymbolProvider.bindTo(_contextKeyService);
    this._hasReferenceProvider = EditorContextKeys.hasReferenceProvider.bindTo(_contextKeyService);
    this._hasRenameProvider = EditorContextKeys.hasRenameProvider.bindTo(_contextKeyService);
    this._hasSignatureHelpProvider = EditorContextKeys.hasSignatureHelpProvider.bindTo(_contextKeyService);
    this._hasInlayHintsProvider = EditorContextKeys.hasInlayHintsProvider.bindTo(_contextKeyService);
    this._hasDocumentFormattingProvider = EditorContextKeys.hasDocumentFormattingProvider.bindTo(_contextKeyService);
    this._hasDocumentSelectionFormattingProvider = EditorContextKeys.hasDocumentSelectionFormattingProvider.bindTo(_contextKeyService);
    this._hasMultipleDocumentFormattingProvider = EditorContextKeys.hasMultipleDocumentFormattingProvider.bindTo(_contextKeyService);
    this._hasMultipleDocumentSelectionFormattingProvider = EditorContextKeys.hasMultipleDocumentSelectionFormattingProvider.bindTo(_contextKeyService);
    this._isInWalkThrough = EditorContextKeys.isInWalkThroughSnippet.bindTo(_contextKeyService);
    const update = () => this._update();
    this._register(_editor.onDidChangeModel(update));
    this._register(_editor.onDidChangeModelLanguage(update));
    this._register(_languageFeaturesService.completionProvider.onDidChange(update));
    this._register(_languageFeaturesService.codeActionProvider.onDidChange(update));
    this._register(_languageFeaturesService.codeLensProvider.onDidChange(update));
    this._register(_languageFeaturesService.definitionProvider.onDidChange(update));
    this._register(_languageFeaturesService.declarationProvider.onDidChange(update));
    this._register(_languageFeaturesService.implementationProvider.onDidChange(update));
    this._register(_languageFeaturesService.typeDefinitionProvider.onDidChange(update));
    this._register(_languageFeaturesService.hoverProvider.onDidChange(update));
    this._register(_languageFeaturesService.documentHighlightProvider.onDidChange(update));
    this._register(_languageFeaturesService.documentSymbolProvider.onDidChange(update));
    this._register(_languageFeaturesService.referenceProvider.onDidChange(update));
    this._register(_languageFeaturesService.renameProvider.onDidChange(update));
    this._register(_languageFeaturesService.documentFormattingEditProvider.onDidChange(update));
    this._register(_languageFeaturesService.documentRangeFormattingEditProvider.onDidChange(update));
    this._register(_languageFeaturesService.signatureHelpProvider.onDidChange(update));
    this._register(_languageFeaturesService.inlayHintsProvider.onDidChange(update));
    update();
  }
  dispose() {
    super.dispose();
  }
  reset() {
    this._contextKeyService.bufferChangeEvents(() => {
      this._langId.reset();
      this._hasCompletionItemProvider.reset();
      this._hasCodeActionsProvider.reset();
      this._hasCodeLensProvider.reset();
      this._hasDefinitionProvider.reset();
      this._hasDeclarationProvider.reset();
      this._hasImplementationProvider.reset();
      this._hasTypeDefinitionProvider.reset();
      this._hasHoverProvider.reset();
      this._hasDocumentHighlightProvider.reset();
      this._hasDocumentSymbolProvider.reset();
      this._hasReferenceProvider.reset();
      this._hasRenameProvider.reset();
      this._hasDocumentFormattingProvider.reset();
      this._hasDocumentSelectionFormattingProvider.reset();
      this._hasSignatureHelpProvider.reset();
      this._isInWalkThrough.reset();
    });
  }
  _update() {
    const model = this._editor.getModel();
    if (!model) {
      this.reset();
      return;
    }
    this._contextKeyService.bufferChangeEvents(() => {
      this._langId.set(model.getLanguageId());
      this._hasCompletionItemProvider.set(this._languageFeaturesService.completionProvider.has(model));
      this._hasCodeActionsProvider.set(this._languageFeaturesService.codeActionProvider.has(model));
      this._hasCodeLensProvider.set(this._languageFeaturesService.codeLensProvider.has(model));
      this._hasDefinitionProvider.set(this._languageFeaturesService.definitionProvider.has(model));
      this._hasDeclarationProvider.set(this._languageFeaturesService.declarationProvider.has(model));
      this._hasImplementationProvider.set(this._languageFeaturesService.implementationProvider.has(model));
      this._hasTypeDefinitionProvider.set(this._languageFeaturesService.typeDefinitionProvider.has(model));
      this._hasHoverProvider.set(this._languageFeaturesService.hoverProvider.has(model));
      this._hasDocumentHighlightProvider.set(this._languageFeaturesService.documentHighlightProvider.has(model));
      this._hasDocumentSymbolProvider.set(this._languageFeaturesService.documentSymbolProvider.has(model));
      this._hasReferenceProvider.set(this._languageFeaturesService.referenceProvider.has(model));
      this._hasRenameProvider.set(this._languageFeaturesService.renameProvider.has(model));
      this._hasSignatureHelpProvider.set(this._languageFeaturesService.signatureHelpProvider.has(model));
      this._hasInlayHintsProvider.set(this._languageFeaturesService.inlayHintsProvider.has(model));
      this._hasDocumentFormattingProvider.set(this._languageFeaturesService.documentFormattingEditProvider.has(model) || this._languageFeaturesService.documentRangeFormattingEditProvider.has(model));
      this._hasDocumentSelectionFormattingProvider.set(this._languageFeaturesService.documentRangeFormattingEditProvider.has(model));
      this._hasMultipleDocumentFormattingProvider.set(this._languageFeaturesService.documentFormattingEditProvider.all(model).length + this._languageFeaturesService.documentRangeFormattingEditProvider.all(model).length > 1);
      this._hasMultipleDocumentSelectionFormattingProvider.set(this._languageFeaturesService.documentRangeFormattingEditProvider.all(model).length > 1);
      this._isInWalkThrough.set(model.uri.scheme === Schemas.walkThroughSnippet);
    });
  }
}
class CodeEditorWidgetFocusTracker extends Disposable {
  constructor(domElement) {
    super();
    this._onChange = this._register(new Emitter$1());
    this.onChange = this._onChange.event;
    this._hasFocus = false;
    this._domFocusTracker = this._register(trackFocus(domElement));
    this._register(this._domFocusTracker.onDidFocus(() => {
      this._hasFocus = true;
      this._onChange.fire(void 0);
    }));
    this._register(this._domFocusTracker.onDidBlur(() => {
      this._hasFocus = false;
      this._onChange.fire(void 0);
    }));
  }
  hasFocus() {
    return this._hasFocus;
  }
}
class EditorDecorationsCollection {
  get length() {
    return this._decorationIds.length;
  }
  constructor(_editor, decorations2) {
    this._editor = _editor;
    this._decorationIds = [];
    this._isChangingDecorations = false;
    if (Array.isArray(decorations2) && decorations2.length > 0) {
      this.set(decorations2);
    }
  }
  onDidChange(listener, thisArgs, disposables) {
    return this._editor.onDidChangeModelDecorations((e) => {
      if (this._isChangingDecorations) {
        return;
      }
      listener.call(thisArgs, e);
    }, disposables);
  }
  getRange(index) {
    if (!this._editor.hasModel()) {
      return null;
    }
    if (index >= this._decorationIds.length) {
      return null;
    }
    return this._editor.getModel().getDecorationRange(this._decorationIds[index]);
  }
  getRanges() {
    if (!this._editor.hasModel()) {
      return [];
    }
    const model = this._editor.getModel();
    const result2 = [];
    for (const decorationId of this._decorationIds) {
      const range2 = model.getDecorationRange(decorationId);
      if (range2) {
        result2.push(range2);
      }
    }
    return result2;
  }
  has(decoration2) {
    return this._decorationIds.includes(decoration2.id);
  }
  clear() {
    if (this._decorationIds.length === 0) {
      return;
    }
    this.set([]);
  }
  set(newDecorations) {
    try {
      this._isChangingDecorations = true;
      this._editor.changeDecorations((accessor) => {
        this._decorationIds = accessor.deltaDecorations(this._decorationIds, newDecorations);
      });
    } finally {
      this._isChangingDecorations = false;
    }
    return this._decorationIds;
  }
}
const squigglyStart = encodeURIComponent(`<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 6 3' enable-background='new 0 0 6 3' height='3' width='6'><g fill='`);
const squigglyEnd = encodeURIComponent(`'><polygon points='5.5,0 2.5,3 1.1,3 4.1,0'/><polygon points='4,0 6,2 6,0.6 5.4,0'/><polygon points='0,2 1,3 2.4,3 0,0.6'/></g></svg>`);
function getSquigglySVGData(color) {
  return squigglyStart + encodeURIComponent(color.toString()) + squigglyEnd;
}
const dotdotdotStart = encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" height="3" width="12"><g fill="`);
const dotdotdotEnd = encodeURIComponent(`"><circle cx="1" cy="1" r="1"/><circle cx="5" cy="1" r="1"/><circle cx="9" cy="1" r="1"/></g></svg>`);
function getDotDotDotSVGData(color) {
  return dotdotdotStart + encodeURIComponent(color.toString()) + dotdotdotEnd;
}
registerThemingParticipant((theme, collector) => {
  const errorForeground2 = theme.getColor(editorErrorForeground);
  if (errorForeground2) {
    collector.addRule(`.monaco-editor .${"squiggly-error"} { background: url("data:image/svg+xml,${getSquigglySVGData(errorForeground2)}") repeat-x bottom left; }`);
  }
  const warningForeground = theme.getColor(editorWarningForeground);
  if (warningForeground) {
    collector.addRule(`.monaco-editor .${"squiggly-warning"} { background: url("data:image/svg+xml,${getSquigglySVGData(warningForeground)}") repeat-x bottom left; }`);
  }
  const infoForeground = theme.getColor(editorInfoForeground);
  if (infoForeground) {
    collector.addRule(`.monaco-editor .${"squiggly-info"} { background: url("data:image/svg+xml,${getSquigglySVGData(infoForeground)}") repeat-x bottom left; }`);
  }
  const hintForeground = theme.getColor(editorHintForeground);
  if (hintForeground) {
    collector.addRule(`.monaco-editor .${"squiggly-hint"} { background: url("data:image/svg+xml,${getDotDotDotSVGData(hintForeground)}") no-repeat bottom left; }`);
  }
  const unnecessaryForeground = theme.getColor(editorUnnecessaryCodeOpacity);
  if (unnecessaryForeground) {
    collector.addRule(`.monaco-editor.showUnused .${"squiggly-inline-unnecessary"} { opacity: ${unnecessaryForeground.rgba.a}; }`);
  }
});
const sash = "";
var __decorate$21 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
const DEBUG = false;
var OrthogonalEdge;
(function(OrthogonalEdge2) {
  OrthogonalEdge2["North"] = "north";
  OrthogonalEdge2["South"] = "south";
  OrthogonalEdge2["East"] = "east";
  OrthogonalEdge2["West"] = "west";
})(OrthogonalEdge || (OrthogonalEdge = {}));
let globalSize = 4;
const onDidChangeGlobalSize = new Emitter$1();
let globalHoverDelay = 300;
const onDidChangeHoverDelay = new Emitter$1();
class MouseEventFactory {
  constructor() {
    this.disposables = new DisposableStore();
  }
  get onPointerMove() {
    return this.disposables.add(new DomEmitter(window, "mousemove")).event;
  }
  get onPointerUp() {
    return this.disposables.add(new DomEmitter(window, "mouseup")).event;
  }
  dispose() {
    this.disposables.dispose();
  }
}
__decorate$21([
  memoize
], MouseEventFactory.prototype, "onPointerMove", null);
__decorate$21([
  memoize
], MouseEventFactory.prototype, "onPointerUp", null);
class GestureEventFactory {
  get onPointerMove() {
    return this.disposables.add(new DomEmitter(this.el, EventType.Change)).event;
  }
  get onPointerUp() {
    return this.disposables.add(new DomEmitter(this.el, EventType.End)).event;
  }
  constructor(el) {
    this.el = el;
    this.disposables = new DisposableStore();
  }
  dispose() {
    this.disposables.dispose();
  }
}
__decorate$21([
  memoize
], GestureEventFactory.prototype, "onPointerMove", null);
__decorate$21([
  memoize
], GestureEventFactory.prototype, "onPointerUp", null);
class OrthogonalPointerEventFactory {
  get onPointerMove() {
    return this.factory.onPointerMove;
  }
  get onPointerUp() {
    return this.factory.onPointerUp;
  }
  constructor(factory) {
    this.factory = factory;
  }
  dispose() {
  }
}
__decorate$21([
  memoize
], OrthogonalPointerEventFactory.prototype, "onPointerMove", null);
__decorate$21([
  memoize
], OrthogonalPointerEventFactory.prototype, "onPointerUp", null);
const PointerEventsDisabledCssClass = "pointer-events-disabled";
class Sash extends Disposable {
  get state() {
    return this._state;
  }
  get orthogonalStartSash() {
    return this._orthogonalStartSash;
  }
  get orthogonalEndSash() {
    return this._orthogonalEndSash;
  }
  /**
   * The state of a sash defines whether it can be interacted with by the user
   * as well as what mouse cursor to use, when hovered.
   */
  set state(state) {
    if (this._state === state) {
      return;
    }
    this.el.classList.toggle(
      "disabled",
      state === 0
      /* SashState.Disabled */
    );
    this.el.classList.toggle(
      "minimum",
      state === 1
      /* SashState.AtMinimum */
    );
    this.el.classList.toggle(
      "maximum",
      state === 2
      /* SashState.AtMaximum */
    );
    this._state = state;
    this.onDidEnablementChange.fire(state);
  }
  /**
   * A reference to another sash, perpendicular to this one, which
   * aligns at the start of this one. A corner sash will be created
   * automatically at that location.
   *
   * The start of a horizontal sash is its left-most position.
   * The start of a vertical sash is its top-most position.
   */
  set orthogonalStartSash(sash2) {
    if (this._orthogonalStartSash === sash2) {
      return;
    }
    this.orthogonalStartDragHandleDisposables.clear();
    this.orthogonalStartSashDisposables.clear();
    if (sash2) {
      const onChange = (state) => {
        this.orthogonalStartDragHandleDisposables.clear();
        if (state !== 0) {
          this._orthogonalStartDragHandle = append$1(this.el, $$d(".orthogonal-drag-handle.start"));
          this.orthogonalStartDragHandleDisposables.add(toDisposable(() => this._orthogonalStartDragHandle.remove()));
          this.orthogonalStartDragHandleDisposables.add(new DomEmitter(this._orthogonalStartDragHandle, "mouseenter")).event(() => Sash.onMouseEnter(sash2), void 0, this.orthogonalStartDragHandleDisposables);
          this.orthogonalStartDragHandleDisposables.add(new DomEmitter(this._orthogonalStartDragHandle, "mouseleave")).event(() => Sash.onMouseLeave(sash2), void 0, this.orthogonalStartDragHandleDisposables);
        }
      };
      this.orthogonalStartSashDisposables.add(sash2.onDidEnablementChange.event(onChange, this));
      onChange(sash2.state);
    }
    this._orthogonalStartSash = sash2;
  }
  /**
   * A reference to another sash, perpendicular to this one, which
   * aligns at the end of this one. A corner sash will be created
   * automatically at that location.
   *
   * The end of a horizontal sash is its right-most position.
   * The end of a vertical sash is its bottom-most position.
   */
  set orthogonalEndSash(sash2) {
    if (this._orthogonalEndSash === sash2) {
      return;
    }
    this.orthogonalEndDragHandleDisposables.clear();
    this.orthogonalEndSashDisposables.clear();
    if (sash2) {
      const onChange = (state) => {
        this.orthogonalEndDragHandleDisposables.clear();
        if (state !== 0) {
          this._orthogonalEndDragHandle = append$1(this.el, $$d(".orthogonal-drag-handle.end"));
          this.orthogonalEndDragHandleDisposables.add(toDisposable(() => this._orthogonalEndDragHandle.remove()));
          this.orthogonalEndDragHandleDisposables.add(new DomEmitter(this._orthogonalEndDragHandle, "mouseenter")).event(() => Sash.onMouseEnter(sash2), void 0, this.orthogonalEndDragHandleDisposables);
          this.orthogonalEndDragHandleDisposables.add(new DomEmitter(this._orthogonalEndDragHandle, "mouseleave")).event(() => Sash.onMouseLeave(sash2), void 0, this.orthogonalEndDragHandleDisposables);
        }
      };
      this.orthogonalEndSashDisposables.add(sash2.onDidEnablementChange.event(onChange, this));
      onChange(sash2.state);
    }
    this._orthogonalEndSash = sash2;
  }
  constructor(container2, layoutProvider, options) {
    super();
    this.hoverDelay = globalHoverDelay;
    this.hoverDelayer = this._register(new Delayer(this.hoverDelay));
    this._state = 3;
    this.onDidEnablementChange = this._register(new Emitter$1());
    this._onDidStart = this._register(new Emitter$1());
    this._onDidChange = this._register(new Emitter$1());
    this._onDidReset = this._register(new Emitter$1());
    this._onDidEnd = this._register(new Emitter$1());
    this.orthogonalStartSashDisposables = this._register(new DisposableStore());
    this.orthogonalStartDragHandleDisposables = this._register(new DisposableStore());
    this.orthogonalEndSashDisposables = this._register(new DisposableStore());
    this.orthogonalEndDragHandleDisposables = this._register(new DisposableStore());
    this.onDidStart = this._onDidStart.event;
    this.onDidChange = this._onDidChange.event;
    this.onDidReset = this._onDidReset.event;
    this.onDidEnd = this._onDidEnd.event;
    this.linkedSash = void 0;
    this.el = append$1(container2, $$d(".monaco-sash"));
    if (options.orthogonalEdge) {
      this.el.classList.add(`orthogonal-edge-${options.orthogonalEdge}`);
    }
    if (isMacintosh) {
      this.el.classList.add("mac");
    }
    const onMouseDown = this._register(new DomEmitter(this.el, "mousedown")).event;
    this._register(onMouseDown((e) => this.onPointerStart(e, new MouseEventFactory()), this));
    const onMouseDoubleClick = this._register(new DomEmitter(this.el, "dblclick")).event;
    this._register(onMouseDoubleClick(this.onPointerDoublePress, this));
    const onMouseEnter = this._register(new DomEmitter(this.el, "mouseenter")).event;
    this._register(onMouseEnter(() => Sash.onMouseEnter(this)));
    const onMouseLeave = this._register(new DomEmitter(this.el, "mouseleave")).event;
    this._register(onMouseLeave(() => Sash.onMouseLeave(this)));
    this._register(Gesture.addTarget(this.el));
    const onTouchStart = this._register(new DomEmitter(this.el, EventType.Start)).event;
    this._register(onTouchStart((e) => this.onPointerStart(e, new GestureEventFactory(this.el)), this));
    const onTap = this._register(new DomEmitter(this.el, EventType.Tap)).event;
    let doubleTapTimeout = void 0;
    this._register(onTap((event) => {
      if (doubleTapTimeout) {
        clearTimeout(doubleTapTimeout);
        doubleTapTimeout = void 0;
        this.onPointerDoublePress(event);
        return;
      }
      clearTimeout(doubleTapTimeout);
      doubleTapTimeout = setTimeout(() => doubleTapTimeout = void 0, 250);
    }, this));
    if (typeof options.size === "number") {
      this.size = options.size;
      if (options.orientation === 0) {
        this.el.style.width = `${this.size}px`;
      } else {
        this.el.style.height = `${this.size}px`;
      }
    } else {
      this.size = globalSize;
      this._register(onDidChangeGlobalSize.event((size2) => {
        this.size = size2;
        this.layout();
      }));
    }
    this._register(onDidChangeHoverDelay.event((delay) => this.hoverDelay = delay));
    this.layoutProvider = layoutProvider;
    this.orthogonalStartSash = options.orthogonalStartSash;
    this.orthogonalEndSash = options.orthogonalEndSash;
    this.orientation = options.orientation || 0;
    if (this.orientation === 1) {
      this.el.classList.add("horizontal");
      this.el.classList.remove("vertical");
    } else {
      this.el.classList.remove("horizontal");
      this.el.classList.add("vertical");
    }
    this.el.classList.toggle("debug", DEBUG);
    this.layout();
  }
  onPointerStart(event, pointerEventFactory) {
    EventHelper.stop(event);
    let isMultisashResize = false;
    if (!event.__orthogonalSashEvent) {
      const orthogonalSash = this.getOrthogonalSash(event);
      if (orthogonalSash) {
        isMultisashResize = true;
        event.__orthogonalSashEvent = true;
        orthogonalSash.onPointerStart(event, new OrthogonalPointerEventFactory(pointerEventFactory));
      }
    }
    if (this.linkedSash && !event.__linkedSashEvent) {
      event.__linkedSashEvent = true;
      this.linkedSash.onPointerStart(event, new OrthogonalPointerEventFactory(pointerEventFactory));
    }
    if (!this.state) {
      return;
    }
    const iframes = document.getElementsByTagName("iframe");
    for (const iframe of iframes) {
      iframe.classList.add(PointerEventsDisabledCssClass);
    }
    const startX = event.pageX;
    const startY = event.pageY;
    const altKey = event.altKey;
    const startEvent = { startX, currentX: startX, startY, currentY: startY, altKey };
    this.el.classList.add("active");
    this._onDidStart.fire(startEvent);
    const style2 = createStyleSheet(this.el);
    const updateStyle = () => {
      let cursor = "";
      if (isMultisashResize) {
        cursor = "all-scroll";
      } else if (this.orientation === 1) {
        if (this.state === 1) {
          cursor = "s-resize";
        } else if (this.state === 2) {
          cursor = "n-resize";
        } else {
          cursor = isMacintosh ? "row-resize" : "ns-resize";
        }
      } else {
        if (this.state === 1) {
          cursor = "e-resize";
        } else if (this.state === 2) {
          cursor = "w-resize";
        } else {
          cursor = isMacintosh ? "col-resize" : "ew-resize";
        }
      }
      style2.textContent = `* { cursor: ${cursor} !important; }`;
    };
    const disposables = new DisposableStore();
    updateStyle();
    if (!isMultisashResize) {
      this.onDidEnablementChange.event(updateStyle, null, disposables);
    }
    const onPointerMove = (e) => {
      EventHelper.stop(e, false);
      const event2 = { startX, currentX: e.pageX, startY, currentY: e.pageY, altKey };
      this._onDidChange.fire(event2);
    };
    const onPointerUp = (e) => {
      EventHelper.stop(e, false);
      this.el.removeChild(style2);
      this.el.classList.remove("active");
      this._onDidEnd.fire();
      disposables.dispose();
      for (const iframe of iframes) {
        iframe.classList.remove(PointerEventsDisabledCssClass);
      }
    };
    pointerEventFactory.onPointerMove(onPointerMove, null, disposables);
    pointerEventFactory.onPointerUp(onPointerUp, null, disposables);
    disposables.add(pointerEventFactory);
  }
  onPointerDoublePress(e) {
    const orthogonalSash = this.getOrthogonalSash(e);
    if (orthogonalSash) {
      orthogonalSash._onDidReset.fire();
    }
    if (this.linkedSash) {
      this.linkedSash._onDidReset.fire();
    }
    this._onDidReset.fire();
  }
  static onMouseEnter(sash2, fromLinkedSash = false) {
    if (sash2.el.classList.contains("active")) {
      sash2.hoverDelayer.cancel();
      sash2.el.classList.add("hover");
    } else {
      sash2.hoverDelayer.trigger(() => sash2.el.classList.add("hover"), sash2.hoverDelay).then(void 0, () => {
      });
    }
    if (!fromLinkedSash && sash2.linkedSash) {
      Sash.onMouseEnter(sash2.linkedSash, true);
    }
  }
  static onMouseLeave(sash2, fromLinkedSash = false) {
    sash2.hoverDelayer.cancel();
    sash2.el.classList.remove("hover");
    if (!fromLinkedSash && sash2.linkedSash) {
      Sash.onMouseLeave(sash2.linkedSash, true);
    }
  }
  /**
   * Forcefully stop any user interactions with this sash.
   * Useful when hiding a parent component, while the user is still
   * interacting with the sash.
   */
  clearSashHoverState() {
    Sash.onMouseLeave(this);
  }
  /**
   * Layout the sash. The sash will size and position itself
   * based on its provided {@link ISashLayoutProvider layout provider}.
   */
  layout() {
    if (this.orientation === 0) {
      const verticalProvider = this.layoutProvider;
      this.el.style.left = verticalProvider.getVerticalSashLeft(this) - this.size / 2 + "px";
      if (verticalProvider.getVerticalSashTop) {
        this.el.style.top = verticalProvider.getVerticalSashTop(this) + "px";
      }
      if (verticalProvider.getVerticalSashHeight) {
        this.el.style.height = verticalProvider.getVerticalSashHeight(this) + "px";
      }
    } else {
      const horizontalProvider = this.layoutProvider;
      this.el.style.top = horizontalProvider.getHorizontalSashTop(this) - this.size / 2 + "px";
      if (horizontalProvider.getHorizontalSashLeft) {
        this.el.style.left = horizontalProvider.getHorizontalSashLeft(this) + "px";
      }
      if (horizontalProvider.getHorizontalSashWidth) {
        this.el.style.width = horizontalProvider.getHorizontalSashWidth(this) + "px";
      }
    }
  }
  getOrthogonalSash(e) {
    var _a2;
    const target = (_a2 = e.initialTarget) !== null && _a2 !== void 0 ? _a2 : e.target;
    if (!target || !(target instanceof HTMLElement)) {
      return void 0;
    }
    if (target.classList.contains("orthogonal-drag-handle")) {
      return target.classList.contains("start") ? this.orthogonalStartSash : this.orthogonalEndSash;
    }
    return void 0;
  }
  dispose() {
    super.dispose();
    this.el.remove();
  }
}
var _a$2, _b$1;
class ResourceMapEntry {
  constructor(uri, value) {
    this.uri = uri;
    this.value = value;
  }
}
class ResourceMap {
  constructor(mapOrKeyFn, toKey) {
    this[_a$2] = "ResourceMap";
    if (mapOrKeyFn instanceof ResourceMap) {
      this.map = new Map(mapOrKeyFn.map);
      this.toKey = toKey !== null && toKey !== void 0 ? toKey : ResourceMap.defaultToKey;
    } else {
      this.map = /* @__PURE__ */ new Map();
      this.toKey = mapOrKeyFn !== null && mapOrKeyFn !== void 0 ? mapOrKeyFn : ResourceMap.defaultToKey;
    }
  }
  set(resource, value) {
    this.map.set(this.toKey(resource), new ResourceMapEntry(resource, value));
    return this;
  }
  get(resource) {
    var _c2;
    return (_c2 = this.map.get(this.toKey(resource))) === null || _c2 === void 0 ? void 0 : _c2.value;
  }
  has(resource) {
    return this.map.has(this.toKey(resource));
  }
  get size() {
    return this.map.size;
  }
  clear() {
    this.map.clear();
  }
  delete(resource) {
    return this.map.delete(this.toKey(resource));
  }
  forEach(clb, thisArg) {
    if (typeof thisArg !== "undefined") {
      clb = clb.bind(thisArg);
    }
    for (const [_, entry] of this.map) {
      clb(entry.value, entry.uri, this);
    }
  }
  *values() {
    for (const entry of this.map.values()) {
      yield entry.value;
    }
  }
  *keys() {
    for (const entry of this.map.values()) {
      yield entry.uri;
    }
  }
  *entries() {
    for (const entry of this.map.values()) {
      yield [entry.uri, entry.value];
    }
  }
  *[(_a$2 = Symbol.toStringTag, Symbol.iterator)]() {
    for (const [, entry] of this.map) {
      yield [entry.uri, entry.value];
    }
  }
}
ResourceMap.defaultToKey = (resource) => resource.toString();
class LinkedMap {
  constructor() {
    this[_b$1] = "LinkedMap";
    this._map = /* @__PURE__ */ new Map();
    this._head = void 0;
    this._tail = void 0;
    this._size = 0;
    this._state = 0;
  }
  clear() {
    this._map.clear();
    this._head = void 0;
    this._tail = void 0;
    this._size = 0;
    this._state++;
  }
  isEmpty() {
    return !this._head && !this._tail;
  }
  get size() {
    return this._size;
  }
  get first() {
    var _c2;
    return (_c2 = this._head) === null || _c2 === void 0 ? void 0 : _c2.value;
  }
  get last() {
    var _c2;
    return (_c2 = this._tail) === null || _c2 === void 0 ? void 0 : _c2.value;
  }
  has(key) {
    return this._map.has(key);
  }
  get(key, touch = 0) {
    const item = this._map.get(key);
    if (!item) {
      return void 0;
    }
    if (touch !== 0) {
      this.touch(item, touch);
    }
    return item.value;
  }
  set(key, value, touch = 0) {
    let item = this._map.get(key);
    if (item) {
      item.value = value;
      if (touch !== 0) {
        this.touch(item, touch);
      }
    } else {
      item = { key, value, next: void 0, previous: void 0 };
      switch (touch) {
        case 0:
          this.addItemLast(item);
          break;
        case 1:
          this.addItemFirst(item);
          break;
        case 2:
          this.addItemLast(item);
          break;
        default:
          this.addItemLast(item);
          break;
      }
      this._map.set(key, item);
      this._size++;
    }
    return this;
  }
  delete(key) {
    return !!this.remove(key);
  }
  remove(key) {
    const item = this._map.get(key);
    if (!item) {
      return void 0;
    }
    this._map.delete(key);
    this.removeItem(item);
    this._size--;
    return item.value;
  }
  shift() {
    if (!this._head && !this._tail) {
      return void 0;
    }
    if (!this._head || !this._tail) {
      throw new Error("Invalid list");
    }
    const item = this._head;
    this._map.delete(item.key);
    this.removeItem(item);
    this._size--;
    return item.value;
  }
  forEach(callbackfn, thisArg) {
    const state = this._state;
    let current = this._head;
    while (current) {
      if (thisArg) {
        callbackfn.bind(thisArg)(current.value, current.key, this);
      } else {
        callbackfn(current.value, current.key, this);
      }
      if (this._state !== state) {
        throw new Error(`LinkedMap got modified during iteration.`);
      }
      current = current.next;
    }
  }
  keys() {
    const map2 = this;
    const state = this._state;
    let current = this._head;
    const iterator2 = {
      [Symbol.iterator]() {
        return iterator2;
      },
      next() {
        if (map2._state !== state) {
          throw new Error(`LinkedMap got modified during iteration.`);
        }
        if (current) {
          const result2 = { value: current.key, done: false };
          current = current.next;
          return result2;
        } else {
          return { value: void 0, done: true };
        }
      }
    };
    return iterator2;
  }
  values() {
    const map2 = this;
    const state = this._state;
    let current = this._head;
    const iterator2 = {
      [Symbol.iterator]() {
        return iterator2;
      },
      next() {
        if (map2._state !== state) {
          throw new Error(`LinkedMap got modified during iteration.`);
        }
        if (current) {
          const result2 = { value: current.value, done: false };
          current = current.next;
          return result2;
        } else {
          return { value: void 0, done: true };
        }
      }
    };
    return iterator2;
  }
  entries() {
    const map2 = this;
    const state = this._state;
    let current = this._head;
    const iterator2 = {
      [Symbol.iterator]() {
        return iterator2;
      },
      next() {
        if (map2._state !== state) {
          throw new Error(`LinkedMap got modified during iteration.`);
        }
        if (current) {
          const result2 = { value: [current.key, current.value], done: false };
          current = current.next;
          return result2;
        } else {
          return { value: void 0, done: true };
        }
      }
    };
    return iterator2;
  }
  [(_b$1 = Symbol.toStringTag, Symbol.iterator)]() {
    return this.entries();
  }
  trimOld(newSize) {
    if (newSize >= this.size) {
      return;
    }
    if (newSize === 0) {
      this.clear();
      return;
    }
    let current = this._head;
    let currentSize = this.size;
    while (current && currentSize > newSize) {
      this._map.delete(current.key);
      current = current.next;
      currentSize--;
    }
    this._head = current;
    this._size = currentSize;
    if (current) {
      current.previous = void 0;
    }
    this._state++;
  }
  addItemFirst(item) {
    if (!this._head && !this._tail) {
      this._tail = item;
    } else if (!this._head) {
      throw new Error("Invalid list");
    } else {
      item.next = this._head;
      this._head.previous = item;
    }
    this._head = item;
    this._state++;
  }
  addItemLast(item) {
    if (!this._head && !this._tail) {
      this._head = item;
    } else if (!this._tail) {
      throw new Error("Invalid list");
    } else {
      item.previous = this._tail;
      this._tail.next = item;
    }
    this._tail = item;
    this._state++;
  }
  removeItem(item) {
    if (item === this._head && item === this._tail) {
      this._head = void 0;
      this._tail = void 0;
    } else if (item === this._head) {
      if (!item.next) {
        throw new Error("Invalid list");
      }
      item.next.previous = void 0;
      this._head = item.next;
    } else if (item === this._tail) {
      if (!item.previous) {
        throw new Error("Invalid list");
      }
      item.previous.next = void 0;
      this._tail = item.previous;
    } else {
      const next = item.next;
      const previous = item.previous;
      if (!next || !previous) {
        throw new Error("Invalid list");
      }
      next.previous = previous;
      previous.next = next;
    }
    item.next = void 0;
    item.previous = void 0;
    this._state++;
  }
  touch(item, touch) {
    if (!this._head || !this._tail) {
      throw new Error("Invalid list");
    }
    if (touch !== 1 && touch !== 2) {
      return;
    }
    if (touch === 1) {
      if (item === this._head) {
        return;
      }
      const next = item.next;
      const previous = item.previous;
      if (item === this._tail) {
        previous.next = void 0;
        this._tail = previous;
      } else {
        next.previous = previous;
        previous.next = next;
      }
      item.previous = void 0;
      item.next = this._head;
      this._head.previous = item;
      this._head = item;
      this._state++;
    } else if (touch === 2) {
      if (item === this._tail) {
        return;
      }
      const next = item.next;
      const previous = item.previous;
      if (item === this._head) {
        next.previous = void 0;
        this._head = next;
      } else {
        next.previous = previous;
        previous.next = next;
      }
      item.next = void 0;
      item.previous = this._tail;
      this._tail.next = item;
      this._tail = item;
      this._state++;
    }
  }
  toJSON() {
    const data = [];
    this.forEach((value, key) => {
      data.push([key, value]);
    });
    return data;
  }
  fromJSON(data) {
    this.clear();
    for (const [key, value] of data) {
      this.set(key, value);
    }
  }
}
let LRUCache$2 = class LRUCache extends LinkedMap {
  constructor(limit, ratio = 1) {
    super();
    this._limit = limit;
    this._ratio = Math.min(Math.max(0, ratio), 1);
  }
  get limit() {
    return this._limit;
  }
  set limit(limit) {
    this._limit = limit;
    this.checkTrim();
  }
  get(key, touch = 2) {
    return super.get(key, touch);
  }
  peek(key) {
    return super.get(
      key,
      0
      /* Touch.None */
    );
  }
  set(key, value) {
    super.set(
      key,
      value,
      2
      /* Touch.AsNew */
    );
    this.checkTrim();
    return this;
  }
  checkTrim() {
    if (this.size > this._limit) {
      this.trimOld(Math.round(this._limit * this._ratio));
    }
  }
};
function or(...filter2) {
  return function(word2, wordToMatchAgainst) {
    for (let i = 0, len = filter2.length; i < len; i++) {
      const match2 = filter2[i](word2, wordToMatchAgainst);
      if (match2) {
        return match2;
      }
    }
    return null;
  };
}
_matchesPrefix.bind(void 0, false);
const matchesPrefix = _matchesPrefix.bind(void 0, true);
function _matchesPrefix(ignoreCase, word2, wordToMatchAgainst) {
  if (!wordToMatchAgainst || wordToMatchAgainst.length < word2.length) {
    return null;
  }
  let matches;
  if (ignoreCase) {
    matches = startsWithIgnoreCase(wordToMatchAgainst, word2);
  } else {
    matches = wordToMatchAgainst.indexOf(word2) === 0;
  }
  if (!matches) {
    return null;
  }
  return word2.length > 0 ? [{ start: 0, end: word2.length }] : [];
}
function matchesContiguousSubString(word2, wordToMatchAgainst) {
  const index = wordToMatchAgainst.toLowerCase().indexOf(word2.toLowerCase());
  if (index === -1) {
    return null;
  }
  return [{ start: index, end: index + word2.length }];
}
function matchesSubString(word2, wordToMatchAgainst) {
  return _matchesSubString(word2.toLowerCase(), wordToMatchAgainst.toLowerCase(), 0, 0);
}
function _matchesSubString(word2, wordToMatchAgainst, i, j) {
  if (i === word2.length) {
    return [];
  } else if (j === wordToMatchAgainst.length) {
    return null;
  } else {
    if (word2[i] === wordToMatchAgainst[j]) {
      let result2 = null;
      if (result2 = _matchesSubString(word2, wordToMatchAgainst, i + 1, j + 1)) {
        return join$2({ start: j, end: j + 1 }, result2);
      }
      return null;
    }
    return _matchesSubString(word2, wordToMatchAgainst, i, j + 1);
  }
}
function isLower(code) {
  return 97 <= code && code <= 122;
}
function isUpper(code) {
  return 65 <= code && code <= 90;
}
function isNumber$2(code) {
  return 48 <= code && code <= 57;
}
function isWhitespace$1(code) {
  return code === 32 || code === 9 || code === 10 || code === 13;
}
const wordSeparators = /* @__PURE__ */ new Set();
"()[]{}<>`'\"-/;:,.?!".split("").forEach((s) => wordSeparators.add(s.charCodeAt(0)));
function isWordSeparator(code) {
  return isWhitespace$1(code) || wordSeparators.has(code);
}
function charactersMatch(codeA, codeB) {
  return codeA === codeB || isWordSeparator(codeA) && isWordSeparator(codeB);
}
function isAlphanumeric(code) {
  return isLower(code) || isUpper(code) || isNumber$2(code);
}
function join$2(head, tail3) {
  if (tail3.length === 0) {
    tail3 = [head];
  } else if (head.end === tail3[0].start) {
    tail3[0].start = head.start;
  } else {
    tail3.unshift(head);
  }
  return tail3;
}
function nextAnchor(camelCaseWord, start) {
  for (let i = start; i < camelCaseWord.length; i++) {
    const c = camelCaseWord.charCodeAt(i);
    if (isUpper(c) || isNumber$2(c) || i > 0 && !isAlphanumeric(camelCaseWord.charCodeAt(i - 1))) {
      return i;
    }
  }
  return camelCaseWord.length;
}
function _matchesCamelCase(word2, camelCaseWord, i, j) {
  if (i === word2.length) {
    return [];
  } else if (j === camelCaseWord.length) {
    return null;
  } else if (word2[i] !== camelCaseWord[j].toLowerCase()) {
    return null;
  } else {
    let result2 = null;
    let nextUpperIndex = j + 1;
    result2 = _matchesCamelCase(word2, camelCaseWord, i + 1, j + 1);
    while (!result2 && (nextUpperIndex = nextAnchor(camelCaseWord, nextUpperIndex)) < camelCaseWord.length) {
      result2 = _matchesCamelCase(word2, camelCaseWord, i + 1, nextUpperIndex);
      nextUpperIndex++;
    }
    return result2 === null ? null : join$2({ start: j, end: j + 1 }, result2);
  }
}
function analyzeCamelCaseWord(word2) {
  let upper = 0, lower = 0, alpha = 0, numeric = 0, code = 0;
  for (let i = 0; i < word2.length; i++) {
    code = word2.charCodeAt(i);
    if (isUpper(code)) {
      upper++;
    }
    if (isLower(code)) {
      lower++;
    }
    if (isAlphanumeric(code)) {
      alpha++;
    }
    if (isNumber$2(code)) {
      numeric++;
    }
  }
  const upperPercent = upper / word2.length;
  const lowerPercent = lower / word2.length;
  const alphaPercent = alpha / word2.length;
  const numericPercent = numeric / word2.length;
  return { upperPercent, lowerPercent, alphaPercent, numericPercent };
}
function isUpperCaseWord(analysis) {
  const { upperPercent, lowerPercent } = analysis;
  return lowerPercent === 0 && upperPercent > 0.6;
}
function isCamelCaseWord(analysis) {
  const { upperPercent, lowerPercent, alphaPercent, numericPercent } = analysis;
  return lowerPercent > 0.2 && upperPercent < 0.8 && alphaPercent > 0.6 && numericPercent < 0.2;
}
function isCamelCasePattern(word2) {
  let upper = 0, lower = 0, code = 0, whitespace2 = 0;
  for (let i = 0; i < word2.length; i++) {
    code = word2.charCodeAt(i);
    if (isUpper(code)) {
      upper++;
    }
    if (isLower(code)) {
      lower++;
    }
    if (isWhitespace$1(code)) {
      whitespace2++;
    }
  }
  if ((upper === 0 || lower === 0) && whitespace2 === 0) {
    return word2.length <= 30;
  } else {
    return upper <= 5;
  }
}
function matchesCamelCase(word2, camelCaseWord) {
  if (!camelCaseWord) {
    return null;
  }
  camelCaseWord = camelCaseWord.trim();
  if (camelCaseWord.length === 0) {
    return null;
  }
  if (!isCamelCasePattern(word2)) {
    return null;
  }
  if (camelCaseWord.length > 60) {
    return null;
  }
  const analysis = analyzeCamelCaseWord(camelCaseWord);
  if (!isCamelCaseWord(analysis)) {
    if (!isUpperCaseWord(analysis)) {
      return null;
    }
    camelCaseWord = camelCaseWord.toLowerCase();
  }
  let result2 = null;
  let i = 0;
  word2 = word2.toLowerCase();
  while (i < camelCaseWord.length && (result2 = _matchesCamelCase(word2, camelCaseWord, 0, i)) === null) {
    i = nextAnchor(camelCaseWord, i + 1);
  }
  return result2;
}
function matchesWords(word2, target, contiguous = false) {
  if (!target || target.length === 0) {
    return null;
  }
  let result2 = null;
  let i = 0;
  word2 = word2.toLowerCase();
  target = target.toLowerCase();
  while (i < target.length && (result2 = _matchesWords(word2, target, 0, i, contiguous)) === null) {
    i = nextWord(target, i + 1);
  }
  return result2;
}
function _matchesWords(word2, target, i, j, contiguous) {
  if (i === word2.length) {
    return [];
  } else if (j === target.length) {
    return null;
  } else if (!charactersMatch(word2.charCodeAt(i), target.charCodeAt(j))) {
    return null;
  } else {
    let result2 = null;
    let nextWordIndex = j + 1;
    result2 = _matchesWords(word2, target, i + 1, j + 1, contiguous);
    if (!contiguous) {
      while (!result2 && (nextWordIndex = nextWord(target, nextWordIndex)) < target.length) {
        result2 = _matchesWords(word2, target, i + 1, nextWordIndex, contiguous);
        nextWordIndex++;
      }
    }
    if (!result2) {
      return null;
    }
    if (word2.charCodeAt(i) !== target.charCodeAt(j)) {
      return result2;
    }
    return join$2({ start: j, end: j + 1 }, result2);
  }
}
function nextWord(word2, start) {
  for (let i = start; i < word2.length; i++) {
    if (isWordSeparator(word2.charCodeAt(i)) || i > 0 && isWordSeparator(word2.charCodeAt(i - 1))) {
      return i;
    }
  }
  return word2.length;
}
const fuzzyContiguousFilter = or(matchesPrefix, matchesCamelCase, matchesContiguousSubString);
const fuzzySeparateFilter = or(matchesPrefix, matchesCamelCase, matchesSubString);
const fuzzyRegExpCache = new LRUCache$2(1e4);
function matchesFuzzy(word2, wordToMatchAgainst, enableSeparateSubstringMatching = false) {
  if (typeof word2 !== "string" || typeof wordToMatchAgainst !== "string") {
    return null;
  }
  let regexp = fuzzyRegExpCache.get(word2);
  if (!regexp) {
    regexp = new RegExp(convertSimple2RegExpPattern(word2), "i");
    fuzzyRegExpCache.set(word2, regexp);
  }
  const match2 = regexp.exec(wordToMatchAgainst);
  if (match2) {
    return [{ start: match2.index, end: match2.index + match2[0].length }];
  }
  return enableSeparateSubstringMatching ? fuzzySeparateFilter(word2, wordToMatchAgainst) : fuzzyContiguousFilter(word2, wordToMatchAgainst);
}
function anyScore(pattern, lowPattern, patternPos, word2, lowWord, wordPos) {
  const max = Math.min(13, pattern.length);
  for (; patternPos < max; patternPos++) {
    const result2 = fuzzyScore(pattern, lowPattern, patternPos, word2, lowWord, wordPos, { firstMatchCanBeWeak: true, boostFullMatch: true });
    if (result2) {
      return result2;
    }
  }
  return [0, wordPos];
}
function createMatches(score2) {
  if (typeof score2 === "undefined") {
    return [];
  }
  const res = [];
  const wordPos = score2[1];
  for (let i = score2.length - 1; i > 1; i--) {
    const pos = score2[i] + wordPos;
    const last2 = res[res.length - 1];
    if (last2 && last2.end === pos) {
      last2.end = pos + 1;
    } else {
      res.push({ start: pos, end: pos + 1 });
    }
  }
  return res;
}
const _maxLen = 128;
function initTable() {
  const table2 = [];
  const row = [];
  for (let i = 0; i <= _maxLen; i++) {
    row[i] = 0;
  }
  for (let i = 0; i <= _maxLen; i++) {
    table2.push(row.slice(0));
  }
  return table2;
}
function initArr(maxLen) {
  const row = [];
  for (let i = 0; i <= maxLen; i++) {
    row[i] = 0;
  }
  return row;
}
const _minWordMatchPos = initArr(2 * _maxLen);
const _maxWordMatchPos = initArr(2 * _maxLen);
const _diag = initTable();
const _table = initTable();
const _arrows = initTable();
function isSeparatorAtPos(value, index) {
  if (index < 0 || index >= value.length) {
    return false;
  }
  const code = value.codePointAt(index);
  switch (code) {
    case 95:
    case 45:
    case 46:
    case 32:
    case 47:
    case 92:
    case 39:
    case 34:
    case 58:
    case 36:
    case 60:
    case 62:
    case 40:
    case 41:
    case 91:
    case 93:
    case 123:
    case 125:
      return true;
    case void 0:
      return false;
    default:
      if (isEmojiImprecise(code)) {
        return true;
      }
      return false;
  }
}
function isWhitespaceAtPos(value, index) {
  if (index < 0 || index >= value.length) {
    return false;
  }
  const code = value.charCodeAt(index);
  switch (code) {
    case 32:
    case 9:
      return true;
    default:
      return false;
  }
}
function isUpperCaseAtPos(pos, word2, wordLow) {
  return word2[pos] !== wordLow[pos];
}
function isPatternInWord(patternLow, patternPos, patternLen, wordLow, wordPos, wordLen, fillMinWordPosArr = false) {
  while (patternPos < patternLen && wordPos < wordLen) {
    if (patternLow[patternPos] === wordLow[wordPos]) {
      if (fillMinWordPosArr) {
        _minWordMatchPos[patternPos] = wordPos;
      }
      patternPos += 1;
    }
    wordPos += 1;
  }
  return patternPos === patternLen;
}
var FuzzyScore;
(function(FuzzyScore2) {
  FuzzyScore2.Default = [-100, 0];
  function isDefault(score2) {
    return !score2 || score2.length === 2 && score2[0] === -100 && score2[1] === 0;
  }
  FuzzyScore2.isDefault = isDefault;
})(FuzzyScore || (FuzzyScore = {}));
class FuzzyScoreOptions {
  constructor(firstMatchCanBeWeak, boostFullMatch) {
    this.firstMatchCanBeWeak = firstMatchCanBeWeak;
    this.boostFullMatch = boostFullMatch;
  }
}
FuzzyScoreOptions.default = { boostFullMatch: true, firstMatchCanBeWeak: false };
function fuzzyScore(pattern, patternLow, patternStart, word2, wordLow, wordStart, options = FuzzyScoreOptions.default) {
  const patternLen = pattern.length > _maxLen ? _maxLen : pattern.length;
  const wordLen = word2.length > _maxLen ? _maxLen : word2.length;
  if (patternStart >= patternLen || wordStart >= wordLen || patternLen - patternStart > wordLen - wordStart) {
    return void 0;
  }
  if (!isPatternInWord(patternLow, patternStart, patternLen, wordLow, wordStart, wordLen, true)) {
    return void 0;
  }
  _fillInMaxWordMatchPos(patternLen, wordLen, patternStart, wordStart, patternLow, wordLow);
  let row = 1;
  let column = 1;
  let patternPos = patternStart;
  let wordPos = wordStart;
  const hasStrongFirstMatch = [false];
  for (row = 1, patternPos = patternStart; patternPos < patternLen; row++, patternPos++) {
    const minWordMatchPos = _minWordMatchPos[patternPos];
    const maxWordMatchPos = _maxWordMatchPos[patternPos];
    const nextMaxWordMatchPos = patternPos + 1 < patternLen ? _maxWordMatchPos[patternPos + 1] : wordLen;
    for (column = minWordMatchPos - wordStart + 1, wordPos = minWordMatchPos; wordPos < nextMaxWordMatchPos; column++, wordPos++) {
      let score2 = Number.MIN_SAFE_INTEGER;
      let canComeDiag = false;
      if (wordPos <= maxWordMatchPos) {
        score2 = _doScore(pattern, patternLow, patternPos, patternStart, word2, wordLow, wordPos, wordLen, wordStart, _diag[row - 1][column - 1] === 0, hasStrongFirstMatch);
      }
      let diagScore = 0;
      if (score2 !== Number.MAX_SAFE_INTEGER) {
        canComeDiag = true;
        diagScore = score2 + _table[row - 1][column - 1];
      }
      const canComeLeft = wordPos > minWordMatchPos;
      const leftScore = canComeLeft ? _table[row][column - 1] + (_diag[row][column - 1] > 0 ? -5 : 0) : 0;
      const canComeLeftLeft = wordPos > minWordMatchPos + 1 && _diag[row][column - 1] > 0;
      const leftLeftScore = canComeLeftLeft ? _table[row][column - 2] + (_diag[row][column - 2] > 0 ? -5 : 0) : 0;
      if (canComeLeftLeft && (!canComeLeft || leftLeftScore >= leftScore) && (!canComeDiag || leftLeftScore >= diagScore)) {
        _table[row][column] = leftLeftScore;
        _arrows[row][column] = 3;
        _diag[row][column] = 0;
      } else if (canComeLeft && (!canComeDiag || leftScore >= diagScore)) {
        _table[row][column] = leftScore;
        _arrows[row][column] = 2;
        _diag[row][column] = 0;
      } else if (canComeDiag) {
        _table[row][column] = diagScore;
        _arrows[row][column] = 1;
        _diag[row][column] = _diag[row - 1][column - 1] + 1;
      } else {
        throw new Error(`not possible`);
      }
    }
  }
  if (!hasStrongFirstMatch[0] && !options.firstMatchCanBeWeak) {
    return void 0;
  }
  row--;
  column--;
  const result2 = [_table[row][column], wordStart];
  let backwardsDiagLength = 0;
  let maxMatchColumn = 0;
  while (row >= 1) {
    let diagColumn = column;
    do {
      const arrow = _arrows[row][diagColumn];
      if (arrow === 3) {
        diagColumn = diagColumn - 2;
      } else if (arrow === 2) {
        diagColumn = diagColumn - 1;
      } else {
        break;
      }
    } while (diagColumn >= 1);
    if (backwardsDiagLength > 1 && patternLow[patternStart + row - 1] === wordLow[wordStart + column - 1] && !isUpperCaseAtPos(diagColumn + wordStart - 1, word2, wordLow) && backwardsDiagLength + 1 > _diag[row][diagColumn]) {
      diagColumn = column;
    }
    if (diagColumn === column) {
      backwardsDiagLength++;
    } else {
      backwardsDiagLength = 1;
    }
    if (!maxMatchColumn) {
      maxMatchColumn = diagColumn;
    }
    row--;
    column = diagColumn - 1;
    result2.push(column);
  }
  if (wordLen === patternLen && options.boostFullMatch) {
    result2[0] += 2;
  }
  const skippedCharsCount = maxMatchColumn - patternLen;
  result2[0] -= skippedCharsCount;
  return result2;
}
function _fillInMaxWordMatchPos(patternLen, wordLen, patternStart, wordStart, patternLow, wordLow) {
  let patternPos = patternLen - 1;
  let wordPos = wordLen - 1;
  while (patternPos >= patternStart && wordPos >= wordStart) {
    if (patternLow[patternPos] === wordLow[wordPos]) {
      _maxWordMatchPos[patternPos] = wordPos;
      patternPos--;
    }
    wordPos--;
  }
}
function _doScore(pattern, patternLow, patternPos, patternStart, word2, wordLow, wordPos, wordLen, wordStart, newMatchStart, outFirstMatchStrong) {
  if (patternLow[patternPos] !== wordLow[wordPos]) {
    return Number.MIN_SAFE_INTEGER;
  }
  let score2 = 1;
  let isGapLocation = false;
  if (wordPos === patternPos - patternStart) {
    score2 = pattern[patternPos] === word2[wordPos] ? 7 : 5;
  } else if (isUpperCaseAtPos(wordPos, word2, wordLow) && (wordPos === 0 || !isUpperCaseAtPos(wordPos - 1, word2, wordLow))) {
    score2 = pattern[patternPos] === word2[wordPos] ? 7 : 5;
    isGapLocation = true;
  } else if (isSeparatorAtPos(wordLow, wordPos) && (wordPos === 0 || !isSeparatorAtPos(wordLow, wordPos - 1))) {
    score2 = 5;
  } else if (isSeparatorAtPos(wordLow, wordPos - 1) || isWhitespaceAtPos(wordLow, wordPos - 1)) {
    score2 = 5;
    isGapLocation = true;
  }
  if (score2 > 1 && patternPos === patternStart) {
    outFirstMatchStrong[0] = true;
  }
  if (!isGapLocation) {
    isGapLocation = isUpperCaseAtPos(wordPos, word2, wordLow) || isSeparatorAtPos(wordLow, wordPos - 1) || isWhitespaceAtPos(wordLow, wordPos - 1);
  }
  if (patternPos === patternStart) {
    if (wordPos > wordStart) {
      score2 -= isGapLocation ? 3 : 5;
    }
  } else {
    if (newMatchStart) {
      score2 += isGapLocation ? 2 : 0;
    } else {
      score2 += isGapLocation ? 0 : 1;
    }
  }
  if (wordPos + 1 === wordLen) {
    score2 -= isGapLocation ? 3 : 5;
  }
  return score2;
}
function fuzzyScoreGracefulAggressive(pattern, lowPattern, patternPos, word2, lowWord, wordPos, options) {
  return fuzzyScoreWithPermutations(pattern, lowPattern, patternPos, word2, lowWord, wordPos, true, options);
}
function fuzzyScoreWithPermutations(pattern, lowPattern, patternPos, word2, lowWord, wordPos, aggressive, options) {
  let top = fuzzyScore(pattern, lowPattern, patternPos, word2, lowWord, wordPos, options);
  if (top && !aggressive) {
    return top;
  }
  if (pattern.length >= 3) {
    const tries = Math.min(7, pattern.length - 1);
    for (let movingPatternPos = patternPos + 1; movingPatternPos < tries; movingPatternPos++) {
      const newPattern = nextTypoPermutation(pattern, movingPatternPos);
      if (newPattern) {
        const candidate = fuzzyScore(newPattern, newPattern.toLowerCase(), patternPos, word2, lowWord, wordPos, options);
        if (candidate) {
          candidate[0] -= 3;
          if (!top || candidate[0] > top[0]) {
            top = candidate;
          }
        }
      }
    }
  }
  return top;
}
function nextTypoPermutation(pattern, patternPos) {
  if (patternPos + 1 >= pattern.length) {
    return void 0;
  }
  const swap1 = pattern[patternPos];
  const swap2 = pattern[patternPos + 1];
  if (swap1 === swap2) {
    return void 0;
  }
  return pattern.slice(0, patternPos) + swap2 + swap1 + pattern.slice(patternPos + 2);
}
const iconStartMarker = "$(";
const iconsRegex = new RegExp(`\\$\\(${ThemeIcon.iconNameExpression}(?:${ThemeIcon.iconModifierExpression})?\\)`, "g");
const escapeIconsRegex = new RegExp(`(\\\\)?${iconsRegex.source}`, "g");
function escapeIcons(text2) {
  return text2.replace(escapeIconsRegex, (match2, escaped) => escaped ? match2 : `\\${match2}`);
}
const markdownEscapedIconsRegex = new RegExp(`\\\\${iconsRegex.source}`, "g");
function markdownEscapeEscapedIcons(text2) {
  return text2.replace(markdownEscapedIconsRegex, (match2) => `\\${match2}`);
}
const stripIconsRegex = new RegExp(`(\\s)?(\\\\)?${iconsRegex.source}(\\s)?`, "g");
function stripIcons(text2) {
  if (text2.indexOf(iconStartMarker) === -1) {
    return text2;
  }
  return text2.replace(stripIconsRegex, (match2, preWhitespace, escaped, postWhitespace) => escaped ? match2 : preWhitespace || postWhitespace || "");
}
function getCodiconAriaLabel(text2) {
  if (!text2) {
    return "";
  }
  return text2.replace(/\$\((.*?)\)/g, (_match, codiconName) => ` ${codiconName} `).trim();
}
const _parseIconsRegex = new RegExp(`\\$\\(${ThemeIcon.iconNameCharacter}+\\)`, "g");
function parseLabelWithIcons(input2) {
  _parseIconsRegex.lastIndex = 0;
  let text2 = "";
  const iconOffsets = [];
  let iconsOffset = 0;
  while (true) {
    const pos = _parseIconsRegex.lastIndex;
    const match2 = _parseIconsRegex.exec(input2);
    const chars2 = input2.substring(pos, match2 === null || match2 === void 0 ? void 0 : match2.index);
    if (chars2.length > 0) {
      text2 += chars2;
      for (let i = 0; i < chars2.length; i++) {
        iconOffsets.push(iconsOffset);
      }
    }
    if (!match2) {
      break;
    }
    iconsOffset += match2[0].length;
  }
  return { text: text2, iconOffsets };
}
function matchesFuzzyIconAware(query, target, enableSeparateSubstringMatching = false) {
  const { text: text2, iconOffsets } = target;
  if (!iconOffsets || iconOffsets.length === 0) {
    return matchesFuzzy(query, text2, enableSeparateSubstringMatching);
  }
  const wordToMatchAgainstWithoutIconsTrimmed = ltrim(text2, " ");
  const leadingWhitespaceOffset = text2.length - wordToMatchAgainstWithoutIconsTrimmed.length;
  const matches = matchesFuzzy(query, wordToMatchAgainstWithoutIconsTrimmed, enableSeparateSubstringMatching);
  if (matches) {
    for (const match2 of matches) {
      const iconOffset = iconOffsets[match2.start + leadingWhitespaceOffset] + leadingWhitespaceOffset;
      match2.start += iconOffset;
      match2.end += iconOffset;
    }
  }
  return matches;
}
class MarkdownString {
  constructor(value = "", isTrustedOrOptions = false) {
    var _a2, _b2, _c2;
    this.value = value;
    if (typeof this.value !== "string") {
      throw illegalArgument("value");
    }
    if (typeof isTrustedOrOptions === "boolean") {
      this.isTrusted = isTrustedOrOptions;
      this.supportThemeIcons = false;
      this.supportHtml = false;
    } else {
      this.isTrusted = (_a2 = isTrustedOrOptions.isTrusted) !== null && _a2 !== void 0 ? _a2 : void 0;
      this.supportThemeIcons = (_b2 = isTrustedOrOptions.supportThemeIcons) !== null && _b2 !== void 0 ? _b2 : false;
      this.supportHtml = (_c2 = isTrustedOrOptions.supportHtml) !== null && _c2 !== void 0 ? _c2 : false;
    }
  }
  appendText(value, newlineStyle = 0) {
    this.value += escapeMarkdownSyntaxTokens(this.supportThemeIcons ? escapeIcons(value) : value).replace(/([ \t]+)/g, (_match, g1) => "&nbsp;".repeat(g1.length)).replace(/\>/gm, "\\>").replace(/\n/g, newlineStyle === 1 ? "\\\n" : "\n\n");
    return this;
  }
  appendMarkdown(value) {
    this.value += value;
    return this;
  }
  appendCodeblock(langId, code) {
    this.value += "\n```";
    this.value += langId;
    this.value += "\n";
    this.value += code;
    this.value += "\n```\n";
    return this;
  }
  appendLink(target, label, title2) {
    this.value += "[";
    this.value += this._escape(label, "]");
    this.value += "](";
    this.value += this._escape(String(target), ")");
    if (title2) {
      this.value += ` "${this._escape(this._escape(title2, '"'), ")")}"`;
    }
    this.value += ")";
    return this;
  }
  _escape(value, ch) {
    const r = new RegExp(escapeRegExpCharacters(ch), "g");
    return value.replace(r, (match2, offset) => {
      if (value.charAt(offset - 1) !== "\\") {
        return `\\${match2}`;
      } else {
        return match2;
      }
    });
  }
}
function isEmptyMarkdownString(oneOrMany) {
  if (isMarkdownString(oneOrMany)) {
    return !oneOrMany.value;
  } else if (Array.isArray(oneOrMany)) {
    return oneOrMany.every(isEmptyMarkdownString);
  } else {
    return true;
  }
}
function isMarkdownString(thing) {
  if (thing instanceof MarkdownString) {
    return true;
  } else if (thing && typeof thing === "object") {
    return typeof thing.value === "string" && (typeof thing.isTrusted === "boolean" || typeof thing.isTrusted === "object" || thing.isTrusted === void 0) && (typeof thing.supportThemeIcons === "boolean" || thing.supportThemeIcons === void 0);
  }
  return false;
}
function markdownStringEqual(a, b) {
  if (a === b) {
    return true;
  } else if (!a || !b) {
    return false;
  } else {
    return a.value === b.value && a.isTrusted === b.isTrusted && a.supportThemeIcons === b.supportThemeIcons && a.supportHtml === b.supportHtml && (a.baseUri === b.baseUri || !!a.baseUri && !!b.baseUri && isEqual(URI.from(a.baseUri), URI.from(b.baseUri)));
  }
}
function escapeMarkdownSyntaxTokens(text2) {
  return text2.replace(/[\\`*_{}[\]()#+\-!~]/g, "\\$&");
}
function escapeDoubleQuotes(input2) {
  return input2.replace(/"/g, "&quot;");
}
function removeMarkdownEscapes(text2) {
  if (!text2) {
    return text2;
  }
  return text2.replace(/\\([\\`*_{}[\]()#+\-.!~])/g, "$1");
}
function parseHrefAndDimensions(href) {
  const dimensions = [];
  const splitted = href.split("|").map((s) => s.trim());
  href = splitted[0];
  const parameters = splitted[1];
  if (parameters) {
    const heightFromParams = /height=(\d+)/.exec(parameters);
    const widthFromParams = /width=(\d+)/.exec(parameters);
    const height = heightFromParams ? heightFromParams[1] : "";
    const width = widthFromParams ? widthFromParams[1] : "";
    const widthIsFinite = isFinite(parseInt(width));
    const heightIsFinite = isFinite(parseInt(height));
    if (widthIsFinite) {
      dimensions.push(`width="${width}"`);
    }
    if (heightIsFinite) {
      dimensions.push(`height="${height}"`);
    }
  }
  return { href, dimensions };
}
const diffEditor = "";
class StableEditorScrollState {
  static capture(editor2) {
    if (editor2.getScrollTop() === 0 || editor2.hasPendingScrollAnimation()) {
      return new StableEditorScrollState(editor2.getScrollTop(), editor2.getContentHeight(), null, 0, null);
    }
    let visiblePosition = null;
    let visiblePositionScrollDelta = 0;
    const visibleRanges = editor2.getVisibleRanges();
    if (visibleRanges.length > 0) {
      visiblePosition = visibleRanges[0].getStartPosition();
      const visiblePositionScrollTop = editor2.getTopForPosition(visiblePosition.lineNumber, visiblePosition.column);
      visiblePositionScrollDelta = editor2.getScrollTop() - visiblePositionScrollTop;
    }
    return new StableEditorScrollState(editor2.getScrollTop(), editor2.getContentHeight(), visiblePosition, visiblePositionScrollDelta, editor2.getPosition());
  }
  constructor(_initialScrollTop, _initialContentHeight, _visiblePosition, _visiblePositionScrollDelta, _cursorPosition) {
    this._initialScrollTop = _initialScrollTop;
    this._initialContentHeight = _initialContentHeight;
    this._visiblePosition = _visiblePosition;
    this._visiblePositionScrollDelta = _visiblePositionScrollDelta;
    this._cursorPosition = _cursorPosition;
  }
  restore(editor2) {
    if (this._initialContentHeight === editor2.getContentHeight() && this._initialScrollTop === editor2.getScrollTop()) {
      return;
    }
    if (this._visiblePosition) {
      const visiblePositionScrollTop = editor2.getTopForPosition(this._visiblePosition.lineNumber, this._visiblePosition.column);
      editor2.setScrollTop(visiblePositionScrollTop + this._visiblePositionScrollDelta);
    }
  }
  restoreRelativeVerticalPositionOfCursor(editor2) {
    if (this._initialContentHeight === editor2.getContentHeight() && this._initialScrollTop === editor2.getScrollTop()) {
      return;
    }
    const currentCursorPosition = editor2.getPosition();
    if (!this._cursorPosition || !currentCursorPosition) {
      return;
    }
    const offset = editor2.getTopForLineNumber(currentCursorPosition.lineNumber) - editor2.getTopForLineNumber(this._cursorPosition.lineNumber);
    editor2.setScrollTop(editor2.getScrollTop() + offset);
  }
}
const IAudioCueService = createDecorator("audioCue");
class Sound {
  static register(options) {
    const sound = new Sound(options.fileName);
    return sound;
  }
  constructor(fileName) {
    this.fileName = fileName;
  }
}
Sound.error = Sound.register({ fileName: "error.mp3" });
Sound.warning = Sound.register({ fileName: "warning.mp3" });
Sound.foldedArea = Sound.register({ fileName: "foldedAreas.mp3" });
Sound.break = Sound.register({ fileName: "break.mp3" });
Sound.quickFixes = Sound.register({ fileName: "quickFixes.mp3" });
Sound.taskCompleted = Sound.register({ fileName: "taskCompleted.mp3" });
Sound.taskFailed = Sound.register({ fileName: "taskFailed.mp3" });
Sound.terminalBell = Sound.register({ fileName: "terminalBell.mp3" });
Sound.diffLineInserted = Sound.register({ fileName: "diffLineInserted.mp3" });
Sound.diffLineDeleted = Sound.register({ fileName: "diffLineDeleted.mp3" });
Sound.diffLineModified = Sound.register({ fileName: "diffLineModified.mp3" });
Sound.chatRequestSent = Sound.register({ fileName: "chatRequestSent.mp3" });
Sound.chatResponsePending = Sound.register({ fileName: "chatResponsePending.mp3" });
Sound.chatResponseReceived1 = Sound.register({ fileName: "chatResponseReceived1.mp3" });
Sound.chatResponseReceived2 = Sound.register({ fileName: "chatResponseReceived2.mp3" });
Sound.chatResponseReceived3 = Sound.register({ fileName: "chatResponseReceived3.mp3" });
Sound.chatResponseReceived4 = Sound.register({ fileName: "chatResponseReceived4.mp3" });
class SoundSource {
  constructor(randomOneOf) {
    this.randomOneOf = randomOneOf;
  }
}
class AudioCue {
  static register(options) {
    const soundSource = new SoundSource("randomOneOf" in options.sound ? options.sound.randomOneOf : [options.sound]);
    const audioCue = new AudioCue(soundSource, options.name, options.settingsKey);
    AudioCue._audioCues.add(audioCue);
    return audioCue;
  }
  constructor(sound, name, settingsKey) {
    this.sound = sound;
    this.name = name;
    this.settingsKey = settingsKey;
  }
}
AudioCue._audioCues = /* @__PURE__ */ new Set();
AudioCue.error = AudioCue.register({
  name: localize("audioCues.lineHasError.name", "Error on Line"),
  sound: Sound.error,
  settingsKey: "audioCues.lineHasError"
});
AudioCue.warning = AudioCue.register({
  name: localize("audioCues.lineHasWarning.name", "Warning on Line"),
  sound: Sound.warning,
  settingsKey: "audioCues.lineHasWarning"
});
AudioCue.foldedArea = AudioCue.register({
  name: localize("audioCues.lineHasFoldedArea.name", "Folded Area on Line"),
  sound: Sound.foldedArea,
  settingsKey: "audioCues.lineHasFoldedArea"
});
AudioCue.break = AudioCue.register({
  name: localize("audioCues.lineHasBreakpoint.name", "Breakpoint on Line"),
  sound: Sound.break,
  settingsKey: "audioCues.lineHasBreakpoint"
});
AudioCue.inlineSuggestion = AudioCue.register({
  name: localize("audioCues.lineHasInlineSuggestion.name", "Inline Suggestion on Line"),
  sound: Sound.quickFixes,
  settingsKey: "audioCues.lineHasInlineSuggestion"
});
AudioCue.terminalQuickFix = AudioCue.register({
  name: localize("audioCues.terminalQuickFix.name", "Terminal Quick Fix"),
  sound: Sound.quickFixes,
  settingsKey: "audioCues.terminalQuickFix"
});
AudioCue.onDebugBreak = AudioCue.register({
  name: localize("audioCues.onDebugBreak.name", "Debugger Stopped on Breakpoint"),
  sound: Sound.break,
  settingsKey: "audioCues.onDebugBreak"
});
AudioCue.noInlayHints = AudioCue.register({
  name: localize("audioCues.noInlayHints", "No Inlay Hints on Line"),
  sound: Sound.error,
  settingsKey: "audioCues.noInlayHints"
});
AudioCue.taskCompleted = AudioCue.register({
  name: localize("audioCues.taskCompleted", "Task Completed"),
  sound: Sound.taskCompleted,
  settingsKey: "audioCues.taskCompleted"
});
AudioCue.taskFailed = AudioCue.register({
  name: localize("audioCues.taskFailed", "Task Failed"),
  sound: Sound.taskFailed,
  settingsKey: "audioCues.taskFailed"
});
AudioCue.terminalCommandFailed = AudioCue.register({
  name: localize("audioCues.terminalCommandFailed", "Terminal Command Failed"),
  sound: Sound.error,
  settingsKey: "audioCues.terminalCommandFailed"
});
AudioCue.terminalBell = AudioCue.register({
  name: localize("audioCues.terminalBell", "Terminal Bell"),
  sound: Sound.terminalBell,
  settingsKey: "audioCues.terminalBell"
});
AudioCue.notebookCellCompleted = AudioCue.register({
  name: localize("audioCues.notebookCellCompleted", "Notebook Cell Completed"),
  sound: Sound.taskCompleted,
  settingsKey: "audioCues.notebookCellCompleted"
});
AudioCue.notebookCellFailed = AudioCue.register({
  name: localize("audioCues.notebookCellFailed", "Notebook Cell Failed"),
  sound: Sound.taskFailed,
  settingsKey: "audioCues.notebookCellFailed"
});
AudioCue.diffLineInserted = AudioCue.register({
  name: localize("audioCues.diffLineInserted", "Diff Line Inserted"),
  sound: Sound.diffLineInserted,
  settingsKey: "audioCues.diffLineInserted"
});
AudioCue.diffLineDeleted = AudioCue.register({
  name: localize("audioCues.diffLineDeleted", "Diff Line Deleted"),
  sound: Sound.diffLineDeleted,
  settingsKey: "audioCues.diffLineDeleted"
});
AudioCue.diffLineModified = AudioCue.register({
  name: localize("audioCues.diffLineModified", "Diff Line Modified"),
  sound: Sound.diffLineModified,
  settingsKey: "audioCues.diffLineModified"
});
AudioCue.chatRequestSent = AudioCue.register({
  name: localize("audioCues.chatRequestSent", "Chat Request Sent"),
  sound: Sound.chatRequestSent,
  settingsKey: "audioCues.chatRequestSent"
});
AudioCue.chatResponseReceived = AudioCue.register({
  name: localize("audioCues.chatResponseReceived", "Chat Response Received"),
  settingsKey: "audioCues.chatResponseReceived",
  sound: {
    randomOneOf: [
      Sound.chatResponseReceived1,
      Sound.chatResponseReceived2,
      Sound.chatResponseReceived3,
      Sound.chatResponseReceived4
    ]
  }
});
AudioCue.chatResponsePending = AudioCue.register({
  name: localize("audioCues.chatResponsePending", "Chat Response Pending"),
  sound: Sound.chatResponsePending,
  settingsKey: "audioCues.chatResponsePending"
});
var __decorate$20 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1X = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
const defaultOptions$3 = {
  followsCaret: true,
  ignoreCharChanges: true,
  alwaysRevealFirst: true,
  findResultLoop: true
};
let DiffNavigator = class DiffNavigator2 extends Disposable {
  constructor(editor2, options = {}, _audioCueService, _codeEditorService, _accessibilityService) {
    super();
    this._audioCueService = _audioCueService;
    this._codeEditorService = _codeEditorService;
    this._accessibilityService = _accessibilityService;
    this._onDidUpdate = this._register(new Emitter$1());
    this._editor = editor2;
    this._options = mixin(options, defaultOptions$3, false);
    this.disposed = false;
    this.nextIdx = -1;
    this.ranges = [];
    this.ignoreSelectionChange = false;
    this.revealFirst = Boolean(this._options.alwaysRevealFirst);
    this._register(this._editor.onDidUpdateDiff(() => this._onDiffUpdated()));
    if (this._options.followsCaret) {
      this._register(this._editor.getModifiedEditor().onDidChangeCursorPosition((e) => {
        if (this.ignoreSelectionChange) {
          return;
        }
        this._updateAccessibilityState(e.position.lineNumber);
        this.nextIdx = -1;
      }));
    }
    this._init();
  }
  _init() {
    const changes = this._editor.getLineChanges();
    if (!changes) {
      return;
    }
  }
  _onDiffUpdated() {
    this._init();
    this._compute(this._editor.getLineChanges());
    if (this.revealFirst) {
      if (this._editor.getLineChanges() !== null) {
        this.revealFirst = false;
        this.nextIdx = -1;
        this.next(
          1
          /* ScrollType.Immediate */
        );
      }
    }
  }
  _compute(lineChanges) {
    this.ranges = [];
    if (lineChanges) {
      lineChanges.forEach((lineChange) => {
        if (!this._options.ignoreCharChanges && lineChange.charChanges) {
          lineChange.charChanges.forEach((charChange) => {
            this.ranges.push({
              rhs: true,
              range: new Range$2(charChange.modifiedStartLineNumber, charChange.modifiedStartColumn, charChange.modifiedEndLineNumber, charChange.modifiedEndColumn)
            });
          });
        } else {
          if (lineChange.modifiedEndLineNumber === 0) {
            this.ranges.push({
              rhs: true,
              range: new Range$2(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedStartLineNumber + 1, 1)
            });
          } else {
            this.ranges.push({
              rhs: true,
              range: new Range$2(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedEndLineNumber + 1, 1)
            });
          }
        }
      });
    }
    this.ranges.sort((left, right) => Range$2.compareRangesUsingStarts(left.range, right.range));
    this._onDidUpdate.fire(this);
  }
  _initIdx(fwd) {
    let found = false;
    const position = this._editor.getPosition();
    if (!position) {
      this.nextIdx = 0;
      return;
    }
    for (let i = 0, len = this.ranges.length; i < len && !found; i++) {
      const range2 = this.ranges[i].range;
      if (position.isBeforeOrEqual(range2.getStartPosition())) {
        this.nextIdx = i + (fwd ? 0 : -1);
        found = true;
      }
    }
    if (!found) {
      this.nextIdx = fwd ? 0 : this.ranges.length - 1;
    }
    if (this.nextIdx < 0) {
      this.nextIdx = this.ranges.length - 1;
    }
  }
  _move(fwd, scrollType) {
    ok(!this.disposed, "Illegal State - diff navigator has been disposed");
    if (!this.canNavigate()) {
      return;
    }
    if (this.nextIdx === -1) {
      this._initIdx(fwd);
    } else if (fwd) {
      this.nextIdx += 1;
      if (this.nextIdx >= this.ranges.length) {
        this.nextIdx = 0;
      }
    } else {
      this.nextIdx -= 1;
      if (this.nextIdx < 0) {
        this.nextIdx = this.ranges.length - 1;
      }
    }
    const info = this.ranges[this.nextIdx];
    this.ignoreSelectionChange = true;
    try {
      const pos = info.range.getStartPosition();
      this._editor.setPosition(pos);
      this._editor.revealRangeInCenter(info.range, scrollType);
      this._updateAccessibilityState(pos.lineNumber, true);
    } finally {
      this.ignoreSelectionChange = false;
    }
  }
  _updateAccessibilityState(lineNumber, jumpToChange) {
    var _a2;
    const modifiedEditor = (_a2 = this._editor.getModel()) === null || _a2 === void 0 ? void 0 : _a2.modified;
    if (!modifiedEditor) {
      return;
    }
    const insertedOrModified = modifiedEditor.getLineDecorations(lineNumber).find((l) => l.options.className === "line-insert");
    if (insertedOrModified) {
      this._audioCueService.playAudioCue(AudioCue.diffLineModified, true);
    } else if (jumpToChange) {
      this._audioCueService.playAudioCue(AudioCue.diffLineDeleted, true);
    } else {
      return;
    }
    const codeEditor = this._codeEditorService.getActiveCodeEditor();
    if (jumpToChange && codeEditor && insertedOrModified && this._accessibilityService.isScreenReaderOptimized()) {
      codeEditor.setSelection({ startLineNumber: lineNumber, startColumn: 0, endLineNumber: lineNumber, endColumn: Number.MAX_VALUE });
      codeEditor.writeScreenReaderContent("diff-navigation");
    }
  }
  canNavigate() {
    return this.ranges && this.ranges.length > 0;
  }
  next(scrollType = 0) {
    if (!this.canNavigateNext()) {
      return;
    }
    this._move(true, scrollType);
  }
  previous(scrollType = 0) {
    if (!this.canNavigatePrevious()) {
      return;
    }
    this._move(false, scrollType);
  }
  canNavigateNext() {
    return this.canNavigateLoop() || this.nextIdx < this.ranges.length - 1;
  }
  canNavigatePrevious() {
    return this.canNavigateLoop() || this.nextIdx !== 0;
  }
  canNavigateLoop() {
    return Boolean(this._options.findResultLoop);
  }
  dispose() {
    super.dispose();
    this.ranges = [];
    this.disposed = true;
  }
};
DiffNavigator = __decorate$20([
  __param$1X(2, IAudioCueService),
  __param$1X(3, ICodeEditorService),
  __param$1X(4, IAccessibilityService)
], DiffNavigator);
const DataTransfers = {
  /**
   * Application specific resource transfer type
   */
  RESOURCES: "ResourceURLs",
  /**
   * Browser specific transfer type to download
   */
  DOWNLOAD_URL: "DownloadURL",
  /**
   * Browser specific transfer type for files
   */
  FILES: "Files",
  /**
   * Typically transfer type for copy/paste transfers.
   */
  TEXT: Mimes.text,
  /**
   * Internal type used to pass around text/uri-list data.
   *
   * This is needed to work around https://bugs.chromium.org/p/chromium/issues/detail?id=239745.
   */
  INTERNAL_URI_LIST: "application/vnd.code.uri-list"
};
var __awaiter$1v = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
function setupNativeHover(htmlElement, tooltip) {
  if (isString$4(tooltip)) {
    htmlElement.title = stripIcons(tooltip);
  } else if (tooltip === null || tooltip === void 0 ? void 0 : tooltip.markdownNotSupportedFallback) {
    htmlElement.title = tooltip.markdownNotSupportedFallback;
  } else {
    htmlElement.removeAttribute("title");
  }
}
class UpdatableHoverWidget {
  constructor(hoverDelegate, target, fadeInAnimation) {
    this.hoverDelegate = hoverDelegate;
    this.target = target;
    this.fadeInAnimation = fadeInAnimation;
  }
  update(content, focus, options) {
    var _a2;
    return __awaiter$1v(this, void 0, void 0, function* () {
      if (this._cancellationTokenSource) {
        this._cancellationTokenSource.dispose(true);
        this._cancellationTokenSource = void 0;
      }
      if (this.isDisposed) {
        return;
      }
      let resolvedContent;
      if (content === void 0 || isString$4(content) || content instanceof HTMLElement) {
        resolvedContent = content;
      } else if (!isFunction$2(content.markdown)) {
        resolvedContent = (_a2 = content.markdown) !== null && _a2 !== void 0 ? _a2 : content.markdownNotSupportedFallback;
      } else {
        if (!this._hoverWidget) {
          this.show(localize("iconLabel.loading", "Loading..."), focus);
        }
        this._cancellationTokenSource = new CancellationTokenSource$1();
        const token = this._cancellationTokenSource.token;
        resolvedContent = yield content.markdown(token);
        if (resolvedContent === void 0) {
          resolvedContent = content.markdownNotSupportedFallback;
        }
        if (this.isDisposed || token.isCancellationRequested) {
          return;
        }
      }
      this.show(resolvedContent, focus, options);
    });
  }
  show(content, focus, options) {
    const oldHoverWidget = this._hoverWidget;
    if (this.hasContent(content)) {
      const hoverOptions = Object.assign({ content, target: this.target, showPointer: this.hoverDelegate.placement === "element", hoverPosition: 2, skipFadeInAnimation: !this.fadeInAnimation || !!oldHoverWidget }, options);
      this._hoverWidget = this.hoverDelegate.showHover(hoverOptions, focus);
    }
    oldHoverWidget === null || oldHoverWidget === void 0 ? void 0 : oldHoverWidget.dispose();
  }
  hasContent(content) {
    if (!content) {
      return false;
    }
    if (isMarkdownString(content)) {
      return !!content.value;
    }
    return true;
  }
  get isDisposed() {
    var _a2;
    return (_a2 = this._hoverWidget) === null || _a2 === void 0 ? void 0 : _a2.isDisposed;
  }
  dispose() {
    var _a2, _b2;
    (_a2 = this._hoverWidget) === null || _a2 === void 0 ? void 0 : _a2.dispose();
    (_b2 = this._cancellationTokenSource) === null || _b2 === void 0 ? void 0 : _b2.dispose(true);
    this._cancellationTokenSource = void 0;
  }
}
function setupCustomHover(hoverDelegate, htmlElement, content, options) {
  let hoverPreparation;
  let hoverWidget;
  const hideHover = (disposeWidget, disposePreparation) => {
    var _a2;
    const hadHover = hoverWidget !== void 0;
    if (disposeWidget) {
      hoverWidget === null || hoverWidget === void 0 ? void 0 : hoverWidget.dispose();
      hoverWidget = void 0;
    }
    if (disposePreparation) {
      hoverPreparation === null || hoverPreparation === void 0 ? void 0 : hoverPreparation.dispose();
      hoverPreparation = void 0;
    }
    if (hadHover) {
      (_a2 = hoverDelegate.onDidHideHover) === null || _a2 === void 0 ? void 0 : _a2.call(hoverDelegate);
    }
  };
  const triggerShowHover = (delay, focus, target) => {
    return new TimeoutTimer(() => __awaiter$1v(this, void 0, void 0, function* () {
      if (!hoverWidget || hoverWidget.isDisposed) {
        hoverWidget = new UpdatableHoverWidget(hoverDelegate, target || htmlElement, delay > 0);
        yield hoverWidget.update(content, focus, options);
      }
    }), delay);
  };
  const onMouseOver = () => {
    if (hoverPreparation) {
      return;
    }
    const toDispose = new DisposableStore();
    const onMouseLeave = (e) => hideHover(false, e.fromElement === htmlElement);
    toDispose.add(addDisposableListener(htmlElement, EventType$1.MOUSE_LEAVE, onMouseLeave, true));
    const onMouseDown = () => hideHover(true, true);
    toDispose.add(addDisposableListener(htmlElement, EventType$1.MOUSE_DOWN, onMouseDown, true));
    const target = {
      targetElements: [htmlElement],
      dispose: () => {
      }
    };
    if (hoverDelegate.placement === void 0 || hoverDelegate.placement === "mouse") {
      const onMouseMove = (e) => {
        target.x = e.x + 10;
        if (e.target instanceof HTMLElement && e.target.classList.contains("action-label")) {
          hideHover(true, true);
        }
      };
      toDispose.add(addDisposableListener(htmlElement, EventType$1.MOUSE_MOVE, onMouseMove, true));
    }
    toDispose.add(triggerShowHover(hoverDelegate.delay, false, target));
    hoverPreparation = toDispose;
  };
  const mouseOverDomEmitter = addDisposableListener(htmlElement, EventType$1.MOUSE_OVER, onMouseOver, true);
  const hover2 = {
    show: (focus) => {
      hideHover(false, true);
      triggerShowHover(0, focus);
    },
    hide: () => {
      hideHover(true, true);
    },
    update: (newContent, hoverOptions) => __awaiter$1v(this, void 0, void 0, function* () {
      content = newContent;
      yield hoverWidget === null || hoverWidget === void 0 ? void 0 : hoverWidget.update(content, void 0, hoverOptions);
    }),
    dispose: () => {
      mouseOverDomEmitter.dispose();
      hideHover(true, true);
    }
  };
  return hover2;
}
function renderText(text2, options = {}) {
  const element = createElement(options);
  element.textContent = text2;
  return element;
}
function renderFormattedText(formattedText, options = {}) {
  const element = createElement(options);
  _renderFormattedText(element, parseFormattedText(formattedText, !!options.renderCodeSegments), options.actionHandler, options.renderCodeSegments);
  return element;
}
function createElement(options) {
  const tagName = options.inline ? "span" : "div";
  const element = document.createElement(tagName);
  if (options.className) {
    element.className = options.className;
  }
  return element;
}
class StringStream {
  constructor(source) {
    this.source = source;
    this.index = 0;
  }
  eos() {
    return this.index >= this.source.length;
  }
  next() {
    const next = this.peek();
    this.advance();
    return next;
  }
  peek() {
    return this.source[this.index];
  }
  advance() {
    this.index++;
  }
}
function _renderFormattedText(element, treeNode, actionHandler, renderCodeSegments) {
  let child;
  if (treeNode.type === 2) {
    child = document.createTextNode(treeNode.content || "");
  } else if (treeNode.type === 3) {
    child = document.createElement("b");
  } else if (treeNode.type === 4) {
    child = document.createElement("i");
  } else if (treeNode.type === 7 && renderCodeSegments) {
    child = document.createElement("code");
  } else if (treeNode.type === 5 && actionHandler) {
    const a = document.createElement("a");
    actionHandler.disposables.add(addStandardDisposableListener(a, "click", (event) => {
      actionHandler.callback(String(treeNode.index), event);
    }));
    child = a;
  } else if (treeNode.type === 8) {
    child = document.createElement("br");
  } else if (treeNode.type === 1) {
    child = element;
  }
  if (child && element !== child) {
    element.appendChild(child);
  }
  if (child && Array.isArray(treeNode.children)) {
    treeNode.children.forEach((nodeChild) => {
      _renderFormattedText(child, nodeChild, actionHandler, renderCodeSegments);
    });
  }
}
function parseFormattedText(content, parseCodeSegments) {
  const root3 = {
    type: 1,
    children: []
  };
  let actionViewItemIndex = 0;
  let current = root3;
  const stack = [];
  const stream = new StringStream(content);
  while (!stream.eos()) {
    let next = stream.next();
    const isEscapedFormatType = next === "\\" && formatTagType(stream.peek(), parseCodeSegments) !== 0;
    if (isEscapedFormatType) {
      next = stream.next();
    }
    if (!isEscapedFormatType && isFormatTag(next, parseCodeSegments) && next === stream.peek()) {
      stream.advance();
      if (current.type === 2) {
        current = stack.pop();
      }
      const type = formatTagType(next, parseCodeSegments);
      if (current.type === type || current.type === 5 && type === 6) {
        current = stack.pop();
      } else {
        const newCurrent = {
          type,
          children: []
        };
        if (type === 5) {
          newCurrent.index = actionViewItemIndex;
          actionViewItemIndex++;
        }
        current.children.push(newCurrent);
        stack.push(current);
        current = newCurrent;
      }
    } else if (next === "\n") {
      if (current.type === 2) {
        current = stack.pop();
      }
      current.children.push({
        type: 8
        /* FormatType.NewLine */
      });
    } else {
      if (current.type !== 2) {
        const textCurrent = {
          type: 2,
          content: next
        };
        current.children.push(textCurrent);
        stack.push(current);
        current = textCurrent;
      } else {
        current.content += next;
      }
    }
  }
  if (current.type === 2) {
    current = stack.pop();
  }
  return root3;
}
function isFormatTag(char, supportCodeSegments) {
  return formatTagType(char, supportCodeSegments) !== 0;
}
function formatTagType(char, supportCodeSegments) {
  switch (char) {
    case "*":
      return 3;
    case "_":
      return 4;
    case "[":
      return 5;
    case "]":
      return 6;
    case "`":
      return supportCodeSegments ? 7 : 0;
    default:
      return 0;
  }
}
const labelWithIconsRegex = new RegExp(`(\\\\)?\\$\\((${ThemeIcon.iconNameExpression}(?:${ThemeIcon.iconModifierExpression})?)\\)`, "g");
function renderLabelWithIcons(text2) {
  const elements = new Array();
  let match2;
  let textStart = 0, textStop = 0;
  while ((match2 = labelWithIconsRegex.exec(text2)) !== null) {
    textStop = match2.index || 0;
    if (textStart < textStop) {
      elements.push(text2.substring(textStart, textStop));
    }
    textStart = (match2.index || 0) + match2[0].length;
    const [, escaped, codicon2] = match2;
    elements.push(escaped ? `$(${codicon2})` : renderIcon({ id: codicon2 }));
  }
  if (textStart < text2.length) {
    elements.push(text2.substring(textStart));
  }
  return elements;
}
function renderIcon(icon) {
  const node2 = $$d(`span`);
  node2.classList.add(...ThemeIcon.asClassNameArray(icon));
  return node2;
}
class IdGenerator {
  constructor(prefix2) {
    this._prefix = prefix2;
    this._lastId = 0;
  }
  nextId() {
    return this._prefix + ++this._lastId;
  }
}
const defaultGenerator = new IdGenerator("id#");
let __marked_exports = {};
(function() {
  function define2(deps, factory) {
    factory(__marked_exports);
  }
  define2.amd = true;
  (function(global2, factory) {
    typeof define2 === "function" && define2.amd ? define2(["exports"], factory) : typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.marked = {}));
  })(this, function(exports2) {
    function _defineProperties(target, props) {
      for (var i = 0; i < props.length; i++) {
        var descriptor = props[i];
        descriptor.enumerable = descriptor.enumerable || false;
        descriptor.configurable = true;
        if ("value" in descriptor)
          descriptor.writable = true;
        Object.defineProperty(target, descriptor.key, descriptor);
      }
    }
    function _createClass(Constructor, protoProps, staticProps) {
      if (protoProps)
        _defineProperties(Constructor.prototype, protoProps);
      if (staticProps)
        _defineProperties(Constructor, staticProps);
      Object.defineProperty(Constructor, "prototype", {
        writable: false
      });
      return Constructor;
    }
    function _unsupportedIterableToArray(o, minLen) {
      if (!o)
        return;
      if (typeof o === "string")
        return _arrayLikeToArray(o, minLen);
      var n2 = Object.prototype.toString.call(o).slice(8, -1);
      if (n2 === "Object" && o.constructor)
        n2 = o.constructor.name;
      if (n2 === "Map" || n2 === "Set")
        return Array.from(o);
      if (n2 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n2))
        return _arrayLikeToArray(o, minLen);
    }
    function _arrayLikeToArray(arr, len) {
      if (len == null || len > arr.length)
        len = arr.length;
      for (var i = 0, arr2 = new Array(len); i < len; i++)
        arr2[i] = arr[i];
      return arr2;
    }
    function _createForOfIteratorHelperLoose(o, allowArrayLike) {
      var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
      if (it)
        return (it = it.call(o)).next.bind(it);
      if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
        if (it)
          o = it;
        var i = 0;
        return function() {
          if (i >= o.length)
            return {
              done: true
            };
          return {
            done: false,
            value: o[i++]
          };
        };
      }
      throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
    }
    function getDefaults() {
      return {
        async: false,
        baseUrl: null,
        breaks: false,
        extensions: null,
        gfm: true,
        headerIds: true,
        headerPrefix: "",
        highlight: null,
        langPrefix: "language-",
        mangle: true,
        pedantic: false,
        renderer: null,
        sanitize: false,
        sanitizer: null,
        silent: false,
        smartLists: false,
        smartypants: false,
        tokenizer: null,
        walkTokens: null,
        xhtml: false
      };
    }
    exports2.defaults = getDefaults();
    function changeDefaults(newDefaults) {
      exports2.defaults = newDefaults;
    }
    var escapeTest = /[&<>"']/;
    var escapeReplace = /[&<>"']/g;
    var escapeTestNoEncode = /[<>"']|&(?!#?\w+;)/;
    var escapeReplaceNoEncode = /[<>"']|&(?!#?\w+;)/g;
    var escapeReplacements = {
      "&": "&amp;",
      "<": "&lt;",
      ">": "&gt;",
      '"': "&quot;",
      "'": "&#39;"
    };
    var getEscapeReplacement = function getEscapeReplacement2(ch) {
      return escapeReplacements[ch];
    };
    function escape2(html2, encode) {
      if (encode) {
        if (escapeTest.test(html2)) {
          return html2.replace(escapeReplace, getEscapeReplacement);
        }
      } else {
        if (escapeTestNoEncode.test(html2)) {
          return html2.replace(escapeReplaceNoEncode, getEscapeReplacement);
        }
      }
      return html2;
    }
    var unescapeTest = /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;
    function unescape2(html2) {
      return html2.replace(unescapeTest, function(_, n2) {
        n2 = n2.toLowerCase();
        if (n2 === "colon")
          return ":";
        if (n2.charAt(0) === "#") {
          return n2.charAt(1) === "x" ? String.fromCharCode(parseInt(n2.substring(2), 16)) : String.fromCharCode(+n2.substring(1));
        }
        return "";
      });
    }
    var caret2 = /(^|[^\[])\^/g;
    function edit(regex, opt) {
      regex = typeof regex === "string" ? regex : regex.source;
      opt = opt || "";
      var obj = {
        replace: function replace(name, val) {
          val = val.source || val;
          val = val.replace(caret2, "$1");
          regex = regex.replace(name, val);
          return obj;
        },
        getRegex: function getRegex() {
          return new RegExp(regex, opt);
        }
      };
      return obj;
    }
    var nonWordAndColonTest = /[^\w:]/g;
    var originIndependentUrl = /^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;
    function cleanUrl(sanitize2, base2, href) {
      if (sanitize2) {
        var prot;
        try {
          prot = decodeURIComponent(unescape2(href)).replace(nonWordAndColonTest, "").toLowerCase();
        } catch (e) {
          return null;
        }
        if (prot.indexOf("javascript:") === 0 || prot.indexOf("vbscript:") === 0 || prot.indexOf("data:") === 0) {
          return null;
        }
      }
      if (base2 && !originIndependentUrl.test(href)) {
        href = resolveUrl(base2, href);
      }
      try {
        href = encodeURI(href).replace(/%25/g, "%");
      } catch (e) {
        return null;
      }
      return href;
    }
    var baseUrls = {};
    var justDomain = /^[^:]+:\/*[^/]*$/;
    var protocol = /^([^:]+:)[\s\S]*$/;
    var domain = /^([^:]+:\/*[^/]*)[\s\S]*$/;
    function resolveUrl(base2, href) {
      if (!baseUrls[" " + base2]) {
        if (justDomain.test(base2)) {
          baseUrls[" " + base2] = base2 + "/";
        } else {
          baseUrls[" " + base2] = rtrim2(base2, "/", true);
        }
      }
      base2 = baseUrls[" " + base2];
      var relativeBase = base2.indexOf(":") === -1;
      if (href.substring(0, 2) === "//") {
        if (relativeBase) {
          return href;
        }
        return base2.replace(protocol, "$1") + href;
      } else if (href.charAt(0) === "/") {
        if (relativeBase) {
          return href;
        }
        return base2.replace(domain, "$1") + href;
      } else {
        return base2 + href;
      }
    }
    var noopTest = {
      exec: function noopTest2() {
      }
    };
    function merge2(obj) {
      var i = 1, target, key;
      for (; i < arguments.length; i++) {
        target = arguments[i];
        for (key in target) {
          if (Object.prototype.hasOwnProperty.call(target, key)) {
            obj[key] = target[key];
          }
        }
      }
      return obj;
    }
    function splitCells(tableRow, count) {
      var row = tableRow.replace(/\|/g, function(match2, offset, str2) {
        var escaped = false, curr = offset;
        while (--curr >= 0 && str2[curr] === "\\") {
          escaped = !escaped;
        }
        if (escaped) {
          return "|";
        } else {
          return " |";
        }
      }), cells = row.split(/ \|/);
      var i = 0;
      if (!cells[0].trim()) {
        cells.shift();
      }
      if (cells.length > 0 && !cells[cells.length - 1].trim()) {
        cells.pop();
      }
      if (cells.length > count) {
        cells.splice(count);
      } else {
        while (cells.length < count) {
          cells.push("");
        }
      }
      for (; i < cells.length; i++) {
        cells[i] = cells[i].trim().replace(/\\\|/g, "|");
      }
      return cells;
    }
    function rtrim2(str2, c, invert) {
      var l = str2.length;
      if (l === 0) {
        return "";
      }
      var suffLen = 0;
      while (suffLen < l) {
        var currChar = str2.charAt(l - suffLen - 1);
        if (currChar === c && !invert) {
          suffLen++;
        } else if (currChar !== c && invert) {
          suffLen++;
        } else {
          break;
        }
      }
      return str2.slice(0, l - suffLen);
    }
    function findClosingBracket(str2, b) {
      if (str2.indexOf(b[1]) === -1) {
        return -1;
      }
      var l = str2.length;
      var level = 0, i = 0;
      for (; i < l; i++) {
        if (str2[i] === "\\") {
          i++;
        } else if (str2[i] === b[0]) {
          level++;
        } else if (str2[i] === b[1]) {
          level--;
          if (level < 0) {
            return i;
          }
        }
      }
      return -1;
    }
    function checkSanitizeDeprecation(opt) {
      if (opt && opt.sanitize && !opt.silent) {
        console.warn("marked(): sanitize and sanitizer parameters are deprecated since version 0.7.0, should not be used and will be removed in the future. Read more here: https://marked.js.org/#/USING_ADVANCED.md#options");
      }
    }
    function repeatString(pattern, count) {
      if (count < 1) {
        return "";
      }
      var result2 = "";
      while (count > 1) {
        if (count & 1) {
          result2 += pattern;
        }
        count >>= 1;
        pattern += pattern;
      }
      return result2 + pattern;
    }
    function outputLink(cap, link2, raw, lexer2) {
      var href = link2.href;
      var title2 = link2.title ? escape2(link2.title) : null;
      var text2 = cap[1].replace(/\\([\[\]])/g, "$1");
      if (cap[0].charAt(0) !== "!") {
        lexer2.state.inLink = true;
        var token = {
          type: "link",
          raw,
          href,
          title: title2,
          text: text2,
          tokens: lexer2.inlineTokens(text2)
        };
        lexer2.state.inLink = false;
        return token;
      }
      return {
        type: "image",
        raw,
        href,
        title: title2,
        text: escape2(text2)
      };
    }
    function indentCodeCompensation(raw, text2) {
      var matchIndentToCode = raw.match(/^(\s+)(?:```)/);
      if (matchIndentToCode === null) {
        return text2;
      }
      var indentToCode = matchIndentToCode[1];
      return text2.split("\n").map(function(node2) {
        var matchIndentInNode = node2.match(/^\s+/);
        if (matchIndentInNode === null) {
          return node2;
        }
        var indentInNode = matchIndentInNode[0];
        if (indentInNode.length >= indentToCode.length) {
          return node2.slice(indentToCode.length);
        }
        return node2;
      }).join("\n");
    }
    var Tokenizer2 = /* @__PURE__ */ function() {
      function Tokenizer3(options2) {
        this.options = options2 || exports2.defaults;
      }
      var _proto = Tokenizer3.prototype;
      _proto.space = function space2(src) {
        var cap = this.rules.block.newline.exec(src);
        if (cap && cap[0].length > 0) {
          return {
            type: "space",
            raw: cap[0]
          };
        }
      };
      _proto.code = function code(src) {
        var cap = this.rules.block.code.exec(src);
        if (cap) {
          var text2 = cap[0].replace(/^ {1,4}/gm, "");
          return {
            type: "code",
            raw: cap[0],
            codeBlockStyle: "indented",
            text: !this.options.pedantic ? rtrim2(text2, "\n") : text2
          };
        }
      };
      _proto.fences = function fences(src) {
        var cap = this.rules.block.fences.exec(src);
        if (cap) {
          var raw = cap[0];
          var text2 = indentCodeCompensation(raw, cap[3] || "");
          return {
            type: "code",
            raw,
            lang: cap[2] ? cap[2].trim() : cap[2],
            text: text2
          };
        }
      };
      _proto.heading = function heading(src) {
        var cap = this.rules.block.heading.exec(src);
        if (cap) {
          var text2 = cap[2].trim();
          if (/#$/.test(text2)) {
            var trimmed = rtrim2(text2, "#");
            if (this.options.pedantic) {
              text2 = trimmed.trim();
            } else if (!trimmed || / $/.test(trimmed)) {
              text2 = trimmed.trim();
            }
          }
          return {
            type: "heading",
            raw: cap[0],
            depth: cap[1].length,
            text: text2,
            tokens: this.lexer.inline(text2)
          };
        }
      };
      _proto.hr = function hr(src) {
        var cap = this.rules.block.hr.exec(src);
        if (cap) {
          return {
            type: "hr",
            raw: cap[0]
          };
        }
      };
      _proto.blockquote = function blockquote(src) {
        var cap = this.rules.block.blockquote.exec(src);
        if (cap) {
          var text2 = cap[0].replace(/^ *>[ \t]?/gm, "");
          return {
            type: "blockquote",
            raw: cap[0],
            tokens: this.lexer.blockTokens(text2, []),
            text: text2
          };
        }
      };
      _proto.list = function list2(src) {
        var cap = this.rules.block.list.exec(src);
        if (cap) {
          var raw, istask, ischecked, indent, i, blankLine, endsWithBlankLine, line, nextLine, rawLine, itemContents, endEarly;
          var bull = cap[1].trim();
          var isordered = bull.length > 1;
          var list3 = {
            type: "list",
            raw: "",
            ordered: isordered,
            start: isordered ? +bull.slice(0, -1) : "",
            loose: false,
            items: []
          };
          bull = isordered ? "\\d{1,9}\\" + bull.slice(-1) : "\\" + bull;
          if (this.options.pedantic) {
            bull = isordered ? bull : "[*+-]";
          }
          var itemRegex = new RegExp("^( {0,3}" + bull + ")((?:[	 ][^\\n]*)?(?:\\n|$))");
          while (src) {
            endEarly = false;
            if (!(cap = itemRegex.exec(src))) {
              break;
            }
            if (this.rules.block.hr.test(src)) {
              break;
            }
            raw = cap[0];
            src = src.substring(raw.length);
            line = cap[2].split("\n", 1)[0];
            nextLine = src.split("\n", 1)[0];
            if (this.options.pedantic) {
              indent = 2;
              itemContents = line.trimLeft();
            } else {
              indent = cap[2].search(/[^ ]/);
              indent = indent > 4 ? 1 : indent;
              itemContents = line.slice(indent);
              indent += cap[1].length;
            }
            blankLine = false;
            if (!line && /^ *$/.test(nextLine)) {
              raw += nextLine + "\n";
              src = src.substring(nextLine.length + 1);
              endEarly = true;
            }
            if (!endEarly) {
              var nextBulletRegex = new RegExp("^ {0," + Math.min(3, indent - 1) + "}(?:[*+-]|\\d{1,9}[.)])((?: [^\\n]*)?(?:\\n|$))");
              var hrRegex = new RegExp("^ {0," + Math.min(3, indent - 1) + "}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)");
              var fencesBeginRegex = new RegExp("^ {0," + Math.min(3, indent - 1) + "}(?:```|~~~)");
              var headingBeginRegex = new RegExp("^ {0," + Math.min(3, indent - 1) + "}#");
              while (src) {
                rawLine = src.split("\n", 1)[0];
                line = rawLine;
                if (this.options.pedantic) {
                  line = line.replace(/^ {1,4}(?=( {4})*[^ ])/g, "  ");
                }
                if (fencesBeginRegex.test(line)) {
                  break;
                }
                if (headingBeginRegex.test(line)) {
                  break;
                }
                if (nextBulletRegex.test(line)) {
                  break;
                }
                if (hrRegex.test(src)) {
                  break;
                }
                if (line.search(/[^ ]/) >= indent || !line.trim()) {
                  itemContents += "\n" + line.slice(indent);
                } else if (!blankLine) {
                  itemContents += "\n" + line;
                } else {
                  break;
                }
                if (!blankLine && !line.trim()) {
                  blankLine = true;
                }
                raw += rawLine + "\n";
                src = src.substring(rawLine.length + 1);
              }
            }
            if (!list3.loose) {
              if (endsWithBlankLine) {
                list3.loose = true;
              } else if (/\n *\n *$/.test(raw)) {
                endsWithBlankLine = true;
              }
            }
            if (this.options.gfm) {
              istask = /^\[[ xX]\] /.exec(itemContents);
              if (istask) {
                ischecked = istask[0] !== "[ ] ";
                itemContents = itemContents.replace(/^\[[ xX]\] +/, "");
              }
            }
            list3.items.push({
              type: "list_item",
              raw,
              task: !!istask,
              checked: ischecked,
              loose: false,
              text: itemContents
            });
            list3.raw += raw;
          }
          list3.items[list3.items.length - 1].raw = raw.trimRight();
          list3.items[list3.items.length - 1].text = itemContents.trimRight();
          list3.raw = list3.raw.trimRight();
          var l = list3.items.length;
          for (i = 0; i < l; i++) {
            this.lexer.state.top = false;
            list3.items[i].tokens = this.lexer.blockTokens(list3.items[i].text, []);
            var spacers = list3.items[i].tokens.filter(function(t) {
              return t.type === "space";
            });
            var hasMultipleLineBreaks = spacers.every(function(t) {
              var chars2 = t.raw.split("");
              var lineBreaks = 0;
              for (var _iterator = _createForOfIteratorHelperLoose(chars2), _step; !(_step = _iterator()).done; ) {
                var _char = _step.value;
                if (_char === "\n") {
                  lineBreaks += 1;
                }
                if (lineBreaks > 1) {
                  return true;
                }
              }
              return false;
            });
            if (!list3.loose && spacers.length && hasMultipleLineBreaks) {
              list3.loose = true;
              list3.items[i].loose = true;
            }
          }
          return list3;
        }
      };
      _proto.html = function html2(src) {
        var cap = this.rules.block.html.exec(src);
        if (cap) {
          var token = {
            type: "html",
            raw: cap[0],
            pre: !this.options.sanitizer && (cap[1] === "pre" || cap[1] === "script" || cap[1] === "style"),
            text: cap[0]
          };
          if (this.options.sanitize) {
            var text2 = this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape2(cap[0]);
            token.type = "paragraph";
            token.text = text2;
            token.tokens = this.lexer.inline(text2);
          }
          return token;
        }
      };
      _proto.def = function def2(src) {
        var cap = this.rules.block.def.exec(src);
        if (cap) {
          if (cap[3])
            cap[3] = cap[3].substring(1, cap[3].length - 1);
          var tag3 = cap[1].toLowerCase().replace(/\s+/g, " ");
          return {
            type: "def",
            tag: tag3,
            raw: cap[0],
            href: cap[2],
            title: cap[3]
          };
        }
      };
      _proto.table = function table2(src) {
        var cap = this.rules.block.table.exec(src);
        if (cap) {
          var item = {
            type: "table",
            header: splitCells(cap[1]).map(function(c) {
              return {
                text: c
              };
            }),
            align: cap[2].replace(/^ *|\| *$/g, "").split(/ *\| */),
            rows: cap[3] && cap[3].trim() ? cap[3].replace(/\n[ \t]*$/, "").split("\n") : []
          };
          if (item.header.length === item.align.length) {
            item.raw = cap[0];
            var l = item.align.length;
            var i, j, k, row;
            for (i = 0; i < l; i++) {
              if (/^ *-+: *$/.test(item.align[i])) {
                item.align[i] = "right";
              } else if (/^ *:-+: *$/.test(item.align[i])) {
                item.align[i] = "center";
              } else if (/^ *:-+ *$/.test(item.align[i])) {
                item.align[i] = "left";
              } else {
                item.align[i] = null;
              }
            }
            l = item.rows.length;
            for (i = 0; i < l; i++) {
              item.rows[i] = splitCells(item.rows[i], item.header.length).map(function(c) {
                return {
                  text: c
                };
              });
            }
            l = item.header.length;
            for (j = 0; j < l; j++) {
              item.header[j].tokens = this.lexer.inline(item.header[j].text);
            }
            l = item.rows.length;
            for (j = 0; j < l; j++) {
              row = item.rows[j];
              for (k = 0; k < row.length; k++) {
                row[k].tokens = this.lexer.inline(row[k].text);
              }
            }
            return item;
          }
        }
      };
      _proto.lheading = function lheading(src) {
        var cap = this.rules.block.lheading.exec(src);
        if (cap) {
          return {
            type: "heading",
            raw: cap[0],
            depth: cap[2].charAt(0) === "=" ? 1 : 2,
            text: cap[1],
            tokens: this.lexer.inline(cap[1])
          };
        }
      };
      _proto.paragraph = function paragraph(src) {
        var cap = this.rules.block.paragraph.exec(src);
        if (cap) {
          var text2 = cap[1].charAt(cap[1].length - 1) === "\n" ? cap[1].slice(0, -1) : cap[1];
          return {
            type: "paragraph",
            raw: cap[0],
            text: text2,
            tokens: this.lexer.inline(text2)
          };
        }
      };
      _proto.text = function text2(src) {
        var cap = this.rules.block.text.exec(src);
        if (cap) {
          return {
            type: "text",
            raw: cap[0],
            text: cap[0],
            tokens: this.lexer.inline(cap[0])
          };
        }
      };
      _proto.escape = function escape$12(src) {
        var cap = this.rules.inline.escape.exec(src);
        if (cap) {
          return {
            type: "escape",
            raw: cap[0],
            text: escape2(cap[1])
          };
        }
      };
      _proto.tag = function tag3(src) {
        var cap = this.rules.inline.tag.exec(src);
        if (cap) {
          if (!this.lexer.state.inLink && /^<a /i.test(cap[0])) {
            this.lexer.state.inLink = true;
          } else if (this.lexer.state.inLink && /^<\/a>/i.test(cap[0])) {
            this.lexer.state.inLink = false;
          }
          if (!this.lexer.state.inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
            this.lexer.state.inRawBlock = true;
          } else if (this.lexer.state.inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(cap[0])) {
            this.lexer.state.inRawBlock = false;
          }
          return {
            type: this.options.sanitize ? "text" : "html",
            raw: cap[0],
            inLink: this.lexer.state.inLink,
            inRawBlock: this.lexer.state.inRawBlock,
            text: this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape2(cap[0]) : cap[0]
          };
        }
      };
      _proto.link = function link2(src) {
        var cap = this.rules.inline.link.exec(src);
        if (cap) {
          var trimmedUrl = cap[2].trim();
          if (!this.options.pedantic && /^</.test(trimmedUrl)) {
            if (!/>$/.test(trimmedUrl)) {
              return;
            }
            var rtrimSlash = rtrim2(trimmedUrl.slice(0, -1), "\\");
            if ((trimmedUrl.length - rtrimSlash.length) % 2 === 0) {
              return;
            }
          } else {
            var lastParenIndex = findClosingBracket(cap[2], "()");
            if (lastParenIndex > -1) {
              var start = cap[0].indexOf("!") === 0 ? 5 : 4;
              var linkLen = start + cap[1].length + lastParenIndex;
              cap[2] = cap[2].substring(0, lastParenIndex);
              cap[0] = cap[0].substring(0, linkLen).trim();
              cap[3] = "";
            }
          }
          var href = cap[2];
          var title2 = "";
          if (this.options.pedantic) {
            var link3 = /^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(href);
            if (link3) {
              href = link3[1];
              title2 = link3[3];
            }
          } else {
            title2 = cap[3] ? cap[3].slice(1, -1) : "";
          }
          href = href.trim();
          if (/^</.test(href)) {
            if (this.options.pedantic && !/>$/.test(trimmedUrl)) {
              href = href.slice(1);
            } else {
              href = href.slice(1, -1);
            }
          }
          return outputLink(cap, {
            href: href ? href.replace(this.rules.inline._escapes, "$1") : href,
            title: title2 ? title2.replace(this.rules.inline._escapes, "$1") : title2
          }, cap[0], this.lexer);
        }
      };
      _proto.reflink = function reflink(src, links2) {
        var cap;
        if ((cap = this.rules.inline.reflink.exec(src)) || (cap = this.rules.inline.nolink.exec(src))) {
          var link2 = (cap[2] || cap[1]).replace(/\s+/g, " ");
          link2 = links2[link2.toLowerCase()];
          if (!link2 || !link2.href) {
            var text2 = cap[0].charAt(0);
            return {
              type: "text",
              raw: text2,
              text: text2
            };
          }
          return outputLink(cap, link2, cap[0], this.lexer);
        }
      };
      _proto.emStrong = function emStrong(src, maskedSrc, prevChar) {
        if (prevChar === void 0) {
          prevChar = "";
        }
        var match2 = this.rules.inline.emStrong.lDelim.exec(src);
        if (!match2)
          return;
        if (match2[3] && prevChar.match(/(?:[0-9A-Za-z\xAA\xB2\xB3\xB5\xB9\xBA\xBC-\xBE\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u0660-\u0669\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088E\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0966-\u096F\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09F4-\u09F9\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AE6-\u0AEF\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B6F\u0B71-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0BE6-\u0BF2\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C66-\u0C6F\u0C78-\u0C7E\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D58-\u0D61\u0D66-\u0D78\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DE6-\u0DEF\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F20-\u0F33\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F-\u1049\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u1090-\u1099\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1369-\u137C\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u17E0-\u17E9\u17F0-\u17F9\u1810-\u1819\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A16\u1A20-\u1A54\u1A80-\u1A89\u1A90-\u1A99\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B50-\u1B59\u1B83-\u1BA0\u1BAE-\u1BE5\u1C00-\u1C23\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2070\u2071\u2074-\u2079\u207F-\u2089\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2150-\u2189\u2460-\u249B\u24EA-\u24FF\u2776-\u2793\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2CFD\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u3192-\u3195\u31A0-\u31BF\u31F0-\u31FF\u3220-\u3229\u3248-\u324F\u3251-\u325F\u3280-\u3289\u32B1-\u32BF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7CA\uA7D0\uA7D1\uA7D3\uA7D5-\uA7D9\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA830-\uA835\uA840-\uA873\uA882-\uA8B3\uA8D0-\uA8D9\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA900-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF-\uA9D9\uA9E0-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA50-\uAA59\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD07-\uDD33\uDD40-\uDD78\uDD8A\uDD8B\uDE80-\uDE9C\uDEA0-\uDED0\uDEE1-\uDEFB\uDF00-\uDF23\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDD70-\uDD7A\uDD7C-\uDD8A\uDD8C-\uDD92\uDD94\uDD95\uDD97-\uDDA1\uDDA3-\uDDB1\uDDB3-\uDDB9\uDDBB\uDDBC\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67\uDF80-\uDF85\uDF87-\uDFB0\uDFB2-\uDFBA]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC58-\uDC76\uDC79-\uDC9E\uDCA7-\uDCAF\uDCE0-\uDCF2\uDCF4\uDCF5\uDCFB-\uDD1B\uDD20-\uDD39\uDD80-\uDDB7\uDDBC-\uDDCF\uDDD2-\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE35\uDE40-\uDE48\uDE60-\uDE7E\uDE80-\uDE9F\uDEC0-\uDEC7\uDEC9-\uDEE4\uDEEB-\uDEEF\uDF00-\uDF35\uDF40-\uDF55\uDF58-\uDF72\uDF78-\uDF91\uDFA9-\uDFAF]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2\uDCFA-\uDD23\uDD30-\uDD39\uDE60-\uDE7E\uDE80-\uDEA9\uDEB0\uDEB1\uDF00-\uDF27\uDF30-\uDF45\uDF51-\uDF54\uDF70-\uDF81\uDFB0-\uDFCB\uDFE0-\uDFF6]|\uD804[\uDC03-\uDC37\uDC52-\uDC6F\uDC71\uDC72\uDC75\uDC83-\uDCAF\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD03-\uDD26\uDD36-\uDD3F\uDD44\uDD47\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDD0-\uDDDA\uDDDC\uDDE1-\uDDF4\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDEF0-\uDEF9\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC50-\uDC59\uDC5F-\uDC61\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE50-\uDE59\uDE80-\uDEAA\uDEB8\uDEC0-\uDEC9\uDF00-\uDF1A\uDF30-\uDF3B\uDF40-\uDF46]|\uD806[\uDC00-\uDC2B\uDCA0-\uDCF2\uDCFF-\uDD06\uDD09\uDD0C-\uDD13\uDD15\uDD16\uDD18-\uDD2F\uDD3F\uDD41\uDD50-\uDD59\uDDA0-\uDDA7\uDDAA-\uDDD0\uDDE1\uDDE3\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE89\uDE9D\uDEB0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC50-\uDC6C\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46\uDD50-\uDD59\uDD60-\uDD65\uDD67\uDD68\uDD6A-\uDD89\uDD98\uDDA0-\uDDA9\uDEE0-\uDEF2\uDFB0\uDFC0-\uDFD4]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|\uD80B[\uDF90-\uDFF0]|[\uD80C\uD81C-\uD820\uD822\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879\uD880-\uD883][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDE70-\uDEBE\uDEC0-\uDEC9\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF50-\uDF59\uDF5B-\uDF61\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDE40-\uDE96\uDF00-\uDF4A\uDF50\uDF93-\uDF9F\uDFE0\uDFE1\uDFE3]|\uD821[\uDC00-\uDFF7]|\uD823[\uDC00-\uDCD5\uDD00-\uDD08]|\uD82B[\uDFF0-\uDFF3\uDFF5-\uDFFB\uDFFD\uDFFE]|\uD82C[\uDC00-\uDD22\uDD50-\uDD52\uDD64-\uDD67\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD834[\uDEE0-\uDEF3\uDF60-\uDF78]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD837[\uDF00-\uDF1E]|\uD838[\uDD00-\uDD2C\uDD37-\uDD3D\uDD40-\uDD49\uDD4E\uDE90-\uDEAD\uDEC0-\uDEEB\uDEF0-\uDEF9]|\uD839[\uDFE0-\uDFE6\uDFE8-\uDFEB\uDFED\uDFEE\uDFF0-\uDFFE]|\uD83A[\uDC00-\uDCC4\uDCC7-\uDCCF\uDD00-\uDD43\uDD4B\uDD50-\uDD59]|\uD83B[\uDC71-\uDCAB\uDCAD-\uDCAF\uDCB1-\uDCB4\uDD01-\uDD2D\uDD2F-\uDD3D\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD83C[\uDD00-\uDD0C]|\uD83E[\uDFF0-\uDFF9]|\uD869[\uDC00-\uDEDF\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF38\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uD884[\uDC00-\uDF4A])/))
          return;
        var nextChar = match2[1] || match2[2] || "";
        if (!nextChar || nextChar && (prevChar === "" || this.rules.inline.punctuation.exec(prevChar))) {
          var lLength = match2[0].length - 1;
          var rDelim, rLength, delimTotal = lLength, midDelimTotal = 0;
          var endReg = match2[0][0] === "*" ? this.rules.inline.emStrong.rDelimAst : this.rules.inline.emStrong.rDelimUnd;
          endReg.lastIndex = 0;
          maskedSrc = maskedSrc.slice(-1 * src.length + lLength);
          while ((match2 = endReg.exec(maskedSrc)) != null) {
            rDelim = match2[1] || match2[2] || match2[3] || match2[4] || match2[5] || match2[6];
            if (!rDelim)
              continue;
            rLength = rDelim.length;
            if (match2[3] || match2[4]) {
              delimTotal += rLength;
              continue;
            } else if (match2[5] || match2[6]) {
              if (lLength % 3 && !((lLength + rLength) % 3)) {
                midDelimTotal += rLength;
                continue;
              }
            }
            delimTotal -= rLength;
            if (delimTotal > 0)
              continue;
            rLength = Math.min(rLength, rLength + delimTotal + midDelimTotal);
            if (Math.min(lLength, rLength) % 2) {
              var _text = src.slice(1, lLength + match2.index + rLength);
              return {
                type: "em",
                raw: src.slice(0, lLength + match2.index + rLength + 1),
                text: _text,
                tokens: this.lexer.inlineTokens(_text)
              };
            }
            var text2 = src.slice(2, lLength + match2.index + rLength - 1);
            return {
              type: "strong",
              raw: src.slice(0, lLength + match2.index + rLength + 1),
              text: text2,
              tokens: this.lexer.inlineTokens(text2)
            };
          }
        }
      };
      _proto.codespan = function codespan(src) {
        var cap = this.rules.inline.code.exec(src);
        if (cap) {
          var text2 = cap[2].replace(/\n/g, " ");
          var hasNonSpaceChars = /[^ ]/.test(text2);
          var hasSpaceCharsOnBothEnds = /^ /.test(text2) && / $/.test(text2);
          if (hasNonSpaceChars && hasSpaceCharsOnBothEnds) {
            text2 = text2.substring(1, text2.length - 1);
          }
          text2 = escape2(text2, true);
          return {
            type: "codespan",
            raw: cap[0],
            text: text2
          };
        }
      };
      _proto.br = function br(src) {
        var cap = this.rules.inline.br.exec(src);
        if (cap) {
          return {
            type: "br",
            raw: cap[0]
          };
        }
      };
      _proto.del = function del2(src) {
        var cap = this.rules.inline.del.exec(src);
        if (cap) {
          return {
            type: "del",
            raw: cap[0],
            text: cap[2],
            tokens: this.lexer.inlineTokens(cap[2])
          };
        }
      };
      _proto.autolink = function autolink(src, mangle2) {
        var cap = this.rules.inline.autolink.exec(src);
        if (cap) {
          var text2, href;
          if (cap[2] === "@") {
            text2 = escape2(this.options.mangle ? mangle2(cap[1]) : cap[1]);
            href = "mailto:" + text2;
          } else {
            text2 = escape2(cap[1]);
            href = text2;
          }
          return {
            type: "link",
            raw: cap[0],
            text: text2,
            href,
            tokens: [{
              type: "text",
              raw: text2,
              text: text2
            }]
          };
        }
      };
      _proto.url = function url(src, mangle2) {
        var cap;
        if (cap = this.rules.inline.url.exec(src)) {
          var text2, href;
          if (cap[2] === "@") {
            text2 = escape2(this.options.mangle ? mangle2(cap[0]) : cap[0]);
            href = "mailto:" + text2;
          } else {
            var prevCapZero;
            do {
              prevCapZero = cap[0];
              cap[0] = this.rules.inline._backpedal.exec(cap[0])[0];
            } while (prevCapZero !== cap[0]);
            text2 = escape2(cap[0]);
            if (cap[1] === "www.") {
              href = "http://" + text2;
            } else {
              href = text2;
            }
          }
          return {
            type: "link",
            raw: cap[0],
            text: text2,
            href,
            tokens: [{
              type: "text",
              raw: text2,
              text: text2
            }]
          };
        }
      };
      _proto.inlineText = function inlineText(src, smartypants2) {
        var cap = this.rules.inline.text.exec(src);
        if (cap) {
          var text2;
          if (this.lexer.state.inRawBlock) {
            text2 = this.options.sanitize ? this.options.sanitizer ? this.options.sanitizer(cap[0]) : escape2(cap[0]) : cap[0];
          } else {
            text2 = escape2(this.options.smartypants ? smartypants2(cap[0]) : cap[0]);
          }
          return {
            type: "text",
            raw: cap[0],
            text: text2
          };
        }
      };
      return Tokenizer3;
    }();
    var block = {
      newline: /^(?: *(?:\n|$))+/,
      code: /^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,
      fences: /^ {0,3}(`{3,}(?=[^`\n]*\n)|~{3,})([^\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~`]* *(?=\n|$)|$)/,
      hr: /^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,
      heading: /^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,
      blockquote: /^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,
      list: /^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/,
      html: "^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))",
      def: /^ {0,3}\[(label)\]: *(?:\n *)?<?([^\s>]+)>?(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/,
      table: noopTest,
      lheading: /^([^\n]+)\n {0,3}(=+|-+) *(?:\n+|$)/,
      // regex template, placeholders will be replaced according to different paragraph
      // interruption rules of commonmark and the original markdown spec:
      _paragraph: /^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,
      text: /^[^\n]+/
    };
    block._label = /(?!\s*\])(?:\\.|[^\[\]\\])+/;
    block._title = /(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/;
    block.def = edit(block.def).replace("label", block._label).replace("title", block._title).getRegex();
    block.bullet = /(?:[*+-]|\d{1,9}[.)])/;
    block.listItemStart = edit(/^( *)(bull) */).replace("bull", block.bullet).getRegex();
    block.list = edit(block.list).replace(/bull/g, block.bullet).replace("hr", "\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def", "\\n+(?=" + block.def.source + ")").getRegex();
    block._tag = "address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul";
    block._comment = /<!--(?!-?>)[\s\S]*?(?:-->|$)/;
    block.html = edit(block.html, "i").replace("comment", block._comment).replace("tag", block._tag).replace("attribute", / +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex();
    block.paragraph = edit(block._paragraph).replace("hr", block.hr).replace("heading", " {0,3}#{1,6} ").replace("|lheading", "").replace("|table", "").replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", block._tag).getRegex();
    block.blockquote = edit(block.blockquote).replace("paragraph", block.paragraph).getRegex();
    block.normal = merge2({}, block);
    block.gfm = merge2({}, block.normal, {
      table: "^ *([^\\n ].*\\|.*)\\n {0,3}(?:\\| *)?(:?-+:? *(?:\\| *:?-+:? *)*)(?:\\| *)?(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)"
      // Cells
    });
    block.gfm.table = edit(block.gfm.table).replace("hr", block.hr).replace("heading", " {0,3}#{1,6} ").replace("blockquote", " {0,3}>").replace("code", " {4}[^\\n]").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", block._tag).getRegex();
    block.gfm.paragraph = edit(block._paragraph).replace("hr", block.hr).replace("heading", " {0,3}#{1,6} ").replace("|lheading", "").replace("table", block.gfm.table).replace("blockquote", " {0,3}>").replace("fences", " {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list", " {0,3}(?:[*+-]|1[.)]) ").replace("html", "</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag", block._tag).getRegex();
    block.pedantic = merge2({}, block.normal, {
      html: edit(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment", block._comment).replace(/tag/g, "(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),
      def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,
      heading: /^(#{1,6})(.*)(?:\n+|$)/,
      fences: noopTest,
      // fences not supported
      paragraph: edit(block.normal._paragraph).replace("hr", block.hr).replace("heading", " *#{1,6} *[^\n]").replace("lheading", block.lheading).replace("blockquote", " {0,3}>").replace("|fences", "").replace("|list", "").replace("|html", "").getRegex()
    });
    var inline = {
      escape: /^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,
      autolink: /^<(scheme:[^\s\x00-\x1f<>]*|email)>/,
      url: noopTest,
      tag: "^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>",
      // CDATA section
      link: /^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/,
      reflink: /^!?\[(label)\]\[(ref)\]/,
      nolink: /^!?\[(ref)\](?:\[\])?/,
      reflinkSearch: "reflink|nolink(?!\\()",
      emStrong: {
        lDelim: /^(?:\*+(?:([punct_])|[^\s*]))|^_+(?:([punct*])|([^\s_]))/,
        //        (1) and (2) can only be a Right Delimiter. (3) and (4) can only be Left.  (5) and (6) can be either Left or Right.
        //          () Skip orphan inside strong  () Consume to delim (1) #***                (2) a***#, a***                   (3) #***a, ***a                 (4) ***#              (5) #***#                 (6) a***a
        rDelimAst: /^[^_*]*?\_\_[^_*]*?\*[^_*]*?(?=\_\_)|[^*]+(?=[^*])|[punct_](\*+)(?=[\s]|$)|[^punct*_\s](\*+)(?=[punct_\s]|$)|[punct_\s](\*+)(?=[^punct*_\s])|[\s](\*+)(?=[punct_])|[punct_](\*+)(?=[punct_])|[^punct*_\s](\*+)(?=[^punct*_\s])/,
        rDelimUnd: /^[^_*]*?\*\*[^_*]*?\_[^_*]*?(?=\*\*)|[^_]+(?=[^_])|[punct*](\_+)(?=[\s]|$)|[^punct*_\s](\_+)(?=[punct*\s]|$)|[punct*\s](\_+)(?=[^punct*_\s])|[\s](\_+)(?=[punct*])|[punct*](\_+)(?=[punct*])/
        // ^- Not allowed for _
      },
      code: /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,
      br: /^( {2,}|\\)\n(?!\s*$)/,
      del: noopTest,
      text: /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,
      punctuation: /^([\spunctuation])/
    };
    inline._punctuation = "!\"#$%&'()+\\-.,/:;<=>?@\\[\\]`^{|}~";
    inline.punctuation = edit(inline.punctuation).replace(/punctuation/g, inline._punctuation).getRegex();
    inline.blockSkip = /\[[^\]]*?\]\([^\)]*?\)|`[^`]*?`|<[^>]*?>/g;
    inline.escapedEmSt = /\\\*|\\_/g;
    inline._comment = edit(block._comment).replace("(?:-->|$)", "-->").getRegex();
    inline.emStrong.lDelim = edit(inline.emStrong.lDelim).replace(/punct/g, inline._punctuation).getRegex();
    inline.emStrong.rDelimAst = edit(inline.emStrong.rDelimAst, "g").replace(/punct/g, inline._punctuation).getRegex();
    inline.emStrong.rDelimUnd = edit(inline.emStrong.rDelimUnd, "g").replace(/punct/g, inline._punctuation).getRegex();
    inline._escapes = /\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g;
    inline._scheme = /[a-zA-Z][a-zA-Z0-9+.-]{1,31}/;
    inline._email = /[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/;
    inline.autolink = edit(inline.autolink).replace("scheme", inline._scheme).replace("email", inline._email).getRegex();
    inline._attribute = /\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/;
    inline.tag = edit(inline.tag).replace("comment", inline._comment).replace("attribute", inline._attribute).getRegex();
    inline._label = /(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/;
    inline._href = /<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/;
    inline._title = /"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/;
    inline.link = edit(inline.link).replace("label", inline._label).replace("href", inline._href).replace("title", inline._title).getRegex();
    inline.reflink = edit(inline.reflink).replace("label", inline._label).replace("ref", block._label).getRegex();
    inline.nolink = edit(inline.nolink).replace("ref", block._label).getRegex();
    inline.reflinkSearch = edit(inline.reflinkSearch, "g").replace("reflink", inline.reflink).replace("nolink", inline.nolink).getRegex();
    inline.normal = merge2({}, inline);
    inline.pedantic = merge2({}, inline.normal, {
      strong: {
        start: /^__|\*\*/,
        middle: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
        endAst: /\*\*(?!\*)/g,
        endUnd: /__(?!_)/g
      },
      em: {
        start: /^_|\*/,
        middle: /^()\*(?=\S)([\s\S]*?\S)\*(?!\*)|^_(?=\S)([\s\S]*?\S)_(?!_)/,
        endAst: /\*(?!\*)/g,
        endUnd: /_(?!_)/g
      },
      link: edit(/^!?\[(label)\]\((.*?)\)/).replace("label", inline._label).getRegex(),
      reflink: edit(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label", inline._label).getRegex()
    });
    inline.gfm = merge2({}, inline.normal, {
      escape: edit(inline.escape).replace("])", "~|])").getRegex(),
      _extended_email: /[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/,
      url: /^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,
      _backpedal: /(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/,
      del: /^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,
      text: /^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/
    });
    inline.gfm.url = edit(inline.gfm.url, "i").replace("email", inline.gfm._extended_email).getRegex();
    inline.breaks = merge2({}, inline.gfm, {
      br: edit(inline.br).replace("{2,}", "*").getRegex(),
      text: edit(inline.gfm.text).replace("\\b_", "\\b_| {2,}\\n").replace(/\{2,\}/g, "*").getRegex()
    });
    function smartypants(text2) {
      return text2.replace(/---/g, "—").replace(/--/g, "–").replace(/(^|[-\u2014/(\[{"\s])'/g, "$1‘").replace(/'/g, "’").replace(/(^|[-\u2014/(\[{\u2018\s])"/g, "$1“").replace(/"/g, "”").replace(/\.{3}/g, "…");
    }
    function mangle(text2) {
      var out = "", i, ch;
      var l = text2.length;
      for (i = 0; i < l; i++) {
        ch = text2.charCodeAt(i);
        if (Math.random() > 0.5) {
          ch = "x" + ch.toString(16);
        }
        out += "&#" + ch + ";";
      }
      return out;
    }
    var Lexer = /* @__PURE__ */ function() {
      function Lexer2(options2) {
        this.tokens = [];
        this.tokens.links = /* @__PURE__ */ Object.create(null);
        this.options = options2 || exports2.defaults;
        this.options.tokenizer = this.options.tokenizer || new Tokenizer2();
        this.tokenizer = this.options.tokenizer;
        this.tokenizer.options = this.options;
        this.tokenizer.lexer = this;
        this.inlineQueue = [];
        this.state = {
          inLink: false,
          inRawBlock: false,
          top: true
        };
        var rules = {
          block: block.normal,
          inline: inline.normal
        };
        if (this.options.pedantic) {
          rules.block = block.pedantic;
          rules.inline = inline.pedantic;
        } else if (this.options.gfm) {
          rules.block = block.gfm;
          if (this.options.breaks) {
            rules.inline = inline.breaks;
          } else {
            rules.inline = inline.gfm;
          }
        }
        this.tokenizer.rules = rules;
      }
      Lexer2.lex = function lex(src, options2) {
        var lexer2 = new Lexer2(options2);
        return lexer2.lex(src);
      };
      Lexer2.lexInline = function lexInline(src, options2) {
        var lexer2 = new Lexer2(options2);
        return lexer2.inlineTokens(src);
      };
      var _proto = Lexer2.prototype;
      _proto.lex = function lex(src) {
        src = src.replace(/\r\n|\r/g, "\n");
        this.blockTokens(src, this.tokens);
        var next;
        while (next = this.inlineQueue.shift()) {
          this.inlineTokens(next.src, next.tokens);
        }
        return this.tokens;
      };
      _proto.blockTokens = function blockTokens(src, tokens) {
        var _this = this;
        if (tokens === void 0) {
          tokens = [];
        }
        if (this.options.pedantic) {
          src = src.replace(/\t/g, "    ").replace(/^ +$/gm, "");
        } else {
          src = src.replace(/^( *)(\t+)/gm, function(_, leading, tabs) {
            return leading + "    ".repeat(tabs.length);
          });
        }
        var token, lastToken, cutSrc, lastParagraphClipped;
        while (src) {
          if (this.options.extensions && this.options.extensions.block && this.options.extensions.block.some(function(extTokenizer) {
            if (token = extTokenizer.call({
              lexer: _this
            }, src, tokens)) {
              src = src.substring(token.raw.length);
              tokens.push(token);
              return true;
            }
            return false;
          })) {
            continue;
          }
          if (token = this.tokenizer.space(src)) {
            src = src.substring(token.raw.length);
            if (token.raw.length === 1 && tokens.length > 0) {
              tokens[tokens.length - 1].raw += "\n";
            } else {
              tokens.push(token);
            }
            continue;
          }
          if (token = this.tokenizer.code(src)) {
            src = src.substring(token.raw.length);
            lastToken = tokens[tokens.length - 1];
            if (lastToken && (lastToken.type === "paragraph" || lastToken.type === "text")) {
              lastToken.raw += "\n" + token.raw;
              lastToken.text += "\n" + token.text;
              this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
            } else {
              tokens.push(token);
            }
            continue;
          }
          if (token = this.tokenizer.fences(src)) {
            src = src.substring(token.raw.length);
            tokens.push(token);
            continue;
          }
          if (token = this.tokenizer.heading(src)) {
            src = src.substring(token.raw.length);
            tokens.push(token);
            continue;
          }
          if (token = this.tokenizer.hr(src)) {
            src = src.substring(token.raw.length);
            tokens.push(token);
            continue;
          }
          if (token = this.tokenizer.blockquote(src)) {
            src = src.substring(token.raw.length);
            tokens.push(token);
            continue;
          }
          if (token = this.tokenizer.list(src)) {
            src = src.substring(token.raw.length);
            tokens.push(token);
            continue;
          }
          if (token = this.tokenizer.html(src)) {
            src = src.substring(token.raw.length);
            tokens.push(token);
            continue;
          }
          if (token = this.tokenizer.def(src)) {
            src = src.substring(token.raw.length);
            lastToken = tokens[tokens.length - 1];
            if (lastToken && (lastToken.type === "paragraph" || lastToken.type === "text")) {
              lastToken.raw += "\n" + token.raw;
              lastToken.text += "\n" + token.raw;
              this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
            } else if (!this.tokens.links[token.tag]) {
              this.tokens.links[token.tag] = {
                href: token.href,
                title: token.title
              };
            }
            continue;
          }
          if (token = this.tokenizer.table(src)) {
            src = src.substring(token.raw.length);
            tokens.push(token);
            continue;
          }
          if (token = this.tokenizer.lheading(src)) {
            src = src.substring(token.raw.length);
            tokens.push(token);
            continue;
          }
          cutSrc = src;
          if (this.options.extensions && this.options.extensions.startBlock) {
            (function() {
              var startIndex = Infinity;
              var tempSrc = src.slice(1);
              var tempStart = void 0;
              _this.options.extensions.startBlock.forEach(function(getStartIndex) {
                tempStart = getStartIndex.call({
                  lexer: this
                }, tempSrc);
                if (typeof tempStart === "number" && tempStart >= 0) {
                  startIndex = Math.min(startIndex, tempStart);
                }
              });
              if (startIndex < Infinity && startIndex >= 0) {
                cutSrc = src.substring(0, startIndex + 1);
              }
            })();
          }
          if (this.state.top && (token = this.tokenizer.paragraph(cutSrc))) {
            lastToken = tokens[tokens.length - 1];
            if (lastParagraphClipped && lastToken.type === "paragraph") {
              lastToken.raw += "\n" + token.raw;
              lastToken.text += "\n" + token.text;
              this.inlineQueue.pop();
              this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
            } else {
              tokens.push(token);
            }
            lastParagraphClipped = cutSrc.length !== src.length;
            src = src.substring(token.raw.length);
            continue;
          }
          if (token = this.tokenizer.text(src)) {
            src = src.substring(token.raw.length);
            lastToken = tokens[tokens.length - 1];
            if (lastToken && lastToken.type === "text") {
              lastToken.raw += "\n" + token.raw;
              lastToken.text += "\n" + token.text;
              this.inlineQueue.pop();
              this.inlineQueue[this.inlineQueue.length - 1].src = lastToken.text;
            } else {
              tokens.push(token);
            }
            continue;
          }
          if (src) {
            var errMsg = "Infinite loop on byte: " + src.charCodeAt(0);
            if (this.options.silent) {
              console.error(errMsg);
              break;
            } else {
              throw new Error(errMsg);
            }
          }
        }
        this.state.top = true;
        return tokens;
      };
      _proto.inline = function inline2(src, tokens) {
        if (tokens === void 0) {
          tokens = [];
        }
        this.inlineQueue.push({
          src,
          tokens
        });
        return tokens;
      };
      _proto.inlineTokens = function inlineTokens(src, tokens) {
        var _this2 = this;
        if (tokens === void 0) {
          tokens = [];
        }
        var token, lastToken, cutSrc;
        var maskedSrc = src;
        var match2;
        var keepPrevChar, prevChar;
        if (this.tokens.links) {
          var links2 = Object.keys(this.tokens.links);
          if (links2.length > 0) {
            while ((match2 = this.tokenizer.rules.inline.reflinkSearch.exec(maskedSrc)) != null) {
              if (links2.includes(match2[0].slice(match2[0].lastIndexOf("[") + 1, -1))) {
                maskedSrc = maskedSrc.slice(0, match2.index) + "[" + repeatString("a", match2[0].length - 2) + "]" + maskedSrc.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex);
              }
            }
          }
        }
        while ((match2 = this.tokenizer.rules.inline.blockSkip.exec(maskedSrc)) != null) {
          maskedSrc = maskedSrc.slice(0, match2.index) + "[" + repeatString("a", match2[0].length - 2) + "]" + maskedSrc.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);
        }
        while ((match2 = this.tokenizer.rules.inline.escapedEmSt.exec(maskedSrc)) != null) {
          maskedSrc = maskedSrc.slice(0, match2.index) + "++" + maskedSrc.slice(this.tokenizer.rules.inline.escapedEmSt.lastIndex);
        }
        while (src) {
          if (!keepPrevChar) {
            prevChar = "";
          }
          keepPrevChar = false;
          if (this.options.extensions && this.options.extensions.inline && this.options.extensions.inline.some(function(extTokenizer) {
            if (token = extTokenizer.call({
              lexer: _this2
            }, src, tokens)) {
              src = src.substring(token.raw.length);
              tokens.push(token);
              return true;
            }
            return false;
          })) {
            continue;
          }
          if (token = this.tokenizer.escape(src)) {
            src = src.substring(token.raw.length);
            tokens.push(token);
            continue;
          }
          if (token = this.tokenizer.tag(src)) {
            src = src.substring(token.raw.length);
            lastToken = tokens[tokens.length - 1];
            if (lastToken && token.type === "text" && lastToken.type === "text") {
              lastToken.raw += token.raw;
              lastToken.text += token.text;
            } else {
              tokens.push(token);
            }
            continue;
          }
          if (token = this.tokenizer.link(src)) {
            src = src.substring(token.raw.length);
            tokens.push(token);
            continue;
          }
          if (token = this.tokenizer.reflink(src, this.tokens.links)) {
            src = src.substring(token.raw.length);
            lastToken = tokens[tokens.length - 1];
            if (lastToken && token.type === "text" && lastToken.type === "text") {
              lastToken.raw += token.raw;
              lastToken.text += token.text;
            } else {
              tokens.push(token);
            }
            continue;
          }
          if (token = this.tokenizer.emStrong(src, maskedSrc, prevChar)) {
            src = src.substring(token.raw.length);
            tokens.push(token);
            continue;
          }
          if (token = this.tokenizer.codespan(src)) {
            src = src.substring(token.raw.length);
            tokens.push(token);
            continue;
          }
          if (token = this.tokenizer.br(src)) {
            src = src.substring(token.raw.length);
            tokens.push(token);
            continue;
          }
          if (token = this.tokenizer.del(src)) {
            src = src.substring(token.raw.length);
            tokens.push(token);
            continue;
          }
          if (token = this.tokenizer.autolink(src, mangle)) {
            src = src.substring(token.raw.length);
            tokens.push(token);
            continue;
          }
          if (!this.state.inLink && (token = this.tokenizer.url(src, mangle))) {
            src = src.substring(token.raw.length);
            tokens.push(token);
            continue;
          }
          cutSrc = src;
          if (this.options.extensions && this.options.extensions.startInline) {
            (function() {
              var startIndex = Infinity;
              var tempSrc = src.slice(1);
              var tempStart = void 0;
              _this2.options.extensions.startInline.forEach(function(getStartIndex) {
                tempStart = getStartIndex.call({
                  lexer: this
                }, tempSrc);
                if (typeof tempStart === "number" && tempStart >= 0) {
                  startIndex = Math.min(startIndex, tempStart);
                }
              });
              if (startIndex < Infinity && startIndex >= 0) {
                cutSrc = src.substring(0, startIndex + 1);
              }
            })();
          }
          if (token = this.tokenizer.inlineText(cutSrc, smartypants)) {
            src = src.substring(token.raw.length);
            if (token.raw.slice(-1) !== "_") {
              prevChar = token.raw.slice(-1);
            }
            keepPrevChar = true;
            lastToken = tokens[tokens.length - 1];
            if (lastToken && lastToken.type === "text") {
              lastToken.raw += token.raw;
              lastToken.text += token.text;
            } else {
              tokens.push(token);
            }
            continue;
          }
          if (src) {
            var errMsg = "Infinite loop on byte: " + src.charCodeAt(0);
            if (this.options.silent) {
              console.error(errMsg);
              break;
            } else {
              throw new Error(errMsg);
            }
          }
        }
        return tokens;
      };
      _createClass(Lexer2, null, [{
        key: "rules",
        get: function get2() {
          return {
            block,
            inline
          };
        }
      }]);
      return Lexer2;
    }();
    var Renderer = /* @__PURE__ */ function() {
      function Renderer2(options2) {
        this.options = options2 || exports2.defaults;
      }
      var _proto = Renderer2.prototype;
      _proto.code = function code(_code, infostring, escaped) {
        var lang = (infostring || "").match(/\S*/)[0];
        if (this.options.highlight) {
          var out = this.options.highlight(_code, lang);
          if (out != null && out !== _code) {
            escaped = true;
            _code = out;
          }
        }
        _code = _code.replace(/\n$/, "") + "\n";
        if (!lang) {
          return "<pre><code>" + (escaped ? _code : escape2(_code, true)) + "</code></pre>\n";
        }
        return '<pre><code class="' + this.options.langPrefix + escape2(lang, true) + '">' + (escaped ? _code : escape2(_code, true)) + "</code></pre>\n";
      };
      _proto.blockquote = function blockquote(quote) {
        return "<blockquote>\n" + quote + "</blockquote>\n";
      };
      _proto.html = function html2(_html) {
        return _html;
      };
      _proto.heading = function heading(text2, level, raw, slugger) {
        if (this.options.headerIds) {
          var id3 = this.options.headerPrefix + slugger.slug(raw);
          return "<h" + level + ' id="' + id3 + '">' + text2 + "</h" + level + ">\n";
        }
        return "<h" + level + ">" + text2 + "</h" + level + ">\n";
      };
      _proto.hr = function hr() {
        return this.options.xhtml ? "<hr/>\n" : "<hr>\n";
      };
      _proto.list = function list2(body, ordered, start) {
        var type = ordered ? "ol" : "ul", startatt = ordered && start !== 1 ? ' start="' + start + '"' : "";
        return "<" + type + startatt + ">\n" + body + "</" + type + ">\n";
      };
      _proto.listitem = function listitem(text2) {
        return "<li>" + text2 + "</li>\n";
      };
      _proto.checkbox = function checkbox(checked2) {
        return "<input " + (checked2 ? 'checked="" ' : "") + 'disabled="" type="checkbox"' + (this.options.xhtml ? " /" : "") + "> ";
      };
      _proto.paragraph = function paragraph(text2) {
        return "<p>" + text2 + "</p>\n";
      };
      _proto.table = function table2(header, body) {
        if (body)
          body = "<tbody>" + body + "</tbody>";
        return "<table>\n<thead>\n" + header + "</thead>\n" + body + "</table>\n";
      };
      _proto.tablerow = function tablerow(content) {
        return "<tr>\n" + content + "</tr>\n";
      };
      _proto.tablecell = function tablecell(content, flags) {
        var type = flags.header ? "th" : "td";
        var tag3 = flags.align ? "<" + type + ' align="' + flags.align + '">' : "<" + type + ">";
        return tag3 + content + ("</" + type + ">\n");
      };
      _proto.strong = function strong(text2) {
        return "<strong>" + text2 + "</strong>";
      };
      _proto.em = function em(text2) {
        return "<em>" + text2 + "</em>";
      };
      _proto.codespan = function codespan(text2) {
        return "<code>" + text2 + "</code>";
      };
      _proto.br = function br() {
        return this.options.xhtml ? "<br/>" : "<br>";
      };
      _proto.del = function del2(text2) {
        return "<del>" + text2 + "</del>";
      };
      _proto.link = function link2(href, title2, text2) {
        href = cleanUrl(this.options.sanitize, this.options.baseUrl, href);
        if (href === null) {
          return text2;
        }
        var out = '<a href="' + escape2(href) + '"';
        if (title2) {
          out += ' title="' + title2 + '"';
        }
        out += ">" + text2 + "</a>";
        return out;
      };
      _proto.image = function image(href, title2, text2) {
        href = cleanUrl(this.options.sanitize, this.options.baseUrl, href);
        if (href === null) {
          return text2;
        }
        var out = '<img src="' + href + '" alt="' + text2 + '"';
        if (title2) {
          out += ' title="' + title2 + '"';
        }
        out += this.options.xhtml ? "/>" : ">";
        return out;
      };
      _proto.text = function text2(_text) {
        return _text;
      };
      return Renderer2;
    }();
    var TextRenderer = /* @__PURE__ */ function() {
      function TextRenderer2() {
      }
      var _proto = TextRenderer2.prototype;
      _proto.strong = function strong(text2) {
        return text2;
      };
      _proto.em = function em(text2) {
        return text2;
      };
      _proto.codespan = function codespan(text2) {
        return text2;
      };
      _proto.del = function del2(text2) {
        return text2;
      };
      _proto.html = function html2(text2) {
        return text2;
      };
      _proto.text = function text2(_text) {
        return _text;
      };
      _proto.link = function link2(href, title2, text2) {
        return "" + text2;
      };
      _proto.image = function image(href, title2, text2) {
        return "" + text2;
      };
      _proto.br = function br() {
        return "";
      };
      return TextRenderer2;
    }();
    var Slugger = /* @__PURE__ */ function() {
      function Slugger2() {
        this.seen = {};
      }
      var _proto = Slugger2.prototype;
      _proto.serialize = function serialize(value) {
        return value.toLowerCase().trim().replace(/<[!\/a-z].*?>/ig, "").replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g, "").replace(/\s/g, "-");
      };
      _proto.getNextSafeSlug = function getNextSafeSlug(originalSlug, isDryRun) {
        var slug = originalSlug;
        var occurenceAccumulator = 0;
        if (this.seen.hasOwnProperty(slug)) {
          occurenceAccumulator = this.seen[originalSlug];
          do {
            occurenceAccumulator++;
            slug = originalSlug + "-" + occurenceAccumulator;
          } while (this.seen.hasOwnProperty(slug));
        }
        if (!isDryRun) {
          this.seen[originalSlug] = occurenceAccumulator;
          this.seen[slug] = 0;
        }
        return slug;
      };
      _proto.slug = function slug(value, options2) {
        if (options2 === void 0) {
          options2 = {};
        }
        var slug2 = this.serialize(value);
        return this.getNextSafeSlug(slug2, options2.dryrun);
      };
      return Slugger2;
    }();
    var Parser6 = /* @__PURE__ */ function() {
      function Parser7(options2) {
        this.options = options2 || exports2.defaults;
        this.options.renderer = this.options.renderer || new Renderer();
        this.renderer = this.options.renderer;
        this.renderer.options = this.options;
        this.textRenderer = new TextRenderer();
        this.slugger = new Slugger();
      }
      Parser7.parse = function parse3(tokens, options2) {
        var parser3 = new Parser7(options2);
        return parser3.parse(tokens);
      };
      Parser7.parseInline = function parseInline2(tokens, options2) {
        var parser3 = new Parser7(options2);
        return parser3.parseInline(tokens);
      };
      var _proto = Parser7.prototype;
      _proto.parse = function parse3(tokens, top) {
        if (top === void 0) {
          top = true;
        }
        var out = "", i, j, k, l2, l3, row, cell, header, body, token, ordered, start, loose, itemBody, item, checked2, task, checkbox, ret;
        var l = tokens.length;
        for (i = 0; i < l; i++) {
          token = tokens[i];
          if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) {
            ret = this.options.extensions.renderers[token.type].call({
              parser: this
            }, token);
            if (ret !== false || !["space", "hr", "heading", "code", "table", "blockquote", "list", "html", "paragraph", "text"].includes(token.type)) {
              out += ret || "";
              continue;
            }
          }
          switch (token.type) {
            case "space": {
              continue;
            }
            case "hr": {
              out += this.renderer.hr();
              continue;
            }
            case "heading": {
              out += this.renderer.heading(this.parseInline(token.tokens), token.depth, unescape2(this.parseInline(token.tokens, this.textRenderer)), this.slugger);
              continue;
            }
            case "code": {
              out += this.renderer.code(token.text, token.lang, token.escaped);
              continue;
            }
            case "table": {
              header = "";
              cell = "";
              l2 = token.header.length;
              for (j = 0; j < l2; j++) {
                cell += this.renderer.tablecell(this.parseInline(token.header[j].tokens), {
                  header: true,
                  align: token.align[j]
                });
              }
              header += this.renderer.tablerow(cell);
              body = "";
              l2 = token.rows.length;
              for (j = 0; j < l2; j++) {
                row = token.rows[j];
                cell = "";
                l3 = row.length;
                for (k = 0; k < l3; k++) {
                  cell += this.renderer.tablecell(this.parseInline(row[k].tokens), {
                    header: false,
                    align: token.align[k]
                  });
                }
                body += this.renderer.tablerow(cell);
              }
              out += this.renderer.table(header, body);
              continue;
            }
            case "blockquote": {
              body = this.parse(token.tokens);
              out += this.renderer.blockquote(body);
              continue;
            }
            case "list": {
              ordered = token.ordered;
              start = token.start;
              loose = token.loose;
              l2 = token.items.length;
              body = "";
              for (j = 0; j < l2; j++) {
                item = token.items[j];
                checked2 = item.checked;
                task = item.task;
                itemBody = "";
                if (item.task) {
                  checkbox = this.renderer.checkbox(checked2);
                  if (loose) {
                    if (item.tokens.length > 0 && item.tokens[0].type === "paragraph") {
                      item.tokens[0].text = checkbox + " " + item.tokens[0].text;
                      if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === "text") {
                        item.tokens[0].tokens[0].text = checkbox + " " + item.tokens[0].tokens[0].text;
                      }
                    } else {
                      item.tokens.unshift({
                        type: "text",
                        text: checkbox
                      });
                    }
                  } else {
                    itemBody += checkbox;
                  }
                }
                itemBody += this.parse(item.tokens, loose);
                body += this.renderer.listitem(itemBody, task, checked2);
              }
              out += this.renderer.list(body, ordered, start);
              continue;
            }
            case "html": {
              out += this.renderer.html(token.text);
              continue;
            }
            case "paragraph": {
              out += this.renderer.paragraph(this.parseInline(token.tokens));
              continue;
            }
            case "text": {
              body = token.tokens ? this.parseInline(token.tokens) : token.text;
              while (i + 1 < l && tokens[i + 1].type === "text") {
                token = tokens[++i];
                body += "\n" + (token.tokens ? this.parseInline(token.tokens) : token.text);
              }
              out += top ? this.renderer.paragraph(body) : body;
              continue;
            }
            default: {
              var errMsg = 'Token with "' + token.type + '" type was not found.';
              if (this.options.silent) {
                console.error(errMsg);
                return;
              } else {
                throw new Error(errMsg);
              }
            }
          }
        }
        return out;
      };
      _proto.parseInline = function parseInline2(tokens, renderer2) {
        renderer2 = renderer2 || this.renderer;
        var out = "", i, token, ret;
        var l = tokens.length;
        for (i = 0; i < l; i++) {
          token = tokens[i];
          if (this.options.extensions && this.options.extensions.renderers && this.options.extensions.renderers[token.type]) {
            ret = this.options.extensions.renderers[token.type].call({
              parser: this
            }, token);
            if (ret !== false || !["escape", "html", "link", "image", "strong", "em", "codespan", "br", "del", "text"].includes(token.type)) {
              out += ret || "";
              continue;
            }
          }
          switch (token.type) {
            case "escape": {
              out += renderer2.text(token.text);
              break;
            }
            case "html": {
              out += renderer2.html(token.text);
              break;
            }
            case "link": {
              out += renderer2.link(token.href, token.title, this.parseInline(token.tokens, renderer2));
              break;
            }
            case "image": {
              out += renderer2.image(token.href, token.title, token.text);
              break;
            }
            case "strong": {
              out += renderer2.strong(this.parseInline(token.tokens, renderer2));
              break;
            }
            case "em": {
              out += renderer2.em(this.parseInline(token.tokens, renderer2));
              break;
            }
            case "codespan": {
              out += renderer2.codespan(token.text);
              break;
            }
            case "br": {
              out += renderer2.br();
              break;
            }
            case "del": {
              out += renderer2.del(this.parseInline(token.tokens, renderer2));
              break;
            }
            case "text": {
              out += renderer2.text(token.text);
              break;
            }
            default: {
              var errMsg = 'Token with "' + token.type + '" type was not found.';
              if (this.options.silent) {
                console.error(errMsg);
                return;
              } else {
                throw new Error(errMsg);
              }
            }
          }
        }
        return out;
      };
      return Parser7;
    }();
    function marked2(src, opt, callback) {
      if (typeof src === "undefined" || src === null) {
        throw new Error("marked(): input parameter is undefined or null");
      }
      if (typeof src !== "string") {
        throw new Error("marked(): input parameter is of type " + Object.prototype.toString.call(src) + ", string expected");
      }
      if (typeof opt === "function") {
        callback = opt;
        opt = null;
      }
      opt = merge2({}, marked2.defaults, opt || {});
      checkSanitizeDeprecation(opt);
      if (callback) {
        var highlight = opt.highlight;
        var tokens;
        try {
          tokens = Lexer.lex(src, opt);
        } catch (e) {
          return callback(e);
        }
        var done = function done2(err) {
          var out;
          if (!err) {
            try {
              if (opt.walkTokens) {
                marked2.walkTokens(tokens, opt.walkTokens);
              }
              out = Parser6.parse(tokens, opt);
            } catch (e) {
              err = e;
            }
          }
          opt.highlight = highlight;
          return err ? callback(err) : callback(null, out);
        };
        if (!highlight || highlight.length < 3) {
          return done();
        }
        delete opt.highlight;
        if (!tokens.length)
          return done();
        var pending = 0;
        marked2.walkTokens(tokens, function(token) {
          if (token.type === "code") {
            pending++;
            setTimeout(function() {
              highlight(token.text, token.lang, function(err, code) {
                if (err) {
                  return done(err);
                }
                if (code != null && code !== token.text) {
                  token.text = code;
                  token.escaped = true;
                }
                pending--;
                if (pending === 0) {
                  done();
                }
              });
            }, 0);
          }
        });
        if (pending === 0) {
          done();
        }
        return;
      }
      function onError(e) {
        e.message += "\nPlease report this to https://github.com/markedjs/marked.";
        if (opt.silent) {
          return "<p>An error occurred:</p><pre>" + escape2(e.message + "", true) + "</pre>";
        }
        throw e;
      }
      try {
        var _tokens = Lexer.lex(src, opt);
        if (opt.walkTokens) {
          if (opt.async) {
            return Promise.all(marked2.walkTokens(_tokens, opt.walkTokens)).then(function() {
              return Parser6.parse(_tokens, opt);
            })["catch"](onError);
          }
          marked2.walkTokens(_tokens, opt.walkTokens);
        }
        return Parser6.parse(_tokens, opt);
      } catch (e) {
        onError(e);
      }
    }
    marked2.options = marked2.setOptions = function(opt) {
      merge2(marked2.defaults, opt);
      changeDefaults(marked2.defaults);
      return marked2;
    };
    marked2.getDefaults = getDefaults;
    marked2.defaults = exports2.defaults;
    marked2.use = function() {
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }
      var opts = merge2.apply(void 0, [{}].concat(args));
      var extensions = marked2.defaults.extensions || {
        renderers: {},
        childTokens: {}
      };
      var hasExtensions;
      args.forEach(function(pack) {
        if (pack.extensions) {
          hasExtensions = true;
          pack.extensions.forEach(function(ext) {
            if (!ext.name) {
              throw new Error("extension name required");
            }
            if (ext.renderer) {
              var prevRenderer = extensions.renderers ? extensions.renderers[ext.name] : null;
              if (prevRenderer) {
                extensions.renderers[ext.name] = function() {
                  for (var _len2 = arguments.length, args2 = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
                    args2[_key2] = arguments[_key2];
                  }
                  var ret = ext.renderer.apply(this, args2);
                  if (ret === false) {
                    ret = prevRenderer.apply(this, args2);
                  }
                  return ret;
                };
              } else {
                extensions.renderers[ext.name] = ext.renderer;
              }
            }
            if (ext.tokenizer) {
              if (!ext.level || ext.level !== "block" && ext.level !== "inline") {
                throw new Error("extension level must be 'block' or 'inline'");
              }
              if (extensions[ext.level]) {
                extensions[ext.level].unshift(ext.tokenizer);
              } else {
                extensions[ext.level] = [ext.tokenizer];
              }
              if (ext.start) {
                if (ext.level === "block") {
                  if (extensions.startBlock) {
                    extensions.startBlock.push(ext.start);
                  } else {
                    extensions.startBlock = [ext.start];
                  }
                } else if (ext.level === "inline") {
                  if (extensions.startInline) {
                    extensions.startInline.push(ext.start);
                  } else {
                    extensions.startInline = [ext.start];
                  }
                }
              }
            }
            if (ext.childTokens) {
              extensions.childTokens[ext.name] = ext.childTokens;
            }
          });
        }
        if (pack.renderer) {
          (function() {
            var renderer2 = marked2.defaults.renderer || new Renderer();
            var _loop = function _loop2(prop2) {
              var prevRenderer = renderer2[prop2];
              renderer2[prop2] = function() {
                for (var _len3 = arguments.length, args2 = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
                  args2[_key3] = arguments[_key3];
                }
                var ret = pack.renderer[prop2].apply(renderer2, args2);
                if (ret === false) {
                  ret = prevRenderer.apply(renderer2, args2);
                }
                return ret;
              };
            };
            for (var prop in pack.renderer) {
              _loop(prop);
            }
            opts.renderer = renderer2;
          })();
        }
        if (pack.tokenizer) {
          (function() {
            var tokenizer3 = marked2.defaults.tokenizer || new Tokenizer2();
            var _loop2 = function _loop22(prop2) {
              var prevTokenizer = tokenizer3[prop2];
              tokenizer3[prop2] = function() {
                for (var _len4 = arguments.length, args2 = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
                  args2[_key4] = arguments[_key4];
                }
                var ret = pack.tokenizer[prop2].apply(tokenizer3, args2);
                if (ret === false) {
                  ret = prevTokenizer.apply(tokenizer3, args2);
                }
                return ret;
              };
            };
            for (var prop in pack.tokenizer) {
              _loop2(prop);
            }
            opts.tokenizer = tokenizer3;
          })();
        }
        if (pack.walkTokens) {
          var _walkTokens = marked2.defaults.walkTokens;
          opts.walkTokens = function(token) {
            var values = [];
            values.push(pack.walkTokens.call(this, token));
            if (_walkTokens) {
              values = values.concat(_walkTokens.call(this, token));
            }
            return values;
          };
        }
        if (hasExtensions) {
          opts.extensions = extensions;
        }
        marked2.setOptions(opts);
      });
    };
    marked2.walkTokens = function(tokens, callback) {
      var values = [];
      var _loop3 = function _loop32() {
        var token = _step.value;
        values = values.concat(callback.call(marked2, token));
        switch (token.type) {
          case "table": {
            for (var _iterator2 = _createForOfIteratorHelperLoose(token.header), _step2; !(_step2 = _iterator2()).done; ) {
              var cell = _step2.value;
              values = values.concat(marked2.walkTokens(cell.tokens, callback));
            }
            for (var _iterator3 = _createForOfIteratorHelperLoose(token.rows), _step3; !(_step3 = _iterator3()).done; ) {
              var row = _step3.value;
              for (var _iterator4 = _createForOfIteratorHelperLoose(row), _step4; !(_step4 = _iterator4()).done; ) {
                var _cell = _step4.value;
                values = values.concat(marked2.walkTokens(_cell.tokens, callback));
              }
            }
            break;
          }
          case "list": {
            values = values.concat(marked2.walkTokens(token.items, callback));
            break;
          }
          default: {
            if (marked2.defaults.extensions && marked2.defaults.extensions.childTokens && marked2.defaults.extensions.childTokens[token.type]) {
              marked2.defaults.extensions.childTokens[token.type].forEach(function(childTokens) {
                values = values.concat(marked2.walkTokens(token[childTokens], callback));
              });
            } else if (token.tokens) {
              values = values.concat(marked2.walkTokens(token.tokens, callback));
            }
          }
        }
      };
      for (var _iterator = _createForOfIteratorHelperLoose(tokens), _step; !(_step = _iterator()).done; ) {
        _loop3();
      }
      return values;
    };
    marked2.parseInline = function(src, opt) {
      if (typeof src === "undefined" || src === null) {
        throw new Error("marked.parseInline(): input parameter is undefined or null");
      }
      if (typeof src !== "string") {
        throw new Error("marked.parseInline(): input parameter is of type " + Object.prototype.toString.call(src) + ", string expected");
      }
      opt = merge2({}, marked2.defaults, opt || {});
      checkSanitizeDeprecation(opt);
      try {
        var tokens = Lexer.lexInline(src, opt);
        if (opt.walkTokens) {
          marked2.walkTokens(tokens, opt.walkTokens);
        }
        return Parser6.parseInline(tokens, opt);
      } catch (e) {
        e.message += "\nPlease report this to https://github.com/markedjs/marked.";
        if (opt.silent) {
          return "<p>An error occurred:</p><pre>" + escape2(e.message + "", true) + "</pre>";
        }
        throw e;
      }
    };
    marked2.Parser = Parser6;
    marked2.parser = Parser6.parse;
    marked2.Renderer = Renderer;
    marked2.TextRenderer = TextRenderer;
    marked2.Lexer = Lexer;
    marked2.lexer = Lexer.lex;
    marked2.Tokenizer = Tokenizer2;
    marked2.Slugger = Slugger;
    marked2.parse = marked2;
    var options = marked2.options;
    var setOptions = marked2.setOptions;
    var use = marked2.use;
    var walkTokens = marked2.walkTokens;
    var parseInline = marked2.parseInline;
    var parse2 = marked2;
    var parser2 = Parser6.parse;
    var lexer = Lexer.lex;
    exports2.Lexer = Lexer;
    exports2.Parser = Parser6;
    exports2.Renderer = Renderer;
    exports2.Slugger = Slugger;
    exports2.TextRenderer = TextRenderer;
    exports2.Tokenizer = Tokenizer2;
    exports2.getDefaults = getDefaults;
    exports2.lexer = lexer;
    exports2.marked = marked2;
    exports2.options = options;
    exports2.parse = parse2;
    exports2.parseInline = parseInline;
    exports2.parser = parser2;
    exports2.setOptions = setOptions;
    exports2.use = use;
    exports2.walkTokens = walkTokens;
    Object.defineProperty(exports2, "__esModule", { value: true });
  });
})();
__marked_exports.Lexer || exports.Lexer;
__marked_exports.Parser || exports.Parser;
__marked_exports.Renderer || exports.Renderer;
__marked_exports.Slugger || exports.Slugger;
__marked_exports.TextRenderer || exports.TextRenderer;
__marked_exports.Tokenizer || exports.Tokenizer;
__marked_exports.getDefaults || exports.getDefaults;
__marked_exports.lexer || exports.lexer;
var marked = __marked_exports.marked || exports.marked;
__marked_exports.options || exports.options;
__marked_exports.parse || exports.parse;
__marked_exports.parseInline || exports.parseInline;
__marked_exports.parser || exports.parser;
__marked_exports.setOptions || exports.setOptions;
__marked_exports.use || exports.use;
__marked_exports.walkTokens || exports.walkTokens;
function stringify$6(obj) {
  return JSON.stringify(obj, replacer$1);
}
function parse$b(text2) {
  let data = JSON.parse(text2);
  data = revive(data);
  return data;
}
function replacer$1(key, value) {
  if (value instanceof RegExp) {
    return {
      $mid: 2,
      source: value.source,
      flags: regExpFlags(value)
    };
  }
  return value;
}
function revive(obj, depth = 0) {
  if (!obj || depth > 200) {
    return obj;
  }
  if (typeof obj === "object") {
    switch (obj.$mid) {
      case 1:
        return URI.revive(obj);
      case 2:
        return new RegExp(obj.source, obj.flags);
      case 16:
        return new Date(obj.source);
    }
    if (obj instanceof VSBuffer || obj instanceof Uint8Array) {
      return obj;
    }
    if (Array.isArray(obj)) {
      for (let i = 0; i < obj.length; ++i) {
        obj[i] = revive(obj[i], depth + 1);
      }
    } else {
      for (const key in obj) {
        if (Object.hasOwnProperty.call(obj, key)) {
          obj[key] = revive(obj[key], depth + 1);
        }
      }
    }
  }
  return obj;
}
const defaultMarkedRenderers = Object.freeze({
  image: (href, title2, text2) => {
    let dimensions = [];
    let attributes = [];
    if (href) {
      ({ href, dimensions } = parseHrefAndDimensions(href));
      attributes.push(`src="${escapeDoubleQuotes(href)}"`);
    }
    if (text2) {
      attributes.push(`alt="${escapeDoubleQuotes(text2)}"`);
    }
    if (title2) {
      attributes.push(`title="${escapeDoubleQuotes(title2)}"`);
    }
    if (dimensions.length) {
      attributes = attributes.concat(dimensions);
    }
    return "<img " + attributes.join(" ") + ">";
  },
  paragraph: (text2) => {
    return `<p>${text2}</p>`;
  },
  link: (href, title2, text2) => {
    if (typeof href !== "string") {
      return "";
    }
    if (href === text2) {
      text2 = removeMarkdownEscapes(text2);
    }
    title2 = typeof title2 === "string" ? escapeDoubleQuotes(removeMarkdownEscapes(title2)) : "";
    href = removeMarkdownEscapes(href);
    href = href.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
    return `<a href="${href}" title="${title2 || href}">${text2}</a>`;
  }
});
function renderMarkdown(markdown, options = {}, markedOptions = {}) {
  var _a2, _b2;
  const disposables = new DisposableStore();
  let isDisposed = false;
  const element = createElement(options);
  const _uriMassage = function(part) {
    let data;
    try {
      data = parse$b(decodeURIComponent(part));
    } catch (e) {
    }
    if (!data) {
      return part;
    }
    data = cloneAndChange(data, (value2) => {
      if (markdown.uris && markdown.uris[value2]) {
        return URI.revive(markdown.uris[value2]);
      } else {
        return void 0;
      }
    });
    return encodeURIComponent(JSON.stringify(data));
  };
  const _href = function(href, isDomUri) {
    const data = markdown.uris && markdown.uris[href];
    let uri = URI.revive(data);
    if (isDomUri) {
      if (href.startsWith(Schemas.data + ":")) {
        return href;
      }
      if (!uri) {
        uri = URI.parse(href);
      }
      return FileAccess.uriToBrowserUri(uri).toString(true);
    }
    if (!uri) {
      return href;
    }
    if (URI.parse(href).toString() === uri.toString()) {
      return href;
    }
    if (uri.query) {
      uri = uri.with({ query: _uriMassage(uri.query) });
    }
    return uri.toString();
  };
  const renderer2 = new marked.Renderer();
  renderer2.image = defaultMarkedRenderers.image;
  renderer2.link = defaultMarkedRenderers.link;
  renderer2.paragraph = defaultMarkedRenderers.paragraph;
  const codeBlocks = [];
  const syncCodeBlocks = [];
  if (options.codeBlockRendererSync) {
    renderer2.code = (code, lang) => {
      const id3 = defaultGenerator.nextId();
      const value2 = options.codeBlockRendererSync(postProcessCodeBlockLanguageId(lang), code);
      syncCodeBlocks.push([id3, value2]);
      return `<div class="code" data-code="${id3}">${escape$1(code)}</div>`;
    };
  } else if (options.codeBlockRenderer) {
    renderer2.code = (code, lang) => {
      const id3 = defaultGenerator.nextId();
      const value2 = options.codeBlockRenderer(postProcessCodeBlockLanguageId(lang), code);
      codeBlocks.push(value2.then((element2) => [id3, element2]));
      return `<div class="code" data-code="${id3}">${escape$1(code)}</div>`;
    };
  }
  if (options.actionHandler) {
    const _activateLink = function(event) {
      let target = event.target;
      if (target.tagName !== "A") {
        target = target.parentElement;
        if (!target || target.tagName !== "A") {
          return;
        }
      }
      try {
        let href = target.dataset["href"];
        if (href) {
          if (markdown.baseUri) {
            href = resolveWithBaseUri(URI.from(markdown.baseUri), href);
          }
          options.actionHandler.callback(href, event);
        }
      } catch (err) {
        onUnexpectedError(err);
      } finally {
        event.preventDefault();
      }
    };
    const onClick = options.actionHandler.disposables.add(new DomEmitter(element, "click"));
    const onAuxClick = options.actionHandler.disposables.add(new DomEmitter(element, "auxclick"));
    options.actionHandler.disposables.add(Event$1.any(onClick.event, onAuxClick.event)((e) => {
      const mouseEvent = new StandardMouseEvent(e);
      if (!mouseEvent.leftButton && !mouseEvent.middleButton) {
        return;
      }
      _activateLink(mouseEvent);
    }));
    options.actionHandler.disposables.add(addDisposableListener(element, "keydown", (e) => {
      const keyboardEvent = new StandardKeyboardEvent(e);
      if (!keyboardEvent.equals(
        10
        /* KeyCode.Space */
      ) && !keyboardEvent.equals(
        3
        /* KeyCode.Enter */
      )) {
        return;
      }
      _activateLink(keyboardEvent);
    }));
  }
  if (!markdown.supportHtml) {
    markedOptions.sanitizer = (html2) => {
      const match2 = markdown.isTrusted ? html2.match(/^(<span[^>]+>)|(<\/\s*span>)$/) : void 0;
      return match2 ? html2 : "";
    };
    markedOptions.sanitize = true;
    markedOptions.silent = true;
  }
  markedOptions.renderer = renderer2;
  let value = (_a2 = markdown.value) !== null && _a2 !== void 0 ? _a2 : "";
  if (value.length > 1e5) {
    value = `${value.substr(0, 1e5)}…`;
  }
  if (markdown.supportThemeIcons) {
    value = markdownEscapeEscapedIcons(value);
  }
  let renderedMarkdown2;
  if (options.fillInIncompleteTokens) {
    const opts = Object.assign(Object.assign({}, marked.defaults), markedOptions);
    const tokens = marked.lexer(value, opts);
    const newTokens = fillInIncompleteTokens(tokens);
    renderedMarkdown2 = marked.parser(newTokens, opts);
  } else {
    renderedMarkdown2 = marked.parse(value, markedOptions);
  }
  if (markdown.supportThemeIcons) {
    const elements = renderLabelWithIcons(renderedMarkdown2);
    renderedMarkdown2 = elements.map((e) => typeof e === "string" ? e : e.outerHTML).join("");
  }
  const htmlParser = new DOMParser();
  const markdownHtmlDoc = htmlParser.parseFromString(sanitizeRenderedMarkdown(markdown, renderedMarkdown2), "text/html");
  markdownHtmlDoc.body.querySelectorAll("img").forEach((img) => {
    const src = img.getAttribute("src");
    if (src) {
      let href = src;
      try {
        if (markdown.baseUri) {
          href = resolveWithBaseUri(URI.from(markdown.baseUri), href);
        }
      } catch (err) {
      }
      img.src = _href(href, true);
    }
  });
  markdownHtmlDoc.body.querySelectorAll("a").forEach((a) => {
    const href = a.getAttribute("href");
    a.setAttribute("href", "");
    if (!href || /^data:|javascript:/i.test(href) || /^command:/i.test(href) && !markdown.isTrusted || /^command:(\/\/\/)?_workbench\.downloadResource/i.test(href)) {
      a.replaceWith(...a.childNodes);
    } else {
      let resolvedHref = _href(href, false);
      if (markdown.baseUri) {
        resolvedHref = resolveWithBaseUri(URI.from(markdown.baseUri), href);
      }
      a.dataset.href = resolvedHref;
    }
  });
  element.innerHTML = sanitizeRenderedMarkdown(markdown, markdownHtmlDoc.body.innerHTML);
  if (codeBlocks.length > 0) {
    Promise.all(codeBlocks).then((tuples) => {
      var _a3, _b3;
      if (isDisposed) {
        return;
      }
      const renderedElements = new Map(tuples);
      const placeholderElements = element.querySelectorAll(`div[data-code]`);
      for (const placeholderElement of placeholderElements) {
        const renderedElement = renderedElements.get((_a3 = placeholderElement.dataset["code"]) !== null && _a3 !== void 0 ? _a3 : "");
        if (renderedElement) {
          reset(placeholderElement, renderedElement);
        }
      }
      (_b3 = options.asyncRenderCallback) === null || _b3 === void 0 ? void 0 : _b3.call(options);
    });
  } else if (syncCodeBlocks.length > 0) {
    const renderedElements = new Map(syncCodeBlocks);
    const placeholderElements = element.querySelectorAll(`div[data-code]`);
    for (const placeholderElement of placeholderElements) {
      const renderedElement = renderedElements.get((_b2 = placeholderElement.dataset["code"]) !== null && _b2 !== void 0 ? _b2 : "");
      if (renderedElement) {
        reset(placeholderElement, renderedElement);
      }
    }
  }
  if (options.asyncRenderCallback) {
    for (const img of element.getElementsByTagName("img")) {
      const listener = disposables.add(addDisposableListener(img, "load", () => {
        listener.dispose();
        options.asyncRenderCallback();
      }));
    }
  }
  return {
    element,
    dispose: () => {
      isDisposed = true;
      disposables.dispose();
    }
  };
}
function postProcessCodeBlockLanguageId(lang) {
  if (!lang) {
    return "";
  }
  const parts = lang.split(/[\s+|:|,|\{|\?]/, 1);
  if (parts.length) {
    return parts[0];
  }
  return lang;
}
function resolveWithBaseUri(baseUri, href) {
  const hasScheme = /^\w[\w\d+.-]*:/.test(href);
  if (hasScheme) {
    return href;
  }
  if (baseUri.path.endsWith("/")) {
    return resolvePath(baseUri, href).toString();
  } else {
    return resolvePath(dirname$3(baseUri), href).toString();
  }
}
function sanitizeRenderedMarkdown(options, renderedMarkdown2) {
  const { config: config2, allowedSchemes } = getSanitizerOptions(options);
  addHook("uponSanitizeAttribute", (element, e) => {
    if (e.attrName === "style" || e.attrName === "class") {
      if (element.tagName === "SPAN") {
        if (e.attrName === "style") {
          e.keepAttr = /^(color\:(#[0-9a-fA-F]+|var\(--vscode(-[a-zA-Z]+)+\));)?(background-color\:(#[0-9a-fA-F]+|var\(--vscode(-[a-zA-Z]+)+\));)?$/.test(e.attrValue);
          return;
        } else if (e.attrName === "class") {
          e.keepAttr = /^codicon codicon-[a-z\-]+( codicon-modifier-[a-z\-]+)?$/.test(e.attrValue);
          return;
        }
      }
      e.keepAttr = false;
      return;
    }
  });
  const hook = hookDomPurifyHrefAndSrcSanitizer(allowedSchemes);
  try {
    return sanitize$1(renderedMarkdown2, Object.assign(Object.assign({}, config2), { RETURN_TRUSTED_TYPE: true }));
  } finally {
    removeHook("uponSanitizeAttribute");
    hook.dispose();
  }
}
const allowedMarkdownAttr = [
  "align",
  "autoplay",
  "alt",
  "class",
  "controls",
  "data-code",
  "data-href",
  "height",
  "href",
  "loop",
  "muted",
  "playsinline",
  "poster",
  "src",
  "style",
  "target",
  "title",
  "width",
  "start"
];
function getSanitizerOptions(options) {
  const allowedSchemes = [
    Schemas.http,
    Schemas.https,
    Schemas.mailto,
    Schemas.data,
    Schemas.file,
    Schemas.vscodeFileResource,
    Schemas.vscodeRemote,
    Schemas.vscodeRemoteResource
  ];
  if (options.isTrusted) {
    allowedSchemes.push(Schemas.command);
  }
  return {
    config: {
      // allowedTags should included everything that markdown renders to.
      // Since we have our own sanitize function for marked, it's possible we missed some tag so let dompurify make sure.
      // HTML tags that can result from markdown are from reading https://spec.commonmark.org/0.29/
      // HTML table tags that can result from markdown are from https://github.github.com/gfm/#tables-extension-
      ALLOWED_TAGS: [...basicMarkupHtmlTags],
      ALLOWED_ATTR: allowedMarkdownAttr,
      ALLOW_UNKNOWN_PROTOCOLS: true
    },
    allowedSchemes
  };
}
function renderStringAsPlaintext(string3) {
  return typeof string3 === "string" ? string3 : renderMarkdownAsPlaintext(string3);
}
function renderMarkdownAsPlaintext(markdown) {
  var _a2;
  let value = (_a2 = markdown.value) !== null && _a2 !== void 0 ? _a2 : "";
  if (value.length > 1e5) {
    value = `${value.substr(0, 1e5)}…`;
  }
  const html2 = marked.parse(value, { renderer: plainTextRenderer.value }).replace(/&(#\d+|[a-zA-Z]+);/g, (m) => {
    var _a3;
    return (_a3 = unescapeInfo.get(m)) !== null && _a3 !== void 0 ? _a3 : m;
  });
  return sanitizeRenderedMarkdown({ isTrusted: false }, html2).toString();
}
const unescapeInfo = /* @__PURE__ */ new Map([
  ["&quot;", '"'],
  ["&nbsp;", " "],
  ["&amp;", "&"],
  ["&#39;", "'"],
  ["&lt;", "<"],
  ["&gt;", ">"]
]);
const plainTextRenderer = new Lazy(() => {
  const renderer2 = new marked.Renderer();
  renderer2.code = (code) => {
    return code;
  };
  renderer2.blockquote = (quote) => {
    return quote;
  };
  renderer2.html = (_html) => {
    return "";
  };
  renderer2.heading = (text2, _level, _raw) => {
    return text2 + "\n";
  };
  renderer2.hr = () => {
    return "";
  };
  renderer2.list = (body, _ordered) => {
    return body;
  };
  renderer2.listitem = (text2) => {
    return text2 + "\n";
  };
  renderer2.paragraph = (text2) => {
    return text2 + "\n";
  };
  renderer2.table = (header, body) => {
    return header + body + "\n";
  };
  renderer2.tablerow = (content) => {
    return content;
  };
  renderer2.tablecell = (content, _flags) => {
    return content + " ";
  };
  renderer2.strong = (text2) => {
    return text2;
  };
  renderer2.em = (text2) => {
    return text2;
  };
  renderer2.codespan = (code) => {
    return code;
  };
  renderer2.br = () => {
    return "\n";
  };
  renderer2.del = (text2) => {
    return text2;
  };
  renderer2.image = (_href, _title, _text) => {
    return "";
  };
  renderer2.text = (text2) => {
    return text2;
  };
  renderer2.link = (_href, _title, text2) => {
    return text2;
  };
  return renderer2;
});
function mergeRawTokenText(tokens) {
  let mergedTokenText = "";
  tokens.forEach((token) => {
    mergedTokenText += token.raw;
  });
  return mergedTokenText;
}
function completeSingleLinePattern(token) {
  for (const subtoken of token.tokens) {
    if (subtoken.type === "text") {
      const lines = subtoken.raw.split("\n");
      const lastLine = lines[lines.length - 1];
      if (lastLine.includes("`")) {
        return completeCodespan(token);
      } else if (lastLine.includes("**")) {
        return completeDoublestar(token);
      } else if (lastLine.match(/\*\w/)) {
        return completeStar(token);
      } else if (lastLine.match(/(^|\s)__\w/)) {
        return completeDoubleUnderscore(token);
      } else if (lastLine.match(/(^|\s)_\w/)) {
        return completeUnderscore(token);
      } else if (lastLine.match(/(^|\s)\[.*\]\(\w*/)) {
        return completeLinkTarget(token);
      } else if (lastLine.match(/(^|\s)\[\w/)) {
        return completeLinkText(token);
      }
    }
  }
  return void 0;
}
function fillInIncompleteTokens(tokens) {
  let i;
  let newTokens;
  for (i = 0; i < tokens.length; i++) {
    const token = tokens[i];
    if (token.type === "paragraph" && token.raw.match(/(\n|^)```/)) {
      newTokens = completeCodeBlock(tokens.slice(i));
      break;
    }
    if (token.type === "paragraph" && token.raw.match(/(\n|^)\|/)) {
      newTokens = completeTable(tokens.slice(i));
      break;
    }
    if (i === tokens.length - 1 && token.type === "paragraph") {
      const newToken = completeSingleLinePattern(token);
      if (newToken) {
        newTokens = [newToken];
        break;
      }
    }
  }
  if (newTokens) {
    const newTokensList = [
      ...tokens.slice(0, i),
      ...newTokens
    ];
    newTokensList.links = tokens.links;
    return newTokensList;
  }
  return tokens;
}
function completeCodeBlock(tokens) {
  const mergedRawText = mergeRawTokenText(tokens);
  return marked.lexer(mergedRawText + "\n```");
}
function completeCodespan(token) {
  return completeWithString(token, "`");
}
function completeStar(tokens) {
  return completeWithString(tokens, "*");
}
function completeUnderscore(tokens) {
  return completeWithString(tokens, "_");
}
function completeLinkTarget(tokens) {
  return completeWithString(tokens, ")");
}
function completeLinkText(tokens) {
  return completeWithString(tokens, "](about:blank)");
}
function completeDoublestar(tokens) {
  return completeWithString(tokens, "**");
}
function completeDoubleUnderscore(tokens) {
  return completeWithString(tokens, "__");
}
function completeWithString(tokens, closingString) {
  const mergedRawText = mergeRawTokenText(Array.isArray(tokens) ? tokens : [tokens]);
  return marked.lexer(mergedRawText + closingString)[0];
}
function completeTable(tokens) {
  const mergedRawText = mergeRawTokenText(tokens);
  const lines = mergedRawText.split("\n");
  let numCols;
  let hasSeparatorRow = false;
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i].trim();
    if (typeof numCols === "undefined" && line.match(/^\s*\|/)) {
      const line1Matches = line.match(/(\|[^\|]+)(?=\||$)/g);
      if (line1Matches) {
        numCols = line1Matches.length;
      }
    } else if (typeof numCols === "number") {
      if (line.match(/^\s*\|/)) {
        if (i !== lines.length - 1) {
          return void 0;
        }
        hasSeparatorRow = true;
      } else {
        return void 0;
      }
    }
  }
  if (typeof numCols === "number" && numCols > 0) {
    const prefixText = hasSeparatorRow ? lines.slice(0, -1).join("\n") : mergedRawText;
    const line1EndsInPipe = !!prefixText.match(/\|\s*$/);
    const newRawText = prefixText + (line1EndsInPipe ? "" : "|") + `
|${" --- |".repeat(numCols)}`;
    return marked.lexer(newRawText);
  }
  return void 0;
}
class CombinedSpliceable {
  constructor(spliceables) {
    this.spliceables = spliceables;
  }
  splice(start, deleteCount, elements) {
    this.spliceables.forEach((s) => s.splice(start, deleteCount, elements));
  }
}
function clamp(value, min, max) {
  return Math.min(Math.max(value, min), max);
}
class MovingAverage {
  constructor() {
    this._n = 1;
    this._val = 0;
  }
  update(value) {
    this._val = this._val + (value - this._val) / this._n;
    this._n += 1;
    return this._val;
  }
  get value() {
    return this._val;
  }
}
class SlidingWindowAverage {
  constructor(size2) {
    this._n = 0;
    this._val = 0;
    this._values = [];
    this._index = 0;
    this._sum = 0;
    this._values = new Array(size2);
    this._values.fill(0, 0, size2);
  }
  update(value) {
    const oldValue = this._values[this._index];
    this._values[this._index] = value;
    this._index = (this._index + 1) % this._values.length;
    this._sum -= oldValue;
    this._sum += value;
    if (this._n < this._values.length) {
      this._n += 1;
    }
    this._val = this._sum / this._n;
    return this._val;
  }
  get value() {
    return this._val;
  }
}
const list$3 = "";
class ListError extends Error {
  constructor(user, message) {
    super(`ListError [${user}] ${message}`);
  }
}
var Range$1;
(function(Range3) {
  function intersect(one, other) {
    if (one.start >= other.end || other.start >= one.end) {
      return { start: 0, end: 0 };
    }
    const start = Math.max(one.start, other.start);
    const end = Math.min(one.end, other.end);
    if (end - start <= 0) {
      return { start: 0, end: 0 };
    }
    return { start, end };
  }
  Range3.intersect = intersect;
  function isEmpty2(range2) {
    return range2.end - range2.start <= 0;
  }
  Range3.isEmpty = isEmpty2;
  function intersects2(one, other) {
    return !isEmpty2(intersect(one, other));
  }
  Range3.intersects = intersects2;
  function relativeComplement2(one, other) {
    const result2 = [];
    const first2 = { start: one.start, end: Math.min(other.start, one.end) };
    const second = { start: Math.max(other.end, one.start), end: one.end };
    if (!isEmpty2(first2)) {
      result2.push(first2);
    }
    if (!isEmpty2(second)) {
      result2.push(second);
    }
    return result2;
  }
  Range3.relativeComplement = relativeComplement2;
})(Range$1 || (Range$1 = {}));
function groupIntersect(range2, groups) {
  const result2 = [];
  for (const r of groups) {
    if (range2.start >= r.range.end) {
      continue;
    }
    if (range2.end < r.range.start) {
      break;
    }
    const intersection = Range$1.intersect(range2, r.range);
    if (Range$1.isEmpty(intersection)) {
      continue;
    }
    result2.push({
      range: intersection,
      size: r.size
    });
  }
  return result2;
}
function shift({ start, end }, much) {
  return { start: start + much, end: end + much };
}
function consolidate(groups) {
  const result2 = [];
  let previousGroup = null;
  for (const group2 of groups) {
    const start = group2.range.start;
    const end = group2.range.end;
    const size2 = group2.size;
    if (previousGroup && size2 === previousGroup.size) {
      previousGroup.range.end = end;
      continue;
    }
    previousGroup = { range: { start, end }, size: size2 };
    result2.push(previousGroup);
  }
  return result2;
}
function concat(...groups) {
  return consolidate(groups.reduce((r, g) => r.concat(g), []));
}
class RangeMap {
  get paddingTop() {
    return this._paddingTop;
  }
  set paddingTop(paddingTop) {
    this._size = this._size + paddingTop - this._paddingTop;
    this._paddingTop = paddingTop;
  }
  constructor(topPadding) {
    this.groups = [];
    this._size = 0;
    this._paddingTop = 0;
    this._paddingTop = topPadding !== null && topPadding !== void 0 ? topPadding : 0;
    this._size = this._paddingTop;
  }
  splice(index, deleteCount, items = []) {
    const diff = items.length - deleteCount;
    const before = groupIntersect({ start: 0, end: index }, this.groups);
    const after = groupIntersect({ start: index + deleteCount, end: Number.POSITIVE_INFINITY }, this.groups).map((g) => ({ range: shift(g.range, diff), size: g.size }));
    const middle = items.map((item, i) => ({
      range: { start: index + i, end: index + i + 1 },
      size: item.size
    }));
    this.groups = concat(before, middle, after);
    this._size = this._paddingTop + this.groups.reduce((t, g) => t + g.size * (g.range.end - g.range.start), 0);
  }
  /**
   * Returns the number of items in the range map.
   */
  get count() {
    const len = this.groups.length;
    if (!len) {
      return 0;
    }
    return this.groups[len - 1].range.end;
  }
  /**
   * Returns the sum of the sizes of all items in the range map.
   */
  get size() {
    return this._size;
  }
  /**
   * Returns the index of the item at the given position.
   */
  indexAt(position) {
    if (position < 0) {
      return -1;
    }
    if (position < this._paddingTop) {
      return 0;
    }
    let index = 0;
    let size2 = this._paddingTop;
    for (const group2 of this.groups) {
      const count = group2.range.end - group2.range.start;
      const newSize = size2 + count * group2.size;
      if (position < newSize) {
        return index + Math.floor((position - size2) / group2.size);
      }
      index += count;
      size2 = newSize;
    }
    return index;
  }
  /**
   * Returns the index of the item right after the item at the
   * index of the given position.
   */
  indexAfter(position) {
    return Math.min(this.indexAt(position) + 1, this.count);
  }
  /**
   * Returns the start position of the item at the given index.
   */
  positionAt(index) {
    if (index < 0) {
      return -1;
    }
    let position = 0;
    let count = 0;
    for (const group2 of this.groups) {
      const groupCount = group2.range.end - group2.range.start;
      const newCount = count + groupCount;
      if (index < newCount) {
        return this._paddingTop + position + (index - count) * group2.size;
      }
      position += groupCount * group2.size;
      count = newCount;
    }
    return -1;
  }
}
function removeFromParent(element) {
  var _a2;
  try {
    (_a2 = element.parentElement) === null || _a2 === void 0 ? void 0 : _a2.removeChild(element);
  } catch (e) {
  }
}
class RowCache {
  constructor(renderers) {
    this.renderers = renderers;
    this.cache = /* @__PURE__ */ new Map();
    this.transactionNodesPendingRemoval = /* @__PURE__ */ new Set();
    this.inTransaction = false;
  }
  /**
   * Returns a row either by creating a new one or reusing
   * a previously released row which shares the same templateId.
   *
   * @returns A row and `isReusingConnectedDomNode` if the row's node is already in the dom in a stale position.
   */
  alloc(templateId) {
    let result2 = this.getTemplateCache(templateId).pop();
    let isStale2 = false;
    if (result2) {
      isStale2 = this.transactionNodesPendingRemoval.has(result2.domNode);
      if (isStale2) {
        this.transactionNodesPendingRemoval.delete(result2.domNode);
      }
    } else {
      const domNode = $$d(".monaco-list-row");
      const renderer2 = this.getRenderer(templateId);
      const templateData = renderer2.renderTemplate(domNode);
      result2 = { domNode, templateId, templateData };
    }
    return { row: result2, isReusingConnectedDomNode: isStale2 };
  }
  /**
   * Releases the row for eventual reuse.
   */
  release(row) {
    if (!row) {
      return;
    }
    this.releaseRow(row);
  }
  /**
   * Begin a set of changes that use the cache. This lets us skip work when a row is removed and then inserted again.
   */
  transact(makeChanges) {
    if (this.inTransaction) {
      throw new Error("Already in transaction");
    }
    this.inTransaction = true;
    try {
      makeChanges();
    } finally {
      for (const domNode of this.transactionNodesPendingRemoval) {
        this.doRemoveNode(domNode);
      }
      this.transactionNodesPendingRemoval.clear();
      this.inTransaction = false;
    }
  }
  releaseRow(row) {
    const { domNode, templateId } = row;
    if (domNode) {
      if (this.inTransaction) {
        this.transactionNodesPendingRemoval.add(domNode);
      } else {
        this.doRemoveNode(domNode);
      }
    }
    const cache2 = this.getTemplateCache(templateId);
    cache2.push(row);
  }
  doRemoveNode(domNode) {
    domNode.classList.remove("scrolling");
    removeFromParent(domNode);
  }
  getTemplateCache(templateId) {
    let result2 = this.cache.get(templateId);
    if (!result2) {
      result2 = [];
      this.cache.set(templateId, result2);
    }
    return result2;
  }
  dispose() {
    this.cache.forEach((cachedRows, templateId) => {
      for (const cachedRow of cachedRows) {
        const renderer2 = this.getRenderer(templateId);
        renderer2.disposeTemplate(cachedRow.templateData);
        cachedRow.templateData = null;
      }
    });
    this.cache.clear();
    this.transactionNodesPendingRemoval.clear();
  }
  getRenderer(templateId) {
    const renderer2 = this.renderers.get(templateId);
    if (!renderer2) {
      throw new Error(`No renderer found for ${templateId}`);
    }
    return renderer2;
  }
}
var __decorate$1$ = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
const StaticDND = {
  CurrentDragAndDropData: void 0
};
const DefaultOptions$1 = {
  useShadows: true,
  verticalScrollMode: 1,
  setRowLineHeight: true,
  setRowHeight: true,
  supportDynamicHeights: false,
  dnd: {
    getDragElements(e) {
      return [e];
    },
    getDragURI() {
      return null;
    },
    onDragStart() {
    },
    onDragOver() {
      return false;
    },
    drop() {
    }
  },
  horizontalScrolling: false,
  transformOptimization: true,
  alwaysConsumeMouseWheel: true
};
class ElementsDragAndDropData {
  constructor(elements) {
    this.elements = elements;
  }
  update() {
  }
  getData() {
    return this.elements;
  }
}
class ExternalElementsDragAndDropData {
  constructor(elements) {
    this.elements = elements;
  }
  update() {
  }
  getData() {
    return this.elements;
  }
}
class NativeDragAndDropData {
  constructor() {
    this.types = [];
    this.files = [];
  }
  update(dataTransfer) {
    if (dataTransfer.types) {
      this.types.splice(0, this.types.length, ...dataTransfer.types);
    }
    if (dataTransfer.files) {
      this.files.splice(0, this.files.length);
      for (let i = 0; i < dataTransfer.files.length; i++) {
        const file = dataTransfer.files.item(i);
        if (file && (file.size || file.type)) {
          this.files.push(file);
        }
      }
    }
  }
  getData() {
    return {
      types: this.types,
      files: this.files
    };
  }
}
function equalsDragFeedback(f1, f2) {
  if (Array.isArray(f1) && Array.isArray(f2)) {
    return equals$3(f1, f2);
  }
  return f1 === f2;
}
class ListViewAccessibilityProvider {
  constructor(accessibilityProvider) {
    if (accessibilityProvider === null || accessibilityProvider === void 0 ? void 0 : accessibilityProvider.getSetSize) {
      this.getSetSize = accessibilityProvider.getSetSize.bind(accessibilityProvider);
    } else {
      this.getSetSize = (e, i, l) => l;
    }
    if (accessibilityProvider === null || accessibilityProvider === void 0 ? void 0 : accessibilityProvider.getPosInSet) {
      this.getPosInSet = accessibilityProvider.getPosInSet.bind(accessibilityProvider);
    } else {
      this.getPosInSet = (e, i) => i + 1;
    }
    if (accessibilityProvider === null || accessibilityProvider === void 0 ? void 0 : accessibilityProvider.getRole) {
      this.getRole = accessibilityProvider.getRole.bind(accessibilityProvider);
    } else {
      this.getRole = (_) => "listitem";
    }
    if (accessibilityProvider === null || accessibilityProvider === void 0 ? void 0 : accessibilityProvider.isChecked) {
      this.isChecked = accessibilityProvider.isChecked.bind(accessibilityProvider);
    } else {
      this.isChecked = (_) => void 0;
    }
  }
}
class ListView {
  get contentHeight() {
    return this.rangeMap.size;
  }
  get onDidScroll() {
    return this.scrollableElement.onScroll;
  }
  get horizontalScrolling() {
    return this._horizontalScrolling;
  }
  set horizontalScrolling(value) {
    if (value === this._horizontalScrolling) {
      return;
    }
    if (value && this.supportDynamicHeights) {
      throw new Error("Horizontal scrolling and dynamic heights not supported simultaneously");
    }
    this._horizontalScrolling = value;
    this.domNode.classList.toggle("horizontal-scrolling", this._horizontalScrolling);
    if (this._horizontalScrolling) {
      for (const item of this.items) {
        this.measureItemWidth(item);
      }
      this.updateScrollWidth();
      this.scrollableElement.setScrollDimensions({ width: getContentWidth(this.domNode) });
      this.rowsContainer.style.width = `${Math.max(this.scrollWidth || 0, this.renderWidth)}px`;
    } else {
      this.scrollableElementWidthDelayer.cancel();
      this.scrollableElement.setScrollDimensions({ width: this.renderWidth, scrollWidth: this.renderWidth });
      this.rowsContainer.style.width = "";
    }
  }
  constructor(container2, virtualDelegate, renderers, options = DefaultOptions$1) {
    var _a2, _b2, _c2, _d2, _e2, _f2, _g2, _h2, _j, _k, _l, _m, _o;
    this.virtualDelegate = virtualDelegate;
    this.domId = `list_id_${++ListView.InstanceCount}`;
    this.renderers = /* @__PURE__ */ new Map();
    this.renderWidth = 0;
    this._scrollHeight = 0;
    this.scrollableElementUpdateDisposable = null;
    this.scrollableElementWidthDelayer = new Delayer(50);
    this.splicing = false;
    this.dragOverAnimationStopDisposable = Disposable.None;
    this.dragOverMouseY = 0;
    this.canDrop = false;
    this.currentDragFeedbackDisposable = Disposable.None;
    this.onDragLeaveTimeout = Disposable.None;
    this.disposables = new DisposableStore();
    this._onDidChangeContentHeight = new Emitter$1();
    this._onDidChangeContentWidth = new Emitter$1();
    this._horizontalScrolling = false;
    if (options.horizontalScrolling && options.supportDynamicHeights) {
      throw new Error("Horizontal scrolling and dynamic heights not supported simultaneously");
    }
    this.items = [];
    this.itemId = 0;
    this.rangeMap = new RangeMap((_a2 = options.paddingTop) !== null && _a2 !== void 0 ? _a2 : 0);
    for (const renderer2 of renderers) {
      this.renderers.set(renderer2.templateId, renderer2);
    }
    this.cache = this.disposables.add(new RowCache(this.renderers));
    this.lastRenderTop = 0;
    this.lastRenderHeight = 0;
    this.domNode = document.createElement("div");
    this.domNode.className = "monaco-list";
    this.domNode.classList.add(this.domId);
    this.domNode.tabIndex = 0;
    this.domNode.classList.toggle("mouse-support", typeof options.mouseSupport === "boolean" ? options.mouseSupport : true);
    this._horizontalScrolling = (_b2 = options.horizontalScrolling) !== null && _b2 !== void 0 ? _b2 : DefaultOptions$1.horizontalScrolling;
    this.domNode.classList.toggle("horizontal-scrolling", this._horizontalScrolling);
    this.paddingBottom = typeof options.paddingBottom === "undefined" ? 0 : options.paddingBottom;
    this.accessibilityProvider = new ListViewAccessibilityProvider(options.accessibilityProvider);
    this.rowsContainer = document.createElement("div");
    this.rowsContainer.className = "monaco-list-rows";
    const transformOptimization = (_c2 = options.transformOptimization) !== null && _c2 !== void 0 ? _c2 : DefaultOptions$1.transformOptimization;
    if (transformOptimization) {
      this.rowsContainer.style.transform = "translate3d(0px, 0px, 0px)";
      this.rowsContainer.style.overflow = "hidden";
      this.rowsContainer.style.contain = "strict";
    }
    this.disposables.add(Gesture.addTarget(this.rowsContainer));
    this.scrollable = new Scrollable({
      forceIntegerValues: true,
      smoothScrollDuration: ((_d2 = options.smoothScrolling) !== null && _d2 !== void 0 ? _d2 : false) ? 125 : 0,
      scheduleAtNextAnimationFrame: (cb) => scheduleAtNextAnimationFrame(cb)
    });
    this.scrollableElement = this.disposables.add(new SmoothScrollableElement(this.rowsContainer, {
      alwaysConsumeMouseWheel: (_e2 = options.alwaysConsumeMouseWheel) !== null && _e2 !== void 0 ? _e2 : DefaultOptions$1.alwaysConsumeMouseWheel,
      horizontal: 1,
      vertical: (_f2 = options.verticalScrollMode) !== null && _f2 !== void 0 ? _f2 : DefaultOptions$1.verticalScrollMode,
      useShadows: (_g2 = options.useShadows) !== null && _g2 !== void 0 ? _g2 : DefaultOptions$1.useShadows,
      mouseWheelScrollSensitivity: options.mouseWheelScrollSensitivity,
      fastScrollSensitivity: options.fastScrollSensitivity,
      scrollByPage: options.scrollByPage
    }, this.scrollable));
    this.domNode.appendChild(this.scrollableElement.getDomNode());
    container2.appendChild(this.domNode);
    this.scrollableElement.onScroll(this.onScroll, this, this.disposables);
    this.disposables.add(addDisposableListener(this.rowsContainer, EventType.Change, (e) => this.onTouchChange(e)));
    this.disposables.add(addDisposableListener(this.scrollableElement.getDomNode(), "scroll", (e) => e.target.scrollTop = 0));
    this.disposables.add(addDisposableListener(this.domNode, "dragover", (e) => this.onDragOver(this.toDragEvent(e))));
    this.disposables.add(addDisposableListener(this.domNode, "drop", (e) => this.onDrop(this.toDragEvent(e))));
    this.disposables.add(addDisposableListener(this.domNode, "dragleave", (e) => this.onDragLeave(this.toDragEvent(e))));
    this.disposables.add(addDisposableListener(this.domNode, "dragend", (e) => this.onDragEnd(e)));
    this.setRowLineHeight = (_h2 = options.setRowLineHeight) !== null && _h2 !== void 0 ? _h2 : DefaultOptions$1.setRowLineHeight;
    this.setRowHeight = (_j = options.setRowHeight) !== null && _j !== void 0 ? _j : DefaultOptions$1.setRowHeight;
    this.supportDynamicHeights = (_k = options.supportDynamicHeights) !== null && _k !== void 0 ? _k : DefaultOptions$1.supportDynamicHeights;
    this.dnd = (_l = options.dnd) !== null && _l !== void 0 ? _l : DefaultOptions$1.dnd;
    this.layout((_m = options.initialSize) === null || _m === void 0 ? void 0 : _m.height, (_o = options.initialSize) === null || _o === void 0 ? void 0 : _o.width);
  }
  updateOptions(options) {
    if (options.paddingBottom !== void 0) {
      this.paddingBottom = options.paddingBottom;
      this.scrollableElement.setScrollDimensions({ scrollHeight: this.scrollHeight });
    }
    if (options.smoothScrolling !== void 0) {
      this.scrollable.setSmoothScrollDuration(options.smoothScrolling ? 125 : 0);
    }
    if (options.horizontalScrolling !== void 0) {
      this.horizontalScrolling = options.horizontalScrolling;
    }
    let scrollableOptions;
    if (options.scrollByPage !== void 0) {
      scrollableOptions = Object.assign(Object.assign({}, scrollableOptions !== null && scrollableOptions !== void 0 ? scrollableOptions : {}), { scrollByPage: options.scrollByPage });
    }
    if (options.mouseWheelScrollSensitivity !== void 0) {
      scrollableOptions = Object.assign(Object.assign({}, scrollableOptions !== null && scrollableOptions !== void 0 ? scrollableOptions : {}), { mouseWheelScrollSensitivity: options.mouseWheelScrollSensitivity });
    }
    if (options.fastScrollSensitivity !== void 0) {
      scrollableOptions = Object.assign(Object.assign({}, scrollableOptions !== null && scrollableOptions !== void 0 ? scrollableOptions : {}), { fastScrollSensitivity: options.fastScrollSensitivity });
    }
    if (scrollableOptions) {
      this.scrollableElement.updateOptions(scrollableOptions);
    }
    if (options.paddingTop !== void 0 && options.paddingTop !== this.rangeMap.paddingTop) {
      const lastRenderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight);
      const offset = options.paddingTop - this.rangeMap.paddingTop;
      this.rangeMap.paddingTop = options.paddingTop;
      this.render(lastRenderRange, Math.max(0, this.lastRenderTop + offset), this.lastRenderHeight, void 0, void 0, true);
      this.setScrollTop(this.lastRenderTop);
      this.eventuallyUpdateScrollDimensions();
      if (this.supportDynamicHeights) {
        this._rerender(this.lastRenderTop, this.lastRenderHeight);
      }
    }
  }
  splice(start, deleteCount, elements = []) {
    if (this.splicing) {
      throw new Error("Can't run recursive splices.");
    }
    this.splicing = true;
    try {
      return this._splice(start, deleteCount, elements);
    } finally {
      this.splicing = false;
      this._onDidChangeContentHeight.fire(this.contentHeight);
    }
  }
  _splice(start, deleteCount, elements = []) {
    const previousRenderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight);
    const deleteRange = { start, end: start + deleteCount };
    const removeRange = Range$1.intersect(previousRenderRange, deleteRange);
    const rowsToDispose = /* @__PURE__ */ new Map();
    for (let i = removeRange.end - 1; i >= removeRange.start; i--) {
      const item = this.items[i];
      item.dragStartDisposable.dispose();
      item.checkedDisposable.dispose();
      if (item.row) {
        let rows = rowsToDispose.get(item.templateId);
        if (!rows) {
          rows = [];
          rowsToDispose.set(item.templateId, rows);
        }
        const renderer2 = this.renderers.get(item.templateId);
        if (renderer2 && renderer2.disposeElement) {
          renderer2.disposeElement(item.element, i, item.row.templateData, item.size);
        }
        rows.push(item.row);
      }
      item.row = null;
    }
    const previousRestRange = { start: start + deleteCount, end: this.items.length };
    const previousRenderedRestRange = Range$1.intersect(previousRestRange, previousRenderRange);
    const previousUnrenderedRestRanges = Range$1.relativeComplement(previousRestRange, previousRenderRange);
    const inserted = elements.map((element) => ({
      id: String(this.itemId++),
      element,
      templateId: this.virtualDelegate.getTemplateId(element),
      size: this.virtualDelegate.getHeight(element),
      width: void 0,
      hasDynamicHeight: !!this.virtualDelegate.hasDynamicHeight && this.virtualDelegate.hasDynamicHeight(element),
      lastDynamicHeightWidth: void 0,
      row: null,
      uri: void 0,
      dropTarget: false,
      dragStartDisposable: Disposable.None,
      checkedDisposable: Disposable.None
    }));
    let deleted;
    if (start === 0 && deleteCount >= this.items.length) {
      this.rangeMap = new RangeMap(this.rangeMap.paddingTop);
      this.rangeMap.splice(0, 0, inserted);
      deleted = this.items;
      this.items = inserted;
    } else {
      this.rangeMap.splice(start, deleteCount, inserted);
      deleted = this.items.splice(start, deleteCount, ...inserted);
    }
    const delta = elements.length - deleteCount;
    const renderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight);
    const renderedRestRange = shift(previousRenderedRestRange, delta);
    const updateRange = Range$1.intersect(renderRange, renderedRestRange);
    for (let i = updateRange.start; i < updateRange.end; i++) {
      this.updateItemInDOM(this.items[i], i);
    }
    const removeRanges = Range$1.relativeComplement(renderedRestRange, renderRange);
    for (const range2 of removeRanges) {
      for (let i = range2.start; i < range2.end; i++) {
        this.removeItemFromDOM(i);
      }
    }
    const unrenderedRestRanges = previousUnrenderedRestRanges.map((r) => shift(r, delta));
    const elementsRange = { start, end: start + elements.length };
    const insertRanges = [elementsRange, ...unrenderedRestRanges].map((r) => Range$1.intersect(renderRange, r));
    const beforeElement = this.getNextToLastElement(insertRanges);
    for (const range2 of insertRanges) {
      for (let i = range2.start; i < range2.end; i++) {
        const item = this.items[i];
        const rows = rowsToDispose.get(item.templateId);
        const row = rows === null || rows === void 0 ? void 0 : rows.pop();
        this.insertItemInDOM(i, beforeElement, row);
      }
    }
    for (const rows of rowsToDispose.values()) {
      for (const row of rows) {
        this.cache.release(row);
      }
    }
    this.eventuallyUpdateScrollDimensions();
    if (this.supportDynamicHeights) {
      this._rerender(this.scrollTop, this.renderHeight);
    }
    return deleted.map((i) => i.element);
  }
  eventuallyUpdateScrollDimensions() {
    this._scrollHeight = this.contentHeight;
    this.rowsContainer.style.height = `${this._scrollHeight}px`;
    if (!this.scrollableElementUpdateDisposable) {
      this.scrollableElementUpdateDisposable = scheduleAtNextAnimationFrame(() => {
        this.scrollableElement.setScrollDimensions({ scrollHeight: this.scrollHeight });
        this.updateScrollWidth();
        this.scrollableElementUpdateDisposable = null;
      });
    }
  }
  eventuallyUpdateScrollWidth() {
    if (!this.horizontalScrolling) {
      this.scrollableElementWidthDelayer.cancel();
      return;
    }
    this.scrollableElementWidthDelayer.trigger(() => this.updateScrollWidth());
  }
  updateScrollWidth() {
    if (!this.horizontalScrolling) {
      return;
    }
    let scrollWidth = 0;
    for (const item of this.items) {
      if (typeof item.width !== "undefined") {
        scrollWidth = Math.max(scrollWidth, item.width);
      }
    }
    this.scrollWidth = scrollWidth;
    this.scrollableElement.setScrollDimensions({ scrollWidth: scrollWidth === 0 ? 0 : scrollWidth + 10 });
    this._onDidChangeContentWidth.fire(this.scrollWidth);
  }
  rerender() {
    if (!this.supportDynamicHeights) {
      return;
    }
    for (const item of this.items) {
      item.lastDynamicHeightWidth = void 0;
    }
    this._rerender(this.lastRenderTop, this.lastRenderHeight);
  }
  get length() {
    return this.items.length;
  }
  get renderHeight() {
    const scrollDimensions = this.scrollableElement.getScrollDimensions();
    return scrollDimensions.height;
  }
  get firstVisibleIndex() {
    const range2 = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight);
    const firstElTop = this.rangeMap.positionAt(range2.start);
    const nextElTop = this.rangeMap.positionAt(range2.start + 1);
    if (nextElTop !== -1) {
      const firstElMidpoint = (nextElTop - firstElTop) / 2 + firstElTop;
      if (firstElMidpoint < this.scrollTop) {
        return range2.start + 1;
      }
    }
    return range2.start;
  }
  element(index) {
    return this.items[index].element;
  }
  domElement(index) {
    const row = this.items[index].row;
    return row && row.domNode;
  }
  elementHeight(index) {
    return this.items[index].size;
  }
  elementTop(index) {
    return this.rangeMap.positionAt(index);
  }
  indexAt(position) {
    return this.rangeMap.indexAt(position);
  }
  indexAfter(position) {
    return this.rangeMap.indexAfter(position);
  }
  layout(height, width) {
    const scrollDimensions = {
      height: typeof height === "number" ? height : getContentHeight(this.domNode)
    };
    if (this.scrollableElementUpdateDisposable) {
      this.scrollableElementUpdateDisposable.dispose();
      this.scrollableElementUpdateDisposable = null;
      scrollDimensions.scrollHeight = this.scrollHeight;
    }
    this.scrollableElement.setScrollDimensions(scrollDimensions);
    if (typeof width !== "undefined") {
      this.renderWidth = width;
      if (this.supportDynamicHeights) {
        this._rerender(this.scrollTop, this.renderHeight);
      }
    }
    if (this.horizontalScrolling) {
      this.scrollableElement.setScrollDimensions({
        width: typeof width === "number" ? width : getContentWidth(this.domNode)
      });
    }
  }
  // Render
  render(previousRenderRange, renderTop, renderHeight, renderLeft, scrollWidth, updateItemsInDOM = false) {
    const renderRange = this.getRenderRange(renderTop, renderHeight);
    const rangesToInsert = Range$1.relativeComplement(renderRange, previousRenderRange);
    const rangesToRemove = Range$1.relativeComplement(previousRenderRange, renderRange);
    const beforeElement = this.getNextToLastElement(rangesToInsert);
    if (updateItemsInDOM) {
      const rangesToUpdate = Range$1.intersect(previousRenderRange, renderRange);
      for (let i = rangesToUpdate.start; i < rangesToUpdate.end; i++) {
        this.updateItemInDOM(this.items[i], i);
      }
    }
    this.cache.transact(() => {
      for (const range2 of rangesToRemove) {
        for (let i = range2.start; i < range2.end; i++) {
          this.removeItemFromDOM(i);
        }
      }
      for (const range2 of rangesToInsert) {
        for (let i = range2.start; i < range2.end; i++) {
          this.insertItemInDOM(i, beforeElement);
        }
      }
    });
    if (renderLeft !== void 0) {
      this.rowsContainer.style.left = `-${renderLeft}px`;
    }
    this.rowsContainer.style.top = `-${renderTop}px`;
    if (this.horizontalScrolling && scrollWidth !== void 0) {
      this.rowsContainer.style.width = `${Math.max(scrollWidth, this.renderWidth)}px`;
    }
    this.lastRenderTop = renderTop;
    this.lastRenderHeight = renderHeight;
  }
  // DOM operations
  insertItemInDOM(index, beforeElement, row) {
    const item = this.items[index];
    let isStale2 = false;
    if (!item.row) {
      if (row) {
        item.row = row;
      } else {
        const result2 = this.cache.alloc(item.templateId);
        item.row = result2.row;
        isStale2 = result2.isReusingConnectedDomNode;
      }
    }
    const role = this.accessibilityProvider.getRole(item.element) || "listitem";
    item.row.domNode.setAttribute("role", role);
    const checked2 = this.accessibilityProvider.isChecked(item.element);
    if (typeof checked2 === "boolean") {
      item.row.domNode.setAttribute("aria-checked", String(!!checked2));
    } else if (checked2) {
      const update = (checked3) => item.row.domNode.setAttribute("aria-checked", String(!!checked3));
      update(checked2.value);
      item.checkedDisposable = checked2.onDidChange(update);
    }
    if (isStale2 || !item.row.domNode.parentElement) {
      if (beforeElement) {
        this.rowsContainer.insertBefore(item.row.domNode, beforeElement);
      } else {
        this.rowsContainer.appendChild(item.row.domNode);
      }
    }
    this.updateItemInDOM(item, index);
    const renderer2 = this.renderers.get(item.templateId);
    if (!renderer2) {
      throw new Error(`No renderer found for template id ${item.templateId}`);
    }
    renderer2 === null || renderer2 === void 0 ? void 0 : renderer2.renderElement(item.element, index, item.row.templateData, item.size);
    const uri = this.dnd.getDragURI(item.element);
    item.dragStartDisposable.dispose();
    item.row.domNode.draggable = !!uri;
    if (uri) {
      item.dragStartDisposable = addDisposableListener(item.row.domNode, "dragstart", (event) => this.onDragStart(item.element, uri, event));
    }
    if (this.horizontalScrolling) {
      this.measureItemWidth(item);
      this.eventuallyUpdateScrollWidth();
    }
  }
  measureItemWidth(item) {
    if (!item.row || !item.row.domNode) {
      return;
    }
    item.row.domNode.style.width = "fit-content";
    item.width = getContentWidth(item.row.domNode);
    const style2 = window.getComputedStyle(item.row.domNode);
    if (style2.paddingLeft) {
      item.width += parseFloat(style2.paddingLeft);
    }
    if (style2.paddingRight) {
      item.width += parseFloat(style2.paddingRight);
    }
    item.row.domNode.style.width = "";
  }
  updateItemInDOM(item, index) {
    item.row.domNode.style.top = `${this.elementTop(index)}px`;
    if (this.setRowHeight) {
      item.row.domNode.style.height = `${item.size}px`;
    }
    if (this.setRowLineHeight) {
      item.row.domNode.style.lineHeight = `${item.size}px`;
    }
    item.row.domNode.setAttribute("data-index", `${index}`);
    item.row.domNode.setAttribute("data-last-element", index === this.length - 1 ? "true" : "false");
    item.row.domNode.setAttribute("data-parity", index % 2 === 0 ? "even" : "odd");
    item.row.domNode.setAttribute("aria-setsize", String(this.accessibilityProvider.getSetSize(item.element, index, this.length)));
    item.row.domNode.setAttribute("aria-posinset", String(this.accessibilityProvider.getPosInSet(item.element, index)));
    item.row.domNode.setAttribute("id", this.getElementDomId(index));
    item.row.domNode.classList.toggle("drop-target", item.dropTarget);
  }
  removeItemFromDOM(index) {
    const item = this.items[index];
    item.dragStartDisposable.dispose();
    item.checkedDisposable.dispose();
    if (item.row) {
      const renderer2 = this.renderers.get(item.templateId);
      if (renderer2 && renderer2.disposeElement) {
        renderer2.disposeElement(item.element, index, item.row.templateData, item.size);
      }
      this.cache.release(item.row);
      item.row = null;
    }
    if (this.horizontalScrolling) {
      this.eventuallyUpdateScrollWidth();
    }
  }
  getScrollTop() {
    const scrollPosition = this.scrollableElement.getScrollPosition();
    return scrollPosition.scrollTop;
  }
  setScrollTop(scrollTop, reuseAnimation) {
    if (this.scrollableElementUpdateDisposable) {
      this.scrollableElementUpdateDisposable.dispose();
      this.scrollableElementUpdateDisposable = null;
      this.scrollableElement.setScrollDimensions({ scrollHeight: this.scrollHeight });
    }
    this.scrollableElement.setScrollPosition({ scrollTop, reuseAnimation });
  }
  get scrollTop() {
    return this.getScrollTop();
  }
  set scrollTop(scrollTop) {
    this.setScrollTop(scrollTop);
  }
  get scrollHeight() {
    return this._scrollHeight + (this.horizontalScrolling ? 10 : 0) + this.paddingBottom;
  }
  // Events
  get onMouseClick() {
    return Event$1.map(this.disposables.add(new DomEmitter(this.domNode, "click")).event, (e) => this.toMouseEvent(e), this.disposables);
  }
  get onMouseDblClick() {
    return Event$1.map(this.disposables.add(new DomEmitter(this.domNode, "dblclick")).event, (e) => this.toMouseEvent(e), this.disposables);
  }
  get onMouseMiddleClick() {
    return Event$1.filter(Event$1.map(this.disposables.add(new DomEmitter(this.domNode, "auxclick")).event, (e) => this.toMouseEvent(e), this.disposables), (e) => e.browserEvent.button === 1, this.disposables);
  }
  get onMouseDown() {
    return Event$1.map(this.disposables.add(new DomEmitter(this.domNode, "mousedown")).event, (e) => this.toMouseEvent(e), this.disposables);
  }
  get onMouseOver() {
    return Event$1.map(this.disposables.add(new DomEmitter(this.domNode, "mouseover")).event, (e) => this.toMouseEvent(e), this.disposables);
  }
  get onMouseOut() {
    return Event$1.map(this.disposables.add(new DomEmitter(this.domNode, "mouseout")).event, (e) => this.toMouseEvent(e), this.disposables);
  }
  get onContextMenu() {
    return Event$1.any(Event$1.map(this.disposables.add(new DomEmitter(this.domNode, "contextmenu")).event, (e) => this.toMouseEvent(e), this.disposables), Event$1.map(this.disposables.add(new DomEmitter(this.domNode, EventType.Contextmenu)).event, (e) => this.toGestureEvent(e), this.disposables));
  }
  get onTouchStart() {
    return Event$1.map(this.disposables.add(new DomEmitter(this.domNode, "touchstart")).event, (e) => this.toTouchEvent(e), this.disposables);
  }
  get onTap() {
    return Event$1.map(this.disposables.add(new DomEmitter(this.rowsContainer, EventType.Tap)).event, (e) => this.toGestureEvent(e), this.disposables);
  }
  toMouseEvent(browserEvent) {
    const index = this.getItemIndexFromEventTarget(browserEvent.target || null);
    const item = typeof index === "undefined" ? void 0 : this.items[index];
    const element = item && item.element;
    return { browserEvent, index, element };
  }
  toTouchEvent(browserEvent) {
    const index = this.getItemIndexFromEventTarget(browserEvent.target || null);
    const item = typeof index === "undefined" ? void 0 : this.items[index];
    const element = item && item.element;
    return { browserEvent, index, element };
  }
  toGestureEvent(browserEvent) {
    const index = this.getItemIndexFromEventTarget(browserEvent.initialTarget || null);
    const item = typeof index === "undefined" ? void 0 : this.items[index];
    const element = item && item.element;
    return { browserEvent, index, element };
  }
  toDragEvent(browserEvent) {
    const index = this.getItemIndexFromEventTarget(browserEvent.target || null);
    const item = typeof index === "undefined" ? void 0 : this.items[index];
    const element = item && item.element;
    return { browserEvent, index, element };
  }
  onScroll(e) {
    try {
      const previousRenderRange = this.getRenderRange(this.lastRenderTop, this.lastRenderHeight);
      this.render(previousRenderRange, e.scrollTop, e.height, e.scrollLeft, e.scrollWidth);
      if (this.supportDynamicHeights) {
        this._rerender(e.scrollTop, e.height, e.inSmoothScrolling);
      }
    } catch (err) {
      console.error("Got bad scroll event:", e);
      throw err;
    }
  }
  onTouchChange(event) {
    event.preventDefault();
    event.stopPropagation();
    this.scrollTop -= event.translationY;
  }
  // DND
  onDragStart(element, uri, event) {
    var _a2, _b2;
    if (!event.dataTransfer) {
      return;
    }
    const elements = this.dnd.getDragElements(element);
    event.dataTransfer.effectAllowed = "copyMove";
    event.dataTransfer.setData(DataTransfers.TEXT, uri);
    if (event.dataTransfer.setDragImage) {
      let label;
      if (this.dnd.getDragLabel) {
        label = this.dnd.getDragLabel(elements, event);
      }
      if (typeof label === "undefined") {
        label = String(elements.length);
      }
      const dragImage = $$d(".monaco-drag-image");
      dragImage.textContent = label;
      const getDragImageContainer = (e) => {
        while (e && !e.classList.contains("monaco-workbench")) {
          e = e.parentElement;
        }
        return e || document.body;
      };
      const container2 = getDragImageContainer(this.domNode);
      container2.appendChild(dragImage);
      event.dataTransfer.setDragImage(dragImage, -10, -10);
      setTimeout(() => container2.removeChild(dragImage), 0);
    }
    this.domNode.classList.add("dragging");
    this.currentDragData = new ElementsDragAndDropData(elements);
    StaticDND.CurrentDragAndDropData = new ExternalElementsDragAndDropData(elements);
    (_b2 = (_a2 = this.dnd).onDragStart) === null || _b2 === void 0 ? void 0 : _b2.call(_a2, this.currentDragData, event);
  }
  onDragOver(event) {
    var _a2;
    event.browserEvent.preventDefault();
    this.onDragLeaveTimeout.dispose();
    if (StaticDND.CurrentDragAndDropData && StaticDND.CurrentDragAndDropData.getData() === "vscode-ui") {
      return false;
    }
    this.setupDragAndDropScrollTopAnimation(event.browserEvent);
    if (!event.browserEvent.dataTransfer) {
      return false;
    }
    if (!this.currentDragData) {
      if (StaticDND.CurrentDragAndDropData) {
        this.currentDragData = StaticDND.CurrentDragAndDropData;
      } else {
        if (!event.browserEvent.dataTransfer.types) {
          return false;
        }
        this.currentDragData = new NativeDragAndDropData();
      }
    }
    const result2 = this.dnd.onDragOver(this.currentDragData, event.element, event.index, event.browserEvent);
    this.canDrop = typeof result2 === "boolean" ? result2 : result2.accept;
    if (!this.canDrop) {
      this.currentDragFeedback = void 0;
      this.currentDragFeedbackDisposable.dispose();
      return false;
    }
    event.browserEvent.dataTransfer.dropEffect = typeof result2 !== "boolean" && result2.effect === 0 ? "copy" : "move";
    let feedback;
    if (typeof result2 !== "boolean" && result2.feedback) {
      feedback = result2.feedback;
    } else {
      if (typeof event.index === "undefined") {
        feedback = [-1];
      } else {
        feedback = [event.index];
      }
    }
    feedback = distinct(feedback).filter((i) => i >= -1 && i < this.length).sort((a, b) => a - b);
    feedback = feedback[0] === -1 ? [-1] : feedback;
    if (equalsDragFeedback(this.currentDragFeedback, feedback)) {
      return true;
    }
    this.currentDragFeedback = feedback;
    this.currentDragFeedbackDisposable.dispose();
    if (feedback[0] === -1) {
      this.domNode.classList.add("drop-target");
      this.rowsContainer.classList.add("drop-target");
      this.currentDragFeedbackDisposable = toDisposable(() => {
        this.domNode.classList.remove("drop-target");
        this.rowsContainer.classList.remove("drop-target");
      });
    } else {
      for (const index of feedback) {
        const item = this.items[index];
        item.dropTarget = true;
        (_a2 = item.row) === null || _a2 === void 0 ? void 0 : _a2.domNode.classList.add("drop-target");
      }
      this.currentDragFeedbackDisposable = toDisposable(() => {
        var _a3;
        for (const index of feedback) {
          const item = this.items[index];
          item.dropTarget = false;
          (_a3 = item.row) === null || _a3 === void 0 ? void 0 : _a3.domNode.classList.remove("drop-target");
        }
      });
    }
    return true;
  }
  onDragLeave(event) {
    var _a2, _b2;
    this.onDragLeaveTimeout.dispose();
    this.onDragLeaveTimeout = disposableTimeout(() => this.clearDragOverFeedback(), 100);
    if (this.currentDragData) {
      (_b2 = (_a2 = this.dnd).onDragLeave) === null || _b2 === void 0 ? void 0 : _b2.call(_a2, this.currentDragData, event.element, event.index, event.browserEvent);
    }
  }
  onDrop(event) {
    if (!this.canDrop) {
      return;
    }
    const dragData = this.currentDragData;
    this.teardownDragAndDropScrollTopAnimation();
    this.clearDragOverFeedback();
    this.domNode.classList.remove("dragging");
    this.currentDragData = void 0;
    StaticDND.CurrentDragAndDropData = void 0;
    if (!dragData || !event.browserEvent.dataTransfer) {
      return;
    }
    event.browserEvent.preventDefault();
    dragData.update(event.browserEvent.dataTransfer);
    this.dnd.drop(dragData, event.element, event.index, event.browserEvent);
  }
  onDragEnd(event) {
    var _a2, _b2;
    this.canDrop = false;
    this.teardownDragAndDropScrollTopAnimation();
    this.clearDragOverFeedback();
    this.domNode.classList.remove("dragging");
    this.currentDragData = void 0;
    StaticDND.CurrentDragAndDropData = void 0;
    (_b2 = (_a2 = this.dnd).onDragEnd) === null || _b2 === void 0 ? void 0 : _b2.call(_a2, event);
  }
  clearDragOverFeedback() {
    this.currentDragFeedback = void 0;
    this.currentDragFeedbackDisposable.dispose();
    this.currentDragFeedbackDisposable = Disposable.None;
  }
  // DND scroll top animation
  setupDragAndDropScrollTopAnimation(event) {
    if (!this.dragOverAnimationDisposable) {
      const viewTop = getTopLeftOffset(this.domNode).top;
      this.dragOverAnimationDisposable = animate(this.animateDragAndDropScrollTop.bind(this, viewTop));
    }
    this.dragOverAnimationStopDisposable.dispose();
    this.dragOverAnimationStopDisposable = disposableTimeout(() => {
      if (this.dragOverAnimationDisposable) {
        this.dragOverAnimationDisposable.dispose();
        this.dragOverAnimationDisposable = void 0;
      }
    }, 1e3);
    this.dragOverMouseY = event.pageY;
  }
  animateDragAndDropScrollTop(viewTop) {
    if (this.dragOverMouseY === void 0) {
      return;
    }
    const diff = this.dragOverMouseY - viewTop;
    const upperLimit = this.renderHeight - 35;
    if (diff < 35) {
      this.scrollTop += Math.max(-14, Math.floor(0.3 * (diff - 35)));
    } else if (diff > upperLimit) {
      this.scrollTop += Math.min(14, Math.floor(0.3 * (diff - upperLimit)));
    }
  }
  teardownDragAndDropScrollTopAnimation() {
    this.dragOverAnimationStopDisposable.dispose();
    if (this.dragOverAnimationDisposable) {
      this.dragOverAnimationDisposable.dispose();
      this.dragOverAnimationDisposable = void 0;
    }
  }
  // Util
  getItemIndexFromEventTarget(target) {
    const scrollableElement = this.scrollableElement.getDomNode();
    let element = target;
    while (element instanceof HTMLElement && element !== this.rowsContainer && scrollableElement.contains(element)) {
      const rawIndex = element.getAttribute("data-index");
      if (rawIndex) {
        const index = Number(rawIndex);
        if (!isNaN(index)) {
          return index;
        }
      }
      element = element.parentElement;
    }
    return void 0;
  }
  getRenderRange(renderTop, renderHeight) {
    return {
      start: this.rangeMap.indexAt(renderTop),
      end: this.rangeMap.indexAfter(renderTop + renderHeight - 1)
    };
  }
  /**
   * Given a stable rendered state, checks every rendered element whether it needs
   * to be probed for dynamic height. Adjusts scroll height and top if necessary.
   */
  _rerender(renderTop, renderHeight, inSmoothScrolling) {
    const previousRenderRange = this.getRenderRange(renderTop, renderHeight);
    let anchorElementIndex;
    let anchorElementTopDelta;
    if (renderTop === this.elementTop(previousRenderRange.start)) {
      anchorElementIndex = previousRenderRange.start;
      anchorElementTopDelta = 0;
    } else if (previousRenderRange.end - previousRenderRange.start > 1) {
      anchorElementIndex = previousRenderRange.start + 1;
      anchorElementTopDelta = this.elementTop(anchorElementIndex) - renderTop;
    }
    let heightDiff2 = 0;
    while (true) {
      const renderRange = this.getRenderRange(renderTop, renderHeight);
      let didChange = false;
      for (let i = renderRange.start; i < renderRange.end; i++) {
        const diff = this.probeDynamicHeight(i);
        if (diff !== 0) {
          this.rangeMap.splice(i, 1, [this.items[i]]);
        }
        heightDiff2 += diff;
        didChange = didChange || diff !== 0;
      }
      if (!didChange) {
        if (heightDiff2 !== 0) {
          this.eventuallyUpdateScrollDimensions();
        }
        const unrenderRanges = Range$1.relativeComplement(previousRenderRange, renderRange);
        for (const range2 of unrenderRanges) {
          for (let i = range2.start; i < range2.end; i++) {
            if (this.items[i].row) {
              this.removeItemFromDOM(i);
            }
          }
        }
        const renderRanges = Range$1.relativeComplement(renderRange, previousRenderRange);
        for (const range2 of renderRanges) {
          for (let i = range2.start; i < range2.end; i++) {
            const afterIndex = i + 1;
            const beforeRow = afterIndex < this.items.length ? this.items[afterIndex].row : null;
            const beforeElement = beforeRow ? beforeRow.domNode : null;
            this.insertItemInDOM(i, beforeElement);
          }
        }
        for (let i = renderRange.start; i < renderRange.end; i++) {
          if (this.items[i].row) {
            this.updateItemInDOM(this.items[i], i);
          }
        }
        if (typeof anchorElementIndex === "number") {
          const deltaScrollTop = this.scrollable.getFutureScrollPosition().scrollTop - renderTop;
          const newScrollTop = this.elementTop(anchorElementIndex) - anchorElementTopDelta + deltaScrollTop;
          this.setScrollTop(newScrollTop, inSmoothScrolling);
        }
        this._onDidChangeContentHeight.fire(this.contentHeight);
        return;
      }
    }
  }
  probeDynamicHeight(index) {
    var _a2, _b2, _c2;
    const item = this.items[index];
    if (!!this.virtualDelegate.getDynamicHeight) {
      const newSize = this.virtualDelegate.getDynamicHeight(item.element);
      if (newSize !== null) {
        const size3 = item.size;
        item.size = newSize;
        item.lastDynamicHeightWidth = this.renderWidth;
        return newSize - size3;
      }
    }
    if (!item.hasDynamicHeight || item.lastDynamicHeightWidth === this.renderWidth) {
      return 0;
    }
    if (!!this.virtualDelegate.hasDynamicHeight && !this.virtualDelegate.hasDynamicHeight(item.element)) {
      return 0;
    }
    const size2 = item.size;
    if (item.row) {
      item.row.domNode.style.height = "";
      item.size = item.row.domNode.offsetHeight;
      item.lastDynamicHeightWidth = this.renderWidth;
      return item.size - size2;
    }
    const { row } = this.cache.alloc(item.templateId);
    row.domNode.style.height = "";
    this.rowsContainer.appendChild(row.domNode);
    const renderer2 = this.renderers.get(item.templateId);
    if (!renderer2) {
      throw new BugIndicatingError("Missing renderer for templateId: " + item.templateId);
    }
    renderer2.renderElement(item.element, index, row.templateData, void 0);
    item.size = row.domNode.offsetHeight;
    (_a2 = renderer2.disposeElement) === null || _a2 === void 0 ? void 0 : _a2.call(renderer2, item.element, index, row.templateData, void 0);
    (_c2 = (_b2 = this.virtualDelegate).setDynamicHeight) === null || _c2 === void 0 ? void 0 : _c2.call(_b2, item.element, item.size);
    item.lastDynamicHeightWidth = this.renderWidth;
    this.rowsContainer.removeChild(row.domNode);
    this.cache.release(row);
    return item.size - size2;
  }
  getNextToLastElement(ranges) {
    const lastRange = ranges[ranges.length - 1];
    if (!lastRange) {
      return null;
    }
    const nextToLastItem = this.items[lastRange.end];
    if (!nextToLastItem) {
      return null;
    }
    if (!nextToLastItem.row) {
      return null;
    }
    return nextToLastItem.row.domNode;
  }
  getElementDomId(index) {
    return `${this.domId}_${index}`;
  }
  // Dispose
  dispose() {
    var _a2;
    if (this.items) {
      for (const item of this.items) {
        if (item.row) {
          const renderer2 = this.renderers.get(item.row.templateId);
          if (renderer2) {
            (_a2 = renderer2.disposeElement) === null || _a2 === void 0 ? void 0 : _a2.call(renderer2, item.element, -1, item.row.templateData, void 0);
            renderer2.disposeTemplate(item.row.templateData);
          }
        }
      }
      this.items = [];
    }
    if (this.domNode && this.domNode.parentNode) {
      this.domNode.parentNode.removeChild(this.domNode);
    }
    dispose(this.disposables);
  }
}
ListView.InstanceCount = 0;
__decorate$1$([
  memoize
], ListView.prototype, "onMouseClick", null);
__decorate$1$([
  memoize
], ListView.prototype, "onMouseDblClick", null);
__decorate$1$([
  memoize
], ListView.prototype, "onMouseMiddleClick", null);
__decorate$1$([
  memoize
], ListView.prototype, "onMouseDown", null);
__decorate$1$([
  memoize
], ListView.prototype, "onMouseOver", null);
__decorate$1$([
  memoize
], ListView.prototype, "onMouseOut", null);
__decorate$1$([
  memoize
], ListView.prototype, "onContextMenu", null);
__decorate$1$([
  memoize
], ListView.prototype, "onTouchStart", null);
__decorate$1$([
  memoize
], ListView.prototype, "onTap", null);
var __decorate$1_ = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __awaiter$1u = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class TraitRenderer {
  constructor(trait) {
    this.trait = trait;
    this.renderedElements = [];
  }
  get templateId() {
    return `template:${this.trait.name}`;
  }
  renderTemplate(container2) {
    return container2;
  }
  renderElement(element, index, templateData) {
    const renderedElementIndex = this.renderedElements.findIndex((el) => el.templateData === templateData);
    if (renderedElementIndex >= 0) {
      const rendered = this.renderedElements[renderedElementIndex];
      this.trait.unrender(templateData);
      rendered.index = index;
    } else {
      const rendered = { index, templateData };
      this.renderedElements.push(rendered);
    }
    this.trait.renderIndex(index, templateData);
  }
  splice(start, deleteCount, insertCount) {
    const rendered = [];
    for (const renderedElement of this.renderedElements) {
      if (renderedElement.index < start) {
        rendered.push(renderedElement);
      } else if (renderedElement.index >= start + deleteCount) {
        rendered.push({
          index: renderedElement.index + insertCount - deleteCount,
          templateData: renderedElement.templateData
        });
      }
    }
    this.renderedElements = rendered;
  }
  renderIndexes(indexes) {
    for (const { index, templateData } of this.renderedElements) {
      if (indexes.indexOf(index) > -1) {
        this.trait.renderIndex(index, templateData);
      }
    }
  }
  disposeTemplate(templateData) {
    const index = this.renderedElements.findIndex((el) => el.templateData === templateData);
    if (index < 0) {
      return;
    }
    this.renderedElements.splice(index, 1);
  }
}
let Trait$1 = class Trait {
  get name() {
    return this._trait;
  }
  get renderer() {
    return new TraitRenderer(this);
  }
  constructor(_trait) {
    this._trait = _trait;
    this.length = 0;
    this.indexes = [];
    this.sortedIndexes = [];
    this._onChange = new Emitter$1();
    this.onChange = this._onChange.event;
  }
  splice(start, deleteCount, elements) {
    var _a2;
    deleteCount = Math.max(0, Math.min(deleteCount, this.length - start));
    const diff = elements.length - deleteCount;
    const end = start + deleteCount;
    const sortedIndexes = [];
    let i = 0;
    while (i < this.sortedIndexes.length && this.sortedIndexes[i] < start) {
      sortedIndexes.push(this.sortedIndexes[i++]);
    }
    for (let j = 0; j < elements.length; j++) {
      if (elements[j]) {
        sortedIndexes.push(j + start);
      }
    }
    while (i < this.sortedIndexes.length && this.sortedIndexes[i] >= end) {
      sortedIndexes.push(this.sortedIndexes[i++] + diff);
    }
    const length2 = this.length + diff;
    if (this.sortedIndexes.length > 0 && sortedIndexes.length === 0 && length2 > 0) {
      const first2 = (_a2 = this.sortedIndexes.find((index) => index >= start)) !== null && _a2 !== void 0 ? _a2 : length2 - 1;
      sortedIndexes.push(Math.min(first2, length2 - 1));
    }
    this.renderer.splice(start, deleteCount, elements.length);
    this._set(sortedIndexes, sortedIndexes);
    this.length = length2;
  }
  renderIndex(index, container2) {
    container2.classList.toggle(this._trait, this.contains(index));
  }
  unrender(container2) {
    container2.classList.remove(this._trait);
  }
  /**
   * Sets the indexes which should have this trait.
   *
   * @param indexes Indexes which should have this trait.
   * @return The old indexes which had this trait.
   */
  set(indexes, browserEvent) {
    return this._set(indexes, [...indexes].sort(numericSort), browserEvent);
  }
  _set(indexes, sortedIndexes, browserEvent) {
    const result2 = this.indexes;
    const sortedResult = this.sortedIndexes;
    this.indexes = indexes;
    this.sortedIndexes = sortedIndexes;
    const toRender = disjunction(sortedResult, indexes);
    this.renderer.renderIndexes(toRender);
    this._onChange.fire({ indexes, browserEvent });
    return result2;
  }
  get() {
    return this.indexes;
  }
  contains(index) {
    return binarySearch$4(this.sortedIndexes, index, numericSort) >= 0;
  }
  dispose() {
    dispose(this._onChange);
  }
};
__decorate$1_([
  memoize
], Trait$1.prototype, "renderer", null);
class SelectionTrait extends Trait$1 {
  constructor(setAriaSelected) {
    super("selected");
    this.setAriaSelected = setAriaSelected;
  }
  renderIndex(index, container2) {
    super.renderIndex(index, container2);
    if (this.setAriaSelected) {
      if (this.contains(index)) {
        container2.setAttribute("aria-selected", "true");
      } else {
        container2.setAttribute("aria-selected", "false");
      }
    }
  }
}
class TraitSpliceable {
  constructor(trait, view, identityProvider) {
    this.trait = trait;
    this.view = view;
    this.identityProvider = identityProvider;
  }
  splice(start, deleteCount, elements) {
    if (!this.identityProvider) {
      return this.trait.splice(start, deleteCount, new Array(elements.length).fill(false));
    }
    const pastElementsWithTrait = this.trait.get().map((i) => this.identityProvider.getId(this.view.element(i)).toString());
    if (pastElementsWithTrait.length === 0) {
      return this.trait.splice(start, deleteCount, new Array(elements.length).fill(false));
    }
    const pastElementsWithTraitSet = new Set(pastElementsWithTrait);
    const elementsWithTrait = elements.map((e) => pastElementsWithTraitSet.has(this.identityProvider.getId(e).toString()));
    this.trait.splice(start, deleteCount, elementsWithTrait);
  }
}
function isInputElement(e) {
  return e.tagName === "INPUT" || e.tagName === "TEXTAREA";
}
function isMonacoEditor(e) {
  if (e.classList.contains("monaco-editor")) {
    return true;
  }
  if (e.classList.contains("monaco-list")) {
    return false;
  }
  if (!e.parentElement) {
    return false;
  }
  return isMonacoEditor(e.parentElement);
}
function isButton(e) {
  if (e.tagName === "A" && e.classList.contains("monaco-button") || e.tagName === "DIV" && e.classList.contains("monaco-button-dropdown")) {
    return true;
  }
  if (e.classList.contains("monaco-list")) {
    return false;
  }
  if (!e.parentElement) {
    return false;
  }
  return isButton(e.parentElement);
}
class KeyboardController {
  get onKeyDown() {
    return this.disposables.add(Event$1.chain(this.disposables.add(new DomEmitter(this.view.domNode, "keydown")).event).filter((e) => !isInputElement(e.target)).map((e) => new StandardKeyboardEvent(e)));
  }
  constructor(list2, view, options) {
    this.list = list2;
    this.view = view;
    this.disposables = new DisposableStore();
    this.multipleSelectionDisposables = new DisposableStore();
    this.onKeyDown.filter(
      (e) => e.keyCode === 3
      /* KeyCode.Enter */
    ).on(this.onEnter, this, this.disposables);
    this.onKeyDown.filter(
      (e) => e.keyCode === 16
      /* KeyCode.UpArrow */
    ).on(this.onUpArrow, this, this.disposables);
    this.onKeyDown.filter(
      (e) => e.keyCode === 18
      /* KeyCode.DownArrow */
    ).on(this.onDownArrow, this, this.disposables);
    this.onKeyDown.filter(
      (e) => e.keyCode === 11
      /* KeyCode.PageUp */
    ).on(this.onPageUpArrow, this, this.disposables);
    this.onKeyDown.filter(
      (e) => e.keyCode === 12
      /* KeyCode.PageDown */
    ).on(this.onPageDownArrow, this, this.disposables);
    this.onKeyDown.filter(
      (e) => e.keyCode === 9
      /* KeyCode.Escape */
    ).on(this.onEscape, this, this.disposables);
    if (options.multipleSelectionSupport !== false) {
      this.onKeyDown.filter(
        (e) => (isMacintosh ? e.metaKey : e.ctrlKey) && e.keyCode === 31
        /* KeyCode.KeyA */
      ).on(this.onCtrlA, this, this.multipleSelectionDisposables);
    }
  }
  updateOptions(optionsUpdate) {
    if (optionsUpdate.multipleSelectionSupport !== void 0) {
      this.multipleSelectionDisposables.clear();
      if (optionsUpdate.multipleSelectionSupport) {
        this.onKeyDown.filter(
          (e) => (isMacintosh ? e.metaKey : e.ctrlKey) && e.keyCode === 31
          /* KeyCode.KeyA */
        ).on(this.onCtrlA, this, this.multipleSelectionDisposables);
      }
    }
  }
  onEnter(e) {
    e.preventDefault();
    e.stopPropagation();
    this.list.setSelection(this.list.getFocus(), e.browserEvent);
  }
  onUpArrow(e) {
    e.preventDefault();
    e.stopPropagation();
    this.list.focusPrevious(1, false, e.browserEvent);
    const el = this.list.getFocus()[0];
    this.list.setAnchor(el);
    this.list.reveal(el);
    this.view.domNode.focus();
  }
  onDownArrow(e) {
    e.preventDefault();
    e.stopPropagation();
    this.list.focusNext(1, false, e.browserEvent);
    const el = this.list.getFocus()[0];
    this.list.setAnchor(el);
    this.list.reveal(el);
    this.view.domNode.focus();
  }
  onPageUpArrow(e) {
    e.preventDefault();
    e.stopPropagation();
    this.list.focusPreviousPage(e.browserEvent);
    const el = this.list.getFocus()[0];
    this.list.setAnchor(el);
    this.list.reveal(el);
    this.view.domNode.focus();
  }
  onPageDownArrow(e) {
    e.preventDefault();
    e.stopPropagation();
    this.list.focusNextPage(e.browserEvent);
    const el = this.list.getFocus()[0];
    this.list.setAnchor(el);
    this.list.reveal(el);
    this.view.domNode.focus();
  }
  onCtrlA(e) {
    e.preventDefault();
    e.stopPropagation();
    this.list.setSelection(range$1(this.list.length), e.browserEvent);
    this.list.setAnchor(void 0);
    this.view.domNode.focus();
  }
  onEscape(e) {
    if (this.list.getSelection().length) {
      e.preventDefault();
      e.stopPropagation();
      this.list.setSelection([], e.browserEvent);
      this.list.setAnchor(void 0);
      this.view.domNode.focus();
    }
  }
  dispose() {
    this.disposables.dispose();
    this.multipleSelectionDisposables.dispose();
  }
}
__decorate$1_([
  memoize
], KeyboardController.prototype, "onKeyDown", null);
var TypeNavigationMode;
(function(TypeNavigationMode2) {
  TypeNavigationMode2[TypeNavigationMode2["Automatic"] = 0] = "Automatic";
  TypeNavigationMode2[TypeNavigationMode2["Trigger"] = 1] = "Trigger";
})(TypeNavigationMode || (TypeNavigationMode = {}));
var TypeNavigationControllerState;
(function(TypeNavigationControllerState2) {
  TypeNavigationControllerState2[TypeNavigationControllerState2["Idle"] = 0] = "Idle";
  TypeNavigationControllerState2[TypeNavigationControllerState2["Typing"] = 1] = "Typing";
})(TypeNavigationControllerState || (TypeNavigationControllerState = {}));
const DefaultKeyboardNavigationDelegate = new class {
  mightProducePrintableCharacter(event) {
    if (event.ctrlKey || event.metaKey || event.altKey) {
      return false;
    }
    return event.keyCode >= 31 && event.keyCode <= 56 || event.keyCode >= 21 && event.keyCode <= 30 || event.keyCode >= 98 && event.keyCode <= 107 || event.keyCode >= 85 && event.keyCode <= 95;
  }
}();
class TypeNavigationController {
  constructor(list2, view, keyboardNavigationLabelProvider, keyboardNavigationEventFilter, delegate) {
    this.list = list2;
    this.view = view;
    this.keyboardNavigationLabelProvider = keyboardNavigationLabelProvider;
    this.keyboardNavigationEventFilter = keyboardNavigationEventFilter;
    this.delegate = delegate;
    this.enabled = false;
    this.state = TypeNavigationControllerState.Idle;
    this.mode = TypeNavigationMode.Automatic;
    this.triggered = false;
    this.previouslyFocused = -1;
    this.enabledDisposables = new DisposableStore();
    this.disposables = new DisposableStore();
    this.updateOptions(list2.options);
  }
  updateOptions(options) {
    var _a2, _b2;
    if ((_a2 = options.typeNavigationEnabled) !== null && _a2 !== void 0 ? _a2 : true) {
      this.enable();
    } else {
      this.disable();
    }
    this.mode = (_b2 = options.typeNavigationMode) !== null && _b2 !== void 0 ? _b2 : TypeNavigationMode.Automatic;
  }
  enable() {
    if (this.enabled) {
      return;
    }
    let typing = false;
    const onChar = this.enabledDisposables.add(Event$1.chain(this.enabledDisposables.add(new DomEmitter(this.view.domNode, "keydown")).event)).filter((e) => !isInputElement(e.target)).filter(() => this.mode === TypeNavigationMode.Automatic || this.triggered).map((event) => new StandardKeyboardEvent(event)).filter((e) => typing || this.keyboardNavigationEventFilter(e)).filter((e) => this.delegate.mightProducePrintableCharacter(e)).forEach((e) => EventHelper.stop(e, true)).map((event) => event.browserEvent.key).event;
    const onClear = Event$1.debounce(onChar, () => null, 800, void 0, void 0, void 0, this.enabledDisposables);
    const onInput = Event$1.reduce(Event$1.any(onChar, onClear), (r, i) => i === null ? null : (r || "") + i, void 0, this.enabledDisposables);
    onInput(this.onInput, this, this.enabledDisposables);
    onClear(this.onClear, this, this.enabledDisposables);
    onChar(() => typing = true, void 0, this.enabledDisposables);
    onClear(() => typing = false, void 0, this.enabledDisposables);
    this.enabled = true;
    this.triggered = false;
  }
  disable() {
    if (!this.enabled) {
      return;
    }
    this.enabledDisposables.clear();
    this.enabled = false;
    this.triggered = false;
  }
  onClear() {
    var _a2;
    const focus = this.list.getFocus();
    if (focus.length > 0 && focus[0] === this.previouslyFocused) {
      const ariaLabel = (_a2 = this.list.options.accessibilityProvider) === null || _a2 === void 0 ? void 0 : _a2.getAriaLabel(this.list.element(focus[0]));
      if (ariaLabel) {
        alert(ariaLabel);
      }
    }
    this.previouslyFocused = -1;
  }
  onInput(word2) {
    if (!word2) {
      this.state = TypeNavigationControllerState.Idle;
      this.triggered = false;
      return;
    }
    const focus = this.list.getFocus();
    const start = focus.length > 0 ? focus[0] : 0;
    const delta = this.state === TypeNavigationControllerState.Idle ? 1 : 0;
    this.state = TypeNavigationControllerState.Typing;
    for (let i = 0; i < this.list.length; i++) {
      const index = (start + i + delta) % this.list.length;
      const label = this.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(this.view.element(index));
      const labelStr = label && label.toString();
      if (typeof labelStr === "undefined" || matchesPrefix(word2, labelStr)) {
        this.previouslyFocused = start;
        this.list.setFocus([index]);
        this.list.reveal(index);
        return;
      }
    }
  }
  dispose() {
    this.disable();
    this.enabledDisposables.dispose();
    this.disposables.dispose();
  }
}
class DOMFocusController {
  constructor(list2, view) {
    this.list = list2;
    this.view = view;
    this.disposables = new DisposableStore();
    const onKeyDown = this.disposables.add(Event$1.chain(this.disposables.add(new DomEmitter(view.domNode, "keydown")).event)).filter((e) => !isInputElement(e.target)).map((e) => new StandardKeyboardEvent(e));
    onKeyDown.filter((e) => e.keyCode === 2 && !e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey).on(this.onTab, this, this.disposables);
  }
  onTab(e) {
    if (e.target !== this.view.domNode) {
      return;
    }
    const focus = this.list.getFocus();
    if (focus.length === 0) {
      return;
    }
    const focusedDomElement = this.view.domElement(focus[0]);
    if (!focusedDomElement) {
      return;
    }
    const tabIndexElement = focusedDomElement.querySelector("[tabIndex]");
    if (!tabIndexElement || !(tabIndexElement instanceof HTMLElement) || tabIndexElement.tabIndex === -1) {
      return;
    }
    const style2 = window.getComputedStyle(tabIndexElement);
    if (style2.visibility === "hidden" || style2.display === "none") {
      return;
    }
    e.preventDefault();
    e.stopPropagation();
    tabIndexElement.focus();
  }
  dispose() {
    this.disposables.dispose();
  }
}
function isSelectionSingleChangeEvent(event) {
  return isMacintosh ? event.browserEvent.metaKey : event.browserEvent.ctrlKey;
}
function isSelectionRangeChangeEvent(event) {
  return event.browserEvent.shiftKey;
}
function isMouseRightClick(event) {
  return event instanceof MouseEvent && event.button === 2;
}
const DefaultMultipleSelectionController = {
  isSelectionSingleChangeEvent,
  isSelectionRangeChangeEvent
};
class MouseController {
  constructor(list2) {
    this.list = list2;
    this.disposables = new DisposableStore();
    this._onPointer = new Emitter$1();
    this.onPointer = this._onPointer.event;
    if (list2.options.multipleSelectionSupport !== false) {
      this.multipleSelectionController = this.list.options.multipleSelectionController || DefaultMultipleSelectionController;
    }
    this.mouseSupport = typeof list2.options.mouseSupport === "undefined" || !!list2.options.mouseSupport;
    if (this.mouseSupport) {
      list2.onMouseDown(this.onMouseDown, this, this.disposables);
      list2.onContextMenu(this.onContextMenu, this, this.disposables);
      list2.onMouseDblClick(this.onDoubleClick, this, this.disposables);
      list2.onTouchStart(this.onMouseDown, this, this.disposables);
      this.disposables.add(Gesture.addTarget(list2.getHTMLElement()));
    }
    Event$1.any(list2.onMouseClick, list2.onMouseMiddleClick, list2.onTap)(this.onViewPointer, this, this.disposables);
  }
  updateOptions(optionsUpdate) {
    if (optionsUpdate.multipleSelectionSupport !== void 0) {
      this.multipleSelectionController = void 0;
      if (optionsUpdate.multipleSelectionSupport) {
        this.multipleSelectionController = this.list.options.multipleSelectionController || DefaultMultipleSelectionController;
      }
    }
  }
  isSelectionSingleChangeEvent(event) {
    if (!this.multipleSelectionController) {
      return false;
    }
    return this.multipleSelectionController.isSelectionSingleChangeEvent(event);
  }
  isSelectionRangeChangeEvent(event) {
    if (!this.multipleSelectionController) {
      return false;
    }
    return this.multipleSelectionController.isSelectionRangeChangeEvent(event);
  }
  isSelectionChangeEvent(event) {
    return this.isSelectionSingleChangeEvent(event) || this.isSelectionRangeChangeEvent(event);
  }
  onMouseDown(e) {
    if (isMonacoEditor(e.browserEvent.target)) {
      return;
    }
    if (document.activeElement !== e.browserEvent.target) {
      this.list.domFocus();
    }
  }
  onContextMenu(e) {
    if (isInputElement(e.browserEvent.target) || isMonacoEditor(e.browserEvent.target)) {
      return;
    }
    const focus = typeof e.index === "undefined" ? [] : [e.index];
    this.list.setFocus(focus, e.browserEvent);
  }
  onViewPointer(e) {
    if (!this.mouseSupport) {
      return;
    }
    if (isInputElement(e.browserEvent.target) || isMonacoEditor(e.browserEvent.target)) {
      return;
    }
    if (e.browserEvent.isHandledByList) {
      return;
    }
    e.browserEvent.isHandledByList = true;
    const focus = e.index;
    if (typeof focus === "undefined") {
      this.list.setFocus([], e.browserEvent);
      this.list.setSelection([], e.browserEvent);
      this.list.setAnchor(void 0);
      return;
    }
    if (this.isSelectionRangeChangeEvent(e)) {
      return this.changeSelection(e);
    }
    if (this.isSelectionChangeEvent(e)) {
      return this.changeSelection(e);
    }
    this.list.setFocus([focus], e.browserEvent);
    this.list.setAnchor(focus);
    if (!isMouseRightClick(e.browserEvent)) {
      this.list.setSelection([focus], e.browserEvent);
    }
    this._onPointer.fire(e);
  }
  onDoubleClick(e) {
    if (isInputElement(e.browserEvent.target) || isMonacoEditor(e.browserEvent.target)) {
      return;
    }
    if (this.isSelectionChangeEvent(e)) {
      return;
    }
    if (e.browserEvent.isHandledByList) {
      return;
    }
    e.browserEvent.isHandledByList = true;
    const focus = this.list.getFocus();
    this.list.setSelection(focus, e.browserEvent);
  }
  changeSelection(e) {
    const focus = e.index;
    let anchor = this.list.getAnchor();
    if (this.isSelectionRangeChangeEvent(e)) {
      if (typeof anchor === "undefined") {
        const currentFocus = this.list.getFocus()[0];
        anchor = currentFocus !== null && currentFocus !== void 0 ? currentFocus : focus;
        this.list.setAnchor(anchor);
      }
      const min = Math.min(anchor, focus);
      const max = Math.max(anchor, focus);
      const rangeSelection = range$1(min, max + 1);
      const selection = this.list.getSelection();
      const contiguousRange = getContiguousRangeContaining(disjunction(selection, [anchor]), anchor);
      if (contiguousRange.length === 0) {
        return;
      }
      const newSelection = disjunction(rangeSelection, relativeComplement(selection, contiguousRange));
      this.list.setSelection(newSelection, e.browserEvent);
      this.list.setFocus([focus], e.browserEvent);
    } else if (this.isSelectionSingleChangeEvent(e)) {
      const selection = this.list.getSelection();
      const newSelection = selection.filter((i) => i !== focus);
      this.list.setFocus([focus]);
      this.list.setAnchor(focus);
      if (selection.length === newSelection.length) {
        this.list.setSelection([...newSelection, focus], e.browserEvent);
      } else {
        this.list.setSelection(newSelection, e.browserEvent);
      }
    }
  }
  dispose() {
    this.disposables.dispose();
  }
}
class DefaultStyleController {
  constructor(styleElement, selectorSuffix) {
    this.styleElement = styleElement;
    this.selectorSuffix = selectorSuffix;
  }
  style(styles) {
    var _a2, _b2;
    const suffix = this.selectorSuffix && `.${this.selectorSuffix}`;
    const content = [];
    if (styles.listBackground) {
      content.push(`.monaco-list${suffix} .monaco-list-rows { background: ${styles.listBackground}; }`);
    }
    if (styles.listFocusBackground) {
      content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { background-color: ${styles.listFocusBackground}; }`);
      content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused:hover { background-color: ${styles.listFocusBackground}; }`);
    }
    if (styles.listFocusForeground) {
      content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused { color: ${styles.listFocusForeground}; }`);
    }
    if (styles.listActiveSelectionBackground) {
      content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { background-color: ${styles.listActiveSelectionBackground}; }`);
      content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected:hover { background-color: ${styles.listActiveSelectionBackground}; }`);
    }
    if (styles.listActiveSelectionForeground) {
      content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected { color: ${styles.listActiveSelectionForeground}; }`);
    }
    if (styles.listActiveSelectionIconForeground) {
      content.push(`.monaco-list${suffix}:focus .monaco-list-row.selected .codicon { color: ${styles.listActiveSelectionIconForeground}; }`);
    }
    if (styles.listFocusAndSelectionBackground) {
      content.push(`
				.monaco-drag-image,
				.monaco-list${suffix}:focus .monaco-list-row.selected.focused { background-color: ${styles.listFocusAndSelectionBackground}; }
			`);
    }
    if (styles.listFocusAndSelectionForeground) {
      content.push(`
				.monaco-drag-image,
				.monaco-list${suffix}:focus .monaco-list-row.selected.focused { color: ${styles.listFocusAndSelectionForeground}; }
			`);
    }
    if (styles.listInactiveFocusForeground) {
      content.push(`.monaco-list${suffix} .monaco-list-row.focused { color:  ${styles.listInactiveFocusForeground}; }`);
      content.push(`.monaco-list${suffix} .monaco-list-row.focused:hover { color:  ${styles.listInactiveFocusForeground}; }`);
    }
    if (styles.listInactiveSelectionIconForeground) {
      content.push(`.monaco-list${suffix} .monaco-list-row.focused .codicon { color:  ${styles.listInactiveSelectionIconForeground}; }`);
    }
    if (styles.listInactiveFocusBackground) {
      content.push(`.monaco-list${suffix} .monaco-list-row.focused { background-color:  ${styles.listInactiveFocusBackground}; }`);
      content.push(`.monaco-list${suffix} .monaco-list-row.focused:hover { background-color:  ${styles.listInactiveFocusBackground}; }`);
    }
    if (styles.listInactiveSelectionBackground) {
      content.push(`.monaco-list${suffix} .monaco-list-row.selected { background-color:  ${styles.listInactiveSelectionBackground}; }`);
      content.push(`.monaco-list${suffix} .monaco-list-row.selected:hover { background-color:  ${styles.listInactiveSelectionBackground}; }`);
    }
    if (styles.listInactiveSelectionForeground) {
      content.push(`.monaco-list${suffix} .monaco-list-row.selected { color: ${styles.listInactiveSelectionForeground}; }`);
    }
    if (styles.listHoverBackground) {
      content.push(`.monaco-list${suffix}:not(.drop-target):not(.dragging) .monaco-list-row:hover:not(.selected):not(.focused) { background-color: ${styles.listHoverBackground}; }`);
    }
    if (styles.listHoverForeground) {
      content.push(`.monaco-list${suffix}:not(.drop-target):not(.dragging) .monaco-list-row:hover:not(.selected):not(.focused) { color:  ${styles.listHoverForeground}; }`);
    }
    const focusAndSelectionOutline = asCssValueWithDefault(styles.listFocusAndSelectionOutline, asCssValueWithDefault(styles.listSelectionOutline, (_a2 = styles.listFocusOutline) !== null && _a2 !== void 0 ? _a2 : ""));
    if (focusAndSelectionOutline) {
      content.push(`.monaco-list${suffix}:focus .monaco-list-row.focused.selected { outline: 1px solid ${focusAndSelectionOutline}; outline-offset: -1px;}`);
    }
    if (styles.listFocusOutline) {
      content.push(`
				.monaco-drag-image,
				.monaco-list${suffix}:focus .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; }
				.monaco-workbench.context-menu-visible .monaco-list${suffix}.last-focused .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; }
			`);
    }
    const inactiveFocusAndSelectionOutline = asCssValueWithDefault(styles.listSelectionOutline, (_b2 = styles.listInactiveFocusOutline) !== null && _b2 !== void 0 ? _b2 : "");
    if (inactiveFocusAndSelectionOutline) {
      content.push(`.monaco-list${suffix} .monaco-list-row.focused.selected { outline: 1px dotted ${inactiveFocusAndSelectionOutline}; outline-offset: -1px; }`);
    }
    if (styles.listSelectionOutline) {
      content.push(`.monaco-list${suffix} .monaco-list-row.selected { outline: 1px dotted ${styles.listSelectionOutline}; outline-offset: -1px; }`);
    }
    if (styles.listInactiveFocusOutline) {
      content.push(`.monaco-list${suffix} .monaco-list-row.focused { outline: 1px dotted ${styles.listInactiveFocusOutline}; outline-offset: -1px; }`);
    }
    if (styles.listHoverOutline) {
      content.push(`.monaco-list${suffix} .monaco-list-row:hover { outline: 1px dashed ${styles.listHoverOutline}; outline-offset: -1px; }`);
    }
    if (styles.listDropBackground) {
      content.push(`
				.monaco-list${suffix}.drop-target,
				.monaco-list${suffix} .monaco-list-rows.drop-target,
				.monaco-list${suffix} .monaco-list-row.drop-target { background-color: ${styles.listDropBackground} !important; color: inherit !important; }
			`);
    }
    if (styles.tableColumnsBorder) {
      content.push(`
				.monaco-table > .monaco-split-view2,
				.monaco-table > .monaco-split-view2 .monaco-sash.vertical::before,
				.monaco-workbench:not(.reduce-motion) .monaco-table:hover > .monaco-split-view2,
				.monaco-workbench:not(.reduce-motion) .monaco-table:hover > .monaco-split-view2 .monaco-sash.vertical::before {
					border-color: ${styles.tableColumnsBorder};
				}

				.monaco-workbench:not(.reduce-motion) .monaco-table > .monaco-split-view2,
				.monaco-workbench:not(.reduce-motion) .monaco-table > .monaco-split-view2 .monaco-sash.vertical::before {
					border-color: transparent;
				}
			`);
    }
    if (styles.tableOddRowsBackgroundColor) {
      content.push(`
				.monaco-table .monaco-list-row[data-parity=odd]:not(.focused):not(.selected):not(:hover) .monaco-table-tr,
				.monaco-table .monaco-list:not(:focus) .monaco-list-row[data-parity=odd].focused:not(.selected):not(:hover) .monaco-table-tr,
				.monaco-table .monaco-list:not(.focused) .monaco-list-row[data-parity=odd].focused:not(.selected):not(:hover) .monaco-table-tr {
					background-color: ${styles.tableOddRowsBackgroundColor};
				}
			`);
    }
    this.styleElement.textContent = content.join("\n");
  }
}
const unthemedListStyles = {
  listFocusBackground: "#7FB0D0",
  listActiveSelectionBackground: "#0E639C",
  listActiveSelectionForeground: "#FFFFFF",
  listActiveSelectionIconForeground: "#FFFFFF",
  listFocusAndSelectionOutline: "#90C2F9",
  listFocusAndSelectionBackground: "#094771",
  listFocusAndSelectionForeground: "#FFFFFF",
  listInactiveSelectionBackground: "#3F3F46",
  listInactiveSelectionIconForeground: "#FFFFFF",
  listHoverBackground: "#2A2D2E",
  listDropBackground: "#383B3D",
  treeIndentGuidesStroke: "#a9a9a9",
  treeInactiveIndentGuidesStroke: Color.fromHex("#a9a9a9").transparent(0.4).toString(),
  tableColumnsBorder: Color.fromHex("#cccccc").transparent(0.2).toString(),
  tableOddRowsBackgroundColor: Color.fromHex("#cccccc").transparent(0.04).toString(),
  listBackground: void 0,
  listFocusForeground: void 0,
  listInactiveSelectionForeground: void 0,
  listInactiveFocusForeground: void 0,
  listInactiveFocusBackground: void 0,
  listHoverForeground: void 0,
  listFocusOutline: void 0,
  listInactiveFocusOutline: void 0,
  listSelectionOutline: void 0,
  listHoverOutline: void 0
};
const DefaultOptions = {
  keyboardSupport: true,
  mouseSupport: true,
  multipleSelectionSupport: true,
  dnd: {
    getDragURI() {
      return null;
    },
    onDragStart() {
    },
    onDragOver() {
      return false;
    },
    drop() {
    }
  }
};
function getContiguousRangeContaining(range2, value) {
  const index = range2.indexOf(value);
  if (index === -1) {
    return [];
  }
  const result2 = [];
  let i = index - 1;
  while (i >= 0 && range2[i] === value - (index - i)) {
    result2.push(range2[i--]);
  }
  result2.reverse();
  i = index;
  while (i < range2.length && range2[i] === value + (i - index)) {
    result2.push(range2[i++]);
  }
  return result2;
}
function disjunction(one, other) {
  const result2 = [];
  let i = 0, j = 0;
  while (i < one.length || j < other.length) {
    if (i >= one.length) {
      result2.push(other[j++]);
    } else if (j >= other.length) {
      result2.push(one[i++]);
    } else if (one[i] === other[j]) {
      result2.push(one[i]);
      i++;
      j++;
      continue;
    } else if (one[i] < other[j]) {
      result2.push(one[i++]);
    } else {
      result2.push(other[j++]);
    }
  }
  return result2;
}
function relativeComplement(one, other) {
  const result2 = [];
  let i = 0, j = 0;
  while (i < one.length || j < other.length) {
    if (i >= one.length) {
      result2.push(other[j++]);
    } else if (j >= other.length) {
      result2.push(one[i++]);
    } else if (one[i] === other[j]) {
      i++;
      j++;
      continue;
    } else if (one[i] < other[j]) {
      result2.push(one[i++]);
    } else {
      j++;
    }
  }
  return result2;
}
const numericSort = (a, b) => a - b;
class PipelineRenderer {
  constructor(_templateId, renderers) {
    this._templateId = _templateId;
    this.renderers = renderers;
  }
  get templateId() {
    return this._templateId;
  }
  renderTemplate(container2) {
    return this.renderers.map((r) => r.renderTemplate(container2));
  }
  renderElement(element, index, templateData, height) {
    let i = 0;
    for (const renderer2 of this.renderers) {
      renderer2.renderElement(element, index, templateData[i++], height);
    }
  }
  disposeElement(element, index, templateData, height) {
    var _a2;
    let i = 0;
    for (const renderer2 of this.renderers) {
      (_a2 = renderer2.disposeElement) === null || _a2 === void 0 ? void 0 : _a2.call(renderer2, element, index, templateData[i], height);
      i += 1;
    }
  }
  disposeTemplate(templateData) {
    let i = 0;
    for (const renderer2 of this.renderers) {
      renderer2.disposeTemplate(templateData[i++]);
    }
  }
}
class AccessibiltyRenderer {
  constructor(accessibilityProvider) {
    this.accessibilityProvider = accessibilityProvider;
    this.templateId = "a18n";
  }
  renderTemplate(container2) {
    return container2;
  }
  renderElement(element, index, container2) {
    const ariaLabel = this.accessibilityProvider.getAriaLabel(element);
    if (ariaLabel) {
      container2.setAttribute("aria-label", ariaLabel);
    } else {
      container2.removeAttribute("aria-label");
    }
    const ariaLevel = this.accessibilityProvider.getAriaLevel && this.accessibilityProvider.getAriaLevel(element);
    if (typeof ariaLevel === "number") {
      container2.setAttribute("aria-level", `${ariaLevel}`);
    } else {
      container2.removeAttribute("aria-level");
    }
  }
  disposeTemplate(templateData) {
  }
}
class ListViewDragAndDrop {
  constructor(list2, dnd2) {
    this.list = list2;
    this.dnd = dnd2;
  }
  getDragElements(element) {
    const selection = this.list.getSelectedElements();
    const elements = selection.indexOf(element) > -1 ? selection : [element];
    return elements;
  }
  getDragURI(element) {
    return this.dnd.getDragURI(element);
  }
  getDragLabel(elements, originalEvent) {
    if (this.dnd.getDragLabel) {
      return this.dnd.getDragLabel(elements, originalEvent);
    }
    return void 0;
  }
  onDragStart(data, originalEvent) {
    var _a2, _b2;
    (_b2 = (_a2 = this.dnd).onDragStart) === null || _b2 === void 0 ? void 0 : _b2.call(_a2, data, originalEvent);
  }
  onDragOver(data, targetElement, targetIndex, originalEvent) {
    return this.dnd.onDragOver(data, targetElement, targetIndex, originalEvent);
  }
  onDragLeave(data, targetElement, targetIndex, originalEvent) {
    var _a2, _b2;
    (_b2 = (_a2 = this.dnd).onDragLeave) === null || _b2 === void 0 ? void 0 : _b2.call(_a2, data, targetElement, targetIndex, originalEvent);
  }
  onDragEnd(originalEvent) {
    var _a2, _b2;
    (_b2 = (_a2 = this.dnd).onDragEnd) === null || _b2 === void 0 ? void 0 : _b2.call(_a2, originalEvent);
  }
  drop(data, targetElement, targetIndex, originalEvent) {
    this.dnd.drop(data, targetElement, targetIndex, originalEvent);
  }
}
class List {
  get onDidChangeFocus() {
    return Event$1.map(this.eventBufferer.wrapEvent(this.focus.onChange), (e) => this.toListEvent(e), this.disposables);
  }
  get onDidChangeSelection() {
    return Event$1.map(this.eventBufferer.wrapEvent(this.selection.onChange), (e) => this.toListEvent(e), this.disposables);
  }
  get domId() {
    return this.view.domId;
  }
  get onDidScroll() {
    return this.view.onDidScroll;
  }
  get onMouseClick() {
    return this.view.onMouseClick;
  }
  get onMouseDblClick() {
    return this.view.onMouseDblClick;
  }
  get onMouseMiddleClick() {
    return this.view.onMouseMiddleClick;
  }
  get onPointer() {
    return this.mouseController.onPointer;
  }
  get onMouseDown() {
    return this.view.onMouseDown;
  }
  get onMouseOver() {
    return this.view.onMouseOver;
  }
  get onMouseOut() {
    return this.view.onMouseOut;
  }
  get onTouchStart() {
    return this.view.onTouchStart;
  }
  get onTap() {
    return this.view.onTap;
  }
  /**
   * Possible context menu trigger events:
   * - ContextMenu key
   * - Shift F10
   * - Ctrl Option Shift M (macOS with VoiceOver)
   * - Mouse right click
   */
  get onContextMenu() {
    let didJustPressContextMenuKey = false;
    const fromKeyDown = this.disposables.add(Event$1.chain(this.disposables.add(new DomEmitter(this.view.domNode, "keydown")).event)).map((e) => new StandardKeyboardEvent(e)).filter((e) => didJustPressContextMenuKey = e.keyCode === 58 || e.shiftKey && e.keyCode === 68).map((e) => EventHelper.stop(e, true)).filter(() => false).event;
    const fromKeyUp = this.disposables.add(Event$1.chain(this.disposables.add(new DomEmitter(this.view.domNode, "keyup")).event)).forEach(() => didJustPressContextMenuKey = false).map((e) => new StandardKeyboardEvent(e)).filter((e) => e.keyCode === 58 || e.shiftKey && e.keyCode === 68).map((e) => EventHelper.stop(e, true)).map(({ browserEvent }) => {
      const focus = this.getFocus();
      const index = focus.length ? focus[0] : void 0;
      const element = typeof index !== "undefined" ? this.view.element(index) : void 0;
      const anchor = typeof index !== "undefined" ? this.view.domElement(index) : this.view.domNode;
      return { index, element, anchor, browserEvent };
    }).event;
    const fromMouse = this.disposables.add(Event$1.chain(this.view.onContextMenu)).filter((_) => !didJustPressContextMenuKey).map(({ element, index, browserEvent }) => ({ element, index, anchor: new StandardMouseEvent(browserEvent), browserEvent })).event;
    return Event$1.any(fromKeyDown, fromKeyUp, fromMouse);
  }
  get onKeyDown() {
    return this.disposables.add(new DomEmitter(this.view.domNode, "keydown")).event;
  }
  get onDidFocus() {
    return Event$1.signal(this.disposables.add(new DomEmitter(this.view.domNode, "focus", true)).event);
  }
  constructor(user, container2, virtualDelegate, renderers, _options = DefaultOptions) {
    var _a2, _b2, _c2, _d2;
    this.user = user;
    this._options = _options;
    this.focus = new Trait$1("focused");
    this.anchor = new Trait$1("anchor");
    this.eventBufferer = new EventBufferer();
    this._ariaLabel = "";
    this.disposables = new DisposableStore();
    this._onDidDispose = new Emitter$1();
    this.onDidDispose = this._onDidDispose.event;
    const role = this._options.accessibilityProvider && this._options.accessibilityProvider.getWidgetRole ? (_a2 = this._options.accessibilityProvider) === null || _a2 === void 0 ? void 0 : _a2.getWidgetRole() : "list";
    this.selection = new SelectionTrait(role !== "listbox");
    const baseRenderers = [this.focus.renderer, this.selection.renderer];
    this.accessibilityProvider = _options.accessibilityProvider;
    if (this.accessibilityProvider) {
      baseRenderers.push(new AccessibiltyRenderer(this.accessibilityProvider));
      (_c2 = (_b2 = this.accessibilityProvider).onDidChangeActiveDescendant) === null || _c2 === void 0 ? void 0 : _c2.call(_b2, this.onDidChangeActiveDescendant, this, this.disposables);
    }
    renderers = renderers.map((r) => new PipelineRenderer(r.templateId, [...baseRenderers, r]));
    const viewOptions = Object.assign(Object.assign({}, _options), { dnd: _options.dnd && new ListViewDragAndDrop(this, _options.dnd) });
    this.view = this.createListView(container2, virtualDelegate, renderers, viewOptions);
    this.view.domNode.setAttribute("role", role);
    if (_options.styleController) {
      this.styleController = _options.styleController(this.view.domId);
    } else {
      const styleElement = createStyleSheet(this.view.domNode);
      this.styleController = new DefaultStyleController(styleElement, this.view.domId);
    }
    this.spliceable = new CombinedSpliceable([
      new TraitSpliceable(this.focus, this.view, _options.identityProvider),
      new TraitSpliceable(this.selection, this.view, _options.identityProvider),
      new TraitSpliceable(this.anchor, this.view, _options.identityProvider),
      this.view
    ]);
    this.disposables.add(this.focus);
    this.disposables.add(this.selection);
    this.disposables.add(this.anchor);
    this.disposables.add(this.view);
    this.disposables.add(this._onDidDispose);
    this.disposables.add(new DOMFocusController(this, this.view));
    if (typeof _options.keyboardSupport !== "boolean" || _options.keyboardSupport) {
      this.keyboardController = new KeyboardController(this, this.view, _options);
      this.disposables.add(this.keyboardController);
    }
    if (_options.keyboardNavigationLabelProvider) {
      const delegate = _options.keyboardNavigationDelegate || DefaultKeyboardNavigationDelegate;
      this.typeNavigationController = new TypeNavigationController(this, this.view, _options.keyboardNavigationLabelProvider, (_d2 = _options.keyboardNavigationEventFilter) !== null && _d2 !== void 0 ? _d2 : () => true, delegate);
      this.disposables.add(this.typeNavigationController);
    }
    this.mouseController = this.createMouseController(_options);
    this.disposables.add(this.mouseController);
    this.onDidChangeFocus(this._onFocusChange, this, this.disposables);
    this.onDidChangeSelection(this._onSelectionChange, this, this.disposables);
    if (this.accessibilityProvider) {
      this.ariaLabel = this.accessibilityProvider.getWidgetAriaLabel();
    }
    if (this._options.multipleSelectionSupport !== false) {
      this.view.domNode.setAttribute("aria-multiselectable", "true");
    }
  }
  createListView(container2, virtualDelegate, renderers, viewOptions) {
    return new ListView(container2, virtualDelegate, renderers, viewOptions);
  }
  createMouseController(options) {
    return new MouseController(this);
  }
  updateOptions(optionsUpdate = {}) {
    var _a2, _b2;
    this._options = Object.assign(Object.assign({}, this._options), optionsUpdate);
    (_a2 = this.typeNavigationController) === null || _a2 === void 0 ? void 0 : _a2.updateOptions(this._options);
    if (this._options.multipleSelectionController !== void 0) {
      if (this._options.multipleSelectionSupport) {
        this.view.domNode.setAttribute("aria-multiselectable", "true");
      } else {
        this.view.domNode.removeAttribute("aria-multiselectable");
      }
    }
    this.mouseController.updateOptions(optionsUpdate);
    (_b2 = this.keyboardController) === null || _b2 === void 0 ? void 0 : _b2.updateOptions(optionsUpdate);
    this.view.updateOptions(optionsUpdate);
  }
  get options() {
    return this._options;
  }
  splice(start, deleteCount, elements = []) {
    if (start < 0 || start > this.view.length) {
      throw new ListError(this.user, `Invalid start index: ${start}`);
    }
    if (deleteCount < 0) {
      throw new ListError(this.user, `Invalid delete count: ${deleteCount}`);
    }
    if (deleteCount === 0 && elements.length === 0) {
      return;
    }
    this.eventBufferer.bufferEvents(() => this.spliceable.splice(start, deleteCount, elements));
  }
  rerender() {
    this.view.rerender();
  }
  element(index) {
    return this.view.element(index);
  }
  get length() {
    return this.view.length;
  }
  get contentHeight() {
    return this.view.contentHeight;
  }
  get scrollTop() {
    return this.view.getScrollTop();
  }
  set scrollTop(scrollTop) {
    this.view.setScrollTop(scrollTop);
  }
  get scrollHeight() {
    return this.view.scrollHeight;
  }
  get renderHeight() {
    return this.view.renderHeight;
  }
  get firstVisibleIndex() {
    return this.view.firstVisibleIndex;
  }
  get ariaLabel() {
    return this._ariaLabel;
  }
  set ariaLabel(value) {
    this._ariaLabel = value;
    this.view.domNode.setAttribute("aria-label", value);
  }
  domFocus() {
    this.view.domNode.focus({ preventScroll: true });
  }
  layout(height, width) {
    this.view.layout(height, width);
  }
  setSelection(indexes, browserEvent) {
    for (const index of indexes) {
      if (index < 0 || index >= this.length) {
        throw new ListError(this.user, `Invalid index ${index}`);
      }
    }
    this.selection.set(indexes, browserEvent);
  }
  getSelection() {
    return this.selection.get();
  }
  getSelectedElements() {
    return this.getSelection().map((i) => this.view.element(i));
  }
  setAnchor(index) {
    if (typeof index === "undefined") {
      this.anchor.set([]);
      return;
    }
    if (index < 0 || index >= this.length) {
      throw new ListError(this.user, `Invalid index ${index}`);
    }
    this.anchor.set([index]);
  }
  getAnchor() {
    return firstOrDefault(this.anchor.get(), void 0);
  }
  getAnchorElement() {
    const anchor = this.getAnchor();
    return typeof anchor === "undefined" ? void 0 : this.element(anchor);
  }
  setFocus(indexes, browserEvent) {
    for (const index of indexes) {
      if (index < 0 || index >= this.length) {
        throw new ListError(this.user, `Invalid index ${index}`);
      }
    }
    this.focus.set(indexes, browserEvent);
  }
  focusNext(n2 = 1, loop = false, browserEvent, filter2) {
    if (this.length === 0) {
      return;
    }
    const focus = this.focus.get();
    const index = this.findNextIndex(focus.length > 0 ? focus[0] + n2 : 0, loop, filter2);
    if (index > -1) {
      this.setFocus([index], browserEvent);
    }
  }
  focusPrevious(n2 = 1, loop = false, browserEvent, filter2) {
    if (this.length === 0) {
      return;
    }
    const focus = this.focus.get();
    const index = this.findPreviousIndex(focus.length > 0 ? focus[0] - n2 : 0, loop, filter2);
    if (index > -1) {
      this.setFocus([index], browserEvent);
    }
  }
  focusNextPage(browserEvent, filter2) {
    return __awaiter$1u(this, void 0, void 0, function* () {
      let lastPageIndex = this.view.indexAt(this.view.getScrollTop() + this.view.renderHeight);
      lastPageIndex = lastPageIndex === 0 ? 0 : lastPageIndex - 1;
      const currentlyFocusedElementIndex = this.getFocus()[0];
      if (currentlyFocusedElementIndex !== lastPageIndex && (currentlyFocusedElementIndex === void 0 || lastPageIndex > currentlyFocusedElementIndex)) {
        const lastGoodPageIndex = this.findPreviousIndex(lastPageIndex, false, filter2);
        if (lastGoodPageIndex > -1 && currentlyFocusedElementIndex !== lastGoodPageIndex) {
          this.setFocus([lastGoodPageIndex], browserEvent);
        } else {
          this.setFocus([lastPageIndex], browserEvent);
        }
      } else {
        const previousScrollTop = this.view.getScrollTop();
        let nextpageScrollTop = previousScrollTop + this.view.renderHeight;
        if (lastPageIndex > currentlyFocusedElementIndex) {
          nextpageScrollTop -= this.view.elementHeight(lastPageIndex);
        }
        this.view.setScrollTop(nextpageScrollTop);
        if (this.view.getScrollTop() !== previousScrollTop) {
          this.setFocus([]);
          yield timeout(0);
          yield this.focusNextPage(browserEvent, filter2);
        }
      }
    });
  }
  focusPreviousPage(browserEvent, filter2) {
    return __awaiter$1u(this, void 0, void 0, function* () {
      let firstPageIndex;
      const scrollTop = this.view.getScrollTop();
      if (scrollTop === 0) {
        firstPageIndex = this.view.indexAt(scrollTop);
      } else {
        firstPageIndex = this.view.indexAfter(scrollTop - 1);
      }
      const currentlyFocusedElementIndex = this.getFocus()[0];
      if (currentlyFocusedElementIndex !== firstPageIndex && (currentlyFocusedElementIndex === void 0 || currentlyFocusedElementIndex >= firstPageIndex)) {
        const firstGoodPageIndex = this.findNextIndex(firstPageIndex, false, filter2);
        if (firstGoodPageIndex > -1 && currentlyFocusedElementIndex !== firstGoodPageIndex) {
          this.setFocus([firstGoodPageIndex], browserEvent);
        } else {
          this.setFocus([firstPageIndex], browserEvent);
        }
      } else {
        const previousScrollTop = scrollTop;
        this.view.setScrollTop(scrollTop - this.view.renderHeight);
        if (this.view.getScrollTop() !== previousScrollTop) {
          this.setFocus([]);
          yield timeout(0);
          yield this.focusPreviousPage(browserEvent, filter2);
        }
      }
    });
  }
  focusLast(browserEvent, filter2) {
    if (this.length === 0) {
      return;
    }
    const index = this.findPreviousIndex(this.length - 1, false, filter2);
    if (index > -1) {
      this.setFocus([index], browserEvent);
    }
  }
  focusFirst(browserEvent, filter2) {
    this.focusNth(0, browserEvent, filter2);
  }
  focusNth(n2, browserEvent, filter2) {
    if (this.length === 0) {
      return;
    }
    const index = this.findNextIndex(n2, false, filter2);
    if (index > -1) {
      this.setFocus([index], browserEvent);
    }
  }
  findNextIndex(index, loop = false, filter2) {
    for (let i = 0; i < this.length; i++) {
      if (index >= this.length && !loop) {
        return -1;
      }
      index = index % this.length;
      if (!filter2 || filter2(this.element(index))) {
        return index;
      }
      index++;
    }
    return -1;
  }
  findPreviousIndex(index, loop = false, filter2) {
    for (let i = 0; i < this.length; i++) {
      if (index < 0 && !loop) {
        return -1;
      }
      index = (this.length + index % this.length) % this.length;
      if (!filter2 || filter2(this.element(index))) {
        return index;
      }
      index--;
    }
    return -1;
  }
  getFocus() {
    return this.focus.get();
  }
  getFocusedElements() {
    return this.getFocus().map((i) => this.view.element(i));
  }
  reveal(index, relativeTop) {
    if (index < 0 || index >= this.length) {
      throw new ListError(this.user, `Invalid index ${index}`);
    }
    const scrollTop = this.view.getScrollTop();
    const elementTop = this.view.elementTop(index);
    const elementHeight = this.view.elementHeight(index);
    if (isNumber$3(relativeTop)) {
      const m = elementHeight - this.view.renderHeight;
      this.view.setScrollTop(m * clamp(relativeTop, 0, 1) + elementTop);
    } else {
      const viewItemBottom = elementTop + elementHeight;
      const scrollBottom = scrollTop + this.view.renderHeight;
      if (elementTop < scrollTop && viewItemBottom >= scrollBottom)
        ;
      else if (elementTop < scrollTop || viewItemBottom >= scrollBottom && elementHeight >= this.view.renderHeight) {
        this.view.setScrollTop(elementTop);
      } else if (viewItemBottom >= scrollBottom) {
        this.view.setScrollTop(viewItemBottom - this.view.renderHeight);
      }
    }
  }
  getHTMLElement() {
    return this.view.domNode;
  }
  getElementID(index) {
    return this.view.getElementDomId(index);
  }
  style(styles) {
    this.styleController.style(styles);
  }
  toListEvent({ indexes, browserEvent }) {
    return { indexes, elements: indexes.map((i) => this.view.element(i)), browserEvent };
  }
  _onFocusChange() {
    const focus = this.focus.get();
    this.view.domNode.classList.toggle("element-focused", focus.length > 0);
    this.onDidChangeActiveDescendant();
  }
  onDidChangeActiveDescendant() {
    var _a2;
    const focus = this.focus.get();
    if (focus.length > 0) {
      let id3;
      if ((_a2 = this.accessibilityProvider) === null || _a2 === void 0 ? void 0 : _a2.getActiveDescendantId) {
        id3 = this.accessibilityProvider.getActiveDescendantId(this.view.element(focus[0]));
      }
      this.view.domNode.setAttribute("aria-activedescendant", id3 || this.view.getElementDomId(focus[0]));
    } else {
      this.view.domNode.removeAttribute("aria-activedescendant");
    }
  }
  _onSelectionChange() {
    const selection = this.selection.get();
    this.view.domNode.classList.toggle("selection-none", selection.length === 0);
    this.view.domNode.classList.toggle("selection-single", selection.length === 1);
    this.view.domNode.classList.toggle("selection-multiple", selection.length > 1);
  }
  dispose() {
    this._onDidDispose.fire();
    this.disposables.dispose();
    this._onDidDispose.dispose();
  }
}
__decorate$1_([
  memoize
], List.prototype, "onDidChangeFocus", null);
__decorate$1_([
  memoize
], List.prototype, "onDidChangeSelection", null);
__decorate$1_([
  memoize
], List.prototype, "onContextMenu", null);
__decorate$1_([
  memoize
], List.prototype, "onKeyDown", null);
__decorate$1_([
  memoize
], List.prototype, "onDidFocus", null);
const selectBoxCustom = "";
const $$c = $$d;
const SELECT_OPTION_ENTRY_TEMPLATE_ID = "selectOption.entry.template";
class SelectListRenderer {
  get templateId() {
    return SELECT_OPTION_ENTRY_TEMPLATE_ID;
  }
  renderTemplate(container2) {
    const data = /* @__PURE__ */ Object.create(null);
    data.root = container2;
    data.text = append$1(container2, $$c(".option-text"));
    data.detail = append$1(container2, $$c(".option-detail"));
    data.decoratorRight = append$1(container2, $$c(".option-decorator-right"));
    return data;
  }
  renderElement(element, index, templateData) {
    const data = templateData;
    const text2 = element.text;
    const detail = element.detail;
    const decoratorRight = element.decoratorRight;
    const isDisabled = element.isDisabled;
    data.text.textContent = text2;
    data.detail.textContent = !!detail ? detail : "";
    data.decoratorRight.innerText = !!decoratorRight ? decoratorRight : "";
    if (isDisabled) {
      data.root.classList.add("option-disabled");
    } else {
      data.root.classList.remove("option-disabled");
    }
  }
  disposeTemplate(_templateData) {
  }
}
class SelectBoxList extends Disposable {
  constructor(options, selected, contextViewProvider, styles, selectBoxOptions) {
    super();
    this.options = [];
    this._currentSelection = 0;
    this._hasDetails = false;
    this._skipLayout = false;
    this._sticky = false;
    this._isVisible = false;
    this.styles = styles;
    this.selectBoxOptions = selectBoxOptions || /* @__PURE__ */ Object.create(null);
    if (typeof this.selectBoxOptions.minBottomMargin !== "number") {
      this.selectBoxOptions.minBottomMargin = SelectBoxList.DEFAULT_DROPDOWN_MINIMUM_BOTTOM_MARGIN;
    } else if (this.selectBoxOptions.minBottomMargin < 0) {
      this.selectBoxOptions.minBottomMargin = 0;
    }
    this.selectElement = document.createElement("select");
    this.selectElement.className = "monaco-select-box monaco-select-box-dropdown-padding";
    if (typeof this.selectBoxOptions.ariaLabel === "string") {
      this.selectElement.setAttribute("aria-label", this.selectBoxOptions.ariaLabel);
    }
    if (typeof this.selectBoxOptions.ariaDescription === "string") {
      this.selectElement.setAttribute("aria-description", this.selectBoxOptions.ariaDescription);
    }
    this._onDidSelect = new Emitter$1();
    this._register(this._onDidSelect);
    this.registerListeners();
    this.constructSelectDropDown(contextViewProvider);
    this.selected = selected || 0;
    if (options) {
      this.setOptions(options, selected);
    }
    this.initStyleSheet();
  }
  // IDelegate - List renderer
  getHeight() {
    return 22;
  }
  getTemplateId() {
    return SELECT_OPTION_ENTRY_TEMPLATE_ID;
  }
  constructSelectDropDown(contextViewProvider) {
    this.contextViewProvider = contextViewProvider;
    this.selectDropDownContainer = $$d(".monaco-select-box-dropdown-container");
    this.selectDropDownContainer.classList.add("monaco-select-box-dropdown-padding");
    this.selectionDetailsPane = append$1(this.selectDropDownContainer, $$c(".select-box-details-pane"));
    const widthControlOuterDiv = append$1(this.selectDropDownContainer, $$c(".select-box-dropdown-container-width-control"));
    const widthControlInnerDiv = append$1(widthControlOuterDiv, $$c(".width-control-div"));
    this.widthControlElement = document.createElement("span");
    this.widthControlElement.className = "option-text-width-control";
    append$1(widthControlInnerDiv, this.widthControlElement);
    this._dropDownPosition = 0;
    this.styleElement = createStyleSheet(this.selectDropDownContainer);
    this.selectDropDownContainer.setAttribute("draggable", "true");
    this._register(addDisposableListener(this.selectDropDownContainer, EventType$1.DRAG_START, (e) => {
      EventHelper.stop(e, true);
    }));
  }
  registerListeners() {
    this._register(addStandardDisposableListener(this.selectElement, "change", (e) => {
      this.selected = e.target.selectedIndex;
      this._onDidSelect.fire({
        index: e.target.selectedIndex,
        selected: e.target.value
      });
      if (!!this.options[this.selected] && !!this.options[this.selected].text) {
        this.selectElement.title = this.options[this.selected].text;
      }
    }));
    this._register(addDisposableListener(this.selectElement, EventType$1.CLICK, (e) => {
      EventHelper.stop(e);
      if (this._isVisible) {
        this.hideSelectDropDown(true);
      } else {
        this.showSelectDropDown();
      }
    }));
    this._register(addDisposableListener(this.selectElement, EventType$1.MOUSE_DOWN, (e) => {
      EventHelper.stop(e);
    }));
    let listIsVisibleOnTouchStart;
    this._register(addDisposableListener(this.selectElement, "touchstart", (e) => {
      listIsVisibleOnTouchStart = this._isVisible;
    }));
    this._register(addDisposableListener(this.selectElement, "touchend", (e) => {
      EventHelper.stop(e);
      if (listIsVisibleOnTouchStart) {
        this.hideSelectDropDown(true);
      } else {
        this.showSelectDropDown();
      }
    }));
    this._register(addDisposableListener(this.selectElement, EventType$1.KEY_DOWN, (e) => {
      const event = new StandardKeyboardEvent(e);
      let showDropDown = false;
      if (isMacintosh) {
        if (event.keyCode === 18 || event.keyCode === 16 || event.keyCode === 10 || event.keyCode === 3) {
          showDropDown = true;
        }
      } else {
        if (event.keyCode === 18 && event.altKey || event.keyCode === 16 && event.altKey || event.keyCode === 10 || event.keyCode === 3) {
          showDropDown = true;
        }
      }
      if (showDropDown) {
        this.showSelectDropDown();
        EventHelper.stop(e, true);
      }
    }));
  }
  get onDidSelect() {
    return this._onDidSelect.event;
  }
  setOptions(options, selected) {
    if (!equals$3(this.options, options)) {
      this.options = options;
      this.selectElement.options.length = 0;
      this._hasDetails = false;
      this._cachedMaxDetailsHeight = void 0;
      this.options.forEach((option, index) => {
        this.selectElement.add(this.createOption(option.text, index, option.isDisabled));
        if (typeof option.description === "string") {
          this._hasDetails = true;
        }
      });
    }
    if (selected !== void 0) {
      this.select(selected);
      this._currentSelection = this.selected;
    }
  }
  setOptionsList() {
    var _a2;
    (_a2 = this.selectList) === null || _a2 === void 0 ? void 0 : _a2.splice(0, this.selectList.length, this.options);
  }
  select(index) {
    if (index >= 0 && index < this.options.length) {
      this.selected = index;
    } else if (index > this.options.length - 1) {
      this.select(this.options.length - 1);
    } else if (this.selected < 0) {
      this.selected = 0;
    }
    this.selectElement.selectedIndex = this.selected;
    if (!!this.options[this.selected] && !!this.options[this.selected].text) {
      this.selectElement.title = this.options[this.selected].text;
    }
  }
  focus() {
    if (this.selectElement) {
      this.selectElement.tabIndex = 0;
      this.selectElement.focus();
    }
  }
  blur() {
    if (this.selectElement) {
      this.selectElement.tabIndex = -1;
      this.selectElement.blur();
    }
  }
  setFocusable(focusable) {
    this.selectElement.tabIndex = focusable ? 0 : -1;
  }
  render(container2) {
    this.container = container2;
    container2.classList.add("select-container");
    container2.appendChild(this.selectElement);
    this.styleSelectElement();
  }
  initStyleSheet() {
    const content = [];
    if (this.styles.listFocusBackground) {
      content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.focused { background-color: ${this.styles.listFocusBackground} !important; }`);
    }
    if (this.styles.listFocusForeground) {
      content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.focused { color: ${this.styles.listFocusForeground} !important; }`);
    }
    if (this.styles.decoratorRightForeground) {
      content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row:not(.focused) .option-decorator-right { color: ${this.styles.decoratorRightForeground}; }`);
    }
    if (this.styles.selectBackground && this.styles.selectBorder && this.styles.selectBorder !== this.styles.selectBackground) {
      content.push(`.monaco-select-box-dropdown-container { border: 1px solid ${this.styles.selectBorder} } `);
      content.push(`.monaco-select-box-dropdown-container > .select-box-details-pane.border-top { border-top: 1px solid ${this.styles.selectBorder} } `);
      content.push(`.monaco-select-box-dropdown-container > .select-box-details-pane.border-bottom { border-bottom: 1px solid ${this.styles.selectBorder} } `);
    } else if (this.styles.selectListBorder) {
      content.push(`.monaco-select-box-dropdown-container > .select-box-details-pane.border-top { border-top: 1px solid ${this.styles.selectListBorder} } `);
      content.push(`.monaco-select-box-dropdown-container > .select-box-details-pane.border-bottom { border-bottom: 1px solid ${this.styles.selectListBorder} } `);
    }
    if (this.styles.listHoverForeground) {
      content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row:not(.option-disabled):not(.focused):hover { color: ${this.styles.listHoverForeground} !important; }`);
    }
    if (this.styles.listHoverBackground) {
      content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row:not(.option-disabled):not(.focused):hover { background-color: ${this.styles.listHoverBackground} !important; }`);
    }
    if (this.styles.listFocusOutline) {
      content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.focused { outline: 1.6px dotted ${this.styles.listFocusOutline} !important; outline-offset: -1.6px !important; }`);
    }
    if (this.styles.listHoverOutline) {
      content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row:not(.option-disabled):not(.focused):hover { outline: 1.6px dashed ${this.styles.listHoverOutline} !important; outline-offset: -1.6px !important; }`);
    }
    content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.option-disabled.focused { background-color: transparent !important; color: inherit !important; outline: none !important; }`);
    content.push(`.monaco-select-box-dropdown-container > .select-box-dropdown-list-container .monaco-list .monaco-list-row.option-disabled:hover { background-color: transparent !important; color: inherit !important; outline: none !important; }`);
    this.styleElement.textContent = content.join("\n");
  }
  styleSelectElement() {
    var _a2, _b2, _c2;
    const background = (_a2 = this.styles.selectBackground) !== null && _a2 !== void 0 ? _a2 : "";
    const foreground2 = (_b2 = this.styles.selectForeground) !== null && _b2 !== void 0 ? _b2 : "";
    const border = (_c2 = this.styles.selectBorder) !== null && _c2 !== void 0 ? _c2 : "";
    this.selectElement.style.backgroundColor = background;
    this.selectElement.style.color = foreground2;
    this.selectElement.style.borderColor = border;
  }
  styleList() {
    var _a2, _b2;
    const background = (_a2 = this.styles.selectBackground) !== null && _a2 !== void 0 ? _a2 : "";
    const listBackground = asCssValueWithDefault(this.styles.selectListBackground, background);
    this.selectDropDownListContainer.style.backgroundColor = listBackground;
    this.selectionDetailsPane.style.backgroundColor = listBackground;
    const optionsBorder = (_b2 = this.styles.focusBorder) !== null && _b2 !== void 0 ? _b2 : "";
    this.selectDropDownContainer.style.outlineColor = optionsBorder;
    this.selectDropDownContainer.style.outlineOffset = "-1px";
    this.selectList.style(this.styles);
  }
  createOption(value, index, disabled) {
    const option = document.createElement("option");
    option.value = value;
    option.text = value;
    option.disabled = !!disabled;
    return option;
  }
  // ContextView dropdown methods
  showSelectDropDown() {
    this.selectionDetailsPane.innerText = "";
    if (!this.contextViewProvider || this._isVisible) {
      return;
    }
    this.createSelectList(this.selectDropDownContainer);
    this.setOptionsList();
    this.contextViewProvider.showContextView({
      getAnchor: () => this.selectElement,
      render: (container2) => this.renderSelectDropDown(container2, true),
      layout: () => {
        this.layoutSelectDropDown();
      },
      onHide: () => {
        this.selectDropDownContainer.classList.remove("visible");
        this.selectElement.classList.remove("synthetic-focus");
      },
      anchorPosition: this._dropDownPosition
    }, this.selectBoxOptions.optionsAsChildren ? this.container : void 0);
    this._isVisible = true;
    this.hideSelectDropDown(false);
    this.contextViewProvider.showContextView({
      getAnchor: () => this.selectElement,
      render: (container2) => this.renderSelectDropDown(container2),
      layout: () => this.layoutSelectDropDown(),
      onHide: () => {
        this.selectDropDownContainer.classList.remove("visible");
        this.selectElement.classList.remove("synthetic-focus");
      },
      anchorPosition: this._dropDownPosition
    }, this.selectBoxOptions.optionsAsChildren ? this.container : void 0);
    this._currentSelection = this.selected;
    this._isVisible = true;
    this.selectElement.setAttribute("aria-expanded", "true");
  }
  hideSelectDropDown(focusSelect) {
    if (!this.contextViewProvider || !this._isVisible) {
      return;
    }
    this._isVisible = false;
    this.selectElement.setAttribute("aria-expanded", "false");
    if (focusSelect) {
      this.selectElement.focus();
    }
    this.contextViewProvider.hideContextView();
  }
  renderSelectDropDown(container2, preLayoutPosition) {
    container2.appendChild(this.selectDropDownContainer);
    this.layoutSelectDropDown(preLayoutPosition);
    return {
      dispose: () => {
        try {
          container2.removeChild(this.selectDropDownContainer);
        } catch (error2) {
        }
      }
    };
  }
  // Iterate over detailed descriptions, find max height
  measureMaxDetailsHeight() {
    let maxDetailsPaneHeight = 0;
    this.options.forEach((_option, index) => {
      this.updateDetail(index);
      if (this.selectionDetailsPane.offsetHeight > maxDetailsPaneHeight) {
        maxDetailsPaneHeight = this.selectionDetailsPane.offsetHeight;
      }
    });
    return maxDetailsPaneHeight;
  }
  layoutSelectDropDown(preLayoutPosition) {
    if (this._skipLayout) {
      return false;
    }
    if (this.selectList) {
      this.selectDropDownContainer.classList.add("visible");
      const selectPosition = getDomNodePagePosition(this.selectElement);
      const styles = getComputedStyle(this.selectElement);
      const verticalPadding = parseFloat(styles.getPropertyValue("--dropdown-padding-top")) + parseFloat(styles.getPropertyValue("--dropdown-padding-bottom"));
      const maxSelectDropDownHeightBelow = window.innerHeight - selectPosition.top - selectPosition.height - (this.selectBoxOptions.minBottomMargin || 0);
      const maxSelectDropDownHeightAbove = selectPosition.top - SelectBoxList.DEFAULT_DROPDOWN_MINIMUM_TOP_MARGIN;
      const selectWidth = this.selectElement.offsetWidth;
      const selectMinWidth = this.setWidthControlElement(this.widthControlElement);
      const selectOptimalWidth = Math.max(selectMinWidth, Math.round(selectWidth)).toString() + "px";
      this.selectDropDownContainer.style.width = selectOptimalWidth;
      this.selectList.getHTMLElement().style.height = "";
      this.selectList.layout();
      let listHeight = this.selectList.contentHeight;
      if (this._hasDetails && this._cachedMaxDetailsHeight === void 0) {
        this._cachedMaxDetailsHeight = this.measureMaxDetailsHeight();
      }
      const maxDetailsPaneHeight = this._hasDetails ? this._cachedMaxDetailsHeight : 0;
      const minRequiredDropDownHeight = listHeight + verticalPadding + maxDetailsPaneHeight;
      const maxVisibleOptionsBelow = Math.floor((maxSelectDropDownHeightBelow - verticalPadding - maxDetailsPaneHeight) / this.getHeight());
      const maxVisibleOptionsAbove = Math.floor((maxSelectDropDownHeightAbove - verticalPadding - maxDetailsPaneHeight) / this.getHeight());
      if (preLayoutPosition) {
        if (selectPosition.top + selectPosition.height > window.innerHeight - 22 || selectPosition.top < SelectBoxList.DEFAULT_DROPDOWN_MINIMUM_TOP_MARGIN || maxVisibleOptionsBelow < 1 && maxVisibleOptionsAbove < 1) {
          return false;
        }
        if (maxVisibleOptionsBelow < SelectBoxList.DEFAULT_MINIMUM_VISIBLE_OPTIONS && maxVisibleOptionsAbove > maxVisibleOptionsBelow && this.options.length > maxVisibleOptionsBelow) {
          this._dropDownPosition = 1;
          this.selectDropDownContainer.removeChild(this.selectDropDownListContainer);
          this.selectDropDownContainer.removeChild(this.selectionDetailsPane);
          this.selectDropDownContainer.appendChild(this.selectionDetailsPane);
          this.selectDropDownContainer.appendChild(this.selectDropDownListContainer);
          this.selectionDetailsPane.classList.remove("border-top");
          this.selectionDetailsPane.classList.add("border-bottom");
        } else {
          this._dropDownPosition = 0;
          this.selectDropDownContainer.removeChild(this.selectDropDownListContainer);
          this.selectDropDownContainer.removeChild(this.selectionDetailsPane);
          this.selectDropDownContainer.appendChild(this.selectDropDownListContainer);
          this.selectDropDownContainer.appendChild(this.selectionDetailsPane);
          this.selectionDetailsPane.classList.remove("border-bottom");
          this.selectionDetailsPane.classList.add("border-top");
        }
        return true;
      }
      if (selectPosition.top + selectPosition.height > window.innerHeight - 22 || selectPosition.top < SelectBoxList.DEFAULT_DROPDOWN_MINIMUM_TOP_MARGIN || this._dropDownPosition === 0 && maxVisibleOptionsBelow < 1 || this._dropDownPosition === 1 && maxVisibleOptionsAbove < 1) {
        this.hideSelectDropDown(true);
        return false;
      }
      if (this._dropDownPosition === 0) {
        if (this._isVisible && maxVisibleOptionsBelow + maxVisibleOptionsAbove < 1) {
          this.hideSelectDropDown(true);
          return false;
        }
        if (minRequiredDropDownHeight > maxSelectDropDownHeightBelow) {
          listHeight = maxVisibleOptionsBelow * this.getHeight();
        }
      } else {
        if (minRequiredDropDownHeight > maxSelectDropDownHeightAbove) {
          listHeight = maxVisibleOptionsAbove * this.getHeight();
        }
      }
      this.selectList.layout(listHeight);
      this.selectList.domFocus();
      if (this.selectList.length > 0) {
        this.selectList.setFocus([this.selected || 0]);
        this.selectList.reveal(this.selectList.getFocus()[0] || 0);
      }
      if (this._hasDetails) {
        this.selectList.getHTMLElement().style.height = listHeight + verticalPadding + "px";
        this.selectDropDownContainer.style.height = "";
      } else {
        this.selectDropDownContainer.style.height = listHeight + verticalPadding + "px";
      }
      this.updateDetail(this.selected);
      this.selectDropDownContainer.style.width = selectOptimalWidth;
      this.selectDropDownListContainer.setAttribute("tabindex", "0");
      this.selectElement.classList.add("synthetic-focus");
      this.selectDropDownContainer.classList.add("synthetic-focus");
      return true;
    } else {
      return false;
    }
  }
  setWidthControlElement(container2) {
    let elementWidth = 0;
    if (container2) {
      let longest = 0;
      let longestLength = 0;
      this.options.forEach((option, index) => {
        const detailLength = !!option.detail ? option.detail.length : 0;
        const rightDecoratorLength = !!option.decoratorRight ? option.decoratorRight.length : 0;
        const len = option.text.length + detailLength + rightDecoratorLength;
        if (len > longestLength) {
          longest = index;
          longestLength = len;
        }
      });
      container2.textContent = this.options[longest].text + (!!this.options[longest].decoratorRight ? this.options[longest].decoratorRight + " " : "");
      elementWidth = getTotalWidth(container2);
    }
    return elementWidth;
  }
  createSelectList(parent) {
    if (this.selectList) {
      return;
    }
    this.selectDropDownListContainer = append$1(parent, $$c(".select-box-dropdown-list-container"));
    this.listRenderer = new SelectListRenderer();
    this.selectList = new List("SelectBoxCustom", this.selectDropDownListContainer, this, [this.listRenderer], {
      useShadows: false,
      verticalScrollMode: 3,
      keyboardSupport: false,
      mouseSupport: false,
      accessibilityProvider: {
        getAriaLabel: (element) => {
          let label = element.text;
          if (element.detail) {
            label += `. ${element.detail}`;
          }
          if (element.decoratorRight) {
            label += `. ${element.decoratorRight}`;
          }
          if (element.description) {
            label += `. ${element.description}`;
          }
          return label;
        },
        getWidgetAriaLabel: () => localize({ key: "selectBox", comment: ["Behave like native select dropdown element."] }, "Select Box"),
        getRole: () => isMacintosh ? "" : "option",
        getWidgetRole: () => "listbox"
      }
    });
    if (this.selectBoxOptions.ariaLabel) {
      this.selectList.ariaLabel = this.selectBoxOptions.ariaLabel;
    }
    const onKeyDown = this._register(new DomEmitter(this.selectDropDownListContainer, "keydown"));
    const onSelectDropDownKeyDown = Event$1.chain(onKeyDown.event).filter(() => this.selectList.length > 0).map((e) => new StandardKeyboardEvent(e));
    this._register(onSelectDropDownKeyDown.filter(
      (e) => e.keyCode === 3
      /* KeyCode.Enter */
    ).on((e) => this.onEnter(e), this));
    this._register(onSelectDropDownKeyDown.filter(
      (e) => e.keyCode === 2
      /* KeyCode.Tab */
    ).on((e) => this.onEnter(e), this));
    this._register(onSelectDropDownKeyDown.filter(
      (e) => e.keyCode === 9
      /* KeyCode.Escape */
    ).on((e) => this.onEscape(e), this));
    this._register(onSelectDropDownKeyDown.filter(
      (e) => e.keyCode === 16
      /* KeyCode.UpArrow */
    ).on((e) => this.onUpArrow(e), this));
    this._register(onSelectDropDownKeyDown.filter(
      (e) => e.keyCode === 18
      /* KeyCode.DownArrow */
    ).on((e) => this.onDownArrow(e), this));
    this._register(onSelectDropDownKeyDown.filter(
      (e) => e.keyCode === 12
      /* KeyCode.PageDown */
    ).on(this.onPageDown, this));
    this._register(onSelectDropDownKeyDown.filter(
      (e) => e.keyCode === 11
      /* KeyCode.PageUp */
    ).on(this.onPageUp, this));
    this._register(onSelectDropDownKeyDown.filter(
      (e) => e.keyCode === 14
      /* KeyCode.Home */
    ).on(this.onHome, this));
    this._register(onSelectDropDownKeyDown.filter(
      (e) => e.keyCode === 13
      /* KeyCode.End */
    ).on(this.onEnd, this));
    this._register(onSelectDropDownKeyDown.filter((e) => e.keyCode >= 21 && e.keyCode <= 56 || e.keyCode >= 85 && e.keyCode <= 113).on(this.onCharacter, this));
    this._register(addDisposableListener(this.selectList.getHTMLElement(), EventType$1.POINTER_UP, (e) => this.onPointerUp(e)));
    this._register(this.selectList.onMouseOver((e) => typeof e.index !== "undefined" && this.selectList.setFocus([e.index])));
    this._register(this.selectList.onDidChangeFocus((e) => this.onListFocus(e)));
    this._register(addDisposableListener(this.selectDropDownContainer, EventType$1.FOCUS_OUT, (e) => {
      if (!this._isVisible || isAncestor$1(e.relatedTarget, this.selectDropDownContainer)) {
        return;
      }
      this.onListBlur();
    }));
    this.selectList.getHTMLElement().setAttribute("aria-label", this.selectBoxOptions.ariaLabel || "");
    this.selectList.getHTMLElement().setAttribute("aria-expanded", "true");
    this.styleList();
  }
  // List methods
  // List mouse controller - active exit, select option, fire onDidSelect if change, return focus to parent select
  // Also takes in touchend events
  onPointerUp(e) {
    if (!this.selectList.length) {
      return;
    }
    EventHelper.stop(e);
    const target = e.target;
    if (!target) {
      return;
    }
    if (target.classList.contains("slider")) {
      return;
    }
    const listRowElement = target.closest(".monaco-list-row");
    if (!listRowElement) {
      return;
    }
    const index = Number(listRowElement.getAttribute("data-index"));
    const disabled = listRowElement.classList.contains("option-disabled");
    if (index >= 0 && index < this.options.length && !disabled) {
      this.selected = index;
      this.select(this.selected);
      this.selectList.setFocus([this.selected]);
      this.selectList.reveal(this.selectList.getFocus()[0]);
      if (this.selected !== this._currentSelection) {
        this._currentSelection = this.selected;
        this._onDidSelect.fire({
          index: this.selectElement.selectedIndex,
          selected: this.options[this.selected].text
        });
        if (!!this.options[this.selected] && !!this.options[this.selected].text) {
          this.selectElement.title = this.options[this.selected].text;
        }
      }
      this.hideSelectDropDown(true);
    }
  }
  // List Exit - passive - implicit no selection change, hide drop-down
  onListBlur() {
    if (this._sticky) {
      return;
    }
    if (this.selected !== this._currentSelection) {
      this.select(this._currentSelection);
    }
    this.hideSelectDropDown(false);
  }
  renderDescriptionMarkdown(text2, actionHandler) {
    const cleanRenderedMarkdown = (element) => {
      for (let i = 0; i < element.childNodes.length; i++) {
        const child = element.childNodes.item(i);
        const tagName = child.tagName && child.tagName.toLowerCase();
        if (tagName === "img") {
          element.removeChild(child);
        } else {
          cleanRenderedMarkdown(child);
        }
      }
    };
    const rendered = renderMarkdown({ value: text2, supportThemeIcons: true }, { actionHandler });
    rendered.element.classList.add("select-box-description-markdown");
    cleanRenderedMarkdown(rendered.element);
    return rendered.element;
  }
  // List Focus Change - passive - update details pane with newly focused element's data
  onListFocus(e) {
    if (!this._isVisible || !this._hasDetails) {
      return;
    }
    this.updateDetail(e.indexes[0]);
  }
  updateDetail(selectedIndex) {
    var _a2, _b2;
    this.selectionDetailsPane.innerText = "";
    const option = this.options[selectedIndex];
    const description = (_a2 = option === null || option === void 0 ? void 0 : option.description) !== null && _a2 !== void 0 ? _a2 : "";
    const descriptionIsMarkdown = (_b2 = option === null || option === void 0 ? void 0 : option.descriptionIsMarkdown) !== null && _b2 !== void 0 ? _b2 : false;
    if (description) {
      if (descriptionIsMarkdown) {
        const actionHandler = option.descriptionMarkdownActionHandler;
        this.selectionDetailsPane.appendChild(this.renderDescriptionMarkdown(description, actionHandler));
      } else {
        this.selectionDetailsPane.innerText = description;
      }
      this.selectionDetailsPane.style.display = "block";
    } else {
      this.selectionDetailsPane.style.display = "none";
    }
    this._skipLayout = true;
    this.contextViewProvider.layout();
    this._skipLayout = false;
  }
  // List keyboard controller
  // List exit - active - hide ContextView dropdown, reset selection, return focus to parent select
  onEscape(e) {
    EventHelper.stop(e);
    this.select(this._currentSelection);
    this.hideSelectDropDown(true);
  }
  // List exit - active - hide ContextView dropdown, return focus to parent select, fire onDidSelect if change
  onEnter(e) {
    EventHelper.stop(e);
    if (this.selected !== this._currentSelection) {
      this._currentSelection = this.selected;
      this._onDidSelect.fire({
        index: this.selectElement.selectedIndex,
        selected: this.options[this.selected].text
      });
      if (!!this.options[this.selected] && !!this.options[this.selected].text) {
        this.selectElement.title = this.options[this.selected].text;
      }
    }
    this.hideSelectDropDown(true);
  }
  // List navigation - have to handle a disabled option (jump over)
  onDownArrow(e) {
    if (this.selected < this.options.length - 1) {
      EventHelper.stop(e, true);
      const nextOptionDisabled = this.options[this.selected + 1].isDisabled;
      if (nextOptionDisabled && this.options.length > this.selected + 2) {
        this.selected += 2;
      } else if (nextOptionDisabled) {
        return;
      } else {
        this.selected++;
      }
      this.select(this.selected);
      this.selectList.setFocus([this.selected]);
      this.selectList.reveal(this.selectList.getFocus()[0]);
    }
  }
  onUpArrow(e) {
    if (this.selected > 0) {
      EventHelper.stop(e, true);
      const previousOptionDisabled = this.options[this.selected - 1].isDisabled;
      if (previousOptionDisabled && this.selected > 1) {
        this.selected -= 2;
      } else {
        this.selected--;
      }
      this.select(this.selected);
      this.selectList.setFocus([this.selected]);
      this.selectList.reveal(this.selectList.getFocus()[0]);
    }
  }
  onPageUp(e) {
    EventHelper.stop(e);
    this.selectList.focusPreviousPage();
    setTimeout(() => {
      this.selected = this.selectList.getFocus()[0];
      if (this.options[this.selected].isDisabled && this.selected < this.options.length - 1) {
        this.selected++;
        this.selectList.setFocus([this.selected]);
      }
      this.selectList.reveal(this.selected);
      this.select(this.selected);
    }, 1);
  }
  onPageDown(e) {
    EventHelper.stop(e);
    this.selectList.focusNextPage();
    setTimeout(() => {
      this.selected = this.selectList.getFocus()[0];
      if (this.options[this.selected].isDisabled && this.selected > 0) {
        this.selected--;
        this.selectList.setFocus([this.selected]);
      }
      this.selectList.reveal(this.selected);
      this.select(this.selected);
    }, 1);
  }
  onHome(e) {
    EventHelper.stop(e);
    if (this.options.length < 2) {
      return;
    }
    this.selected = 0;
    if (this.options[this.selected].isDisabled && this.selected > 1) {
      this.selected++;
    }
    this.selectList.setFocus([this.selected]);
    this.selectList.reveal(this.selected);
    this.select(this.selected);
  }
  onEnd(e) {
    EventHelper.stop(e);
    if (this.options.length < 2) {
      return;
    }
    this.selected = this.options.length - 1;
    if (this.options[this.selected].isDisabled && this.selected > 1) {
      this.selected--;
    }
    this.selectList.setFocus([this.selected]);
    this.selectList.reveal(this.selected);
    this.select(this.selected);
  }
  // Mimic option first character navigation of native select
  onCharacter(e) {
    const ch = KeyCodeUtils.toString(e.keyCode);
    let optionIndex = -1;
    for (let i = 0; i < this.options.length - 1; i++) {
      optionIndex = (i + this.selected + 1) % this.options.length;
      if (this.options[optionIndex].text.charAt(0).toUpperCase() === ch && !this.options[optionIndex].isDisabled) {
        this.select(optionIndex);
        this.selectList.setFocus([optionIndex]);
        this.selectList.reveal(this.selectList.getFocus()[0]);
        EventHelper.stop(e);
        break;
      }
    }
  }
  dispose() {
    this.hideSelectDropDown(false);
    super.dispose();
  }
}
SelectBoxList.DEFAULT_DROPDOWN_MINIMUM_BOTTOM_MARGIN = 32;
SelectBoxList.DEFAULT_DROPDOWN_MINIMUM_TOP_MARGIN = 2;
SelectBoxList.DEFAULT_MINIMUM_VISIBLE_OPTIONS = 3;
class SelectBoxNative extends Disposable {
  constructor(options, selected, styles, selectBoxOptions) {
    super();
    this.selected = 0;
    this.selectBoxOptions = selectBoxOptions || /* @__PURE__ */ Object.create(null);
    this.options = [];
    this.selectElement = document.createElement("select");
    this.selectElement.className = "monaco-select-box";
    if (typeof this.selectBoxOptions.ariaLabel === "string") {
      this.selectElement.setAttribute("aria-label", this.selectBoxOptions.ariaLabel);
    }
    if (typeof this.selectBoxOptions.ariaDescription === "string") {
      this.selectElement.setAttribute("aria-description", this.selectBoxOptions.ariaDescription);
    }
    this._onDidSelect = this._register(new Emitter$1());
    this.styles = styles;
    this.registerListeners();
    this.setOptions(options, selected);
  }
  registerListeners() {
    this._register(Gesture.addTarget(this.selectElement));
    [EventType.Tap].forEach((eventType) => {
      this._register(addDisposableListener(this.selectElement, eventType, (e) => {
        this.selectElement.focus();
      }));
    });
    this._register(addStandardDisposableListener(this.selectElement, "click", (e) => {
      EventHelper.stop(e, true);
    }));
    this._register(addStandardDisposableListener(this.selectElement, "change", (e) => {
      this.selectElement.title = e.target.value;
      this._onDidSelect.fire({
        index: e.target.selectedIndex,
        selected: e.target.value
      });
    }));
    this._register(addStandardDisposableListener(this.selectElement, "keydown", (e) => {
      let showSelect = false;
      if (isMacintosh) {
        if (e.keyCode === 18 || e.keyCode === 16 || e.keyCode === 10) {
          showSelect = true;
        }
      } else {
        if (e.keyCode === 18 && e.altKey || e.keyCode === 10 || e.keyCode === 3) {
          showSelect = true;
        }
      }
      if (showSelect) {
        e.stopPropagation();
      }
    }));
  }
  get onDidSelect() {
    return this._onDidSelect.event;
  }
  setOptions(options, selected) {
    if (!this.options || !equals$3(this.options, options)) {
      this.options = options;
      this.selectElement.options.length = 0;
      this.options.forEach((option, index) => {
        this.selectElement.add(this.createOption(option.text, index, option.isDisabled));
      });
    }
    if (selected !== void 0) {
      this.select(selected);
    }
  }
  select(index) {
    if (this.options.length === 0) {
      this.selected = 0;
    } else if (index >= 0 && index < this.options.length) {
      this.selected = index;
    } else if (index > this.options.length - 1) {
      this.select(this.options.length - 1);
    } else if (this.selected < 0) {
      this.selected = 0;
    }
    this.selectElement.selectedIndex = this.selected;
    if (this.selected < this.options.length && typeof this.options[this.selected].text === "string") {
      this.selectElement.title = this.options[this.selected].text;
    } else {
      this.selectElement.title = "";
    }
  }
  focus() {
    if (this.selectElement) {
      this.selectElement.tabIndex = 0;
      this.selectElement.focus();
    }
  }
  blur() {
    if (this.selectElement) {
      this.selectElement.tabIndex = -1;
      this.selectElement.blur();
    }
  }
  setFocusable(focusable) {
    this.selectElement.tabIndex = focusable ? 0 : -1;
  }
  render(container2) {
    container2.classList.add("select-container");
    container2.appendChild(this.selectElement);
    this.setOptions(this.options, this.selected);
    this.applyStyles();
  }
  applyStyles() {
    var _a2, _b2, _c2;
    if (this.selectElement) {
      this.selectElement.style.backgroundColor = (_a2 = this.styles.selectBackground) !== null && _a2 !== void 0 ? _a2 : "";
      this.selectElement.style.color = (_b2 = this.styles.selectForeground) !== null && _b2 !== void 0 ? _b2 : "";
      this.selectElement.style.borderColor = (_c2 = this.styles.selectBorder) !== null && _c2 !== void 0 ? _c2 : "";
    }
  }
  createOption(value, index, disabled) {
    const option = document.createElement("option");
    option.value = value;
    option.text = value;
    option.disabled = !!disabled;
    return option;
  }
}
const selectBox = "";
class SelectBox extends Widget$1 {
  constructor(options, selected, contextViewProvider, styles, selectBoxOptions) {
    super();
    if (isMacintosh && !(selectBoxOptions === null || selectBoxOptions === void 0 ? void 0 : selectBoxOptions.useCustomDrawn)) {
      this.selectBoxDelegate = new SelectBoxNative(options, selected, styles, selectBoxOptions);
    } else {
      this.selectBoxDelegate = new SelectBoxList(options, selected, contextViewProvider, styles, selectBoxOptions);
    }
    this._register(this.selectBoxDelegate);
  }
  // Public SelectBox Methods - routed through delegate interface
  get onDidSelect() {
    return this.selectBoxDelegate.onDidSelect;
  }
  setOptions(options, selected) {
    this.selectBoxDelegate.setOptions(options, selected);
  }
  select(index) {
    this.selectBoxDelegate.select(index);
  }
  focus() {
    this.selectBoxDelegate.focus();
  }
  blur() {
    this.selectBoxDelegate.blur();
  }
  setFocusable(focusable) {
    this.selectBoxDelegate.setFocusable(focusable);
  }
  render(container2) {
    this.selectBoxDelegate.render(container2);
  }
}
const actionbar = "";
class BaseActionViewItem extends Disposable {
  get action() {
    return this._action;
  }
  constructor(context, action, options = {}) {
    super();
    this.options = options;
    this._context = context || this;
    this._action = action;
    if (action instanceof Action) {
      this._register(action.onDidChange((event) => {
        if (!this.element) {
          return;
        }
        this.handleActionChangeEvent(event);
      }));
    }
  }
  handleActionChangeEvent(event) {
    if (event.enabled !== void 0) {
      this.updateEnabled();
    }
    if (event.checked !== void 0) {
      this.updateChecked();
    }
    if (event.class !== void 0) {
      this.updateClass();
    }
    if (event.label !== void 0) {
      this.updateLabel();
      this.updateTooltip();
    }
    if (event.tooltip !== void 0) {
      this.updateTooltip();
    }
  }
  get actionRunner() {
    if (!this._actionRunner) {
      this._actionRunner = this._register(new ActionRunner());
    }
    return this._actionRunner;
  }
  set actionRunner(actionRunner) {
    this._actionRunner = actionRunner;
  }
  isEnabled() {
    return this._action.enabled;
  }
  setActionContext(newContext) {
    this._context = newContext;
  }
  render(container2) {
    const element = this.element = container2;
    this._register(Gesture.addTarget(container2));
    const enableDragging = this.options && this.options.draggable;
    if (enableDragging) {
      container2.draggable = true;
      if (isFirefox$1) {
        this._register(addDisposableListener(container2, EventType$1.DRAG_START, (e) => {
          var _a2;
          return (_a2 = e.dataTransfer) === null || _a2 === void 0 ? void 0 : _a2.setData(DataTransfers.TEXT, this._action.label);
        }));
      }
    }
    this._register(addDisposableListener(element, EventType.Tap, (e) => this.onClick(e, true)));
    this._register(addDisposableListener(element, EventType$1.MOUSE_DOWN, (e) => {
      if (!enableDragging) {
        EventHelper.stop(e, true);
      }
      if (this._action.enabled && e.button === 0) {
        element.classList.add("active");
      }
    }));
    if (isMacintosh) {
      this._register(addDisposableListener(element, EventType$1.CONTEXT_MENU, (e) => {
        if (e.button === 0 && e.ctrlKey === true) {
          this.onClick(e);
        }
      }));
    }
    this._register(addDisposableListener(element, EventType$1.CLICK, (e) => {
      EventHelper.stop(e, true);
      if (!(this.options && this.options.isMenu)) {
        this.onClick(e);
      }
    }));
    this._register(addDisposableListener(element, EventType$1.DBLCLICK, (e) => {
      EventHelper.stop(e, true);
    }));
    [EventType$1.MOUSE_UP, EventType$1.MOUSE_OUT].forEach((event) => {
      this._register(addDisposableListener(element, event, (e) => {
        EventHelper.stop(e);
        element.classList.remove("active");
      }));
    });
  }
  onClick(event, preserveFocus = false) {
    var _a2;
    EventHelper.stop(event, true);
    const context = isUndefinedOrNull(this._context) ? ((_a2 = this.options) === null || _a2 === void 0 ? void 0 : _a2.useEventAsContext) ? event : { preserveFocus } : this._context;
    this.actionRunner.run(this._action, context);
  }
  // Only set the tabIndex on the element once it is about to get focused
  // That way this element wont be a tab stop when it is not needed #106441
  focus() {
    if (this.element) {
      this.element.tabIndex = 0;
      this.element.focus();
      this.element.classList.add("focused");
    }
  }
  blur() {
    if (this.element) {
      this.element.blur();
      this.element.tabIndex = -1;
      this.element.classList.remove("focused");
    }
  }
  setFocusable(focusable) {
    if (this.element) {
      this.element.tabIndex = focusable ? 0 : -1;
    }
  }
  get trapsArrowNavigation() {
    return false;
  }
  updateEnabled() {
  }
  updateLabel() {
  }
  getTooltip() {
    return this.action.tooltip;
  }
  updateTooltip() {
    var _a2;
    if (!this.element) {
      return;
    }
    const title2 = (_a2 = this.getTooltip()) !== null && _a2 !== void 0 ? _a2 : "";
    this.updateAriaLabel();
    if (!this.options.hoverDelegate) {
      this.element.title = title2;
    } else {
      this.element.title = "";
      if (!this.customHover) {
        this.customHover = setupCustomHover(this.options.hoverDelegate, this.element, title2);
        this._store.add(this.customHover);
      } else {
        this.customHover.update(title2);
      }
    }
  }
  updateAriaLabel() {
    var _a2;
    if (this.element) {
      const title2 = (_a2 = this.getTooltip()) !== null && _a2 !== void 0 ? _a2 : "";
      this.element.setAttribute("aria-label", title2);
    }
  }
  updateClass() {
  }
  updateChecked() {
  }
  dispose() {
    if (this.element) {
      this.element.remove();
      this.element = void 0;
    }
    this._context = void 0;
    super.dispose();
  }
}
class ActionViewItem extends BaseActionViewItem {
  constructor(context, action, options) {
    super(context, action, options);
    this.options = options;
    this.options.icon = options.icon !== void 0 ? options.icon : false;
    this.options.label = options.label !== void 0 ? options.label : true;
    this.cssClass = "";
  }
  render(container2) {
    super.render(container2);
    if (this.element) {
      this.label = append$1(this.element, $$d("a.action-label"));
    }
    if (this.label) {
      this.label.setAttribute("role", this.getDefaultAriaRole());
    }
    if (this.options.label && this.options.keybinding && this.element) {
      append$1(this.element, $$d("span.keybinding")).textContent = this.options.keybinding;
    }
    this.updateClass();
    this.updateLabel();
    this.updateTooltip();
    this.updateEnabled();
    this.updateChecked();
  }
  getDefaultAriaRole() {
    if (this._action.id === Separator.ID) {
      return "presentation";
    } else {
      if (this.options.isMenu) {
        return "menuitem";
      } else {
        return "button";
      }
    }
  }
  // Only set the tabIndex on the element once it is about to get focused
  // That way this element wont be a tab stop when it is not needed #106441
  focus() {
    if (this.label) {
      this.label.tabIndex = 0;
      this.label.focus();
    }
  }
  blur() {
    if (this.label) {
      this.label.tabIndex = -1;
    }
  }
  setFocusable(focusable) {
    if (this.label) {
      this.label.tabIndex = focusable ? 0 : -1;
    }
  }
  updateLabel() {
    if (this.options.label && this.label) {
      this.label.textContent = this.action.label;
    }
  }
  getTooltip() {
    let title2 = null;
    if (this.action.tooltip) {
      title2 = this.action.tooltip;
    } else if (!this.options.label && this.action.label && this.options.icon) {
      title2 = this.action.label;
      if (this.options.keybinding) {
        title2 = localize({ key: "titleLabel", comment: ["action title", "action keybinding"] }, "{0} ({1})", title2, this.options.keybinding);
      }
    }
    return title2 !== null && title2 !== void 0 ? title2 : void 0;
  }
  updateClass() {
    var _a2;
    if (this.cssClass && this.label) {
      this.label.classList.remove(...this.cssClass.split(" "));
    }
    if (this.options.icon) {
      this.cssClass = this.action.class;
      if (this.label) {
        this.label.classList.add("codicon");
        if (this.cssClass) {
          this.label.classList.add(...this.cssClass.split(" "));
        }
      }
      this.updateEnabled();
    } else {
      (_a2 = this.label) === null || _a2 === void 0 ? void 0 : _a2.classList.remove("codicon");
    }
  }
  updateEnabled() {
    var _a2, _b2;
    if (this.action.enabled) {
      if (this.label) {
        this.label.removeAttribute("aria-disabled");
        this.label.classList.remove("disabled");
      }
      (_a2 = this.element) === null || _a2 === void 0 ? void 0 : _a2.classList.remove("disabled");
    } else {
      if (this.label) {
        this.label.setAttribute("aria-disabled", "true");
        this.label.classList.add("disabled");
      }
      (_b2 = this.element) === null || _b2 === void 0 ? void 0 : _b2.classList.add("disabled");
    }
  }
  updateAriaLabel() {
    var _a2;
    if (this.label) {
      const title2 = (_a2 = this.getTooltip()) !== null && _a2 !== void 0 ? _a2 : "";
      this.label.setAttribute("aria-label", title2);
    }
  }
  updateChecked() {
    if (this.label) {
      if (this.action.checked !== void 0) {
        this.label.classList.toggle("checked", this.action.checked);
        this.label.setAttribute("aria-checked", this.action.checked ? "true" : "false");
        this.label.setAttribute("role", "checkbox");
      } else {
        this.label.classList.remove("checked");
        this.label.setAttribute("aria-checked", "");
        this.label.setAttribute("role", this.getDefaultAriaRole());
      }
    }
  }
}
class SelectActionViewItem extends BaseActionViewItem {
  constructor(ctx, action, options, selected, contextViewProvider, styles, selectBoxOptions) {
    super(ctx, action);
    this.selectBox = new SelectBox(options, selected, contextViewProvider, styles, selectBoxOptions);
    this.selectBox.setFocusable(false);
    this._register(this.selectBox);
    this.registerListeners();
  }
  select(index) {
    this.selectBox.select(index);
  }
  registerListeners() {
    this._register(this.selectBox.onDidSelect((e) => this.runAction(e.selected, e.index)));
  }
  runAction(option, index) {
    this.actionRunner.run(this._action, this.getActionContext(option, index));
  }
  getActionContext(option, index) {
    return option;
  }
  setFocusable(focusable) {
    this.selectBox.setFocusable(focusable);
  }
  focus() {
    var _a2;
    (_a2 = this.selectBox) === null || _a2 === void 0 ? void 0 : _a2.focus();
  }
  blur() {
    var _a2;
    (_a2 = this.selectBox) === null || _a2 === void 0 ? void 0 : _a2.blur();
  }
  render(container2) {
    this.selectBox.render(container2);
  }
}
var __awaiter$1t = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class ActionBar extends Disposable {
  constructor(container2, options = {}) {
    var _a2, _b2, _c2, _d2, _e2, _f2;
    super();
    this._actionRunnerDisposables = this._register(new DisposableStore());
    this.viewItemDisposables = this._register(new DisposableMap());
    this.triggerKeyDown = false;
    this.focusable = true;
    this._onDidBlur = this._register(new Emitter$1());
    this.onDidBlur = this._onDidBlur.event;
    this._onDidCancel = this._register(new Emitter$1({ onWillAddFirstListener: () => this.cancelHasListener = true }));
    this.onDidCancel = this._onDidCancel.event;
    this.cancelHasListener = false;
    this._onDidRun = this._register(new Emitter$1());
    this.onDidRun = this._onDidRun.event;
    this._onWillRun = this._register(new Emitter$1());
    this.onWillRun = this._onWillRun.event;
    this.options = options;
    this._context = (_a2 = options.context) !== null && _a2 !== void 0 ? _a2 : null;
    this._orientation = (_b2 = this.options.orientation) !== null && _b2 !== void 0 ? _b2 : 0;
    this._triggerKeys = {
      keyDown: (_d2 = (_c2 = this.options.triggerKeys) === null || _c2 === void 0 ? void 0 : _c2.keyDown) !== null && _d2 !== void 0 ? _d2 : false,
      keys: (_f2 = (_e2 = this.options.triggerKeys) === null || _e2 === void 0 ? void 0 : _e2.keys) !== null && _f2 !== void 0 ? _f2 : [
        3,
        10
        /* KeyCode.Space */
      ]
    };
    if (this.options.actionRunner) {
      this._actionRunner = this.options.actionRunner;
    } else {
      this._actionRunner = new ActionRunner();
      this._actionRunnerDisposables.add(this._actionRunner);
    }
    this._actionRunnerDisposables.add(this._actionRunner.onDidRun((e) => this._onDidRun.fire(e)));
    this._actionRunnerDisposables.add(this._actionRunner.onWillRun((e) => this._onWillRun.fire(e)));
    this.viewItems = [];
    this.focusedItem = void 0;
    this.domNode = document.createElement("div");
    this.domNode.className = "monaco-action-bar";
    if (options.animated !== false) {
      this.domNode.classList.add("animated");
    }
    let previousKeys;
    let nextKeys;
    switch (this._orientation) {
      case 0:
        previousKeys = [
          15
          /* KeyCode.LeftArrow */
        ];
        nextKeys = [
          17
          /* KeyCode.RightArrow */
        ];
        break;
      case 1:
        previousKeys = [
          16
          /* KeyCode.UpArrow */
        ];
        nextKeys = [
          18
          /* KeyCode.DownArrow */
        ];
        this.domNode.className += " vertical";
        break;
    }
    this._register(addDisposableListener(this.domNode, EventType$1.KEY_DOWN, (e) => {
      const event = new StandardKeyboardEvent(e);
      let eventHandled = true;
      const focusedItem = typeof this.focusedItem === "number" ? this.viewItems[this.focusedItem] : void 0;
      if (previousKeys && (event.equals(previousKeys[0]) || event.equals(previousKeys[1]))) {
        eventHandled = this.focusPrevious();
      } else if (nextKeys && (event.equals(nextKeys[0]) || event.equals(nextKeys[1]))) {
        eventHandled = this.focusNext();
      } else if (event.equals(
        9
        /* KeyCode.Escape */
      ) && this.cancelHasListener) {
        this._onDidCancel.fire();
      } else if (event.equals(
        14
        /* KeyCode.Home */
      )) {
        eventHandled = this.focusFirst();
      } else if (event.equals(
        13
        /* KeyCode.End */
      )) {
        eventHandled = this.focusLast();
      } else if (event.equals(
        2
        /* KeyCode.Tab */
      ) && focusedItem instanceof BaseActionViewItem && focusedItem.trapsArrowNavigation) {
        eventHandled = this.focusNext();
      } else if (this.isTriggerKeyEvent(event)) {
        if (this._triggerKeys.keyDown) {
          this.doTrigger(event);
        } else {
          this.triggerKeyDown = true;
        }
      } else {
        eventHandled = false;
      }
      if (eventHandled) {
        event.preventDefault();
        event.stopPropagation();
      }
    }));
    this._register(addDisposableListener(this.domNode, EventType$1.KEY_UP, (e) => {
      const event = new StandardKeyboardEvent(e);
      if (this.isTriggerKeyEvent(event)) {
        if (!this._triggerKeys.keyDown && this.triggerKeyDown) {
          this.triggerKeyDown = false;
          this.doTrigger(event);
        }
        event.preventDefault();
        event.stopPropagation();
      } else if (event.equals(
        2
        /* KeyCode.Tab */
      ) || event.equals(
        1024 | 2
        /* KeyCode.Tab */
      )) {
        this.updateFocusedItem();
      }
    }));
    this.focusTracker = this._register(trackFocus(this.domNode));
    this._register(this.focusTracker.onDidBlur(() => {
      if (getActiveElement() === this.domNode || !isAncestor$1(getActiveElement(), this.domNode)) {
        this._onDidBlur.fire();
        this.focusedItem = void 0;
        this.previouslyFocusedItem = void 0;
        this.triggerKeyDown = false;
      }
    }));
    this._register(this.focusTracker.onDidFocus(() => this.updateFocusedItem()));
    this.actionsList = document.createElement("ul");
    this.actionsList.className = "actions-container";
    this.actionsList.setAttribute("role", this.options.ariaRole || "toolbar");
    if (this.options.ariaLabel) {
      this.actionsList.setAttribute("aria-label", this.options.ariaLabel);
    }
    this.domNode.appendChild(this.actionsList);
    container2.appendChild(this.domNode);
  }
  refreshRole() {
    if (this.length() >= 2) {
      this.actionsList.setAttribute("role", this.options.ariaRole || "toolbar");
    } else {
      this.actionsList.setAttribute("role", "presentation");
    }
  }
  // Some action bars should not be focusable at times
  // When an action bar is not focusable make sure to make all the elements inside it not focusable
  // When an action bar is focusable again, make sure the first item can be focused
  setFocusable(focusable) {
    this.focusable = focusable;
    if (this.focusable) {
      const firstEnabled = this.viewItems.find((vi) => vi instanceof BaseActionViewItem && vi.isEnabled());
      if (firstEnabled instanceof BaseActionViewItem) {
        firstEnabled.setFocusable(true);
      }
    } else {
      this.viewItems.forEach((vi) => {
        if (vi instanceof BaseActionViewItem) {
          vi.setFocusable(false);
        }
      });
    }
  }
  isTriggerKeyEvent(event) {
    let ret = false;
    this._triggerKeys.keys.forEach((keyCode) => {
      ret = ret || event.equals(keyCode);
    });
    return ret;
  }
  updateFocusedItem() {
    for (let i = 0; i < this.actionsList.children.length; i++) {
      const elem = this.actionsList.children[i];
      if (isAncestor$1(getActiveElement(), elem)) {
        this.focusedItem = i;
        break;
      }
    }
  }
  get context() {
    return this._context;
  }
  set context(context) {
    this._context = context;
    this.viewItems.forEach((i) => i.setActionContext(context));
  }
  get actionRunner() {
    return this._actionRunner;
  }
  set actionRunner(actionRunner) {
    this._actionRunner = actionRunner;
    this._actionRunnerDisposables.clear();
    this._actionRunnerDisposables.add(this._actionRunner.onDidRun((e) => this._onDidRun.fire(e)));
    this._actionRunnerDisposables.add(this._actionRunner.onWillRun((e) => this._onWillRun.fire(e)));
    this.viewItems.forEach((item) => item.actionRunner = actionRunner);
  }
  getContainer() {
    return this.domNode;
  }
  getAction(indexOrElement) {
    var _a2;
    if (typeof indexOrElement === "number") {
      return (_a2 = this.viewItems[indexOrElement]) === null || _a2 === void 0 ? void 0 : _a2.action;
    }
    if (indexOrElement instanceof HTMLElement) {
      while (indexOrElement.parentElement !== this.actionsList) {
        if (!indexOrElement.parentElement) {
          return void 0;
        }
        indexOrElement = indexOrElement.parentElement;
      }
      for (let i = 0; i < this.actionsList.childNodes.length; i++) {
        if (this.actionsList.childNodes[i] === indexOrElement) {
          return this.viewItems[i].action;
        }
      }
    }
    return void 0;
  }
  push(arg, options = {}) {
    const actions = Array.isArray(arg) ? arg : [arg];
    let index = isNumber$3(options.index) ? options.index : null;
    actions.forEach((action) => {
      const actionViewItemElement = document.createElement("li");
      actionViewItemElement.className = "action-item";
      actionViewItemElement.setAttribute("role", "presentation");
      let item;
      const viewItemOptions = Object.assign({ hoverDelegate: this.options.hoverDelegate }, options);
      if (this.options.actionViewItemProvider) {
        item = this.options.actionViewItemProvider(action, viewItemOptions);
      }
      if (!item) {
        item = new ActionViewItem(this.context, action, viewItemOptions);
      }
      if (!this.options.allowContextMenu) {
        this.viewItemDisposables.set(item, addDisposableListener(actionViewItemElement, EventType$1.CONTEXT_MENU, (e) => {
          EventHelper.stop(e, true);
        }));
      }
      item.actionRunner = this._actionRunner;
      item.setActionContext(this.context);
      item.render(actionViewItemElement);
      if (this.focusable && item instanceof BaseActionViewItem && this.viewItems.length === 0) {
        item.setFocusable(true);
      }
      if (index === null || index < 0 || index >= this.actionsList.children.length) {
        this.actionsList.appendChild(actionViewItemElement);
        this.viewItems.push(item);
      } else {
        this.actionsList.insertBefore(actionViewItemElement, this.actionsList.children[index]);
        this.viewItems.splice(index, 0, item);
        index++;
      }
    });
    if (typeof this.focusedItem === "number") {
      this.focus(this.focusedItem);
    }
    this.refreshRole();
  }
  clear() {
    if (this.isEmpty()) {
      return;
    }
    this.viewItems = dispose(this.viewItems);
    this.viewItemDisposables.clearAndDisposeAll();
    clearNode(this.actionsList);
    this.refreshRole();
  }
  length() {
    return this.viewItems.length;
  }
  isEmpty() {
    return this.viewItems.length === 0;
  }
  focus(arg) {
    let selectFirst = false;
    let index = void 0;
    if (arg === void 0) {
      selectFirst = true;
    } else if (typeof arg === "number") {
      index = arg;
    } else if (typeof arg === "boolean") {
      selectFirst = arg;
    }
    if (selectFirst && typeof this.focusedItem === "undefined") {
      const firstEnabled = this.viewItems.findIndex((item) => item.isEnabled());
      this.focusedItem = firstEnabled === -1 ? void 0 : firstEnabled;
      this.updateFocus(void 0, void 0, true);
    } else {
      if (index !== void 0) {
        this.focusedItem = index;
      }
      this.updateFocus(void 0, void 0, true);
    }
  }
  focusFirst() {
    this.focusedItem = this.length() - 1;
    return this.focusNext(true);
  }
  focusLast() {
    this.focusedItem = 0;
    return this.focusPrevious(true);
  }
  focusNext(forceLoop) {
    if (typeof this.focusedItem === "undefined") {
      this.focusedItem = this.viewItems.length - 1;
    } else if (this.viewItems.length <= 1) {
      return false;
    }
    const startIndex = this.focusedItem;
    let item;
    do {
      if (!forceLoop && this.options.preventLoopNavigation && this.focusedItem + 1 >= this.viewItems.length) {
        this.focusedItem = startIndex;
        return false;
      }
      this.focusedItem = (this.focusedItem + 1) % this.viewItems.length;
      item = this.viewItems[this.focusedItem];
    } while (this.focusedItem !== startIndex && (this.options.focusOnlyEnabledItems && !item.isEnabled() || item.action.id === Separator.ID));
    this.updateFocus();
    return true;
  }
  focusPrevious(forceLoop) {
    if (typeof this.focusedItem === "undefined") {
      this.focusedItem = 0;
    } else if (this.viewItems.length <= 1) {
      return false;
    }
    const startIndex = this.focusedItem;
    let item;
    do {
      this.focusedItem = this.focusedItem - 1;
      if (this.focusedItem < 0) {
        if (!forceLoop && this.options.preventLoopNavigation) {
          this.focusedItem = startIndex;
          return false;
        }
        this.focusedItem = this.viewItems.length - 1;
      }
      item = this.viewItems[this.focusedItem];
    } while (this.focusedItem !== startIndex && (this.options.focusOnlyEnabledItems && !item.isEnabled() || item.action.id === Separator.ID));
    this.updateFocus(true);
    return true;
  }
  updateFocus(fromRight, preventScroll, forceFocus = false) {
    var _a2;
    if (typeof this.focusedItem === "undefined") {
      this.actionsList.focus({ preventScroll });
    }
    if (this.previouslyFocusedItem !== void 0 && this.previouslyFocusedItem !== this.focusedItem) {
      (_a2 = this.viewItems[this.previouslyFocusedItem]) === null || _a2 === void 0 ? void 0 : _a2.blur();
    }
    const actionViewItem = this.focusedItem !== void 0 && this.viewItems[this.focusedItem];
    if (actionViewItem) {
      let focusItem = true;
      if (!isFunction$2(actionViewItem.focus)) {
        focusItem = false;
      }
      if (this.options.focusOnlyEnabledItems && isFunction$2(actionViewItem.isEnabled) && !actionViewItem.isEnabled()) {
        focusItem = false;
      }
      if (actionViewItem.action.id === Separator.ID) {
        focusItem = false;
      }
      if (!focusItem) {
        this.actionsList.focus({ preventScroll });
        this.previouslyFocusedItem = void 0;
      } else if (forceFocus || this.previouslyFocusedItem !== this.focusedItem) {
        actionViewItem.focus(fromRight);
        this.previouslyFocusedItem = this.focusedItem;
      }
    }
  }
  doTrigger(event) {
    if (typeof this.focusedItem === "undefined") {
      return;
    }
    const actionViewItem = this.viewItems[this.focusedItem];
    if (actionViewItem instanceof BaseActionViewItem) {
      const context = actionViewItem._context === null || actionViewItem._context === void 0 ? event : actionViewItem._context;
      this.run(actionViewItem._action, context);
    }
  }
  run(action, context) {
    return __awaiter$1t(this, void 0, void 0, function* () {
      yield this._actionRunner.run(action, context);
    });
  }
  dispose() {
    this._context = void 0;
    this.viewItems = dispose(this.viewItems);
    this.getContainer().remove();
    super.dispose();
  }
}
const diffReview = "";
const Extensions$2 = {
  IconContribution: "base.contributions.icons"
};
var IconContribution;
(function(IconContribution2) {
  function getDefinition(contribution, registry) {
    let definition = contribution.defaults;
    while (ThemeIcon.isThemeIcon(definition)) {
      const c = iconRegistry.getIcon(definition.id);
      if (!c) {
        return void 0;
      }
      definition = c.defaults;
    }
    return definition;
  }
  IconContribution2.getDefinition = getDefinition;
})(IconContribution || (IconContribution = {}));
var IconFontDefinition;
(function(IconFontDefinition2) {
  function toJSONObject(iconFont) {
    return {
      weight: iconFont.weight,
      style: iconFont.style,
      src: iconFont.src.map((s) => ({ format: s.format, location: s.location.toString() }))
    };
  }
  IconFontDefinition2.toJSONObject = toJSONObject;
  function fromJSONObject(json) {
    const stringOrUndef = (s) => isString$4(s) ? s : void 0;
    if (json && Array.isArray(json.src) && json.src.every((s) => isString$4(s.format) && isString$4(s.location))) {
      return {
        weight: stringOrUndef(json.weight),
        style: stringOrUndef(json.style),
        src: json.src.map((s) => ({ format: s.format, location: URI.parse(s.location) }))
      };
    }
    return void 0;
  }
  IconFontDefinition2.fromJSONObject = fromJSONObject;
})(IconFontDefinition || (IconFontDefinition = {}));
class IconRegistry {
  constructor() {
    this._onDidChange = new Emitter$1();
    this.onDidChange = this._onDidChange.event;
    this.iconSchema = {
      definitions: {
        icons: {
          type: "object",
          properties: {
            fontId: { type: "string", description: localize("iconDefinition.fontId", "The id of the font to use. If not set, the font that is defined first is used.") },
            fontCharacter: { type: "string", description: localize("iconDefinition.fontCharacter", "The font character associated with the icon definition.") }
          },
          additionalProperties: false,
          defaultSnippets: [{ body: { fontCharacter: "\\\\e030" } }]
        }
      },
      type: "object",
      properties: {}
    };
    this.iconReferenceSchema = { type: "string", pattern: `^${ThemeIcon.iconNameExpression}$`, enum: [], enumDescriptions: [] };
    this.iconsById = {};
    this.iconFontsById = {};
  }
  registerIcon(id3, defaults, description, deprecationMessage) {
    const existing = this.iconsById[id3];
    if (existing) {
      if (description && !existing.description) {
        existing.description = description;
        this.iconSchema.properties[id3].markdownDescription = `${description} $(${id3})`;
        const enumIndex = this.iconReferenceSchema.enum.indexOf(id3);
        if (enumIndex !== -1) {
          this.iconReferenceSchema.enumDescriptions[enumIndex] = description;
        }
        this._onDidChange.fire();
      }
      return existing;
    }
    const iconContribution = { id: id3, description, defaults, deprecationMessage };
    this.iconsById[id3] = iconContribution;
    const propertySchema = { $ref: "#/definitions/icons" };
    if (deprecationMessage) {
      propertySchema.deprecationMessage = deprecationMessage;
    }
    if (description) {
      propertySchema.markdownDescription = `${description}: $(${id3})`;
    }
    this.iconSchema.properties[id3] = propertySchema;
    this.iconReferenceSchema.enum.push(id3);
    this.iconReferenceSchema.enumDescriptions.push(description || "");
    this._onDidChange.fire();
    return { id: id3 };
  }
  getIcons() {
    return Object.keys(this.iconsById).map((id3) => this.iconsById[id3]);
  }
  getIcon(id3) {
    return this.iconsById[id3];
  }
  getIconSchema() {
    return this.iconSchema;
  }
  toString() {
    const sorter2 = (i1, i2) => {
      return i1.id.localeCompare(i2.id);
    };
    const classNames = (i) => {
      while (ThemeIcon.isThemeIcon(i.defaults)) {
        i = this.iconsById[i.defaults.id];
      }
      return `codicon codicon-${i ? i.id : ""}`;
    };
    const reference = [];
    reference.push(`| preview     | identifier                        | default codicon ID                | description`);
    reference.push(`| ----------- | --------------------------------- | --------------------------------- | --------------------------------- |`);
    const contributions = Object.keys(this.iconsById).map((key) => this.iconsById[key]);
    for (const i of contributions.filter((i2) => !!i2.description).sort(sorter2)) {
      reference.push(`|<i class="${classNames(i)}"></i>|${i.id}|${ThemeIcon.isThemeIcon(i.defaults) ? i.defaults.id : i.id}|${i.description || ""}|`);
    }
    reference.push(`| preview     | identifier                        `);
    reference.push(`| ----------- | --------------------------------- |`);
    for (const i of contributions.filter((i2) => !ThemeIcon.isThemeIcon(i2.defaults)).sort(sorter2)) {
      reference.push(`|<i class="${classNames(i)}"></i>|${i.id}|`);
    }
    return reference.join("\n");
  }
}
const iconRegistry = new IconRegistry();
Registry.add(Extensions$2.IconContribution, iconRegistry);
function registerIcon(id3, defaults, description, deprecationMessage) {
  return iconRegistry.registerIcon(id3, defaults, description, deprecationMessage);
}
function getIconRegistry() {
  return iconRegistry;
}
function initialize() {
  const codiconFontCharacters = getCodiconFontCharacters();
  for (const icon in codiconFontCharacters) {
    const fontCharacter = "\\" + codiconFontCharacters[icon].toString(16);
    iconRegistry.registerIcon(icon, { fontCharacter });
  }
}
initialize();
const iconsSchemaId = "vscode://schemas/icons";
const schemaRegistry = Registry.as(Extensions$7.JSONContribution);
schemaRegistry.registerSchema(iconsSchemaId, iconRegistry.getIconSchema());
const delayer = new RunOnceScheduler(() => schemaRegistry.notifySchemaChanged(iconsSchemaId), 200);
iconRegistry.onDidChange(() => {
  if (!delayer.isScheduled()) {
    delayer.schedule();
  }
});
const widgetClose = registerIcon("widget-close", Codicon.close, localize("widgetClose", "Icon for the close action in widgets."));
registerIcon("goto-previous-location", Codicon.arrowUp, localize("previousChangeIcon", "Icon for goto previous editor location."));
registerIcon("goto-next-location", Codicon.arrowDown, localize("nextChangeIcon", "Icon for goto next editor location."));
ThemeIcon.modify(Codicon.sync, "spin");
ThemeIcon.modify(Codicon.loading, "spin");
var __decorate$1Z = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1W = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$1s = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
const DIFF_LINES_PADDING = 3;
class DiffEntry {
  constructor(originalLineStart, originalLineEnd, modifiedLineStart, modifiedLineEnd) {
    this.originalLineStart = originalLineStart;
    this.originalLineEnd = originalLineEnd;
    this.modifiedLineStart = modifiedLineStart;
    this.modifiedLineEnd = modifiedLineEnd;
  }
  getType() {
    if (this.originalLineStart === 0) {
      return 1;
    }
    if (this.modifiedLineStart === 0) {
      return 2;
    }
    return 0;
  }
}
class Diff {
  constructor(entries) {
    this.entries = entries;
  }
}
const diffReviewInsertIcon = registerIcon("diff-review-insert", Codicon.add, localize("diffReviewInsertIcon", "Icon for 'Insert' in diff review."));
const diffReviewRemoveIcon = registerIcon("diff-review-remove", Codicon.remove, localize("diffReviewRemoveIcon", "Icon for 'Remove' in diff review."));
const diffReviewCloseIcon = registerIcon("diff-review-close", Codicon.close, localize("diffReviewCloseIcon", "Icon for 'Close' in diff review."));
let DiffReview = class DiffReview2 extends Disposable {
  constructor(diffEditor2, _languageService, _audioCueService, _configurationService) {
    super();
    this._languageService = _languageService;
    this._audioCueService = _audioCueService;
    this._configurationService = _configurationService;
    this._width = 0;
    this._diffEditor = diffEditor2;
    this._isVisible = false;
    this.shadow = createFastDomNode(document.createElement("div"));
    this.shadow.setClassName("diff-review-shadow");
    this.actionBarContainer = createFastDomNode(document.createElement("div"));
    this.actionBarContainer.setClassName("diff-review-actions");
    this._actionBar = this._register(new ActionBar(this.actionBarContainer.domNode));
    this._actionBar.push(new Action("diffreview.close", localize("label.close", "Close"), "close-diff-review " + ThemeIcon.asClassName(diffReviewCloseIcon), true, () => __awaiter$1s(this, void 0, void 0, function* () {
      return this.hide();
    })), { label: false, icon: true });
    this.domNode = createFastDomNode(document.createElement("div"));
    this.domNode.setClassName("diff-review monaco-editor-background");
    this._content = createFastDomNode(document.createElement("div"));
    this._content.setClassName("diff-review-content");
    this._content.setAttribute("role", "code");
    this.scrollbar = this._register(new DomScrollableElement(this._content.domNode, {}));
    this.domNode.domNode.appendChild(this.scrollbar.getDomNode());
    this._register(diffEditor2.onDidUpdateDiff(() => {
      if (!this._isVisible) {
        return;
      }
      this._diffs = this._compute();
      this._render();
    }));
    this._register(diffEditor2.getModifiedEditor().onDidChangeCursorPosition(() => {
      if (!this._isVisible) {
        return;
      }
      this._render();
    }));
    this._register(addStandardDisposableListener(this.domNode.domNode, "click", (e) => {
      e.preventDefault();
      const row = findParentWithClass(e.target, "diff-review-row");
      if (row) {
        this._goToRow(row);
      }
    }));
    this._register(addStandardDisposableListener(this.domNode.domNode, "keydown", (e) => {
      if (e.equals(
        18
        /* KeyCode.DownArrow */
      ) || e.equals(
        2048 | 18
        /* KeyCode.DownArrow */
      ) || e.equals(
        512 | 18
        /* KeyCode.DownArrow */
      )) {
        e.preventDefault();
        this._goToRow(this._getNextRow(), "next");
      }
      if (e.equals(
        16
        /* KeyCode.UpArrow */
      ) || e.equals(
        2048 | 16
        /* KeyCode.UpArrow */
      ) || e.equals(
        512 | 16
        /* KeyCode.UpArrow */
      )) {
        e.preventDefault();
        this._goToRow(this._getPrevRow(), "previous");
      }
      if (e.equals(
        9
        /* KeyCode.Escape */
      ) || e.equals(
        2048 | 9
        /* KeyCode.Escape */
      ) || e.equals(
        512 | 9
        /* KeyCode.Escape */
      ) || e.equals(
        1024 | 9
        /* KeyCode.Escape */
      ) || e.equals(
        10
        /* KeyCode.Space */
      ) || e.equals(
        3
        /* KeyCode.Enter */
      )) {
        e.preventDefault();
        this.accept();
      }
    }));
    this._register(this._configurationService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("accessibility.verbosity.diffEditor")) {
        this._diffEditor.updateOptions({ accessibilityVerbose: this._configurationService.getValue("accessibility.verbosity.diffEditor") });
      }
    }));
    this._diffs = [];
    this._currentDiff = null;
  }
  prev() {
    let index = 0;
    if (!this._isVisible) {
      this._diffs = this._compute();
    }
    if (this._isVisible) {
      let currentIndex = -1;
      for (let i = 0, len = this._diffs.length; i < len; i++) {
        if (this._diffs[i] === this._currentDiff) {
          currentIndex = i;
          break;
        }
      }
      index = this._diffs.length + currentIndex - 1;
    } else {
      index = this._findDiffIndex(this._diffEditor.getPosition());
    }
    if (this._diffs.length === 0) {
      return;
    }
    index = index % this._diffs.length;
    const entries = this._diffs[index].entries;
    this._diffEditor.setPosition(new Position$2(entries[0].modifiedLineStart, 1));
    this._diffEditor.setSelection({ startColumn: 1, startLineNumber: entries[0].modifiedLineStart, endColumn: 1073741824, endLineNumber: entries[entries.length - 1].modifiedLineEnd });
    this._isVisible = true;
    this._diffEditor.doLayout();
    this._render();
    this._goToRow(this._getPrevRow(), "previous");
  }
  next() {
    let index = 0;
    if (!this._isVisible) {
      this._diffs = this._compute();
    }
    if (this._isVisible) {
      let currentIndex = -1;
      for (let i = 0, len = this._diffs.length; i < len; i++) {
        if (this._diffs[i] === this._currentDiff) {
          currentIndex = i;
          break;
        }
      }
      index = currentIndex + 1;
    } else {
      index = this._findDiffIndex(this._diffEditor.getPosition());
    }
    if (this._diffs.length === 0) {
      return;
    }
    index = index % this._diffs.length;
    const entries = this._diffs[index].entries;
    this._diffEditor.setPosition(new Position$2(entries[0].modifiedLineStart, 1));
    this._diffEditor.setSelection({ startColumn: 1, startLineNumber: entries[0].modifiedLineStart, endColumn: 1073741824, endLineNumber: entries[entries.length - 1].modifiedLineEnd });
    this._isVisible = true;
    this._diffEditor.doLayout();
    this._render();
    this._goToRow(this._getNextRow(), "next");
  }
  accept() {
    let jumpToLineNumber = -1;
    const current = this._getCurrentFocusedRow();
    if (current) {
      const lineNumber = parseInt(current.getAttribute("data-line"), 10);
      if (!isNaN(lineNumber)) {
        jumpToLineNumber = lineNumber;
      }
    }
    this.hide();
    if (jumpToLineNumber !== -1) {
      this._diffEditor.setPosition(new Position$2(jumpToLineNumber, 1));
      this._diffEditor.revealPosition(
        new Position$2(jumpToLineNumber, 1),
        1
        /* ScrollType.Immediate */
      );
    }
  }
  hide() {
    this._isVisible = false;
    this._diffEditor.updateOptions({ readOnly: false });
    this._diffEditor.focus();
    this._diffEditor.doLayout();
    this._render();
  }
  _getPrevRow() {
    const current = this._getCurrentFocusedRow();
    if (!current) {
      return this._getFirstRow();
    }
    if (current.previousElementSibling) {
      return current.previousElementSibling;
    }
    return current;
  }
  _getNextRow() {
    const current = this._getCurrentFocusedRow();
    if (!current) {
      return this._getFirstRow();
    }
    if (current.nextElementSibling) {
      return current.nextElementSibling;
    }
    return current;
  }
  _getFirstRow() {
    return this.domNode.domNode.querySelector(".diff-review-row");
  }
  _getCurrentFocusedRow() {
    const result2 = document.activeElement;
    if (result2 && /diff-review-row/.test(result2.className)) {
      return result2;
    }
    return null;
  }
  _goToRow(row, type) {
    const current = this._getCurrentFocusedRow();
    row.tabIndex = 0;
    row.focus();
    if (current && current !== row) {
      current.tabIndex = -1;
    }
    const element = !type ? current : type === "next" ? current === null || current === void 0 ? void 0 : current.nextElementSibling : current === null || current === void 0 ? void 0 : current.previousElementSibling;
    if (element === null || element === void 0 ? void 0 : element.classList.contains(
      "line-insert"
      /* DiffEditorLineClasses.Insert */
    )) {
      this._audioCueService.playAudioCue(AudioCue.diffLineInserted, true);
    } else if (element === null || element === void 0 ? void 0 : element.classList.contains(
      "line-delete"
      /* DiffEditorLineClasses.Delete */
    )) {
      this._audioCueService.playAudioCue(AudioCue.diffLineDeleted, true);
    }
    this.scrollbar.scanDomNode();
  }
  isVisible() {
    return this._isVisible;
  }
  layout(top, width, height) {
    this._width = width;
    this.shadow.setTop(top - 6);
    this.shadow.setWidth(width);
    this.shadow.setHeight(this._isVisible ? 6 : 0);
    this.domNode.setTop(top);
    this.domNode.setWidth(width);
    this.domNode.setHeight(height);
    this._content.setHeight(height);
    this._content.setWidth(width);
    if (this._isVisible) {
      this.actionBarContainer.setAttribute("aria-hidden", "false");
      this.actionBarContainer.setDisplay("block");
    } else {
      this.actionBarContainer.setAttribute("aria-hidden", "true");
      this.actionBarContainer.setDisplay("none");
    }
  }
  _compute() {
    const lineChanges = this._diffEditor.getLineChanges();
    if (!lineChanges || lineChanges.length === 0) {
      return [];
    }
    const originalModel = this._diffEditor.getOriginalEditor().getModel();
    const modifiedModel = this._diffEditor.getModifiedEditor().getModel();
    if (!originalModel || !modifiedModel) {
      return [];
    }
    return DiffReview2._mergeAdjacent(lineChanges, originalModel.getLineCount(), modifiedModel.getLineCount());
  }
  static _mergeAdjacent(lineChanges, originalLineCount, modifiedLineCount) {
    if (!lineChanges || lineChanges.length === 0) {
      return [];
    }
    const diffs = [];
    let diffsLength = 0;
    for (let i = 0, len = lineChanges.length; i < len; i++) {
      const lineChange = lineChanges[i];
      const originalStart = lineChange.originalStartLineNumber;
      const originalEnd = lineChange.originalEndLineNumber;
      const modifiedStart = lineChange.modifiedStartLineNumber;
      const modifiedEnd = lineChange.modifiedEndLineNumber;
      const r2 = [];
      let rLength2 = 0;
      {
        const originalEqualAbove = originalEnd === 0 ? originalStart : originalStart - 1;
        const modifiedEqualAbove = modifiedEnd === 0 ? modifiedStart : modifiedStart - 1;
        let minOriginal = 1;
        let minModified = 1;
        if (i > 0) {
          const prevLineChange = lineChanges[i - 1];
          if (prevLineChange.originalEndLineNumber === 0) {
            minOriginal = prevLineChange.originalStartLineNumber + 1;
          } else {
            minOriginal = prevLineChange.originalEndLineNumber + 1;
          }
          if (prevLineChange.modifiedEndLineNumber === 0) {
            minModified = prevLineChange.modifiedStartLineNumber + 1;
          } else {
            minModified = prevLineChange.modifiedEndLineNumber + 1;
          }
        }
        let fromOriginal = originalEqualAbove - DIFF_LINES_PADDING + 1;
        let fromModified = modifiedEqualAbove - DIFF_LINES_PADDING + 1;
        if (fromOriginal < minOriginal) {
          const delta = minOriginal - fromOriginal;
          fromOriginal = fromOriginal + delta;
          fromModified = fromModified + delta;
        }
        if (fromModified < minModified) {
          const delta = minModified - fromModified;
          fromOriginal = fromOriginal + delta;
          fromModified = fromModified + delta;
        }
        r2[rLength2++] = new DiffEntry(fromOriginal, originalEqualAbove, fromModified, modifiedEqualAbove);
      }
      {
        if (originalEnd !== 0) {
          r2[rLength2++] = new DiffEntry(originalStart, originalEnd, 0, 0);
        }
      }
      {
        if (modifiedEnd !== 0) {
          r2[rLength2++] = new DiffEntry(0, 0, modifiedStart, modifiedEnd);
        }
      }
      {
        const originalEqualBelow = originalEnd === 0 ? originalStart + 1 : originalEnd + 1;
        const modifiedEqualBelow = modifiedEnd === 0 ? modifiedStart + 1 : modifiedEnd + 1;
        let maxOriginal = originalLineCount;
        let maxModified = modifiedLineCount;
        if (i + 1 < len) {
          const nextLineChange = lineChanges[i + 1];
          if (nextLineChange.originalEndLineNumber === 0) {
            maxOriginal = nextLineChange.originalStartLineNumber;
          } else {
            maxOriginal = nextLineChange.originalStartLineNumber - 1;
          }
          if (nextLineChange.modifiedEndLineNumber === 0) {
            maxModified = nextLineChange.modifiedStartLineNumber;
          } else {
            maxModified = nextLineChange.modifiedStartLineNumber - 1;
          }
        }
        let toOriginal = originalEqualBelow + DIFF_LINES_PADDING - 1;
        let toModified = modifiedEqualBelow + DIFF_LINES_PADDING - 1;
        if (toOriginal > maxOriginal) {
          const delta = maxOriginal - toOriginal;
          toOriginal = toOriginal + delta;
          toModified = toModified + delta;
        }
        if (toModified > maxModified) {
          const delta = maxModified - toModified;
          toOriginal = toOriginal + delta;
          toModified = toModified + delta;
        }
        r2[rLength2++] = new DiffEntry(originalEqualBelow, toOriginal, modifiedEqualBelow, toModified);
      }
      diffs[diffsLength++] = new Diff(r2);
    }
    let curr = diffs[0].entries;
    const r = [];
    let rLength = 0;
    for (let i = 1, len = diffs.length; i < len; i++) {
      const thisDiff = diffs[i].entries;
      const currLast = curr[curr.length - 1];
      const thisFirst = thisDiff[0];
      if (currLast.getType() === 0 && thisFirst.getType() === 0 && thisFirst.originalLineStart <= currLast.originalLineEnd) {
        curr[curr.length - 1] = new DiffEntry(currLast.originalLineStart, thisFirst.originalLineEnd, currLast.modifiedLineStart, thisFirst.modifiedLineEnd);
        curr = curr.concat(thisDiff.slice(1));
        continue;
      }
      r[rLength++] = new Diff(curr);
      curr = thisDiff;
    }
    r[rLength++] = new Diff(curr);
    return r;
  }
  _findDiffIndex(pos) {
    const lineNumber = pos.lineNumber;
    for (let i = 0, len = this._diffs.length; i < len; i++) {
      const diff = this._diffs[i].entries;
      const lastModifiedLine = diff[diff.length - 1].modifiedLineEnd;
      if (lineNumber <= lastModifiedLine) {
        return i;
      }
    }
    return 0;
  }
  _render() {
    const originalOptions = this._diffEditor.getOriginalEditor().getOptions();
    const modifiedOptions = this._diffEditor.getModifiedEditor().getOptions();
    const originalModel = this._diffEditor.getOriginalEditor().getModel();
    const modifiedModel = this._diffEditor.getModifiedEditor().getModel();
    const originalModelOpts = originalModel.getOptions();
    const modifiedModelOpts = modifiedModel.getOptions();
    if (!this._isVisible || !originalModel || !modifiedModel) {
      clearNode(this._content.domNode);
      this._currentDiff = null;
      this.scrollbar.scanDomNode();
      return;
    }
    this._diffEditor.updateOptions({ readOnly: true });
    const diffIndex = this._findDiffIndex(this._diffEditor.getPosition());
    if (this._diffs[diffIndex] === this._currentDiff) {
      return;
    }
    this._currentDiff = this._diffs[diffIndex];
    const diffs = this._diffs[diffIndex].entries;
    const container2 = document.createElement("div");
    container2.className = "diff-review-table";
    container2.setAttribute("role", "list");
    container2.setAttribute("aria-label", 'Difference review. Use "Stage | Unstage | Revert Selected Ranges" commands');
    applyFontInfo(container2, modifiedOptions.get(
      49
      /* EditorOption.fontInfo */
    ));
    let minOriginalLine = 0;
    let maxOriginalLine = 0;
    let minModifiedLine = 0;
    let maxModifiedLine = 0;
    for (let i = 0, len = diffs.length; i < len; i++) {
      const diffEntry = diffs[i];
      const originalLineStart = diffEntry.originalLineStart;
      const originalLineEnd = diffEntry.originalLineEnd;
      const modifiedLineStart = diffEntry.modifiedLineStart;
      const modifiedLineEnd = diffEntry.modifiedLineEnd;
      if (originalLineStart !== 0 && (minOriginalLine === 0 || originalLineStart < minOriginalLine)) {
        minOriginalLine = originalLineStart;
      }
      if (originalLineEnd !== 0 && (maxOriginalLine === 0 || originalLineEnd > maxOriginalLine)) {
        maxOriginalLine = originalLineEnd;
      }
      if (modifiedLineStart !== 0 && (minModifiedLine === 0 || modifiedLineStart < minModifiedLine)) {
        minModifiedLine = modifiedLineStart;
      }
      if (modifiedLineEnd !== 0 && (maxModifiedLine === 0 || modifiedLineEnd > maxModifiedLine)) {
        maxModifiedLine = modifiedLineEnd;
      }
    }
    const header = document.createElement("div");
    header.className = "diff-review-row";
    const cell = document.createElement("div");
    cell.className = "diff-review-cell diff-review-summary";
    const originalChangedLinesCnt = maxOriginalLine - minOriginalLine + 1;
    const modifiedChangedLinesCnt = maxModifiedLine - minModifiedLine + 1;
    cell.appendChild(document.createTextNode(`${diffIndex + 1}/${this._diffs.length}: @@ -${minOriginalLine},${originalChangedLinesCnt} +${minModifiedLine},${modifiedChangedLinesCnt} @@`));
    header.setAttribute("data-line", String(minModifiedLine));
    const getAriaLines = (lines) => {
      if (lines === 0) {
        return localize("no_lines_changed", "no lines changed");
      } else if (lines === 1) {
        return localize("one_line_changed", "1 line changed");
      } else {
        return localize("more_lines_changed", "{0} lines changed", lines);
      }
    };
    const originalChangedLinesCntAria = getAriaLines(originalChangedLinesCnt);
    const modifiedChangedLinesCntAria = getAriaLines(modifiedChangedLinesCnt);
    header.setAttribute("aria-label", localize({
      key: "header",
      comment: [
        "This is the ARIA label for a git diff header.",
        "A git diff header looks like this: @@ -154,12 +159,39 @@.",
        "That encodes that at original line 154 (which is now line 159), 12 lines were removed/changed with 39 lines.",
        "Variables 0 and 1 refer to the diff index out of total number of diffs.",
        "Variables 2 and 4 will be numbers (a line number).",
        'Variables 3 and 5 will be "no lines changed", "1 line changed" or "X lines changed", localized separately.'
      ]
    }, "Difference {0} of {1}: original line {2}, {3}, modified line {4}, {5}", diffIndex + 1, this._diffs.length, minOriginalLine, originalChangedLinesCntAria, minModifiedLine, modifiedChangedLinesCntAria));
    header.appendChild(cell);
    header.setAttribute("role", "listitem");
    container2.appendChild(header);
    const lineHeight = modifiedOptions.get(
      65
      /* EditorOption.lineHeight */
    );
    let modLine = minModifiedLine;
    for (let i = 0, len = diffs.length; i < len; i++) {
      const diffEntry = diffs[i];
      DiffReview2._renderSection(container2, diffEntry, modLine, lineHeight, this._width, originalOptions, originalModel, originalModelOpts, modifiedOptions, modifiedModel, modifiedModelOpts, this._languageService.languageIdCodec);
      if (diffEntry.modifiedLineStart !== 0) {
        modLine = diffEntry.modifiedLineEnd;
      }
    }
    clearNode(this._content.domNode);
    this._content.domNode.appendChild(container2);
    this.scrollbar.scanDomNode();
  }
  static _renderSection(dest, diffEntry, modLine, lineHeight, width, originalOptions, originalModel, originalModelOpts, modifiedOptions, modifiedModel, modifiedModelOpts, languageIdCodec) {
    const type = diffEntry.getType();
    let rowClassName = "diff-review-row";
    let lineNumbersExtraClassName = "";
    const spacerClassName = "diff-review-spacer";
    let spacerIcon = null;
    switch (type) {
      case 1:
        rowClassName = "diff-review-row line-insert";
        lineNumbersExtraClassName = " char-insert";
        spacerIcon = diffReviewInsertIcon;
        break;
      case 2:
        rowClassName = "diff-review-row line-delete";
        lineNumbersExtraClassName = " char-delete";
        spacerIcon = diffReviewRemoveIcon;
        break;
    }
    const originalLineStart = diffEntry.originalLineStart;
    const originalLineEnd = diffEntry.originalLineEnd;
    const modifiedLineStart = diffEntry.modifiedLineStart;
    const modifiedLineEnd = diffEntry.modifiedLineEnd;
    const cnt = Math.max(modifiedLineEnd - modifiedLineStart, originalLineEnd - originalLineStart);
    const originalLayoutInfo = originalOptions.get(
      142
      /* EditorOption.layoutInfo */
    );
    const originalLineNumbersWidth = originalLayoutInfo.glyphMarginWidth + originalLayoutInfo.lineNumbersWidth;
    const modifiedLayoutInfo = modifiedOptions.get(
      142
      /* EditorOption.layoutInfo */
    );
    const modifiedLineNumbersWidth = 10 + modifiedLayoutInfo.glyphMarginWidth + modifiedLayoutInfo.lineNumbersWidth;
    for (let i = 0; i <= cnt; i++) {
      const originalLine = originalLineStart === 0 ? 0 : originalLineStart + i;
      const modifiedLine = modifiedLineStart === 0 ? 0 : modifiedLineStart + i;
      const row = document.createElement("div");
      row.style.minWidth = width + "px";
      row.className = rowClassName;
      row.setAttribute("role", "listitem");
      if (modifiedLine !== 0) {
        modLine = modifiedLine;
      }
      row.setAttribute("data-line", String(modLine));
      const cell = document.createElement("div");
      cell.className = "diff-review-cell";
      cell.style.height = `${lineHeight}px`;
      row.appendChild(cell);
      const originalLineNumber = document.createElement("span");
      originalLineNumber.style.width = originalLineNumbersWidth + "px";
      originalLineNumber.style.minWidth = originalLineNumbersWidth + "px";
      originalLineNumber.className = "diff-review-line-number" + lineNumbersExtraClassName;
      if (originalLine !== 0) {
        originalLineNumber.appendChild(document.createTextNode(String(originalLine)));
      } else {
        originalLineNumber.innerText = " ";
      }
      cell.appendChild(originalLineNumber);
      const modifiedLineNumber = document.createElement("span");
      modifiedLineNumber.style.width = modifiedLineNumbersWidth + "px";
      modifiedLineNumber.style.minWidth = modifiedLineNumbersWidth + "px";
      modifiedLineNumber.style.paddingRight = "10px";
      modifiedLineNumber.className = "diff-review-line-number" + lineNumbersExtraClassName;
      if (modifiedLine !== 0) {
        modifiedLineNumber.appendChild(document.createTextNode(String(modifiedLine)));
      } else {
        modifiedLineNumber.innerText = " ";
      }
      cell.appendChild(modifiedLineNumber);
      const spacer = document.createElement("span");
      spacer.className = spacerClassName;
      if (spacerIcon) {
        const spacerCodicon = document.createElement("span");
        spacerCodicon.className = ThemeIcon.asClassName(spacerIcon);
        spacerCodicon.innerText = "  ";
        spacer.appendChild(spacerCodicon);
      } else {
        spacer.innerText = "  ";
      }
      cell.appendChild(spacer);
      let lineContent;
      if (modifiedLine !== 0) {
        let html2 = this._renderLine(modifiedModel, modifiedOptions, modifiedModelOpts.tabSize, modifiedLine, languageIdCodec);
        if (DiffReview2._ttPolicy) {
          html2 = DiffReview2._ttPolicy.createHTML(html2);
        }
        cell.insertAdjacentHTML("beforeend", html2);
        lineContent = modifiedModel.getLineContent(modifiedLine);
      } else {
        let html2 = this._renderLine(originalModel, originalOptions, originalModelOpts.tabSize, originalLine, languageIdCodec);
        if (DiffReview2._ttPolicy) {
          html2 = DiffReview2._ttPolicy.createHTML(html2);
        }
        cell.insertAdjacentHTML("beforeend", html2);
        lineContent = originalModel.getLineContent(originalLine);
      }
      if (lineContent.length === 0) {
        lineContent = localize("blankLine", "blank");
      }
      let ariaLabel = "";
      switch (type) {
        case 0:
          if (originalLine === modifiedLine) {
            ariaLabel = localize({ key: "unchangedLine", comment: ["The placeholders are contents of the line and should not be translated."] }, "{0} unchanged line {1}", lineContent, originalLine);
          } else {
            ariaLabel = localize("equalLine", "{0} original line {1} modified line {2}", lineContent, originalLine, modifiedLine);
          }
          break;
        case 1:
          ariaLabel = localize("insertLine", "+ {0} modified line {1}", lineContent, modifiedLine);
          break;
        case 2:
          ariaLabel = localize("deleteLine", "- {0} original line {1}", lineContent, originalLine);
          break;
      }
      row.setAttribute("aria-label", ariaLabel);
      dest.appendChild(row);
    }
  }
  static _renderLine(model, options, tabSize, lineNumber, languageIdCodec) {
    const lineContent = model.getLineContent(lineNumber);
    const fontInfo = options.get(
      49
      /* EditorOption.fontInfo */
    );
    const lineTokens = LineTokens.createEmpty(lineContent, languageIdCodec);
    const isBasicASCII2 = ViewLineRenderingData.isBasicASCII(lineContent, model.mightContainNonBasicASCII());
    const containsRTL2 = ViewLineRenderingData.containsRTL(lineContent, isBasicASCII2, model.mightContainRTL());
    const r = renderViewLine2(new RenderLineInput(fontInfo.isMonospace && !options.get(
      32
      /* EditorOption.disableMonospaceOptimizations */
    ), fontInfo.canUseHalfwidthRightwardsArrow, lineContent, false, isBasicASCII2, containsRTL2, 0, lineTokens, [], tabSize, 0, fontInfo.spaceWidth, fontInfo.middotWidth, fontInfo.wsmiddotWidth, options.get(
      115
      /* EditorOption.stopRenderingLineAfter */
    ), options.get(
      97
      /* EditorOption.renderWhitespace */
    ), options.get(
      92
      /* EditorOption.renderControlCharacters */
    ), options.get(
      50
      /* EditorOption.fontLigatures */
    ) !== EditorFontLigatures.OFF, null));
    return r.html;
  }
};
DiffReview._ttPolicy = createTrustedTypesPolicy("diffReview", { createHTML: (value) => value });
DiffReview = __decorate$1Z([
  __param$1W(1, ILanguageService),
  __param$1W(2, IAudioCueService),
  __param$1W(3, IConfigurationService)
], DiffReview);
var __awaiter$1r = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class InlineDiffMargin extends Disposable {
  get visibility() {
    return this._visibility;
  }
  set visibility(_visibility) {
    if (this._visibility !== _visibility) {
      this._visibility = _visibility;
      if (_visibility) {
        this._diffActions.style.visibility = "visible";
      } else {
        this._diffActions.style.visibility = "hidden";
      }
    }
  }
  constructor(_viewZoneId, _marginDomNode, editor2, diff, _contextMenuService, _clipboardService) {
    super();
    this._viewZoneId = _viewZoneId;
    this._marginDomNode = _marginDomNode;
    this.editor = editor2;
    this.diff = diff;
    this._contextMenuService = _contextMenuService;
    this._clipboardService = _clipboardService;
    this._visibility = false;
    this._marginDomNode.style.zIndex = "10";
    this._diffActions = document.createElement("div");
    this._diffActions.className = ThemeIcon.asClassName(Codicon.lightBulb) + " lightbulb-glyph";
    this._diffActions.style.position = "absolute";
    const lineHeight = editor2.getOption(
      65
      /* EditorOption.lineHeight */
    );
    const lineFeed = editor2.getModel().getEOL();
    this._diffActions.style.right = "0px";
    this._diffActions.style.visibility = "hidden";
    this._diffActions.style.height = `${lineHeight}px`;
    this._diffActions.style.lineHeight = `${lineHeight}px`;
    this._marginDomNode.appendChild(this._diffActions);
    const actions = [];
    const isDeletion = diff.modifiedEndLineNumber === 0;
    actions.push(new Action("diff.clipboard.copyDeletedContent", isDeletion ? diff.originalEndLineNumber > diff.modifiedStartLineNumber ? localize("diff.clipboard.copyDeletedLinesContent.label", "Copy deleted lines") : localize("diff.clipboard.copyDeletedLinesContent.single.label", "Copy deleted line") : diff.originalEndLineNumber > diff.modifiedStartLineNumber ? localize("diff.clipboard.copyChangedLinesContent.label", "Copy changed lines") : localize("diff.clipboard.copyChangedLinesContent.single.label", "Copy changed line"), void 0, true, () => __awaiter$1r(this, void 0, void 0, function* () {
      const range2 = new Range$2(diff.originalStartLineNumber, 1, diff.originalEndLineNumber + 1, 1);
      const deletedText = diff.originalModel.getValueInRange(range2);
      yield this._clipboardService.writeText(deletedText);
    })));
    let currentLineNumberOffset = 0;
    let copyLineAction = void 0;
    if (diff.originalEndLineNumber > diff.modifiedStartLineNumber) {
      copyLineAction = new Action("diff.clipboard.copyDeletedLineContent", isDeletion ? localize("diff.clipboard.copyDeletedLineContent.label", "Copy deleted line ({0})", diff.originalStartLineNumber) : localize("diff.clipboard.copyChangedLineContent.label", "Copy changed line ({0})", diff.originalStartLineNumber), void 0, true, () => __awaiter$1r(this, void 0, void 0, function* () {
        const lineContent = diff.originalModel.getLineContent(diff.originalStartLineNumber + currentLineNumberOffset);
        if (lineContent === "") {
          const eof = diff.originalModel.getEndOfLineSequence();
          yield this._clipboardService.writeText(eof === 0 ? "\n" : "\r\n");
        } else {
          yield this._clipboardService.writeText(lineContent);
        }
      }));
      actions.push(copyLineAction);
    }
    const readOnly = editor2.getOption(
      89
      /* EditorOption.readOnly */
    );
    if (!readOnly) {
      actions.push(new Action("diff.inline.revertChange", localize("diff.inline.revertChange.label", "Revert this change"), void 0, true, () => __awaiter$1r(this, void 0, void 0, function* () {
        const range2 = new Range$2(diff.originalStartLineNumber, 1, diff.originalEndLineNumber, diff.originalModel.getLineMaxColumn(diff.originalEndLineNumber));
        const deletedText = diff.originalModel.getValueInRange(range2);
        if (diff.modifiedEndLineNumber === 0) {
          const column = editor2.getModel().getLineMaxColumn(diff.modifiedStartLineNumber);
          editor2.executeEdits("diffEditor", [
            {
              range: new Range$2(diff.modifiedStartLineNumber, column, diff.modifiedStartLineNumber, column),
              text: lineFeed + deletedText
            }
          ]);
        } else {
          const column = editor2.getModel().getLineMaxColumn(diff.modifiedEndLineNumber);
          editor2.executeEdits("diffEditor", [
            {
              range: new Range$2(diff.modifiedStartLineNumber, 1, diff.modifiedEndLineNumber, column),
              text: deletedText
            }
          ]);
        }
      })));
    }
    const useShadowDOM = editor2.getOption(
      125
      /* EditorOption.useShadowDOM */
    ) && !isIOS;
    const showContextMenu = (x, y) => {
      var _a2;
      this._contextMenuService.showContextMenu({
        domForShadowRoot: useShadowDOM ? (_a2 = editor2.getDomNode()) !== null && _a2 !== void 0 ? _a2 : void 0 : void 0,
        getAnchor: () => {
          return {
            x,
            y
          };
        },
        getActions: () => {
          if (copyLineAction) {
            copyLineAction.label = isDeletion ? localize("diff.clipboard.copyDeletedLineContent.label", "Copy deleted line ({0})", diff.originalStartLineNumber + currentLineNumberOffset) : localize("diff.clipboard.copyChangedLineContent.label", "Copy changed line ({0})", diff.originalStartLineNumber + currentLineNumberOffset);
          }
          return actions;
        },
        autoSelectFirstItem: true
      });
    };
    this._register(addStandardDisposableListener(this._diffActions, "mousedown", (e) => {
      const { top, height } = getDomNodePagePosition(this._diffActions);
      const pad2 = Math.floor(lineHeight / 3);
      e.preventDefault();
      showContextMenu(e.posx, top + height + pad2);
    }));
    this._register(editor2.onMouseMove((e) => {
      if (e.target.type === 8 || e.target.type === 5) {
        const viewZoneId = e.target.detail.viewZoneId;
        if (viewZoneId === this._viewZoneId) {
          this.visibility = true;
          currentLineNumberOffset = this._updateLightBulbPosition(this._marginDomNode, e.event.browserEvent.y, lineHeight);
        } else {
          this.visibility = false;
        }
      } else {
        this.visibility = false;
      }
    }));
    this._register(editor2.onMouseDown((e) => {
      if (!e.event.rightButton) {
        return;
      }
      if (e.target.type === 8 || e.target.type === 5) {
        const viewZoneId = e.target.detail.viewZoneId;
        if (viewZoneId === this._viewZoneId) {
          e.event.preventDefault();
          currentLineNumberOffset = this._updateLightBulbPosition(this._marginDomNode, e.event.browserEvent.y, lineHeight);
          showContextMenu(e.event.posx, e.event.posy + lineHeight);
        }
      }
    }));
  }
  _updateLightBulbPosition(marginDomNode, y, lineHeight) {
    const { top } = getDomNodePagePosition(marginDomNode);
    const offset = y - top;
    const lineNumberOffset = Math.floor(offset / lineHeight);
    const newTop = lineNumberOffset * lineHeight;
    this._diffActions.style.top = `${newTop}px`;
    if (this.diff.viewLineCounts) {
      let acc = 0;
      for (let i = 0; i < this.diff.viewLineCounts.length; i++) {
        acc += this.diff.viewLineCounts[i];
        if (lineNumberOffset < acc) {
          return i;
        }
      }
    }
    return lineNumberOffset;
  }
}
class LinesDiff {
  constructor(changes, moves, hitTimeout) {
    this.changes = changes;
    this.moves = moves;
    this.hitTimeout = hitTimeout;
  }
}
class LineRangeMapping {
  static inverse(mapping, originalLineCount, modifiedLineCount) {
    const result2 = [];
    let lastOriginalEndLineNumber = 1;
    let lastModifiedEndLineNumber = 1;
    for (const m of mapping) {
      const r2 = new LineRangeMapping(new LineRange2(lastOriginalEndLineNumber, m.originalRange.startLineNumber), new LineRange2(lastModifiedEndLineNumber, m.modifiedRange.startLineNumber), void 0);
      if (!r2.modifiedRange.isEmpty) {
        result2.push(r2);
      }
      lastOriginalEndLineNumber = m.originalRange.endLineNumberExclusive;
      lastModifiedEndLineNumber = m.modifiedRange.endLineNumberExclusive;
    }
    const r = new LineRangeMapping(new LineRange2(lastOriginalEndLineNumber, originalLineCount + 1), new LineRange2(lastModifiedEndLineNumber, modifiedLineCount + 1), void 0);
    if (!r.modifiedRange.isEmpty) {
      result2.push(r);
    }
    return result2;
  }
  constructor(originalRange, modifiedRange, innerChanges) {
    this.originalRange = originalRange;
    this.modifiedRange = modifiedRange;
    this.innerChanges = innerChanges;
  }
  toString() {
    return `{${this.originalRange.toString()}->${this.modifiedRange.toString()}}`;
  }
  get changedLineCount() {
    return Math.max(this.originalRange.length, this.modifiedRange.length);
  }
  flip() {
    var _a2;
    return new LineRangeMapping(this.modifiedRange, this.originalRange, (_a2 = this.innerChanges) === null || _a2 === void 0 ? void 0 : _a2.map((c) => c.flip()));
  }
}
class RangeMapping {
  constructor(originalRange, modifiedRange) {
    this.originalRange = originalRange;
    this.modifiedRange = modifiedRange;
  }
  toString() {
    return `{${this.originalRange.toString()}->${this.modifiedRange.toString()}}`;
  }
  flip() {
    return new RangeMapping(this.modifiedRange, this.originalRange);
  }
}
class SimpleLineRangeMapping {
  constructor(original, modified) {
    this.original = original;
    this.modified = modified;
  }
  toString() {
    return `{${this.original.toString()}->${this.modified.toString()}}`;
  }
  flip() {
    return new SimpleLineRangeMapping(this.modified, this.original);
  }
}
class MovedText {
  constructor(lineRangeMapping, changes) {
    this.lineRangeMapping = lineRangeMapping;
    this.changes = changes;
  }
  flip() {
    return new MovedText(this.lineRangeMapping.flip(), this.changes.map((c) => c.flip()));
  }
}
const IEditorWorkerService = createDecorator("editorWorkerService");
var __decorate$1Y = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1V = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$1q = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
let WorkerBasedDocumentDiffProvider = class WorkerBasedDocumentDiffProvider2 {
  constructor(options, editorWorkerService, telemetryService) {
    this.editorWorkerService = editorWorkerService;
    this.telemetryService = telemetryService;
    this.onDidChangeEventEmitter = new Emitter$1();
    this.onDidChange = this.onDidChangeEventEmitter.event;
    this.diffAlgorithm = "advanced";
    this.diffAlgorithmOnDidChangeSubscription = void 0;
    this.setOptions(options);
  }
  dispose() {
    var _a2;
    (_a2 = this.diffAlgorithmOnDidChangeSubscription) === null || _a2 === void 0 ? void 0 : _a2.dispose();
  }
  computeDiff(original, modified, options) {
    var _a2;
    return __awaiter$1q(this, void 0, void 0, function* () {
      if (typeof this.diffAlgorithm !== "string") {
        return this.diffAlgorithm.computeDiff(original, modified, options);
      }
      if (original.getLineCount() === 1 && original.getLineMaxColumn(1) === 1) {
        return {
          changes: [
            new LineRangeMapping(new LineRange2(1, 2), new LineRange2(1, modified.getLineCount() + 1), [
              new RangeMapping(original.getFullModelRange(), modified.getFullModelRange())
            ])
          ],
          identical: false,
          quitEarly: false,
          moves: []
        };
      }
      const uriKey = JSON.stringify([original.uri.toString(), modified.uri.toString()]);
      const context = JSON.stringify([original.id, modified.id, original.getAlternativeVersionId(), modified.getAlternativeVersionId(), JSON.stringify(options)]);
      const c = WorkerBasedDocumentDiffProvider2.diffCache.get(uriKey);
      if (c && c.context === context) {
        return c.result;
      }
      const sw = StopWatch.create();
      const result2 = yield this.editorWorkerService.computeDiff(original.uri, modified.uri, options, this.diffAlgorithm);
      const timeMs = sw.elapsed();
      this.telemetryService.publicLog2("diffEditor.computeDiff", {
        timeMs,
        timedOut: (_a2 = result2 === null || result2 === void 0 ? void 0 : result2.quitEarly) !== null && _a2 !== void 0 ? _a2 : true
      });
      if (!result2) {
        throw new Error("no diff result available");
      }
      if (WorkerBasedDocumentDiffProvider2.diffCache.size > 10) {
        WorkerBasedDocumentDiffProvider2.diffCache.delete(WorkerBasedDocumentDiffProvider2.diffCache.keys().next().value);
      }
      WorkerBasedDocumentDiffProvider2.diffCache.set(uriKey, { result: result2, context });
      return result2;
    });
  }
  setOptions(newOptions) {
    var _a2;
    let didChange = false;
    if (newOptions.diffAlgorithm) {
      if (this.diffAlgorithm !== newOptions.diffAlgorithm) {
        (_a2 = this.diffAlgorithmOnDidChangeSubscription) === null || _a2 === void 0 ? void 0 : _a2.dispose();
        this.diffAlgorithmOnDidChangeSubscription = void 0;
        this.diffAlgorithm = newOptions.diffAlgorithm;
        if (typeof newOptions.diffAlgorithm !== "string") {
          this.diffAlgorithmOnDidChangeSubscription = newOptions.diffAlgorithm.onDidChange(() => this.onDidChangeEventEmitter.fire());
        }
        didChange = true;
      }
    }
    if (didChange) {
      this.onDidChangeEventEmitter.fire();
    }
  }
};
WorkerBasedDocumentDiffProvider.diffCache = /* @__PURE__ */ new Map();
WorkerBasedDocumentDiffProvider = __decorate$1Y([
  __param$1V(1, IEditorWorkerService),
  __param$1V(2, ITelemetryService)
], WorkerBasedDocumentDiffProvider);
const IClipboardService = createDecorator("clipboardService");
const IContextViewService = createDecorator("contextViewService");
const IContextMenuService = createDecorator("contextMenuService");
const IProgressService = createDecorator("progressService");
class Progress {
  constructor(callback, opts) {
    this.callback = callback;
    this.report = (opts === null || opts === void 0 ? void 0 : opts.async) ? this._reportAsync.bind(this) : this._reportSync.bind(this);
  }
  _reportSync(item) {
    this._value = item;
    this.callback(this._value);
  }
  _reportAsync(item) {
    Promise.resolve(this._lastTask).finally(() => {
      this._value = item;
      const r = this.callback(this._value);
      this._lastTask = Promise.resolve(r).finally(() => this._lastTask = void 0);
    });
  }
}
Progress.None = Object.freeze({ report() {
} });
const IEditorProgressService = createDecorator("editorProgressService");
var __decorate$1X = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1U = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$1p = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class VisualEditorState {
  constructor(_contextMenuService, _clipboardService) {
    this._contextMenuService = _contextMenuService;
    this._clipboardService = _clipboardService;
    this._zones = [];
    this._inlineDiffMargins = [];
    this._zonesMap = {};
    this._decorations = [];
  }
  getForeignViewZones(allViewZones) {
    return allViewZones.filter((z) => !this._zonesMap[String(z.id)]);
  }
  clean(editor2) {
    if (this._zones.length > 0) {
      editor2.changeViewZones((viewChangeAccessor) => {
        for (const zoneId of this._zones) {
          viewChangeAccessor.removeZone(zoneId);
        }
      });
    }
    this._zones = [];
    this._zonesMap = {};
    editor2.changeDecorations((changeAccessor) => {
      this._decorations = changeAccessor.deltaDecorations(this._decorations, []);
    });
  }
  apply(editor2, overviewRuler, newDecorations, restoreScrollState) {
    const scrollState = restoreScrollState ? StableEditorScrollState.capture(editor2) : null;
    editor2.changeViewZones((viewChangeAccessor) => {
      var _a2;
      for (const zoneId of this._zones) {
        viewChangeAccessor.removeZone(zoneId);
      }
      for (const inlineDiffMargin of this._inlineDiffMargins) {
        inlineDiffMargin.dispose();
      }
      this._zones = [];
      this._zonesMap = {};
      this._inlineDiffMargins = [];
      for (let i = 0, length2 = newDecorations.zones.length; i < length2; i++) {
        const viewZone = newDecorations.zones[i];
        viewZone.suppressMouseDown = true;
        viewZone.showInHiddenAreas = true;
        const zoneId = viewChangeAccessor.addZone(viewZone);
        this._zones.push(zoneId);
        this._zonesMap[String(zoneId)] = true;
        if (newDecorations.zones[i].diff && viewZone.marginDomNode) {
          viewZone.suppressMouseDown = false;
          if (((_a2 = newDecorations.zones[i].diff) === null || _a2 === void 0 ? void 0 : _a2.originalModel.getValueLength()) !== 0) {
            this._inlineDiffMargins.push(new InlineDiffMargin(zoneId, viewZone.marginDomNode, editor2, newDecorations.zones[i].diff, this._contextMenuService, this._clipboardService));
          }
        }
      }
    });
    scrollState === null || scrollState === void 0 ? void 0 : scrollState.restore(editor2);
    editor2.changeDecorations((changeAccessor) => {
      this._decorations = changeAccessor.deltaDecorations(this._decorations, newDecorations.decorations);
    });
    overviewRuler === null || overviewRuler === void 0 ? void 0 : overviewRuler.setZones(newDecorations.overviewZones);
  }
}
let DIFF_EDITOR_ID = 0;
const diffInsertIcon$1 = registerIcon("diff-insert", Codicon.add, localize("diffInsertIcon", "Line decoration for inserts in the diff editor."));
const diffRemoveIcon$1 = registerIcon("diff-remove", Codicon.remove, localize("diffRemoveIcon", "Line decoration for removals in the diff editor."));
const diffEditorWidgetTtPolicy = createTrustedTypesPolicy("diffEditorWidget", { createHTML: (value) => value });
const ariaNavigationTip = localize("diff-aria-navigation-tip", " use Shift + F7 to navigate changes");
let DiffEditorWidget = class DiffEditorWidget2 extends Disposable {
  constructor(domElement, options, codeEditorWidgetOptions, clipboardService, contextKeyService, instantiationService, codeEditorService, themeService, notificationService, contextMenuService, _editorProgressService) {
    super();
    this._editorProgressService = _editorProgressService;
    this._onDidDispose = this._register(new Emitter$1());
    this.onDidDispose = this._onDidDispose.event;
    this._onDidChangeModel = this._register(new Emitter$1());
    this.onDidChangeModel = this._onDidChangeModel.event;
    this._onDidUpdateDiff = this._register(new Emitter$1());
    this.onDidUpdateDiff = this._onDidUpdateDiff.event;
    this._onDidContentSizeChange = this._register(new Emitter$1());
    this._lastOriginalWarning = null;
    this._lastModifiedWarning = null;
    codeEditorService.willCreateDiffEditor();
    this._documentDiffProvider = this._register(instantiationService.createInstance(WorkerBasedDocumentDiffProvider, options));
    this._register(this._documentDiffProvider.onDidChange((e) => this._beginUpdateDecorationsSoon()));
    this._codeEditorService = codeEditorService;
    this._contextKeyService = this._register(contextKeyService.createScoped(domElement));
    this._instantiationService = instantiationService.createChild(new ServiceCollection([IContextKeyService, this._contextKeyService]));
    this._contextKeyService.createKey("isInDiffEditor", true);
    this._themeService = themeService;
    this._notificationService = notificationService;
    this._id = ++DIFF_EDITOR_ID;
    this._state = 0;
    this._updatingDiffProgress = null;
    this._domElement = domElement;
    options = options || {};
    this._options = validateDiffEditorOptions$1(options, {
      enableSplitViewResizing: true,
      splitViewDefaultRatio: 0.5,
      renderSideBySide: true,
      renderMarginRevertIcon: true,
      maxComputationTime: 5e3,
      maxFileSize: 50,
      ignoreTrimWhitespace: true,
      renderIndicators: true,
      originalEditable: false,
      diffCodeLens: false,
      renderOverviewRuler: true,
      diffWordWrap: "inherit",
      diffAlgorithm: "advanced",
      accessibilityVerbose: false,
      experimental: {
        collapseUnchangedRegions: false
      },
      isInEmbeddedEditor: false,
      onlyShowAccessibleDiffViewer: false
    });
    this.isEmbeddedDiffEditorKey = EditorContextKeys.isEmbeddedDiffEditor.bindTo(this._contextKeyService);
    this.isEmbeddedDiffEditorKey.set(typeof options.isInEmbeddedEditor !== "undefined" ? options.isInEmbeddedEditor : false);
    this._updateDecorationsRunner = this._register(new RunOnceScheduler(() => this._updateDecorations(), 0));
    this._containerDomElement = document.createElement("div");
    this._containerDomElement.className = DiffEditorWidget2._getClassName(this._themeService.getColorTheme(), this._options.renderSideBySide);
    this._containerDomElement.style.position = "relative";
    this._containerDomElement.style.height = "100%";
    this._domElement.appendChild(this._containerDomElement);
    this._overviewViewportDomElement = createFastDomNode(document.createElement("div"));
    this._overviewViewportDomElement.setClassName("diffViewport");
    this._overviewViewportDomElement.setPosition("absolute");
    this._overviewDomElement = document.createElement("div");
    this._overviewDomElement.className = "diffOverview";
    this._overviewDomElement.style.position = "absolute";
    this._overviewDomElement.appendChild(this._overviewViewportDomElement.domNode);
    this._register(addStandardDisposableListener(this._overviewDomElement, EventType$1.POINTER_DOWN, (e) => {
      this._modifiedEditor.delegateVerticalScrollbarPointerDown(e);
    }));
    this._register(addDisposableListener(this._overviewDomElement, EventType$1.MOUSE_WHEEL, (e) => {
      this._modifiedEditor.delegateScrollFromMouseWheelEvent(e);
    }, { passive: false }));
    if (this._options.renderOverviewRuler) {
      this._containerDomElement.appendChild(this._overviewDomElement);
    }
    this._originalDomNode = document.createElement("div");
    this._originalDomNode.className = "editor original";
    this._originalDomNode.style.position = "absolute";
    this._originalDomNode.style.height = "100%";
    this._containerDomElement.appendChild(this._originalDomNode);
    this._modifiedDomNode = document.createElement("div");
    this._modifiedDomNode.className = "editor modified";
    this._modifiedDomNode.style.position = "absolute";
    this._modifiedDomNode.style.height = "100%";
    this._containerDomElement.appendChild(this._modifiedDomNode);
    this._beginUpdateDecorationsTimeout = -1;
    this._currentlyChangingViewZones = false;
    this._diffComputationToken = 0;
    this._originalEditorState = new VisualEditorState(contextMenuService, clipboardService);
    this._modifiedEditorState = new VisualEditorState(contextMenuService, clipboardService);
    this._isVisible = true;
    this._isHandlingScrollEvent = false;
    this._elementSizeObserver = this._register(new ElementSizeObserver(this._containerDomElement, options.dimension));
    this._register(this._elementSizeObserver.onDidChange(() => this._onDidContainerSizeChanged()));
    if (options.automaticLayout) {
      this._elementSizeObserver.startObserving();
    }
    this._diffComputationResult = null;
    this._originalEditor = this._createLeftHandSideEditor(options, codeEditorWidgetOptions.originalEditor || {});
    this._modifiedEditor = this._createRightHandSideEditor(options, codeEditorWidgetOptions.modifiedEditor || {});
    this._originalOverviewRuler = null;
    this._modifiedOverviewRuler = null;
    this._reviewPane = instantiationService.createInstance(DiffReview, this);
    this._containerDomElement.appendChild(this._reviewPane.domNode.domNode);
    this._containerDomElement.appendChild(this._reviewPane.shadow.domNode);
    this._containerDomElement.appendChild(this._reviewPane.actionBarContainer.domNode);
    if (this._options.renderSideBySide) {
      this._setStrategy(new DiffEditorWidgetSideBySide(this._createDataSource(), this._options.enableSplitViewResizing, this._options.splitViewDefaultRatio));
    } else {
      this._setStrategy(new DiffEditorWidgetInline(this._createDataSource(), this._options.enableSplitViewResizing));
    }
    this._register(themeService.onDidColorThemeChange((t) => {
      if (this._strategy && this._strategy.applyColors(t)) {
        this._updateDecorationsRunner.schedule();
      }
      this._containerDomElement.className = DiffEditorWidget2._getClassName(this._themeService.getColorTheme(), this._options.renderSideBySide);
    }));
    const contributions = EditorExtensionsRegistry.getDiffEditorContributions();
    for (const desc of contributions) {
      try {
        this._register(instantiationService.createInstance(desc.ctor, this));
      } catch (err) {
        onUnexpectedError(err);
      }
    }
    this._codeEditorService.addDiffEditor(this);
  }
  _setState(newState) {
    if (this._state === newState) {
      return;
    }
    this._state = newState;
    if (this._updatingDiffProgress) {
      this._updatingDiffProgress.done();
      this._updatingDiffProgress = null;
    }
    if (this._state === 1) {
      this._updatingDiffProgress = this._editorProgressService.show(true, 1e3);
    }
  }
  accessibleDiffViewerNext() {
    this._reviewPane.next();
  }
  accessibleDiffViewerPrev() {
    this._reviewPane.prev();
  }
  static _getClassName(theme, renderSideBySide) {
    let result2 = "monaco-diff-editor monaco-editor-background ";
    if (renderSideBySide) {
      result2 += "side-by-side ";
    }
    result2 += getThemeTypeSelector(theme.type);
    return result2;
  }
  _disposeOverviewRulers() {
    if (this._originalOverviewRuler) {
      this._overviewDomElement.removeChild(this._originalOverviewRuler.getDomNode());
      this._originalOverviewRuler.dispose();
      this._originalOverviewRuler = null;
    }
    if (this._modifiedOverviewRuler) {
      this._overviewDomElement.removeChild(this._modifiedOverviewRuler.getDomNode());
      this._modifiedOverviewRuler.dispose();
      this._modifiedOverviewRuler = null;
    }
  }
  _createOverviewRulers() {
    if (!this._options.renderOverviewRuler) {
      return;
    }
    ok(!this._originalOverviewRuler && !this._modifiedOverviewRuler);
    if (this._originalEditor.hasModel()) {
      this._originalOverviewRuler = this._originalEditor.createOverviewRuler("original diffOverviewRuler");
      this._overviewDomElement.appendChild(this._originalOverviewRuler.getDomNode());
    }
    if (this._modifiedEditor.hasModel()) {
      this._modifiedOverviewRuler = this._modifiedEditor.createOverviewRuler("modified diffOverviewRuler");
      this._overviewDomElement.appendChild(this._modifiedOverviewRuler.getDomNode());
    }
    this._layoutOverviewRulers();
  }
  _createLeftHandSideEditor(options, codeEditorWidgetOptions) {
    const editor2 = this._createInnerEditor(this._instantiationService, this._originalDomNode, this._adjustOptionsForLeftHandSide(options), codeEditorWidgetOptions);
    this._register(editor2.onDidScrollChange((e) => {
      if (this._isHandlingScrollEvent) {
        return;
      }
      if (!e.scrollTopChanged && !e.scrollLeftChanged && !e.scrollHeightChanged) {
        return;
      }
      this._isHandlingScrollEvent = true;
      this._modifiedEditor.setScrollPosition({
        scrollLeft: e.scrollLeft,
        scrollTop: e.scrollTop
      });
      this._isHandlingScrollEvent = false;
      this._layoutOverviewViewport();
    }));
    this._register(editor2.onDidChangeViewZones(() => {
      this._onViewZonesChanged();
    }));
    this._register(editor2.onDidChangeConfiguration((e) => {
      if (!editor2.getModel()) {
        return;
      }
      if (e.hasChanged(
        49
        /* EditorOption.fontInfo */
      )) {
        this._updateDecorationsRunner.schedule();
      }
      if (e.hasChanged(
        143
        /* EditorOption.wrappingInfo */
      )) {
        this._updateDecorationsRunner.cancel();
        this._updateDecorations();
      }
    }));
    this._register(editor2.onDidChangeHiddenAreas(() => {
      this._updateDecorationsRunner.cancel();
      this._updateDecorations();
    }));
    this._register(editor2.onDidChangeModelContent(() => {
      if (this._isVisible) {
        this._beginUpdateDecorationsSoon();
      }
    }));
    const isInDiffLeftEditorKey = this._contextKeyService.createKey("isInDiffLeftEditor", editor2.hasWidgetFocus());
    this._register(editor2.onDidFocusEditorWidget(() => isInDiffLeftEditorKey.set(true)));
    this._register(editor2.onDidBlurEditorWidget(() => isInDiffLeftEditorKey.set(false)));
    this._register(editor2.onDidContentSizeChange((e) => {
      const width = this._originalEditor.getContentWidth() + this._modifiedEditor.getContentWidth() + DiffEditorWidget2.ONE_OVERVIEW_WIDTH;
      const height = Math.max(this._modifiedEditor.getContentHeight(), this._originalEditor.getContentHeight());
      this._onDidContentSizeChange.fire({
        contentHeight: height,
        contentWidth: width,
        contentHeightChanged: e.contentHeightChanged,
        contentWidthChanged: e.contentWidthChanged
      });
    }));
    return editor2;
  }
  _createRightHandSideEditor(options, codeEditorWidgetOptions) {
    const editor2 = this._createInnerEditor(this._instantiationService, this._modifiedDomNode, this._adjustOptionsForRightHandSide(options), codeEditorWidgetOptions);
    this._register(editor2.onDidScrollChange((e) => {
      if (this._isHandlingScrollEvent) {
        return;
      }
      if (!e.scrollTopChanged && !e.scrollLeftChanged && !e.scrollHeightChanged) {
        return;
      }
      this._isHandlingScrollEvent = true;
      this._originalEditor.setScrollPosition({
        scrollLeft: e.scrollLeft,
        scrollTop: e.scrollTop
      });
      this._isHandlingScrollEvent = false;
      this._layoutOverviewViewport();
    }));
    this._register(editor2.onDidChangeViewZones(() => {
      this._onViewZonesChanged();
    }));
    this._register(editor2.onDidChangeConfiguration((e) => {
      if (!editor2.getModel()) {
        return;
      }
      if (e.hasChanged(
        49
        /* EditorOption.fontInfo */
      )) {
        this._updateDecorationsRunner.schedule();
      }
      if (e.hasChanged(
        143
        /* EditorOption.wrappingInfo */
      )) {
        this._updateDecorationsRunner.cancel();
        this._updateDecorations();
      }
    }));
    this._register(editor2.onDidChangeHiddenAreas(() => {
      this._updateDecorationsRunner.cancel();
      this._updateDecorations();
    }));
    this._register(editor2.onDidChangeModelContent(() => {
      if (this._isVisible) {
        this._beginUpdateDecorationsSoon();
      }
    }));
    this._register(editor2.onDidChangeModelOptions((e) => {
      if (e.tabSize) {
        this._updateDecorationsRunner.schedule();
      }
    }));
    const isInDiffRightEditorKey = this._contextKeyService.createKey("isInDiffRightEditor", editor2.hasWidgetFocus());
    this._register(editor2.onDidFocusEditorWidget(() => isInDiffRightEditorKey.set(true)));
    this._register(editor2.onDidBlurEditorWidget(() => isInDiffRightEditorKey.set(false)));
    this._register(editor2.onDidContentSizeChange((e) => {
      const width = this._originalEditor.getContentWidth() + this._modifiedEditor.getContentWidth() + DiffEditorWidget2.ONE_OVERVIEW_WIDTH;
      const height = Math.max(this._modifiedEditor.getContentHeight(), this._originalEditor.getContentHeight());
      this._onDidContentSizeChange.fire({
        contentHeight: height,
        contentWidth: width,
        contentHeightChanged: e.contentHeightChanged,
        contentWidthChanged: e.contentWidthChanged
      });
    }));
    this._register(editor2.onMouseDown((event) => {
      var _a2, _b2;
      if (!event.event.rightButton && event.target.position && ((_a2 = event.target.element) === null || _a2 === void 0 ? void 0 : _a2.className.includes("arrow-revert-change"))) {
        const lineNumber = event.target.position.lineNumber;
        const viewZone = event.target;
        const change = (_b2 = this._diffComputationResult) === null || _b2 === void 0 ? void 0 : _b2.changes.find((c) => (
          // delete change
          (viewZone === null || viewZone === void 0 ? void 0 : viewZone.detail.afterLineNumber) === c.modifiedStartLineNumber || // other changes
          c.modifiedEndLineNumber > 0 && c.modifiedStartLineNumber === lineNumber
        ));
        if (change) {
          this.revertChange(change);
        }
        event.event.stopPropagation();
        this._updateDecorations();
        return;
      }
    }));
    return editor2;
  }
  /**
   * Reverts a change in the modified editor.
   */
  revertChange(change) {
    const editor2 = this._modifiedEditor;
    const original = this._originalEditor.getModel();
    const modified = this._modifiedEditor.getModel();
    if (!original || !modified || !editor2) {
      return;
    }
    const originalRange = change.originalEndLineNumber > 0 ? new Range$2(change.originalStartLineNumber, 1, change.originalEndLineNumber, original.getLineMaxColumn(change.originalEndLineNumber)) : null;
    const originalContent = originalRange ? original.getValueInRange(originalRange) : null;
    const newRange = change.modifiedEndLineNumber > 0 ? new Range$2(change.modifiedStartLineNumber, 1, change.modifiedEndLineNumber, modified.getLineMaxColumn(change.modifiedEndLineNumber)) : null;
    const eol = modified.getEOL();
    if (change.originalEndLineNumber === 0 && newRange) {
      let range2 = newRange;
      if (change.modifiedStartLineNumber > 1) {
        range2 = newRange.setStartPosition(change.modifiedStartLineNumber - 1, modified.getLineMaxColumn(change.modifiedStartLineNumber - 1));
      } else if (change.modifiedEndLineNumber < modified.getLineCount()) {
        range2 = newRange.setEndPosition(change.modifiedEndLineNumber + 1, 1);
      }
      editor2.executeEdits("diffEditor", [{
        range: range2,
        text: ""
      }]);
    } else if (change.modifiedEndLineNumber === 0 && originalContent !== null) {
      const insertAt = change.modifiedStartLineNumber < modified.getLineCount() ? new Position$2(change.modifiedStartLineNumber + 1, 1) : new Position$2(change.modifiedStartLineNumber, modified.getLineMaxColumn(change.modifiedStartLineNumber));
      editor2.executeEdits("diffEditor", [{
        range: Range$2.fromPositions(insertAt, insertAt),
        text: change.modifiedStartLineNumber < modified.getLineCount() ? originalContent + eol : eol + originalContent
      }]);
    } else if (newRange && originalContent !== null) {
      editor2.executeEdits("diffEditor", [{
        range: newRange,
        text: originalContent
      }]);
    }
  }
  _createInnerEditor(instantiationService, container2, options, editorWidgetOptions) {
    return instantiationService.createInstance(CodeEditorWidget, container2, options, editorWidgetOptions);
  }
  dispose() {
    this._codeEditorService.removeDiffEditor(this);
    if (this._beginUpdateDecorationsTimeout !== -1) {
      window.clearTimeout(this._beginUpdateDecorationsTimeout);
      this._beginUpdateDecorationsTimeout = -1;
    }
    this._cleanViewZonesAndDecorations();
    if (this._originalOverviewRuler) {
      this._overviewDomElement.removeChild(this._originalOverviewRuler.getDomNode());
      this._originalOverviewRuler.dispose();
    }
    if (this._modifiedOverviewRuler) {
      this._overviewDomElement.removeChild(this._modifiedOverviewRuler.getDomNode());
      this._modifiedOverviewRuler.dispose();
    }
    this._overviewDomElement.removeChild(this._overviewViewportDomElement.domNode);
    if (this._options.renderOverviewRuler) {
      this._containerDomElement.removeChild(this._overviewDomElement);
    }
    this._containerDomElement.removeChild(this._originalDomNode);
    this._originalEditor.dispose();
    this._containerDomElement.removeChild(this._modifiedDomNode);
    this._modifiedEditor.dispose();
    this._strategy.dispose();
    this._containerDomElement.removeChild(this._reviewPane.domNode.domNode);
    this._containerDomElement.removeChild(this._reviewPane.shadow.domNode);
    this._containerDomElement.removeChild(this._reviewPane.actionBarContainer.domNode);
    this._reviewPane.dispose();
    this._domElement.removeChild(this._containerDomElement);
    this._onDidDispose.fire();
    super.dispose();
  }
  //------------ begin IDiffEditor methods
  getId() {
    return this.getEditorType() + ":" + this._id;
  }
  getEditorType() {
    return EditorType.IDiffEditor;
  }
  getLineChanges() {
    if (!this._diffComputationResult) {
      return null;
    }
    return this._diffComputationResult.changes;
  }
  getOriginalEditor() {
    return this._originalEditor;
  }
  getModifiedEditor() {
    return this._modifiedEditor;
  }
  updateOptions(_newOptions) {
    const newOptions = validateDiffEditorOptions$1(_newOptions, this._options);
    const changed = changedDiffEditorOptions(this._options, newOptions);
    this._options = newOptions;
    this.isEmbeddedDiffEditorKey.set(typeof _newOptions.isInEmbeddedEditor !== "undefined" ? _newOptions.isInEmbeddedEditor : false);
    const beginUpdateDecorations = changed.ignoreTrimWhitespace || changed.renderIndicators || changed.renderMarginRevertIcon;
    const beginUpdateDecorationsSoon = this._isVisible && (changed.maxComputationTime || changed.maxFileSize);
    this._documentDiffProvider.setOptions(newOptions);
    if (beginUpdateDecorations) {
      this._beginUpdateDecorations();
    } else if (beginUpdateDecorationsSoon) {
      this._beginUpdateDecorationsSoon();
    }
    this._modifiedEditor.updateOptions(this._adjustOptionsForRightHandSide(_newOptions));
    this._originalEditor.updateOptions(this._adjustOptionsForLeftHandSide(_newOptions));
    this._strategy.setEnableSplitViewResizing(this._options.enableSplitViewResizing, this._options.splitViewDefaultRatio);
    if (changed.renderSideBySide) {
      if (this._options.renderSideBySide) {
        this._setStrategy(new DiffEditorWidgetSideBySide(this._createDataSource(), this._options.enableSplitViewResizing, this._options.splitViewDefaultRatio));
      } else {
        this._setStrategy(new DiffEditorWidgetInline(this._createDataSource(), this._options.enableSplitViewResizing));
      }
      this._containerDomElement.className = DiffEditorWidget2._getClassName(this._themeService.getColorTheme(), this._options.renderSideBySide);
    }
    if (changed.renderOverviewRuler) {
      if (this._options.renderOverviewRuler) {
        this._containerDomElement.appendChild(this._overviewDomElement);
      } else {
        this._containerDomElement.removeChild(this._overviewDomElement);
      }
    }
  }
  getModel() {
    return {
      original: this._originalEditor.getModel(),
      modified: this._modifiedEditor.getModel()
    };
  }
  createViewModel(model) {
    return {
      model,
      waitForDiff() {
        return __awaiter$1p(this, void 0, void 0, function* () {
        });
      }
    };
  }
  setModel(model) {
    if (model && "model" in model) {
      model = model.model;
    }
    if (model && (!model.original || !model.modified)) {
      throw new Error(!model.original ? "DiffEditorWidget.setModel: Original model is null" : "DiffEditorWidget.setModel: Modified model is null");
    }
    this._cleanViewZonesAndDecorations();
    this._disposeOverviewRulers();
    this._originalEditor.setModel(model ? model.original : null);
    this._modifiedEditor.setModel(model ? model.modified : null);
    this._updateDecorationsRunner.cancel();
    if (model) {
      this._originalEditor.setScrollTop(0);
      this._modifiedEditor.setScrollTop(0);
    }
    this._diffComputationResult = null;
    this._diffComputationToken++;
    this._setState(
      0
      /* editorBrowser.DiffEditorState.Idle */
    );
    if (model) {
      this._createOverviewRulers();
      this._beginUpdateDecorations();
    }
    this._layoutOverviewViewport();
    this._onDidChangeModel.fire();
    this._diffNavigator = this._register(this._instantiationService.createInstance(DiffNavigator, this, {
      alwaysRevealFirst: false,
      findResultLoop: this.getModifiedEditor().getOption(
        40
        /* EditorOption.find */
      ).loop
    }));
  }
  getContainerDomNode() {
    return this._domElement;
  }
  // #region editorBrowser.IDiffEditor: Delegating to modified Editor
  getVisibleColumnFromPosition(position) {
    return this._modifiedEditor.getVisibleColumnFromPosition(position);
  }
  getPosition() {
    return this._modifiedEditor.getPosition();
  }
  setPosition(position, source = "api") {
    this._modifiedEditor.setPosition(position, source);
  }
  revealLine(lineNumber, scrollType = 0) {
    this._modifiedEditor.revealLine(lineNumber, scrollType);
  }
  revealLineInCenter(lineNumber, scrollType = 0) {
    this._modifiedEditor.revealLineInCenter(lineNumber, scrollType);
  }
  revealLineInCenterIfOutsideViewport(lineNumber, scrollType = 0) {
    this._modifiedEditor.revealLineInCenterIfOutsideViewport(lineNumber, scrollType);
  }
  revealLineNearTop(lineNumber, scrollType = 0) {
    this._modifiedEditor.revealLineNearTop(lineNumber, scrollType);
  }
  revealPosition(position, scrollType = 0) {
    this._modifiedEditor.revealPosition(position, scrollType);
  }
  revealPositionInCenter(position, scrollType = 0) {
    this._modifiedEditor.revealPositionInCenter(position, scrollType);
  }
  revealPositionInCenterIfOutsideViewport(position, scrollType = 0) {
    this._modifiedEditor.revealPositionInCenterIfOutsideViewport(position, scrollType);
  }
  revealPositionNearTop(position, scrollType = 0) {
    this._modifiedEditor.revealPositionNearTop(position, scrollType);
  }
  getSelection() {
    return this._modifiedEditor.getSelection();
  }
  getSelections() {
    return this._modifiedEditor.getSelections();
  }
  setSelection(something, source = "api") {
    this._modifiedEditor.setSelection(something, source);
  }
  setSelections(ranges, source = "api") {
    this._modifiedEditor.setSelections(ranges, source);
  }
  revealLines(startLineNumber, endLineNumber, scrollType = 0) {
    this._modifiedEditor.revealLines(startLineNumber, endLineNumber, scrollType);
  }
  revealLinesInCenter(startLineNumber, endLineNumber, scrollType = 0) {
    this._modifiedEditor.revealLinesInCenter(startLineNumber, endLineNumber, scrollType);
  }
  revealLinesInCenterIfOutsideViewport(startLineNumber, endLineNumber, scrollType = 0) {
    this._modifiedEditor.revealLinesInCenterIfOutsideViewport(startLineNumber, endLineNumber, scrollType);
  }
  revealLinesNearTop(startLineNumber, endLineNumber, scrollType = 0) {
    this._modifiedEditor.revealLinesNearTop(startLineNumber, endLineNumber, scrollType);
  }
  revealRange(range2, scrollType = 0, revealVerticalInCenter = false, revealHorizontal = true) {
    this._modifiedEditor.revealRange(range2, scrollType, revealVerticalInCenter, revealHorizontal);
  }
  revealRangeInCenter(range2, scrollType = 0) {
    this._modifiedEditor.revealRangeInCenter(range2, scrollType);
  }
  revealRangeInCenterIfOutsideViewport(range2, scrollType = 0) {
    this._modifiedEditor.revealRangeInCenterIfOutsideViewport(range2, scrollType);
  }
  revealRangeNearTop(range2, scrollType = 0) {
    this._modifiedEditor.revealRangeNearTop(range2, scrollType);
  }
  revealRangeNearTopIfOutsideViewport(range2, scrollType = 0) {
    this._modifiedEditor.revealRangeNearTopIfOutsideViewport(range2, scrollType);
  }
  revealRangeAtTop(range2, scrollType = 0) {
    this._modifiedEditor.revealRangeAtTop(range2, scrollType);
  }
  getSupportedActions() {
    return this._modifiedEditor.getSupportedActions();
  }
  focus() {
    this._modifiedEditor.focus();
  }
  trigger(source, handlerId, payload) {
    this._modifiedEditor.trigger(source, handlerId, payload);
  }
  createDecorationsCollection(decorations2) {
    return this._modifiedEditor.createDecorationsCollection(decorations2);
  }
  changeDecorations(callback) {
    return this._modifiedEditor.changeDecorations(callback);
  }
  // #endregion
  saveViewState() {
    const originalViewState = this._originalEditor.saveViewState();
    const modifiedViewState = this._modifiedEditor.saveViewState();
    return {
      original: originalViewState,
      modified: modifiedViewState
    };
  }
  restoreViewState(s) {
    if (s && s.original && s.modified) {
      const diffEditorState = s;
      this._originalEditor.restoreViewState(diffEditorState.original);
      this._modifiedEditor.restoreViewState(diffEditorState.modified);
    }
  }
  layout(dimension) {
    this._elementSizeObserver.observe(dimension);
  }
  hasTextFocus() {
    return this._originalEditor.hasTextFocus() || this._modifiedEditor.hasTextFocus();
  }
  //------------ end IDiffEditor methods
  //------------ begin layouting methods
  _onDidContainerSizeChanged() {
    this._doLayout();
  }
  _getReviewHeight() {
    return this._reviewPane.isVisible() ? this._elementSizeObserver.getHeight() : 0;
  }
  _layoutOverviewRulers() {
    if (!this._options.renderOverviewRuler) {
      return;
    }
    if (!this._originalOverviewRuler || !this._modifiedOverviewRuler) {
      return;
    }
    const height = this._elementSizeObserver.getHeight();
    const reviewHeight = this._getReviewHeight();
    const freeSpace = DiffEditorWidget2.ENTIRE_DIFF_OVERVIEW_WIDTH - 2 * DiffEditorWidget2.ONE_OVERVIEW_WIDTH;
    const layoutInfo = this._modifiedEditor.getLayoutInfo();
    if (layoutInfo) {
      this._originalOverviewRuler.setLayout({
        top: 0,
        width: DiffEditorWidget2.ONE_OVERVIEW_WIDTH,
        right: freeSpace + DiffEditorWidget2.ONE_OVERVIEW_WIDTH,
        height: height - reviewHeight
      });
      this._modifiedOverviewRuler.setLayout({
        top: 0,
        right: 0,
        width: DiffEditorWidget2.ONE_OVERVIEW_WIDTH,
        height: height - reviewHeight
      });
    }
  }
  //------------ end layouting methods
  _onViewZonesChanged() {
    if (this._currentlyChangingViewZones) {
      return;
    }
    this._updateDecorationsRunner.schedule();
  }
  _beginUpdateDecorationsSoon() {
    if (this._beginUpdateDecorationsTimeout !== -1) {
      window.clearTimeout(this._beginUpdateDecorationsTimeout);
      this._beginUpdateDecorationsTimeout = -1;
    }
    this._beginUpdateDecorationsTimeout = window.setTimeout(() => this._beginUpdateDecorations(), DiffEditorWidget2.UPDATE_DIFF_DECORATIONS_DELAY);
  }
  static _equals(a, b) {
    if (!a && !b) {
      return true;
    }
    if (!a || !b) {
      return false;
    }
    return a.toString() === b.toString();
  }
  _beginUpdateDecorations() {
    if (this._beginUpdateDecorationsTimeout !== -1) {
      window.clearTimeout(this._beginUpdateDecorationsTimeout);
      this._beginUpdateDecorationsTimeout = -1;
    }
    const currentOriginalModel = this._originalEditor.getModel();
    const currentModifiedModel = this._modifiedEditor.getModel();
    if (!currentOriginalModel || !currentModifiedModel) {
      return;
    }
    this._diffComputationToken++;
    const currentToken = this._diffComputationToken;
    const diffLimit = this._options.maxFileSize * 1024 * 1024;
    const canSyncModelForDiff = (model) => {
      const bufferTextLength = model.getValueLength();
      return diffLimit === 0 || bufferTextLength <= diffLimit;
    };
    if (!canSyncModelForDiff(currentOriginalModel) || !canSyncModelForDiff(currentModifiedModel)) {
      if (!DiffEditorWidget2._equals(currentOriginalModel.uri, this._lastOriginalWarning) || !DiffEditorWidget2._equals(currentModifiedModel.uri, this._lastModifiedWarning)) {
        this._lastOriginalWarning = currentOriginalModel.uri;
        this._lastModifiedWarning = currentModifiedModel.uri;
        this._notificationService.warn(localize("diff.tooLarge", "Cannot compare files because one file is too large."));
      }
      return;
    }
    this._setState(
      1
      /* editorBrowser.DiffEditorState.ComputingDiff */
    );
    this._documentDiffProvider.computeDiff(currentOriginalModel, currentModifiedModel, {
      ignoreTrimWhitespace: this._options.ignoreTrimWhitespace,
      maxComputationTimeMs: this._options.maxComputationTime,
      computeMoves: false
    }).then((result2) => {
      if (currentToken === this._diffComputationToken && currentOriginalModel === this._originalEditor.getModel() && currentModifiedModel === this._modifiedEditor.getModel()) {
        this._setState(
          2
          /* editorBrowser.DiffEditorState.DiffComputed */
        );
        this._diffComputationResult = {
          identical: result2.identical,
          quitEarly: result2.quitEarly,
          changes2: result2.changes,
          changes: result2.changes.map((m) => {
            let originalStartLineNumber;
            let originalEndLineNumber;
            let modifiedStartLineNumber;
            let modifiedEndLineNumber;
            let innerChanges = m.innerChanges;
            if (m.originalRange.isEmpty) {
              originalStartLineNumber = m.originalRange.startLineNumber - 1;
              originalEndLineNumber = 0;
              innerChanges = void 0;
            } else {
              originalStartLineNumber = m.originalRange.startLineNumber;
              originalEndLineNumber = m.originalRange.endLineNumberExclusive - 1;
            }
            if (m.modifiedRange.isEmpty) {
              modifiedStartLineNumber = m.modifiedRange.startLineNumber - 1;
              modifiedEndLineNumber = 0;
              innerChanges = void 0;
            } else {
              modifiedStartLineNumber = m.modifiedRange.startLineNumber;
              modifiedEndLineNumber = m.modifiedRange.endLineNumberExclusive - 1;
            }
            return {
              originalStartLineNumber,
              originalEndLineNumber,
              modifiedStartLineNumber,
              modifiedEndLineNumber,
              charChanges: innerChanges === null || innerChanges === void 0 ? void 0 : innerChanges.map((m2) => ({
                originalStartLineNumber: m2.originalRange.startLineNumber,
                originalStartColumn: m2.originalRange.startColumn,
                originalEndLineNumber: m2.originalRange.endLineNumber,
                originalEndColumn: m2.originalRange.endColumn,
                modifiedStartLineNumber: m2.modifiedRange.startLineNumber,
                modifiedStartColumn: m2.modifiedRange.startColumn,
                modifiedEndLineNumber: m2.modifiedRange.endLineNumber,
                modifiedEndColumn: m2.modifiedRange.endColumn
              }))
            };
          })
        };
        this._updateDecorationsRunner.schedule();
        this._onDidUpdateDiff.fire();
      }
    }, (error2) => {
      if (currentToken === this._diffComputationToken && currentOriginalModel === this._originalEditor.getModel() && currentModifiedModel === this._modifiedEditor.getModel()) {
        this._setState(
          2
          /* editorBrowser.DiffEditorState.DiffComputed */
        );
        this._diffComputationResult = null;
        this._updateDecorationsRunner.schedule();
      }
    });
  }
  _cleanViewZonesAndDecorations() {
    this._originalEditorState.clean(this._originalEditor);
    this._modifiedEditorState.clean(this._modifiedEditor);
  }
  _updateDecorations() {
    if (!this._originalEditor.getModel() || !this._modifiedEditor.getModel()) {
      return;
    }
    const lineChanges = this._diffComputationResult ? this._diffComputationResult.changes : [];
    const foreignOriginal = this._originalEditorState.getForeignViewZones(this._originalEditor.getWhitespaces());
    const foreignModified = this._modifiedEditorState.getForeignViewZones(this._modifiedEditor.getWhitespaces());
    const renderMarginRevertIcon = this._options.renderMarginRevertIcon && !this._modifiedEditor.getOption(
      89
      /* EditorOption.readOnly */
    );
    const diffDecorations = this._strategy.getEditorsDiffDecorations(lineChanges, this._options.ignoreTrimWhitespace, this._options.renderIndicators, renderMarginRevertIcon, foreignOriginal, foreignModified);
    try {
      this._currentlyChangingViewZones = true;
      this._originalEditorState.apply(this._originalEditor, this._originalOverviewRuler, diffDecorations.original, false);
      this._modifiedEditorState.apply(this._modifiedEditor, this._modifiedOverviewRuler, diffDecorations.modified, true);
    } finally {
      this._currentlyChangingViewZones = false;
    }
  }
  _adjustOptionsForSubEditor(options) {
    const clonedOptions = Object.assign({}, options);
    clonedOptions.inDiffEditor = true;
    clonedOptions.automaticLayout = false;
    clonedOptions.scrollbar = Object.assign({}, clonedOptions.scrollbar || {});
    clonedOptions.scrollbar.vertical = "visible";
    clonedOptions.folding = false;
    clonedOptions.codeLens = this._options.diffCodeLens;
    clonedOptions.fixedOverflowWidgets = true;
    clonedOptions.minimap = Object.assign({}, clonedOptions.minimap || {});
    clonedOptions.minimap.enabled = false;
    return clonedOptions;
  }
  _adjustOptionsForLeftHandSide(options) {
    const result2 = this._adjustOptionsForSubEditor(options);
    if (!this._options.renderSideBySide) {
      result2.wordWrapOverride1 = "off";
      result2.wordWrapOverride2 = "off";
      result2.stickyScroll = { enabled: false };
    } else {
      result2.wordWrapOverride1 = this._options.diffWordWrap;
    }
    if (options.originalAriaLabel) {
      result2.ariaLabel = options.originalAriaLabel;
    }
    this._updateAriaLabel(result2);
    result2.readOnly = !this._options.originalEditable;
    result2.dropIntoEditor = { enabled: !result2.readOnly };
    result2.extraEditorClassName = "original-in-monaco-diff-editor";
    return Object.assign(Object.assign({}, result2), { dimension: {
      height: 0,
      width: 0
    } });
  }
  _updateAriaLabel(options) {
    var _a2;
    let ariaLabel = (_a2 = options.ariaLabel) !== null && _a2 !== void 0 ? _a2 : "";
    if (this._options.accessibilityVerbose) {
      ariaLabel += ariaNavigationTip;
    } else if (ariaLabel) {
      ariaLabel = ariaLabel.replaceAll(ariaNavigationTip, "");
    }
    options.ariaLabel = ariaLabel;
  }
  _adjustOptionsForRightHandSide(options) {
    const result2 = this._adjustOptionsForSubEditor(options);
    if (options.modifiedAriaLabel) {
      result2.ariaLabel = options.modifiedAriaLabel;
    }
    this._updateAriaLabel(result2);
    result2.wordWrapOverride1 = this._options.diffWordWrap;
    result2.revealHorizontalRightPadding = EditorOptions.revealHorizontalRightPadding.defaultValue + DiffEditorWidget2.ENTIRE_DIFF_OVERVIEW_WIDTH;
    result2.scrollbar.verticalHasArrows = false;
    result2.extraEditorClassName = "modified-in-monaco-diff-editor";
    return Object.assign(Object.assign({}, result2), { dimension: {
      height: 0,
      width: 0
    } });
  }
  doLayout() {
    this._elementSizeObserver.observe();
    this._doLayout();
  }
  _doLayout() {
    const width = this._elementSizeObserver.getWidth();
    const height = this._elementSizeObserver.getHeight();
    const reviewHeight = this._getReviewHeight();
    const splitPoint = this._strategy.layout();
    this._originalDomNode.style.width = splitPoint + "px";
    this._originalDomNode.style.left = "0px";
    this._modifiedDomNode.style.width = width - splitPoint - DiffEditorWidget2.ENTIRE_DIFF_OVERVIEW_WIDTH + "px";
    this._modifiedDomNode.style.left = splitPoint + "px";
    this._overviewDomElement.style.top = "0px";
    this._overviewDomElement.style.height = height - reviewHeight + "px";
    this._overviewDomElement.style.width = DiffEditorWidget2.ENTIRE_DIFF_OVERVIEW_WIDTH + "px";
    this._overviewDomElement.style.left = width - DiffEditorWidget2.ENTIRE_DIFF_OVERVIEW_WIDTH + "px";
    this._overviewViewportDomElement.setWidth(DiffEditorWidget2.ENTIRE_DIFF_OVERVIEW_WIDTH);
    this._overviewViewportDomElement.setHeight(30);
    this._originalEditor.layout({ width: splitPoint, height: height - reviewHeight });
    this._modifiedEditor.layout({ width: width - splitPoint - (this._options.renderOverviewRuler ? DiffEditorWidget2.ENTIRE_DIFF_OVERVIEW_WIDTH : 0), height: height - reviewHeight });
    if (this._originalOverviewRuler || this._modifiedOverviewRuler) {
      this._layoutOverviewRulers();
    }
    this._reviewPane.layout(height - reviewHeight, width, reviewHeight);
    this._layoutOverviewViewport();
  }
  _layoutOverviewViewport() {
    const layout2 = this._computeOverviewViewport();
    if (!layout2) {
      this._overviewViewportDomElement.setTop(0);
      this._overviewViewportDomElement.setHeight(0);
    } else {
      this._overviewViewportDomElement.setTop(layout2.top);
      this._overviewViewportDomElement.setHeight(layout2.height);
    }
  }
  _computeOverviewViewport() {
    const layoutInfo = this._modifiedEditor.getLayoutInfo();
    if (!layoutInfo) {
      return null;
    }
    const scrollTop = this._modifiedEditor.getScrollTop();
    const scrollHeight = this._modifiedEditor.getScrollHeight();
    const computedAvailableSize = Math.max(0, layoutInfo.height);
    const computedRepresentableSize = Math.max(0, computedAvailableSize - 2 * 0);
    const computedRatio = scrollHeight > 0 ? computedRepresentableSize / scrollHeight : 0;
    const computedSliderSize = Math.max(0, Math.floor(layoutInfo.height * computedRatio));
    const computedSliderPosition = Math.floor(scrollTop * computedRatio);
    return {
      height: computedSliderSize,
      top: computedSliderPosition
    };
  }
  _createDataSource() {
    return {
      getWidth: () => {
        return this._elementSizeObserver.getWidth();
      },
      getHeight: () => {
        return this._elementSizeObserver.getHeight() - this._getReviewHeight();
      },
      getOptions: () => {
        return {
          renderOverviewRuler: this._options.renderOverviewRuler
        };
      },
      getContainerDomNode: () => {
        return this._containerDomElement;
      },
      relayoutEditors: () => {
        this._doLayout();
      },
      getOriginalEditor: () => {
        return this._originalEditor;
      },
      getModifiedEditor: () => {
        return this._modifiedEditor;
      }
    };
  }
  _setStrategy(newStrategy) {
    var _a2;
    (_a2 = this._strategy) === null || _a2 === void 0 ? void 0 : _a2.dispose();
    this._strategy = newStrategy;
    if (this._boundarySashes) {
      newStrategy.setBoundarySashes(this._boundarySashes);
    }
    newStrategy.applyColors(this._themeService.getColorTheme());
    if (this._diffComputationResult) {
      this._updateDecorations();
    }
    this._doLayout();
  }
};
DiffEditorWidget.ONE_OVERVIEW_WIDTH = 15;
DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH = 30;
DiffEditorWidget.UPDATE_DIFF_DECORATIONS_DELAY = 200;
DiffEditorWidget = __decorate$1X([
  __param$1U(3, IClipboardService),
  __param$1U(4, IContextKeyService),
  __param$1U(5, IInstantiationService),
  __param$1U(6, ICodeEditorService),
  __param$1U(7, IThemeService),
  __param$1U(8, INotificationService),
  __param$1U(9, IContextMenuService),
  __param$1U(10, IEditorProgressService)
], DiffEditorWidget);
class DiffEditorWidgetStyle extends Disposable {
  constructor(dataSource) {
    super();
    this._dataSource = dataSource;
    this._insertColor = null;
    this._removeColor = null;
  }
  applyColors(theme) {
    const newInsertColor = theme.getColor(diffOverviewRulerInserted) || (theme.getColor(diffInserted) || defaultInsertColor).transparent(2);
    const newRemoveColor = theme.getColor(diffOverviewRulerRemoved) || (theme.getColor(diffRemoved) || defaultRemoveColor).transparent(2);
    const hasChanges = !newInsertColor.equals(this._insertColor) || !newRemoveColor.equals(this._removeColor);
    this._insertColor = newInsertColor;
    this._removeColor = newRemoveColor;
    return hasChanges;
  }
  getEditorsDiffDecorations(lineChanges, ignoreTrimWhitespace, renderIndicators, renderMarginRevertIcon, originalWhitespaces, modifiedWhitespaces) {
    modifiedWhitespaces = modifiedWhitespaces.sort((a, b) => {
      return a.afterLineNumber - b.afterLineNumber;
    });
    originalWhitespaces = originalWhitespaces.sort((a, b) => {
      return a.afterLineNumber - b.afterLineNumber;
    });
    const zones = this._getViewZones(lineChanges, originalWhitespaces, modifiedWhitespaces, renderIndicators);
    const originalDecorations = this._getOriginalEditorDecorations(zones, lineChanges, ignoreTrimWhitespace, renderIndicators);
    const modifiedDecorations = this._getModifiedEditorDecorations(zones, lineChanges, ignoreTrimWhitespace, renderIndicators, renderMarginRevertIcon);
    return {
      original: {
        decorations: originalDecorations.decorations,
        overviewZones: originalDecorations.overviewZones,
        zones: zones.original
      },
      modified: {
        decorations: modifiedDecorations.decorations,
        overviewZones: modifiedDecorations.overviewZones,
        zones: zones.modified
      }
    };
  }
  setBoundarySashes(_sashes) {
  }
}
class ForeignViewZonesIterator {
  constructor(source) {
    this._source = source;
    this._index = -1;
    this.current = null;
    this.advance();
  }
  advance() {
    this._index++;
    if (this._index < this._source.length) {
      this.current = this._source[this._index];
    } else {
      this.current = null;
    }
  }
}
class ViewZonesComputer {
  constructor(_lineChanges, _originalForeignVZ, _modifiedForeignVZ, _originalEditor, _modifiedEditor) {
    this._lineChanges = _lineChanges;
    this._originalForeignVZ = _originalForeignVZ;
    this._modifiedForeignVZ = _modifiedForeignVZ;
    this._originalEditor = _originalEditor;
    this._modifiedEditor = _modifiedEditor;
  }
  static _getViewLineCount(editor2, startLineNumber, endLineNumber) {
    const model = editor2.getModel();
    const viewModel = editor2._getViewModel();
    if (model && viewModel) {
      const viewRange = getViewRange(model, viewModel, startLineNumber, endLineNumber);
      return viewRange.endLineNumber - viewRange.startLineNumber + 1;
    }
    return endLineNumber - startLineNumber + 1;
  }
  getViewZones() {
    const originalLineHeight = this._originalEditor.getOption(
      65
      /* EditorOption.lineHeight */
    );
    const modifiedLineHeight = this._modifiedEditor.getOption(
      65
      /* EditorOption.lineHeight */
    );
    const originalHasWrapping = this._originalEditor.getOption(
      143
      /* EditorOption.wrappingInfo */
    ).wrappingColumn !== -1;
    const modifiedHasWrapping = this._modifiedEditor.getOption(
      143
      /* EditorOption.wrappingInfo */
    ).wrappingColumn !== -1;
    const hasWrapping = originalHasWrapping || modifiedHasWrapping;
    const originalModel = this._originalEditor.getModel();
    const originalCoordinatesConverter = this._originalEditor._getViewModel().coordinatesConverter;
    const modifiedCoordinatesConverter = this._modifiedEditor._getViewModel().coordinatesConverter;
    const result2 = {
      original: [],
      modified: []
    };
    let lineChangeModifiedLength = 0;
    let lineChangeOriginalLength = 0;
    let originalEquivalentLineNumber = 0;
    let modifiedEquivalentLineNumber = 0;
    let originalEndEquivalentLineNumber = 0;
    let modifiedEndEquivalentLineNumber = 0;
    const sortMyViewZones = (a, b) => {
      return a.afterLineNumber - b.afterLineNumber;
    };
    const addAndCombineIfPossible = (destination, item) => {
      if (item.domNode === null && destination.length > 0) {
        const lastItem = destination[destination.length - 1];
        if (lastItem.afterLineNumber === item.afterLineNumber && lastItem.domNode === null) {
          lastItem.heightInLines += item.heightInLines;
          return;
        }
      }
      destination.push(item);
    };
    const modifiedForeignVZ = new ForeignViewZonesIterator(this._modifiedForeignVZ);
    const originalForeignVZ = new ForeignViewZonesIterator(this._originalForeignVZ);
    let lastOriginalLineNumber = 1;
    let lastModifiedLineNumber = 1;
    for (let i = 0, length2 = this._lineChanges.length; i <= length2; i++) {
      const lineChange = i < length2 ? this._lineChanges[i] : null;
      if (lineChange !== null) {
        originalEquivalentLineNumber = lineChange.originalStartLineNumber + (lineChange.originalEndLineNumber > 0 ? -1 : 0);
        modifiedEquivalentLineNumber = lineChange.modifiedStartLineNumber + (lineChange.modifiedEndLineNumber > 0 ? -1 : 0);
        lineChangeOriginalLength = lineChange.originalEndLineNumber > 0 ? ViewZonesComputer._getViewLineCount(this._originalEditor, lineChange.originalStartLineNumber, lineChange.originalEndLineNumber) : 0;
        lineChangeModifiedLength = lineChange.modifiedEndLineNumber > 0 ? ViewZonesComputer._getViewLineCount(this._modifiedEditor, lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber) : 0;
        originalEndEquivalentLineNumber = Math.max(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber);
        modifiedEndEquivalentLineNumber = Math.max(lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber);
      } else {
        originalEquivalentLineNumber += 1e7 + lineChangeOriginalLength;
        modifiedEquivalentLineNumber += 1e7 + lineChangeModifiedLength;
        originalEndEquivalentLineNumber = originalEquivalentLineNumber;
        modifiedEndEquivalentLineNumber = modifiedEquivalentLineNumber;
      }
      let stepOriginal = [];
      let stepModified = [];
      if (hasWrapping) {
        let count;
        if (lineChange) {
          if (lineChange.originalEndLineNumber > 0) {
            count = lineChange.originalStartLineNumber - lastOriginalLineNumber;
          } else {
            count = lineChange.modifiedStartLineNumber - lastModifiedLineNumber;
          }
        } else {
          count = originalModel.getLineCount() - lastOriginalLineNumber + 1;
        }
        for (let i2 = 0; i2 < count; i2++) {
          const originalLineNumber = lastOriginalLineNumber + i2;
          const modifiedLineNumber = lastModifiedLineNumber + i2;
          const originalViewLineCount = originalCoordinatesConverter.getModelLineViewLineCount(originalLineNumber);
          const modifiedViewLineCount = modifiedCoordinatesConverter.getModelLineViewLineCount(modifiedLineNumber);
          if (originalViewLineCount < modifiedViewLineCount) {
            stepOriginal.push({
              afterLineNumber: originalLineNumber,
              heightInLines: modifiedViewLineCount - originalViewLineCount,
              domNode: null,
              marginDomNode: null
            });
          } else if (originalViewLineCount > modifiedViewLineCount) {
            stepModified.push({
              afterLineNumber: modifiedLineNumber,
              heightInLines: originalViewLineCount - modifiedViewLineCount,
              domNode: null,
              marginDomNode: null
            });
          }
        }
        if (lineChange) {
          lastOriginalLineNumber = (lineChange.originalEndLineNumber > 0 ? lineChange.originalEndLineNumber : lineChange.originalStartLineNumber) + 1;
          lastModifiedLineNumber = (lineChange.modifiedEndLineNumber > 0 ? lineChange.modifiedEndLineNumber : lineChange.modifiedStartLineNumber) + 1;
        }
      }
      while (modifiedForeignVZ.current && modifiedForeignVZ.current.afterLineNumber <= modifiedEndEquivalentLineNumber) {
        let viewZoneLineNumber;
        if (modifiedForeignVZ.current.afterLineNumber <= modifiedEquivalentLineNumber) {
          viewZoneLineNumber = originalEquivalentLineNumber - modifiedEquivalentLineNumber + modifiedForeignVZ.current.afterLineNumber;
        } else {
          viewZoneLineNumber = originalEndEquivalentLineNumber;
        }
        let marginDomNode = null;
        if (lineChange && lineChange.modifiedStartLineNumber <= modifiedForeignVZ.current.afterLineNumber && modifiedForeignVZ.current.afterLineNumber <= lineChange.modifiedEndLineNumber) {
          marginDomNode = this._createOriginalMarginDomNodeForModifiedForeignViewZoneInAddedRegion();
        }
        stepOriginal.push({
          afterLineNumber: viewZoneLineNumber,
          heightInLines: modifiedForeignVZ.current.height / modifiedLineHeight,
          domNode: null,
          marginDomNode
        });
        modifiedForeignVZ.advance();
      }
      while (originalForeignVZ.current && originalForeignVZ.current.afterLineNumber <= originalEndEquivalentLineNumber) {
        let viewZoneLineNumber;
        if (originalForeignVZ.current.afterLineNumber <= originalEquivalentLineNumber) {
          viewZoneLineNumber = modifiedEquivalentLineNumber - originalEquivalentLineNumber + originalForeignVZ.current.afterLineNumber;
        } else {
          viewZoneLineNumber = modifiedEndEquivalentLineNumber;
        }
        stepModified.push({
          afterLineNumber: viewZoneLineNumber,
          heightInLines: originalForeignVZ.current.height / originalLineHeight,
          domNode: null
        });
        originalForeignVZ.advance();
      }
      if (lineChange !== null && isChangeOrInsert(lineChange)) {
        const r = this._produceOriginalFromDiff(lineChange, lineChangeOriginalLength, lineChangeModifiedLength);
        if (r) {
          stepOriginal.push(r);
        }
      }
      if (lineChange !== null && isChangeOrDelete(lineChange)) {
        const r = this._produceModifiedFromDiff(lineChange, lineChangeOriginalLength, lineChangeModifiedLength);
        if (r) {
          stepModified.push(r);
        }
      }
      let stepOriginalIndex = 0;
      let stepModifiedIndex = 0;
      stepOriginal = stepOriginal.sort(sortMyViewZones);
      stepModified = stepModified.sort(sortMyViewZones);
      while (stepOriginalIndex < stepOriginal.length && stepModifiedIndex < stepModified.length) {
        const original = stepOriginal[stepOriginalIndex];
        const modified = stepModified[stepModifiedIndex];
        const originalDelta = original.afterLineNumber - originalEquivalentLineNumber;
        const modifiedDelta = modified.afterLineNumber - modifiedEquivalentLineNumber;
        if (originalDelta < modifiedDelta) {
          addAndCombineIfPossible(result2.original, original);
          stepOriginalIndex++;
        } else if (modifiedDelta < originalDelta) {
          addAndCombineIfPossible(result2.modified, modified);
          stepModifiedIndex++;
        } else if (original.shouldNotShrink) {
          addAndCombineIfPossible(result2.original, original);
          stepOriginalIndex++;
        } else if (modified.shouldNotShrink) {
          addAndCombineIfPossible(result2.modified, modified);
          stepModifiedIndex++;
        } else {
          if (original.heightInLines >= modified.heightInLines) {
            original.heightInLines -= modified.heightInLines;
            stepModifiedIndex++;
          } else {
            modified.heightInLines -= original.heightInLines;
            stepOriginalIndex++;
          }
        }
      }
      while (stepOriginalIndex < stepOriginal.length) {
        addAndCombineIfPossible(result2.original, stepOriginal[stepOriginalIndex]);
        stepOriginalIndex++;
      }
      while (stepModifiedIndex < stepModified.length) {
        addAndCombineIfPossible(result2.modified, stepModified[stepModifiedIndex]);
        stepModifiedIndex++;
      }
    }
    return {
      original: ViewZonesComputer._ensureDomNodes(result2.original),
      modified: ViewZonesComputer._ensureDomNodes(result2.modified)
    };
  }
  static _ensureDomNodes(zones) {
    return zones.map((z) => {
      if (!z.domNode) {
        z.domNode = createFakeLinesDiv();
      }
      return z;
    });
  }
}
function createDecoration(startLineNumber, startColumn, endLineNumber, endColumn, options) {
  return {
    range: new Range$2(startLineNumber, startColumn, endLineNumber, endColumn),
    options
  };
}
const DECORATIONS = {
  arrowRevertChange: ModelDecorationOptions.register({
    description: "diff-editor-arrow-revert-change",
    glyphMarginHoverMessage: new MarkdownString(void 0, { isTrusted: true, supportThemeIcons: true }).appendMarkdown(localize("revertChangeHoverMessage", "Click to revert change")),
    glyphMarginClassName: "arrow-revert-change " + ThemeIcon.asClassName(Codicon.arrowRight),
    zIndex: 10001
  }),
  charDelete: ModelDecorationOptions.register({
    description: "diff-editor-char-delete",
    className: "char-delete"
  }),
  charDeleteWholeLine: ModelDecorationOptions.register({
    description: "diff-editor-char-delete-whole-line",
    className: "char-delete",
    isWholeLine: true
  }),
  charInsert: ModelDecorationOptions.register({
    description: "diff-editor-char-insert",
    className: "char-insert"
  }),
  charInsertWholeLine: ModelDecorationOptions.register({
    description: "diff-editor-char-insert-whole-line",
    className: "char-insert",
    isWholeLine: true
  }),
  lineInsert: ModelDecorationOptions.register({
    description: "diff-editor-line-insert",
    className: "line-insert",
    marginClassName: "gutter-insert",
    isWholeLine: true
  }),
  lineInsertWithSign: ModelDecorationOptions.register({
    description: "diff-editor-line-insert-with-sign",
    className: "line-insert",
    linesDecorationsClassName: "insert-sign " + ThemeIcon.asClassName(diffInsertIcon$1),
    marginClassName: "gutter-insert",
    isWholeLine: true
  }),
  lineDelete: ModelDecorationOptions.register({
    description: "diff-editor-line-delete",
    className: "line-delete",
    marginClassName: "gutter-delete",
    isWholeLine: true
  }),
  lineDeleteWithSign: ModelDecorationOptions.register({
    description: "diff-editor-line-delete-with-sign",
    className: "line-delete",
    linesDecorationsClassName: "delete-sign " + ThemeIcon.asClassName(diffRemoveIcon$1),
    marginClassName: "gutter-delete",
    isWholeLine: true
  }),
  lineDeleteMargin: ModelDecorationOptions.register({
    description: "diff-editor-line-delete-margin",
    marginClassName: "gutter-delete"
  })
};
class DiffEditorWidgetSideBySide extends DiffEditorWidgetStyle {
  constructor(dataSource, enableSplitViewResizing, defaultSashRatio) {
    super(dataSource);
    this._disableSash = enableSplitViewResizing === false;
    this._defaultRatio = defaultSashRatio;
    this._sashRatio = null;
    this._sashPosition = null;
    this._startSashPosition = null;
    this._sash = this._register(new Sash(this._dataSource.getContainerDomNode(), this, {
      orientation: 0
      /* Orientation.VERTICAL */
    }));
    if (this._disableSash) {
      this._sash.state = 0;
    }
    this._sash.onDidStart(() => this._onSashDragStart());
    this._sash.onDidChange((e) => this._onSashDrag(e));
    this._sash.onDidEnd(() => this._onSashDragEnd());
    this._sash.onDidReset(() => this._onSashReset());
  }
  setEnableSplitViewResizing(enableSplitViewResizing, defaultRatio) {
    this._defaultRatio = defaultRatio;
    const newDisableSash = enableSplitViewResizing === false;
    if (this._disableSash !== newDisableSash) {
      this._disableSash = newDisableSash;
      this._sash.state = this._disableSash ? 0 : 3;
    }
  }
  layout(sashRatio = this._sashRatio || this._defaultRatio) {
    const w = this._dataSource.getWidth();
    const contentWidth = w - (this._dataSource.getOptions().renderOverviewRuler ? DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH : 0);
    let sashPosition = Math.floor((sashRatio || this._defaultRatio) * contentWidth);
    const midPoint = Math.floor(this._defaultRatio * contentWidth);
    sashPosition = this._disableSash ? midPoint : sashPosition || midPoint;
    if (contentWidth > DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH * 2) {
      if (sashPosition < DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH) {
        sashPosition = DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH;
      }
      if (sashPosition > contentWidth - DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH) {
        sashPosition = contentWidth - DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH;
      }
    } else {
      sashPosition = midPoint;
    }
    if (this._sashPosition !== sashPosition) {
      this._sashPosition = sashPosition;
    }
    this._sash.layout();
    return this._sashPosition;
  }
  _onSashDragStart() {
    this._startSashPosition = this._sashPosition;
  }
  _onSashDrag(e) {
    const w = this._dataSource.getWidth();
    const contentWidth = w - (this._dataSource.getOptions().renderOverviewRuler ? DiffEditorWidget.ENTIRE_DIFF_OVERVIEW_WIDTH : 0);
    const sashPosition = this.layout((this._startSashPosition + (e.currentX - e.startX)) / contentWidth);
    this._sashRatio = sashPosition / contentWidth;
    this._dataSource.relayoutEditors();
  }
  _onSashDragEnd() {
    this._sash.layout();
  }
  _onSashReset() {
    this._sashRatio = this._defaultRatio;
    this._dataSource.relayoutEditors();
    this._sash.layout();
  }
  getVerticalSashTop(sash2) {
    return 0;
  }
  getVerticalSashLeft(sash2) {
    return this._sashPosition;
  }
  getVerticalSashHeight(sash2) {
    return this._dataSource.getHeight();
  }
  setBoundarySashes(sashes) {
    this._sash.orthogonalEndSash = sashes.bottom;
  }
  _getViewZones(lineChanges, originalForeignVZ, modifiedForeignVZ) {
    const originalEditor = this._dataSource.getOriginalEditor();
    const modifiedEditor = this._dataSource.getModifiedEditor();
    const c = new SideBySideViewZonesComputer(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor);
    return c.getViewZones();
  }
  _getOriginalEditorDecorations(zones, lineChanges, ignoreTrimWhitespace, renderIndicators) {
    const originalEditor = this._dataSource.getOriginalEditor();
    const overviewZoneColor = String(this._removeColor);
    const result2 = {
      decorations: [],
      overviewZones: []
    };
    const originalModel = originalEditor.getModel();
    const originalViewModel = originalEditor._getViewModel();
    for (const lineChange of lineChanges) {
      if (isChangeOrDelete(lineChange)) {
        result2.decorations.push({
          range: new Range$2(
            lineChange.originalStartLineNumber,
            1,
            lineChange.originalEndLineNumber,
            1073741824
            /* Constants.MAX_SAFE_SMALL_INTEGER */
          ),
          options: renderIndicators ? DECORATIONS.lineDeleteWithSign : DECORATIONS.lineDelete
        });
        if (!isChangeOrInsert(lineChange) || !lineChange.charChanges) {
          result2.decorations.push(createDecoration(lineChange.originalStartLineNumber, 1, lineChange.originalEndLineNumber, 1073741824, DECORATIONS.charDeleteWholeLine));
        }
        const viewRange = getViewRange(originalModel, originalViewModel, lineChange.originalStartLineNumber, lineChange.originalEndLineNumber);
        result2.overviewZones.push(new OverviewRulerZone(
          viewRange.startLineNumber,
          viewRange.endLineNumber,
          /*use endLineNumber*/
          0,
          overviewZoneColor
        ));
        if (lineChange.charChanges) {
          for (const charChange of lineChange.charChanges) {
            if (isCharChangeOrDelete(charChange)) {
              if (ignoreTrimWhitespace) {
                for (let lineNumber = charChange.originalStartLineNumber; lineNumber <= charChange.originalEndLineNumber; lineNumber++) {
                  let startColumn;
                  let endColumn;
                  if (lineNumber === charChange.originalStartLineNumber) {
                    startColumn = charChange.originalStartColumn;
                  } else {
                    startColumn = originalModel.getLineFirstNonWhitespaceColumn(lineNumber);
                  }
                  if (lineNumber === charChange.originalEndLineNumber) {
                    endColumn = charChange.originalEndColumn;
                  } else {
                    endColumn = originalModel.getLineLastNonWhitespaceColumn(lineNumber);
                  }
                  result2.decorations.push(createDecoration(lineNumber, startColumn, lineNumber, endColumn, DECORATIONS.charDelete));
                }
              } else {
                result2.decorations.push(createDecoration(charChange.originalStartLineNumber, charChange.originalStartColumn, charChange.originalEndLineNumber, charChange.originalEndColumn, DECORATIONS.charDelete));
              }
            }
          }
        }
      }
    }
    return result2;
  }
  _getModifiedEditorDecorations(zones, lineChanges, ignoreTrimWhitespace, renderIndicators, renderMarginRevertIcon) {
    const modifiedEditor = this._dataSource.getModifiedEditor();
    const overviewZoneColor = String(this._insertColor);
    const result2 = {
      decorations: [],
      overviewZones: []
    };
    const modifiedModel = modifiedEditor.getModel();
    const modifiedViewModel = modifiedEditor._getViewModel();
    for (const lineChange of lineChanges) {
      if (renderMarginRevertIcon) {
        if (lineChange.modifiedEndLineNumber > 0) {
          result2.decorations.push({
            range: new Range$2(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedStartLineNumber, 1),
            options: DECORATIONS.arrowRevertChange
          });
        } else {
          const viewZone = zones.modified.find((z) => z.afterLineNumber === lineChange.modifiedStartLineNumber);
          if (viewZone) {
            viewZone.marginDomNode = createViewZoneMarginArrow();
          }
        }
      }
      if (isChangeOrInsert(lineChange)) {
        result2.decorations.push({
          range: new Range$2(
            lineChange.modifiedStartLineNumber,
            1,
            lineChange.modifiedEndLineNumber,
            1073741824
            /* Constants.MAX_SAFE_SMALL_INTEGER */
          ),
          options: renderIndicators ? DECORATIONS.lineInsertWithSign : DECORATIONS.lineInsert
        });
        if (!isChangeOrDelete(lineChange) || !lineChange.charChanges) {
          result2.decorations.push(createDecoration(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedEndLineNumber, 1073741824, DECORATIONS.charInsertWholeLine));
        }
        const viewRange = getViewRange(modifiedModel, modifiedViewModel, lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber);
        result2.overviewZones.push(new OverviewRulerZone(
          viewRange.startLineNumber,
          viewRange.endLineNumber,
          /*use endLineNumber*/
          0,
          overviewZoneColor
        ));
        if (lineChange.charChanges) {
          for (const charChange of lineChange.charChanges) {
            if (isCharChangeOrInsert(charChange)) {
              if (ignoreTrimWhitespace) {
                for (let lineNumber = charChange.modifiedStartLineNumber; lineNumber <= charChange.modifiedEndLineNumber; lineNumber++) {
                  let startColumn;
                  let endColumn;
                  if (lineNumber === charChange.modifiedStartLineNumber) {
                    startColumn = charChange.modifiedStartColumn;
                  } else {
                    startColumn = modifiedModel.getLineFirstNonWhitespaceColumn(lineNumber);
                  }
                  if (lineNumber === charChange.modifiedEndLineNumber) {
                    endColumn = charChange.modifiedEndColumn;
                  } else {
                    endColumn = modifiedModel.getLineLastNonWhitespaceColumn(lineNumber);
                  }
                  result2.decorations.push(createDecoration(lineNumber, startColumn, lineNumber, endColumn, DECORATIONS.charInsert));
                }
              } else {
                result2.decorations.push(createDecoration(charChange.modifiedStartLineNumber, charChange.modifiedStartColumn, charChange.modifiedEndLineNumber, charChange.modifiedEndColumn, DECORATIONS.charInsert));
              }
            }
          }
        }
      }
    }
    return result2;
  }
}
DiffEditorWidgetSideBySide.MINIMUM_EDITOR_WIDTH = 100;
class SideBySideViewZonesComputer extends ViewZonesComputer {
  constructor(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor) {
    super(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor);
  }
  _createOriginalMarginDomNodeForModifiedForeignViewZoneInAddedRegion() {
    return null;
  }
  _produceOriginalFromDiff(lineChange, lineChangeOriginalLength, lineChangeModifiedLength) {
    if (lineChangeModifiedLength > lineChangeOriginalLength) {
      return {
        afterLineNumber: Math.max(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber),
        heightInLines: lineChangeModifiedLength - lineChangeOriginalLength,
        domNode: null
      };
    }
    return null;
  }
  _produceModifiedFromDiff(lineChange, lineChangeOriginalLength, lineChangeModifiedLength) {
    if (lineChangeOriginalLength > lineChangeModifiedLength) {
      return {
        afterLineNumber: Math.max(lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber),
        heightInLines: lineChangeOriginalLength - lineChangeModifiedLength,
        domNode: null
      };
    }
    return null;
  }
}
class DiffEditorWidgetInline extends DiffEditorWidgetStyle {
  constructor(dataSource, enableSplitViewResizing) {
    super(dataSource);
    this._decorationsLeft = dataSource.getOriginalEditor().getLayoutInfo().decorationsLeft;
    this._register(dataSource.getOriginalEditor().onDidLayoutChange((layoutInfo) => {
      if (this._decorationsLeft !== layoutInfo.decorationsLeft) {
        this._decorationsLeft = layoutInfo.decorationsLeft;
        dataSource.relayoutEditors();
      }
    }));
  }
  setEnableSplitViewResizing(enableSplitViewResizing) {
  }
  _getViewZones(lineChanges, originalForeignVZ, modifiedForeignVZ, renderIndicators) {
    const originalEditor = this._dataSource.getOriginalEditor();
    const modifiedEditor = this._dataSource.getModifiedEditor();
    const computer = new InlineViewZonesComputer(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor, renderIndicators);
    return computer.getViewZones();
  }
  _getOriginalEditorDecorations(zones, lineChanges, ignoreTrimWhitespace, renderIndicators) {
    const overviewZoneColor = String(this._removeColor);
    const result2 = {
      decorations: [],
      overviewZones: []
    };
    const originalEditor = this._dataSource.getOriginalEditor();
    const originalModel = originalEditor.getModel();
    const originalViewModel = originalEditor._getViewModel();
    let zoneIndex = 0;
    for (const lineChange of lineChanges) {
      if (isChangeOrDelete(lineChange)) {
        result2.decorations.push({
          range: new Range$2(
            lineChange.originalStartLineNumber,
            1,
            lineChange.originalEndLineNumber,
            1073741824
            /* Constants.MAX_SAFE_SMALL_INTEGER */
          ),
          options: DECORATIONS.lineDeleteMargin
        });
        while (zoneIndex < zones.modified.length) {
          const zone = zones.modified[zoneIndex];
          if (zone.diff && zone.diff.originalStartLineNumber >= lineChange.originalStartLineNumber) {
            break;
          }
          zoneIndex++;
        }
        let zoneHeightInLines = 0;
        if (zoneIndex < zones.modified.length) {
          const zone = zones.modified[zoneIndex];
          if (zone.diff && zone.diff.originalStartLineNumber === lineChange.originalStartLineNumber && zone.diff.originalEndLineNumber === lineChange.originalEndLineNumber && zone.diff.modifiedStartLineNumber === lineChange.modifiedStartLineNumber && zone.diff.modifiedEndLineNumber === lineChange.modifiedEndLineNumber) {
            zoneHeightInLines = zone.heightInLines;
          }
        }
        const viewRange = getViewRange(originalModel, originalViewModel, lineChange.originalStartLineNumber, lineChange.originalEndLineNumber);
        result2.overviewZones.push(new OverviewRulerZone(viewRange.startLineNumber, viewRange.endLineNumber, zoneHeightInLines, overviewZoneColor));
      }
    }
    return result2;
  }
  _getModifiedEditorDecorations(zones, lineChanges, ignoreTrimWhitespace, renderIndicators, renderMarginRevertIcon) {
    const modifiedEditor = this._dataSource.getModifiedEditor();
    const overviewZoneColor = String(this._insertColor);
    const result2 = {
      decorations: [],
      overviewZones: []
    };
    const modifiedModel = modifiedEditor.getModel();
    const modifiedViewModel = modifiedEditor._getViewModel();
    for (const lineChange of lineChanges) {
      if (isChangeOrInsert(lineChange)) {
        result2.decorations.push({
          range: new Range$2(
            lineChange.modifiedStartLineNumber,
            1,
            lineChange.modifiedEndLineNumber,
            1073741824
            /* Constants.MAX_SAFE_SMALL_INTEGER */
          ),
          options: renderIndicators ? DECORATIONS.lineInsertWithSign : DECORATIONS.lineInsert
        });
        const viewRange = getViewRange(modifiedModel, modifiedViewModel, lineChange.modifiedStartLineNumber, lineChange.modifiedEndLineNumber);
        result2.overviewZones.push(new OverviewRulerZone(
          viewRange.startLineNumber,
          viewRange.endLineNumber,
          /*use endLineNumber*/
          0,
          overviewZoneColor
        ));
        if (lineChange.charChanges) {
          for (const charChange of lineChange.charChanges) {
            if (isCharChangeOrInsert(charChange)) {
              if (ignoreTrimWhitespace) {
                for (let lineNumber = charChange.modifiedStartLineNumber; lineNumber <= charChange.modifiedEndLineNumber; lineNumber++) {
                  let startColumn;
                  let endColumn;
                  if (lineNumber === charChange.modifiedStartLineNumber) {
                    startColumn = charChange.modifiedStartColumn;
                  } else {
                    startColumn = modifiedModel.getLineFirstNonWhitespaceColumn(lineNumber);
                  }
                  if (lineNumber === charChange.modifiedEndLineNumber) {
                    endColumn = charChange.modifiedEndColumn;
                  } else {
                    endColumn = modifiedModel.getLineLastNonWhitespaceColumn(lineNumber);
                  }
                  result2.decorations.push(createDecoration(lineNumber, startColumn, lineNumber, endColumn, DECORATIONS.charInsert));
                }
              } else {
                result2.decorations.push(createDecoration(charChange.modifiedStartLineNumber, charChange.modifiedStartColumn, charChange.modifiedEndLineNumber, charChange.modifiedEndColumn, DECORATIONS.charInsert));
              }
            }
          }
        } else {
          result2.decorations.push(createDecoration(lineChange.modifiedStartLineNumber, 1, lineChange.modifiedEndLineNumber, 1073741824, DECORATIONS.charInsertWholeLine));
        }
      }
    }
    return result2;
  }
  layout() {
    return Math.max(5, this._decorationsLeft);
  }
}
class InlineViewZonesComputer extends ViewZonesComputer {
  constructor(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor, renderIndicators) {
    super(lineChanges, originalForeignVZ, modifiedForeignVZ, originalEditor, modifiedEditor);
    this._originalModel = originalEditor.getModel();
    this._renderIndicators = renderIndicators;
    this._pendingLineChange = [];
    this._pendingViewZones = [];
    this._lineBreaksComputer = this._modifiedEditor._getViewModel().createLineBreaksComputer();
  }
  getViewZones() {
    const result2 = super.getViewZones();
    this._finalize(result2);
    return result2;
  }
  _createOriginalMarginDomNodeForModifiedForeignViewZoneInAddedRegion() {
    const result2 = document.createElement("div");
    result2.className = "inline-added-margin-view-zone";
    return result2;
  }
  _produceOriginalFromDiff(lineChange, lineChangeOriginalLength, lineChangeModifiedLength) {
    const marginDomNode = document.createElement("div");
    marginDomNode.className = "inline-added-margin-view-zone";
    return {
      afterLineNumber: Math.max(lineChange.originalStartLineNumber, lineChange.originalEndLineNumber),
      heightInLines: lineChangeModifiedLength,
      domNode: document.createElement("div"),
      marginDomNode
    };
  }
  _produceModifiedFromDiff(lineChange, lineChangeOriginalLength, lineChangeModifiedLength) {
    const domNode = document.createElement("div");
    domNode.className = `view-lines line-delete ${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`;
    const marginDomNode = document.createElement("div");
    marginDomNode.className = "inline-deleted-margin-view-zone";
    const viewZone = {
      shouldNotShrink: true,
      afterLineNumber: lineChange.modifiedEndLineNumber === 0 ? lineChange.modifiedStartLineNumber : lineChange.modifiedStartLineNumber - 1,
      heightInLines: lineChangeOriginalLength,
      minWidthInPx: 0,
      domNode,
      marginDomNode,
      diff: {
        originalStartLineNumber: lineChange.originalStartLineNumber,
        originalEndLineNumber: lineChange.originalEndLineNumber,
        modifiedStartLineNumber: lineChange.modifiedStartLineNumber,
        modifiedEndLineNumber: lineChange.modifiedEndLineNumber,
        originalModel: this._originalModel,
        viewLineCounts: null
      }
    };
    for (let lineNumber = lineChange.originalStartLineNumber; lineNumber <= lineChange.originalEndLineNumber; lineNumber++) {
      this._lineBreaksComputer.addRequest(this._originalModel.getLineContent(lineNumber), null, null);
    }
    this._pendingLineChange.push(lineChange);
    this._pendingViewZones.push(viewZone);
    return viewZone;
  }
  _finalize(result2) {
    const modifiedEditorOptions = this._modifiedEditor.getOptions();
    const tabSize = this._modifiedEditor.getModel().getOptions().tabSize;
    const fontInfo = modifiedEditorOptions.get(
      49
      /* EditorOption.fontInfo */
    );
    const disableMonospaceOptimizations = modifiedEditorOptions.get(
      32
      /* EditorOption.disableMonospaceOptimizations */
    );
    const typicalHalfwidthCharacterWidth = fontInfo.typicalHalfwidthCharacterWidth;
    const scrollBeyondLastColumn = modifiedEditorOptions.get(
      102
      /* EditorOption.scrollBeyondLastColumn */
    );
    const mightContainNonBasicASCII = this._originalModel.mightContainNonBasicASCII();
    const mightContainRTL = this._originalModel.mightContainRTL();
    const lineHeight = modifiedEditorOptions.get(
      65
      /* EditorOption.lineHeight */
    );
    const layoutInfo = modifiedEditorOptions.get(
      142
      /* EditorOption.layoutInfo */
    );
    const lineDecorationsWidth = layoutInfo.decorationsWidth;
    const stopRenderingLineAfter = modifiedEditorOptions.get(
      115
      /* EditorOption.stopRenderingLineAfter */
    );
    const renderWhitespace = modifiedEditorOptions.get(
      97
      /* EditorOption.renderWhitespace */
    );
    const renderControlCharacters = modifiedEditorOptions.get(
      92
      /* EditorOption.renderControlCharacters */
    );
    const fontLigatures = modifiedEditorOptions.get(
      50
      /* EditorOption.fontLigatures */
    );
    const lineBreaks = this._lineBreaksComputer.finalize();
    let lineBreakIndex = 0;
    for (let i = 0; i < this._pendingLineChange.length; i++) {
      const lineChange = this._pendingLineChange[i];
      const viewZone = this._pendingViewZones[i];
      const domNode = viewZone.domNode;
      applyFontInfo(domNode, fontInfo);
      const marginDomNode = viewZone.marginDomNode;
      applyFontInfo(marginDomNode, fontInfo);
      const decorations2 = [];
      if (lineChange.charChanges) {
        for (const charChange of lineChange.charChanges) {
          if (isCharChangeOrDelete(charChange)) {
            decorations2.push(new InlineDecoration(
              new Range$2(charChange.originalStartLineNumber, charChange.originalStartColumn, charChange.originalEndLineNumber, charChange.originalEndColumn),
              "char-delete",
              0
              /* InlineDecorationType.Regular */
            ));
          }
        }
      }
      const hasCharChanges = decorations2.length > 0;
      const sb = new StringBuilder(1e4);
      let maxCharsPerLine = 0;
      let renderedLineCount = 0;
      let viewLineCounts = null;
      for (let lineNumber = lineChange.originalStartLineNumber; lineNumber <= lineChange.originalEndLineNumber; lineNumber++) {
        const lineIndex = lineNumber - lineChange.originalStartLineNumber;
        const lineTokens = this._originalModel.tokenization.getLineTokens(lineNumber);
        const lineContent = lineTokens.getLineContent();
        const lineBreakData = lineBreaks[lineBreakIndex++];
        const actualDecorations = LineDecoration.filter(decorations2, lineNumber, 1, lineContent.length + 1);
        if (lineBreakData) {
          let lastBreakOffset = 0;
          for (const breakOffset of lineBreakData.breakOffsets) {
            const viewLineTokens = lineTokens.sliceAndInflate(lastBreakOffset, breakOffset, 0);
            const viewLineContent = lineContent.substring(lastBreakOffset, breakOffset);
            maxCharsPerLine = Math.max(maxCharsPerLine, this._renderOriginalLine(renderedLineCount++, viewLineContent, viewLineTokens, LineDecoration.extractWrapped(actualDecorations, lastBreakOffset, breakOffset), hasCharChanges, mightContainNonBasicASCII, mightContainRTL, fontInfo, disableMonospaceOptimizations, lineHeight, lineDecorationsWidth, stopRenderingLineAfter, renderWhitespace, renderControlCharacters, fontLigatures, tabSize, sb, marginDomNode));
            lastBreakOffset = breakOffset;
          }
          if (!viewLineCounts) {
            viewLineCounts = [];
          }
          while (viewLineCounts.length < lineIndex) {
            viewLineCounts[viewLineCounts.length] = 1;
          }
          viewLineCounts[lineIndex] = lineBreakData.breakOffsets.length;
          viewZone.heightInLines += lineBreakData.breakOffsets.length - 1;
          const marginDomNode2 = document.createElement("div");
          marginDomNode2.className = "gutter-delete";
          result2.original.push({
            afterLineNumber: lineNumber,
            afterColumn: 0,
            heightInLines: lineBreakData.breakOffsets.length - 1,
            domNode: createFakeLinesDiv(),
            marginDomNode: marginDomNode2
          });
        } else {
          maxCharsPerLine = Math.max(maxCharsPerLine, this._renderOriginalLine(renderedLineCount++, lineContent, lineTokens, actualDecorations, hasCharChanges, mightContainNonBasicASCII, mightContainRTL, fontInfo, disableMonospaceOptimizations, lineHeight, lineDecorationsWidth, stopRenderingLineAfter, renderWhitespace, renderControlCharacters, fontLigatures, tabSize, sb, marginDomNode));
        }
      }
      maxCharsPerLine += scrollBeyondLastColumn;
      const html2 = sb.build();
      const trustedhtml = diffEditorWidgetTtPolicy ? diffEditorWidgetTtPolicy.createHTML(html2) : html2;
      domNode.innerHTML = trustedhtml;
      viewZone.minWidthInPx = maxCharsPerLine * typicalHalfwidthCharacterWidth;
      if (viewLineCounts) {
        const cnt = lineChange.originalEndLineNumber - lineChange.originalStartLineNumber;
        while (viewLineCounts.length <= cnt) {
          viewLineCounts[viewLineCounts.length] = 1;
        }
      }
      viewZone.diff.viewLineCounts = viewLineCounts;
    }
    result2.original.sort((a, b) => {
      return a.afterLineNumber - b.afterLineNumber;
    });
  }
  _renderOriginalLine(renderedLineCount, lineContent, lineTokens, decorations2, hasCharChanges, mightContainNonBasicASCII, mightContainRTL, fontInfo, disableMonospaceOptimizations, lineHeight, lineDecorationsWidth, stopRenderingLineAfter, renderWhitespace, renderControlCharacters, fontLigatures, tabSize, sb, marginDomNode) {
    sb.appendString('<div class="view-line');
    if (!hasCharChanges) {
      sb.appendString(" char-delete");
    }
    sb.appendString('" style="top:');
    sb.appendString(String(renderedLineCount * lineHeight));
    sb.appendString('px;width:1000000px;">');
    const isBasicASCII2 = ViewLineRenderingData.isBasicASCII(lineContent, mightContainNonBasicASCII);
    const containsRTL2 = ViewLineRenderingData.containsRTL(lineContent, isBasicASCII2, mightContainRTL);
    const output = renderViewLine(new RenderLineInput(
      fontInfo.isMonospace && !disableMonospaceOptimizations,
      fontInfo.canUseHalfwidthRightwardsArrow,
      lineContent,
      false,
      isBasicASCII2,
      containsRTL2,
      0,
      lineTokens,
      decorations2,
      tabSize,
      0,
      fontInfo.spaceWidth,
      fontInfo.middotWidth,
      fontInfo.wsmiddotWidth,
      stopRenderingLineAfter,
      renderWhitespace,
      renderControlCharacters,
      fontLigatures !== EditorFontLigatures.OFF,
      null
      // Send no selections, original line cannot be selected
    ), sb);
    sb.appendString("</div>");
    if (this._renderIndicators) {
      const marginElement = document.createElement("div");
      marginElement.className = `delete-sign ${ThemeIcon.asClassName(diffRemoveIcon$1)}`;
      marginElement.setAttribute("style", `position:absolute;top:${renderedLineCount * lineHeight}px;width:${lineDecorationsWidth}px;height:${lineHeight}px;right:0;`);
      marginDomNode.appendChild(marginElement);
    }
    return output.characterMapping.getHorizontalOffset(output.characterMapping.length);
  }
}
function validateDiffWordWrap(value, defaultValue) {
  return stringSet(value, defaultValue, ["off", "on", "inherit"]);
}
function isChangeOrInsert(lineChange) {
  return lineChange.modifiedEndLineNumber > 0;
}
function isChangeOrDelete(lineChange) {
  return lineChange.originalEndLineNumber > 0;
}
function isCharChangeOrInsert(charChange) {
  if (charChange.modifiedStartLineNumber === charChange.modifiedEndLineNumber) {
    return charChange.modifiedEndColumn - charChange.modifiedStartColumn > 0;
  }
  return charChange.modifiedEndLineNumber - charChange.modifiedStartLineNumber > 0;
}
function isCharChangeOrDelete(charChange) {
  if (charChange.originalStartLineNumber === charChange.originalEndLineNumber) {
    return charChange.originalEndColumn - charChange.originalStartColumn > 0;
  }
  return charChange.originalEndLineNumber - charChange.originalStartLineNumber > 0;
}
function createFakeLinesDiv() {
  const r = document.createElement("div");
  r.className = "diagonal-fill";
  return r;
}
function createViewZoneMarginArrow() {
  const arrow = document.createElement("div");
  arrow.className = "arrow-revert-change " + ThemeIcon.asClassName(Codicon.arrowRight);
  return $$d("div", {}, arrow);
}
function getViewRange(model, viewModel, startLineNumber, endLineNumber) {
  const lineCount = model.getLineCount();
  startLineNumber = Math.min(lineCount, Math.max(1, startLineNumber));
  endLineNumber = Math.min(lineCount, Math.max(1, endLineNumber));
  return viewModel.coordinatesConverter.convertModelRangeToViewRange(new Range$2(startLineNumber, model.getLineMinColumn(startLineNumber), endLineNumber, model.getLineMaxColumn(endLineNumber)));
}
function validateDiffEditorOptions$1(options, defaults) {
  return {
    enableSplitViewResizing: boolean(options.enableSplitViewResizing, defaults.enableSplitViewResizing),
    splitViewDefaultRatio: clampedFloat(options.splitViewDefaultRatio, 0.5, 0.1, 0.9),
    renderSideBySide: boolean(options.renderSideBySide, defaults.renderSideBySide),
    renderMarginRevertIcon: boolean(options.renderMarginRevertIcon, defaults.renderMarginRevertIcon),
    maxComputationTime: clampedInt(
      options.maxComputationTime,
      defaults.maxComputationTime,
      0,
      1073741824
      /* Constants.MAX_SAFE_SMALL_INTEGER */
    ),
    maxFileSize: clampedInt(
      options.maxFileSize,
      defaults.maxFileSize,
      0,
      1073741824
      /* Constants.MAX_SAFE_SMALL_INTEGER */
    ),
    ignoreTrimWhitespace: boolean(options.ignoreTrimWhitespace, defaults.ignoreTrimWhitespace),
    renderIndicators: boolean(options.renderIndicators, defaults.renderIndicators),
    originalEditable: boolean(options.originalEditable, defaults.originalEditable),
    diffCodeLens: boolean(options.diffCodeLens, defaults.diffCodeLens),
    renderOverviewRuler: boolean(options.renderOverviewRuler, defaults.renderOverviewRuler),
    diffWordWrap: validateDiffWordWrap(options.diffWordWrap, defaults.diffWordWrap),
    diffAlgorithm: stringSet(options.diffAlgorithm, defaults.diffAlgorithm, ["legacy", "advanced"], { "smart": "legacy", "experimental": "advanced" }),
    accessibilityVerbose: boolean(options.accessibilityVerbose, defaults.accessibilityVerbose),
    experimental: {
      collapseUnchangedRegions: false
    },
    isInEmbeddedEditor: boolean(options.isInEmbeddedEditor, defaults.isInEmbeddedEditor),
    onlyShowAccessibleDiffViewer: false
  };
}
function changedDiffEditorOptions(a, b) {
  return {
    enableSplitViewResizing: a.enableSplitViewResizing !== b.enableSplitViewResizing,
    renderSideBySide: a.renderSideBySide !== b.renderSideBySide,
    renderMarginRevertIcon: a.renderMarginRevertIcon !== b.renderMarginRevertIcon,
    maxComputationTime: a.maxComputationTime !== b.maxComputationTime,
    maxFileSize: a.maxFileSize !== b.maxFileSize,
    ignoreTrimWhitespace: a.ignoreTrimWhitespace !== b.ignoreTrimWhitespace,
    renderIndicators: a.renderIndicators !== b.renderIndicators,
    originalEditable: a.originalEditable !== b.originalEditable,
    diffCodeLens: a.diffCodeLens !== b.diffCodeLens,
    renderOverviewRuler: a.renderOverviewRuler !== b.renderOverviewRuler,
    diffWordWrap: a.diffWordWrap !== b.diffWordWrap,
    diffAlgorithm: a.diffAlgorithm !== b.diffAlgorithm,
    accessibilityVerbose: a.accessibilityVerbose !== b.accessibilityVerbose
  };
}
registerThemingParticipant((theme, collector) => {
  const diffDiagonalFillColor = theme.getColor(diffDiagonalFill);
  collector.addRule(`
	.monaco-editor .diagonal-fill {
		background-image: linear-gradient(
			-45deg,
			${diffDiagonalFillColor} 12.5%,
			#0000 12.5%, #0000 50%,
			${diffDiagonalFillColor} 50%, ${diffDiagonalFillColor} 62.5%,
			#0000 62.5%, #0000 100%
		);
		background-size: 8px 8px;
	}
	`);
});
const anchorSelect = "";
var __decorate$1W = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1T = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$1o = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
const SelectionAnchorSet = new RawContextKey("selectionAnchorSet", false);
let SelectionAnchorController = class SelectionAnchorController2 {
  static get(editor2) {
    return editor2.getContribution(SelectionAnchorController2.ID);
  }
  constructor(editor2, contextKeyService) {
    this.editor = editor2;
    this.selectionAnchorSetContextKey = SelectionAnchorSet.bindTo(contextKeyService);
    this.modelChangeListener = editor2.onDidChangeModel(() => this.selectionAnchorSetContextKey.reset());
  }
  setSelectionAnchor() {
    if (this.editor.hasModel()) {
      const position = this.editor.getPosition();
      this.editor.changeDecorations((accessor) => {
        if (this.decorationId) {
          accessor.removeDecoration(this.decorationId);
        }
        this.decorationId = accessor.addDecoration(Selection$1.fromPositions(position, position), {
          description: "selection-anchor",
          stickiness: 1,
          hoverMessage: new MarkdownString().appendText(localize("selectionAnchor", "Selection Anchor")),
          className: "selection-anchor"
        });
      });
      this.selectionAnchorSetContextKey.set(!!this.decorationId);
      alert(localize("anchorSet", "Anchor set at {0}:{1}", position.lineNumber, position.column));
    }
  }
  goToSelectionAnchor() {
    if (this.editor.hasModel() && this.decorationId) {
      const anchorPosition = this.editor.getModel().getDecorationRange(this.decorationId);
      if (anchorPosition) {
        this.editor.setPosition(anchorPosition.getStartPosition());
      }
    }
  }
  selectFromAnchorToCursor() {
    if (this.editor.hasModel() && this.decorationId) {
      const start = this.editor.getModel().getDecorationRange(this.decorationId);
      if (start) {
        const end = this.editor.getPosition();
        this.editor.setSelection(Selection$1.fromPositions(start.getStartPosition(), end));
        this.cancelSelectionAnchor();
      }
    }
  }
  cancelSelectionAnchor() {
    if (this.decorationId) {
      const decorationId = this.decorationId;
      this.editor.changeDecorations((accessor) => {
        accessor.removeDecoration(decorationId);
        this.decorationId = void 0;
      });
      this.selectionAnchorSetContextKey.set(false);
    }
  }
  dispose() {
    this.cancelSelectionAnchor();
    this.modelChangeListener.dispose();
  }
};
SelectionAnchorController.ID = "editor.contrib.selectionAnchorController";
SelectionAnchorController = __decorate$1W([
  __param$1T(1, IContextKeyService)
], SelectionAnchorController);
class SetSelectionAnchor extends EditorAction {
  constructor() {
    super({
      id: "editor.action.setSelectionAnchor",
      label: localize("setSelectionAnchor", "Set Selection Anchor"),
      alias: "Set Selection Anchor",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: KeyChord(
          2048 | 41,
          2048 | 32
          /* KeyCode.KeyB */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(_accessor, editor2) {
    var _a2;
    return __awaiter$1o(this, void 0, void 0, function* () {
      (_a2 = SelectionAnchorController.get(editor2)) === null || _a2 === void 0 ? void 0 : _a2.setSelectionAnchor();
    });
  }
}
class GoToSelectionAnchor extends EditorAction {
  constructor() {
    super({
      id: "editor.action.goToSelectionAnchor",
      label: localize("goToSelectionAnchor", "Go to Selection Anchor"),
      alias: "Go to Selection Anchor",
      precondition: SelectionAnchorSet
    });
  }
  run(_accessor, editor2) {
    var _a2;
    return __awaiter$1o(this, void 0, void 0, function* () {
      (_a2 = SelectionAnchorController.get(editor2)) === null || _a2 === void 0 ? void 0 : _a2.goToSelectionAnchor();
    });
  }
}
class SelectFromAnchorToCursor extends EditorAction {
  constructor() {
    super({
      id: "editor.action.selectFromAnchorToCursor",
      label: localize("selectFromAnchorToCursor", "Select from Anchor to Cursor"),
      alias: "Select from Anchor to Cursor",
      precondition: SelectionAnchorSet,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: KeyChord(
          2048 | 41,
          2048 | 41
          /* KeyCode.KeyK */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(_accessor, editor2) {
    var _a2;
    return __awaiter$1o(this, void 0, void 0, function* () {
      (_a2 = SelectionAnchorController.get(editor2)) === null || _a2 === void 0 ? void 0 : _a2.selectFromAnchorToCursor();
    });
  }
}
class CancelSelectionAnchor extends EditorAction {
  constructor() {
    super({
      id: "editor.action.cancelSelectionAnchor",
      label: localize("cancelSelectionAnchor", "Cancel Selection Anchor"),
      alias: "Cancel Selection Anchor",
      precondition: SelectionAnchorSet,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 9,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(_accessor, editor2) {
    var _a2;
    return __awaiter$1o(this, void 0, void 0, function* () {
      (_a2 = SelectionAnchorController.get(editor2)) === null || _a2 === void 0 ? void 0 : _a2.cancelSelectionAnchor();
    });
  }
}
registerEditorContribution(
  SelectionAnchorController.ID,
  SelectionAnchorController,
  4
  /* EditorContributionInstantiation.Lazy */
);
registerEditorAction(SetSelectionAnchor);
registerEditorAction(GoToSelectionAnchor);
registerEditorAction(SelectFromAnchorToCursor);
registerEditorAction(CancelSelectionAnchor);
const bracketMatching = "";
const overviewRulerBracketMatchForeground = registerColor("editorOverviewRuler.bracketMatchForeground", { dark: "#A0A0A0", light: "#A0A0A0", hcDark: "#A0A0A0", hcLight: "#A0A0A0" }, localize("overviewRulerBracketMatchForeground", "Overview ruler marker color for matching brackets."));
class JumpToBracketAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.jumpToBracket",
      label: localize("smartSelect.jumpBracket", "Go to Bracket"),
      alias: "Go to Bracket",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 1024 | 93,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor2) {
    var _a2;
    (_a2 = BracketMatchingController.get(editor2)) === null || _a2 === void 0 ? void 0 : _a2.jumpToBracket();
  }
}
class SelectToBracketAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.selectToBracket",
      label: localize("smartSelect.selectToBracket", "Select to Bracket"),
      alias: "Select to Bracket",
      precondition: void 0,
      description: {
        description: `Select to Bracket`,
        args: [{
          name: "args",
          schema: {
            type: "object",
            properties: {
              "selectBrackets": {
                type: "boolean",
                default: true
              }
            }
          }
        }]
      }
    });
  }
  run(accessor, editor2, args) {
    var _a2;
    let selectBrackets = true;
    if (args && args.selectBrackets === false) {
      selectBrackets = false;
    }
    (_a2 = BracketMatchingController.get(editor2)) === null || _a2 === void 0 ? void 0 : _a2.selectToBracket(selectBrackets);
  }
}
class RemoveBracketsAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.removeBrackets",
      label: localize("smartSelect.removeBrackets", "Remove Brackets"),
      alias: "Remove Brackets",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 512 | 1,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor2) {
    var _a2;
    (_a2 = BracketMatchingController.get(editor2)) === null || _a2 === void 0 ? void 0 : _a2.removeBrackets(this.id);
  }
}
class BracketsData {
  constructor(position, brackets, options) {
    this.position = position;
    this.brackets = brackets;
    this.options = options;
  }
}
class BracketMatchingController extends Disposable {
  static get(editor2) {
    return editor2.getContribution(BracketMatchingController.ID);
  }
  constructor(editor2) {
    super();
    this._editor = editor2;
    this._lastBracketsData = [];
    this._lastVersionId = 0;
    this._decorations = this._editor.createDecorationsCollection();
    this._updateBracketsSoon = this._register(new RunOnceScheduler(() => this._updateBrackets(), 50));
    this._matchBrackets = this._editor.getOption(
      70
      /* EditorOption.matchBrackets */
    );
    this._updateBracketsSoon.schedule();
    this._register(editor2.onDidChangeCursorPosition((e) => {
      if (this._matchBrackets === "never") {
        return;
      }
      this._updateBracketsSoon.schedule();
    }));
    this._register(editor2.onDidChangeModelContent((e) => {
      this._updateBracketsSoon.schedule();
    }));
    this._register(editor2.onDidChangeModel((e) => {
      this._lastBracketsData = [];
      this._updateBracketsSoon.schedule();
    }));
    this._register(editor2.onDidChangeModelLanguageConfiguration((e) => {
      this._lastBracketsData = [];
      this._updateBracketsSoon.schedule();
    }));
    this._register(editor2.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        70
        /* EditorOption.matchBrackets */
      )) {
        this._matchBrackets = this._editor.getOption(
          70
          /* EditorOption.matchBrackets */
        );
        this._decorations.clear();
        this._lastBracketsData = [];
        this._lastVersionId = 0;
        this._updateBracketsSoon.schedule();
      }
    }));
    this._register(editor2.onDidBlurEditorWidget(() => {
      this._updateBracketsSoon.schedule();
    }));
    this._register(editor2.onDidFocusEditorWidget(() => {
      this._updateBracketsSoon.schedule();
    }));
  }
  jumpToBracket() {
    if (!this._editor.hasModel()) {
      return;
    }
    const model = this._editor.getModel();
    const newSelections = this._editor.getSelections().map((selection) => {
      const position = selection.getStartPosition();
      const brackets = model.bracketPairs.matchBracket(position);
      let newCursorPosition = null;
      if (brackets) {
        if (brackets[0].containsPosition(position) && !brackets[1].containsPosition(position)) {
          newCursorPosition = brackets[1].getStartPosition();
        } else if (brackets[1].containsPosition(position)) {
          newCursorPosition = brackets[0].getStartPosition();
        }
      } else {
        const enclosingBrackets = model.bracketPairs.findEnclosingBrackets(position);
        if (enclosingBrackets) {
          newCursorPosition = enclosingBrackets[1].getStartPosition();
        } else {
          const nextBracket = model.bracketPairs.findNextBracket(position);
          if (nextBracket && nextBracket.range) {
            newCursorPosition = nextBracket.range.getStartPosition();
          }
        }
      }
      if (newCursorPosition) {
        return new Selection$1(newCursorPosition.lineNumber, newCursorPosition.column, newCursorPosition.lineNumber, newCursorPosition.column);
      }
      return new Selection$1(position.lineNumber, position.column, position.lineNumber, position.column);
    });
    this._editor.setSelections(newSelections);
    this._editor.revealRange(newSelections[0]);
  }
  selectToBracket(selectBrackets) {
    if (!this._editor.hasModel()) {
      return;
    }
    const model = this._editor.getModel();
    const newSelections = [];
    this._editor.getSelections().forEach((selection) => {
      const position = selection.getStartPosition();
      let brackets = model.bracketPairs.matchBracket(position);
      if (!brackets) {
        brackets = model.bracketPairs.findEnclosingBrackets(position);
        if (!brackets) {
          const nextBracket = model.bracketPairs.findNextBracket(position);
          if (nextBracket && nextBracket.range) {
            brackets = model.bracketPairs.matchBracket(nextBracket.range.getStartPosition());
          }
        }
      }
      let selectFrom = null;
      let selectTo = null;
      if (brackets) {
        brackets.sort(Range$2.compareRangesUsingStarts);
        const [open, close] = brackets;
        selectFrom = selectBrackets ? open.getStartPosition() : open.getEndPosition();
        selectTo = selectBrackets ? close.getEndPosition() : close.getStartPosition();
        if (close.containsPosition(position)) {
          const tmp = selectFrom;
          selectFrom = selectTo;
          selectTo = tmp;
        }
      }
      if (selectFrom && selectTo) {
        newSelections.push(new Selection$1(selectFrom.lineNumber, selectFrom.column, selectTo.lineNumber, selectTo.column));
      }
    });
    if (newSelections.length > 0) {
      this._editor.setSelections(newSelections);
      this._editor.revealRange(newSelections[0]);
    }
  }
  removeBrackets(editSource) {
    if (!this._editor.hasModel()) {
      return;
    }
    const model = this._editor.getModel();
    this._editor.getSelections().forEach((selection) => {
      const position = selection.getPosition();
      let brackets = model.bracketPairs.matchBracket(position);
      if (!brackets) {
        brackets = model.bracketPairs.findEnclosingBrackets(position);
      }
      if (brackets) {
        this._editor.pushUndoStop();
        this._editor.executeEdits(editSource, [
          { range: brackets[0], text: "" },
          { range: brackets[1], text: "" }
        ]);
        this._editor.pushUndoStop();
      }
    });
  }
  _updateBrackets() {
    if (this._matchBrackets === "never") {
      return;
    }
    this._recomputeBrackets();
    const newDecorations = [];
    let newDecorationsLen = 0;
    for (const bracketData of this._lastBracketsData) {
      const brackets = bracketData.brackets;
      if (brackets) {
        newDecorations[newDecorationsLen++] = { range: brackets[0], options: bracketData.options };
        newDecorations[newDecorationsLen++] = { range: brackets[1], options: bracketData.options };
      }
    }
    this._decorations.set(newDecorations);
  }
  _recomputeBrackets() {
    if (!this._editor.hasModel() || !this._editor.hasWidgetFocus()) {
      this._lastBracketsData = [];
      this._lastVersionId = 0;
      return;
    }
    const selections2 = this._editor.getSelections();
    if (selections2.length > 100) {
      this._lastBracketsData = [];
      this._lastVersionId = 0;
      return;
    }
    const model = this._editor.getModel();
    const versionId = model.getVersionId();
    let previousData = [];
    if (this._lastVersionId === versionId) {
      previousData = this._lastBracketsData;
    }
    const positions = [];
    let positionsLen = 0;
    for (let i = 0, len = selections2.length; i < len; i++) {
      const selection = selections2[i];
      if (selection.isEmpty()) {
        positions[positionsLen++] = selection.getStartPosition();
      }
    }
    if (positions.length > 1) {
      positions.sort(Position$2.compare);
    }
    const newData = [];
    let newDataLen = 0;
    let previousIndex = 0;
    const previousLen = previousData.length;
    for (let i = 0, len = positions.length; i < len; i++) {
      const position = positions[i];
      while (previousIndex < previousLen && previousData[previousIndex].position.isBefore(position)) {
        previousIndex++;
      }
      if (previousIndex < previousLen && previousData[previousIndex].position.equals(position)) {
        newData[newDataLen++] = previousData[previousIndex];
      } else {
        let brackets = model.bracketPairs.matchBracket(
          position,
          20
          /* give at most 20ms to compute */
        );
        let options = BracketMatchingController._DECORATION_OPTIONS_WITH_OVERVIEW_RULER;
        if (!brackets && this._matchBrackets === "always") {
          brackets = model.bracketPairs.findEnclosingBrackets(
            position,
            20
            /* give at most 20ms to compute */
          );
          options = BracketMatchingController._DECORATION_OPTIONS_WITHOUT_OVERVIEW_RULER;
        }
        newData[newDataLen++] = new BracketsData(position, brackets, options);
      }
    }
    this._lastBracketsData = newData;
    this._lastVersionId = versionId;
  }
}
BracketMatchingController.ID = "editor.contrib.bracketMatchingController";
BracketMatchingController._DECORATION_OPTIONS_WITH_OVERVIEW_RULER = ModelDecorationOptions.register({
  description: "bracket-match-overview",
  stickiness: 1,
  className: "bracket-match",
  overviewRuler: {
    color: themeColorFromId(overviewRulerBracketMatchForeground),
    position: OverviewRulerLane$1.Center
  }
});
BracketMatchingController._DECORATION_OPTIONS_WITHOUT_OVERVIEW_RULER = ModelDecorationOptions.register({
  description: "bracket-match-no-overview",
  stickiness: 1,
  className: "bracket-match"
});
registerEditorContribution(
  BracketMatchingController.ID,
  BracketMatchingController,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
registerEditorAction(SelectToBracketAction);
registerEditorAction(JumpToBracketAction);
registerEditorAction(RemoveBracketsAction);
MenuRegistry.appendMenuItem(MenuId.MenubarGoMenu, {
  group: "5_infile_nav",
  command: {
    id: "editor.action.jumpToBracket",
    title: localize({ key: "miGoToBracket", comment: ["&& denotes a mnemonic"] }, "Go to &&Bracket")
  },
  order: 2
});
class MoveCaretCommand {
  constructor(selection, isMovingLeft) {
    this._selection = selection;
    this._isMovingLeft = isMovingLeft;
  }
  getEditOperations(model, builder) {
    if (this._selection.startLineNumber !== this._selection.endLineNumber || this._selection.isEmpty()) {
      return;
    }
    const lineNumber = this._selection.startLineNumber;
    const startColumn = this._selection.startColumn;
    const endColumn = this._selection.endColumn;
    if (this._isMovingLeft && startColumn === 1) {
      return;
    }
    if (!this._isMovingLeft && endColumn === model.getLineMaxColumn(lineNumber)) {
      return;
    }
    if (this._isMovingLeft) {
      const rangeBefore = new Range$2(lineNumber, startColumn - 1, lineNumber, startColumn);
      const charBefore = model.getValueInRange(rangeBefore);
      builder.addEditOperation(rangeBefore, null);
      builder.addEditOperation(new Range$2(lineNumber, endColumn, lineNumber, endColumn), charBefore);
    } else {
      const rangeAfter = new Range$2(lineNumber, endColumn, lineNumber, endColumn + 1);
      const charAfter = model.getValueInRange(rangeAfter);
      builder.addEditOperation(rangeAfter, null);
      builder.addEditOperation(new Range$2(lineNumber, startColumn, lineNumber, startColumn), charAfter);
    }
  }
  computeCursorState(model, helper) {
    if (this._isMovingLeft) {
      return new Selection$1(this._selection.startLineNumber, this._selection.startColumn - 1, this._selection.endLineNumber, this._selection.endColumn - 1);
    } else {
      return new Selection$1(this._selection.startLineNumber, this._selection.startColumn + 1, this._selection.endLineNumber, this._selection.endColumn + 1);
    }
  }
}
class MoveCaretAction extends EditorAction {
  constructor(left, opts) {
    super(opts);
    this.left = left;
  }
  run(accessor, editor2) {
    if (!editor2.hasModel()) {
      return;
    }
    const commands = [];
    const selections2 = editor2.getSelections();
    for (const selection of selections2) {
      commands.push(new MoveCaretCommand(selection, this.left));
    }
    editor2.pushUndoStop();
    editor2.executeCommands(this.id, commands);
    editor2.pushUndoStop();
  }
}
class MoveCaretLeftAction extends MoveCaretAction {
  constructor() {
    super(true, {
      id: "editor.action.moveCarretLeftAction",
      label: localize("caret.moveLeft", "Move Selected Text Left"),
      alias: "Move Selected Text Left",
      precondition: EditorContextKeys.writable
    });
  }
}
class MoveCaretRightAction extends MoveCaretAction {
  constructor() {
    super(false, {
      id: "editor.action.moveCarretRightAction",
      label: localize("caret.moveRight", "Move Selected Text Right"),
      alias: "Move Selected Text Right",
      precondition: EditorContextKeys.writable
    });
  }
}
registerEditorAction(MoveCaretLeftAction);
registerEditorAction(MoveCaretRightAction);
class TransposeLettersAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.transposeLetters",
      label: localize("transposeLetters.label", "Transpose Letters"),
      alias: "Transpose Letters",
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 0,
        mac: {
          primary: 256 | 50
          /* KeyCode.KeyT */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor2) {
    if (!editor2.hasModel()) {
      return;
    }
    const model = editor2.getModel();
    const commands = [];
    const selections2 = editor2.getSelections();
    for (const selection of selections2) {
      if (!selection.isEmpty()) {
        continue;
      }
      const lineNumber = selection.startLineNumber;
      const column = selection.startColumn;
      const lastColumn = model.getLineMaxColumn(lineNumber);
      if (lineNumber === 1 && (column === 1 || column === 2 && lastColumn === 2)) {
        continue;
      }
      const endPosition = column === lastColumn ? selection.getPosition() : MoveOperations.rightPosition(model, selection.getPosition().lineNumber, selection.getPosition().column);
      const middlePosition = MoveOperations.leftPosition(model, endPosition);
      const beginPosition = MoveOperations.leftPosition(model, middlePosition);
      const leftChar = model.getValueInRange(Range$2.fromPositions(beginPosition, middlePosition));
      const rightChar = model.getValueInRange(Range$2.fromPositions(middlePosition, endPosition));
      const replaceRange = Range$2.fromPositions(beginPosition, endPosition);
      commands.push(new ReplaceCommand(replaceRange, rightChar + leftChar));
    }
    if (commands.length > 0) {
      editor2.pushUndoStop();
      editor2.executeCommands(this.id, commands);
      editor2.pushUndoStop();
    }
  }
}
registerEditorAction(TransposeLettersAction);
var __awaiter$1n = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
const CLIPBOARD_CONTEXT_MENU_GROUP = "9_cutcopypaste";
const supportsCut = isNative || document.queryCommandSupported("cut");
const supportsCopy = isNative || document.queryCommandSupported("copy");
const supportsPaste = typeof navigator.clipboard === "undefined" || isFirefox$1 ? document.queryCommandSupported("paste") : true;
function registerCommand$1(command) {
  command.register();
  return command;
}
const CutAction = supportsCut ? registerCommand$1(new MultiCommand({
  id: "editor.action.clipboardCutAction",
  precondition: void 0,
  kbOpts: (
    // Do not bind cut keybindings in the browser,
    // since browsers do that for us and it avoids security prompts
    isNative ? {
      primary: 2048 | 54,
      win: { primary: 2048 | 54, secondary: [
        1024 | 20
        /* KeyCode.Delete */
      ] },
      weight: 100
      /* KeybindingWeight.EditorContrib */
    } : void 0
  ),
  menuOpts: [{
    menuId: MenuId.MenubarEditMenu,
    group: "2_ccp",
    title: localize({ key: "miCut", comment: ["&& denotes a mnemonic"] }, "Cu&&t"),
    order: 1
  }, {
    menuId: MenuId.EditorContext,
    group: CLIPBOARD_CONTEXT_MENU_GROUP,
    title: localize("actions.clipboard.cutLabel", "Cut"),
    when: EditorContextKeys.writable,
    order: 1
  }, {
    menuId: MenuId.CommandPalette,
    group: "",
    title: localize("actions.clipboard.cutLabel", "Cut"),
    order: 1
  }, {
    menuId: MenuId.SimpleEditorContext,
    group: CLIPBOARD_CONTEXT_MENU_GROUP,
    title: localize("actions.clipboard.cutLabel", "Cut"),
    when: EditorContextKeys.writable,
    order: 1
  }]
})) : void 0;
const CopyAction = supportsCopy ? registerCommand$1(new MultiCommand({
  id: "editor.action.clipboardCopyAction",
  precondition: void 0,
  kbOpts: (
    // Do not bind copy keybindings in the browser,
    // since browsers do that for us and it avoids security prompts
    isNative ? {
      primary: 2048 | 33,
      win: { primary: 2048 | 33, secondary: [
        2048 | 19
        /* KeyCode.Insert */
      ] },
      weight: 100
      /* KeybindingWeight.EditorContrib */
    } : void 0
  ),
  menuOpts: [{
    menuId: MenuId.MenubarEditMenu,
    group: "2_ccp",
    title: localize({ key: "miCopy", comment: ["&& denotes a mnemonic"] }, "&&Copy"),
    order: 2
  }, {
    menuId: MenuId.EditorContext,
    group: CLIPBOARD_CONTEXT_MENU_GROUP,
    title: localize("actions.clipboard.copyLabel", "Copy"),
    order: 2
  }, {
    menuId: MenuId.CommandPalette,
    group: "",
    title: localize("actions.clipboard.copyLabel", "Copy"),
    order: 1
  }, {
    menuId: MenuId.SimpleEditorContext,
    group: CLIPBOARD_CONTEXT_MENU_GROUP,
    title: localize("actions.clipboard.copyLabel", "Copy"),
    order: 2
  }]
})) : void 0;
MenuRegistry.appendMenuItem(MenuId.MenubarEditMenu, { submenu: MenuId.MenubarCopy, title: { value: localize("copy as", "Copy As"), original: "Copy As" }, group: "2_ccp", order: 3 });
MenuRegistry.appendMenuItem(MenuId.EditorContext, { submenu: MenuId.EditorContextCopy, title: { value: localize("copy as", "Copy As"), original: "Copy As" }, group: CLIPBOARD_CONTEXT_MENU_GROUP, order: 3 });
MenuRegistry.appendMenuItem(MenuId.EditorContext, { submenu: MenuId.EditorContextShare, title: { value: localize("share", "Share"), original: "Share" }, group: "11_share", order: -1, when: ContextKeyExpr.and(ContextKeyExpr.notEquals("resourceScheme", "output"), EditorContextKeys.editorTextFocus) });
MenuRegistry.appendMenuItem(MenuId.EditorTitleContext, { submenu: MenuId.EditorTitleContextShare, title: { value: localize("share", "Share"), original: "Share" }, group: "11_share", order: -1 });
MenuRegistry.appendMenuItem(MenuId.ExplorerContext, { submenu: MenuId.ExplorerContextShare, title: { value: localize("share", "Share"), original: "Share" }, group: "11_share", order: -1 });
const PasteAction = supportsPaste ? registerCommand$1(new MultiCommand({
  id: "editor.action.clipboardPasteAction",
  precondition: void 0,
  kbOpts: (
    // Do not bind paste keybindings in the browser,
    // since browsers do that for us and it avoids security prompts
    isNative ? {
      primary: 2048 | 52,
      win: { primary: 2048 | 52, secondary: [
        1024 | 19
        /* KeyCode.Insert */
      ] },
      linux: { primary: 2048 | 52, secondary: [
        1024 | 19
        /* KeyCode.Insert */
      ] },
      weight: 100
      /* KeybindingWeight.EditorContrib */
    } : void 0
  ),
  menuOpts: [{
    menuId: MenuId.MenubarEditMenu,
    group: "2_ccp",
    title: localize({ key: "miPaste", comment: ["&& denotes a mnemonic"] }, "&&Paste"),
    order: 4
  }, {
    menuId: MenuId.EditorContext,
    group: CLIPBOARD_CONTEXT_MENU_GROUP,
    title: localize("actions.clipboard.pasteLabel", "Paste"),
    when: EditorContextKeys.writable,
    order: 4
  }, {
    menuId: MenuId.CommandPalette,
    group: "",
    title: localize("actions.clipboard.pasteLabel", "Paste"),
    order: 1
  }, {
    menuId: MenuId.SimpleEditorContext,
    group: CLIPBOARD_CONTEXT_MENU_GROUP,
    title: localize("actions.clipboard.pasteLabel", "Paste"),
    when: EditorContextKeys.writable,
    order: 4
  }]
})) : void 0;
class ExecCommandCopyWithSyntaxHighlightingAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.clipboardCopyWithSyntaxHighlightingAction",
      label: localize("actions.clipboard.copyWithSyntaxHighlightingLabel", "Copy With Syntax Highlighting"),
      alias: "Copy With Syntax Highlighting",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 0,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor2) {
    if (!editor2.hasModel()) {
      return;
    }
    const emptySelectionClipboard = editor2.getOption(
      36
      /* EditorOption.emptySelectionClipboard */
    );
    if (!emptySelectionClipboard && editor2.getSelection().isEmpty()) {
      return;
    }
    CopyOptions.forceCopyWithSyntaxHighlighting = true;
    editor2.focus();
    document.execCommand("copy");
    CopyOptions.forceCopyWithSyntaxHighlighting = false;
  }
}
function registerExecCommandImpl(target, browserCommand) {
  if (!target) {
    return;
  }
  target.addImplementation(1e4, "code-editor", (accessor, args) => {
    const focusedEditor = accessor.get(ICodeEditorService).getFocusedCodeEditor();
    if (focusedEditor && focusedEditor.hasTextFocus()) {
      const emptySelectionClipboard = focusedEditor.getOption(
        36
        /* EditorOption.emptySelectionClipboard */
      );
      const selection = focusedEditor.getSelection();
      if (selection && selection.isEmpty() && !emptySelectionClipboard) {
        return true;
      }
      document.execCommand(browserCommand);
      return true;
    }
    return false;
  });
  target.addImplementation(0, "generic-dom", (accessor, args) => {
    document.execCommand(browserCommand);
    return true;
  });
}
registerExecCommandImpl(CutAction, "cut");
registerExecCommandImpl(CopyAction, "copy");
if (PasteAction) {
  PasteAction.addImplementation(1e4, "code-editor", (accessor, args) => {
    const codeEditorService = accessor.get(ICodeEditorService);
    const clipboardService = accessor.get(IClipboardService);
    const focusedEditor = codeEditorService.getFocusedCodeEditor();
    if (focusedEditor && focusedEditor.hasTextFocus()) {
      const result2 = document.execCommand("paste");
      if (!result2 && isWeb) {
        return (() => __awaiter$1n(void 0, void 0, void 0, function* () {
          const clipboardText = yield clipboardService.readText();
          if (clipboardText !== "") {
            const metadata = InMemoryClipboardMetadataManager.INSTANCE.get(clipboardText);
            let pasteOnNewLine = false;
            let multicursorText = null;
            let mode = null;
            if (metadata) {
              pasteOnNewLine = focusedEditor.getOption(
                36
                /* EditorOption.emptySelectionClipboard */
              ) && !!metadata.isFromEmptySelection;
              multicursorText = typeof metadata.multicursorText !== "undefined" ? metadata.multicursorText : null;
              mode = metadata.mode;
            }
            focusedEditor.trigger("keyboard", "paste", {
              text: clipboardText,
              pasteOnNewLine,
              multicursorText,
              mode
            });
          }
        }))();
      }
      return true;
    }
    return false;
  });
  PasteAction.addImplementation(0, "generic-dom", (accessor, args) => {
    document.execCommand("paste");
    return true;
  });
}
if (supportsCopy) {
  registerEditorAction(ExecCommandCopyWithSyntaxHighlightingAction);
}
const editorConfigurationBaseNode = Object.freeze({
  id: "editor",
  order: 5,
  type: "object",
  title: localize("editorConfigurationTitle", "Editor"),
  scope: 5
});
const editorConfiguration = Object.assign(Object.assign({}, editorConfigurationBaseNode), { properties: {
  "editor.tabSize": {
    type: "number",
    default: EDITOR_MODEL_DEFAULTS.tabSize,
    minimum: 1,
    markdownDescription: localize("tabSize", "The number of spaces a tab is equal to. This setting is overridden based on the file contents when {0} is on.", "`#editor.detectIndentation#`")
  },
  "editor.indentSize": {
    "anyOf": [
      {
        type: "string",
        enum: ["tabSize"]
      },
      {
        type: "number",
        minimum: 1
      }
    ],
    default: "tabSize",
    markdownDescription: localize("indentSize", 'The number of spaces used for indentation or `"tabSize"` to use the value from `#editor.tabSize#`. This setting is overridden based on the file contents when `#editor.detectIndentation#` is on.')
  },
  "editor.insertSpaces": {
    type: "boolean",
    default: EDITOR_MODEL_DEFAULTS.insertSpaces,
    markdownDescription: localize("insertSpaces", "Insert spaces when pressing `Tab`. This setting is overridden based on the file contents when {0} is on.", "`#editor.detectIndentation#`")
  },
  "editor.detectIndentation": {
    type: "boolean",
    default: EDITOR_MODEL_DEFAULTS.detectIndentation,
    markdownDescription: localize("detectIndentation", "Controls whether {0} and {1} will be automatically detected when a file is opened based on the file contents.", "`#editor.tabSize#`", "`#editor.insertSpaces#`")
  },
  "editor.trimAutoWhitespace": {
    type: "boolean",
    default: EDITOR_MODEL_DEFAULTS.trimAutoWhitespace,
    description: localize("trimAutoWhitespace", "Remove trailing auto inserted whitespace.")
  },
  "editor.largeFileOptimizations": {
    type: "boolean",
    default: EDITOR_MODEL_DEFAULTS.largeFileOptimizations,
    description: localize("largeFileOptimizations", "Special handling for large files to disable certain memory intensive features.")
  },
  "editor.wordBasedSuggestions": {
    type: "boolean",
    default: true,
    description: localize("wordBasedSuggestions", "Controls whether completions should be computed based on words in the document.")
  },
  "editor.wordBasedSuggestionsMode": {
    enum: ["currentDocument", "matchingDocuments", "allDocuments"],
    default: "matchingDocuments",
    enumDescriptions: [
      localize("wordBasedSuggestionsMode.currentDocument", "Only suggest words from the active document."),
      localize("wordBasedSuggestionsMode.matchingDocuments", "Suggest words from all open documents of the same language."),
      localize("wordBasedSuggestionsMode.allDocuments", "Suggest words from all open documents.")
    ],
    description: localize("wordBasedSuggestionsMode", "Controls from which documents word based completions are computed.")
  },
  "editor.semanticHighlighting.enabled": {
    enum: [true, false, "configuredByTheme"],
    enumDescriptions: [
      localize("semanticHighlighting.true", "Semantic highlighting enabled for all color themes."),
      localize("semanticHighlighting.false", "Semantic highlighting disabled for all color themes."),
      localize("semanticHighlighting.configuredByTheme", "Semantic highlighting is configured by the current color theme's `semanticHighlighting` setting.")
    ],
    default: "configuredByTheme",
    description: localize("semanticHighlighting.enabled", "Controls whether the semanticHighlighting is shown for the languages that support it.")
  },
  "editor.stablePeek": {
    type: "boolean",
    default: false,
    markdownDescription: localize("stablePeek", "Keep peek editors open even when double-clicking their content or when hitting `Escape`.")
  },
  "editor.maxTokenizationLineLength": {
    type: "integer",
    default: 2e4,
    description: localize("maxTokenizationLineLength", "Lines above this length will not be tokenized for performance reasons")
  },
  "editor.experimental.asyncTokenization": {
    type: "boolean",
    default: false,
    description: localize("editor.experimental.asyncTokenization", "Controls whether the tokenization should happen asynchronously on a web worker."),
    tags: ["experimental"]
  },
  "editor.experimental.asyncTokenizationLogging": {
    type: "boolean",
    default: false,
    description: localize("editor.experimental.asyncTokenizationLogging", "Controls whether async tokenization should be logged. For debugging only.")
  },
  "editor.experimental.asyncTokenizationVerification": {
    type: "boolean",
    default: false,
    description: localize("editor.experimental.asyncTokenizationVerification", "Controls whether async tokenization should be verified against legacy background tokenization. Might slow down tokenization. For debugging only.")
  },
  "editor.language.brackets": {
    type: ["array", "null"],
    default: null,
    description: localize("schema.brackets", "Defines the bracket symbols that increase or decrease the indentation."),
    items: {
      type: "array",
      items: [
        {
          type: "string",
          description: localize("schema.openBracket", "The opening bracket character or string sequence.")
        },
        {
          type: "string",
          description: localize("schema.closeBracket", "The closing bracket character or string sequence.")
        }
      ]
    }
  },
  "editor.language.colorizedBracketPairs": {
    type: ["array", "null"],
    default: null,
    description: localize("schema.colorizedBracketPairs", "Defines the bracket pairs that are colorized by their nesting level if bracket pair colorization is enabled."),
    items: {
      type: "array",
      items: [
        {
          type: "string",
          description: localize("schema.openBracket", "The opening bracket character or string sequence.")
        },
        {
          type: "string",
          description: localize("schema.closeBracket", "The closing bracket character or string sequence.")
        }
      ]
    }
  },
  "diffEditor.maxComputationTime": {
    type: "number",
    default: 5e3,
    description: localize("maxComputationTime", "Timeout in milliseconds after which diff computation is cancelled. Use 0 for no timeout.")
  },
  "diffEditor.maxFileSize": {
    type: "number",
    default: 50,
    description: localize("maxFileSize", "Maximum file size in MB for which to compute diffs. Use 0 for no limit.")
  },
  "diffEditor.renderSideBySide": {
    type: "boolean",
    default: true,
    description: localize("sideBySide", "Controls whether the diff editor shows the diff side by side or inline.")
  },
  "diffEditor.renderMarginRevertIcon": {
    type: "boolean",
    default: true,
    description: localize("renderMarginRevertIcon", "When enabled, the diff editor shows arrows in its glyph margin to revert changes.")
  },
  "diffEditor.ignoreTrimWhitespace": {
    type: "boolean",
    default: true,
    description: localize("ignoreTrimWhitespace", "When enabled, the diff editor ignores changes in leading or trailing whitespace.")
  },
  "diffEditor.renderIndicators": {
    type: "boolean",
    default: true,
    description: localize("renderIndicators", "Controls whether the diff editor shows +/- indicators for added/removed changes.")
  },
  "diffEditor.codeLens": {
    type: "boolean",
    default: false,
    description: localize("codeLens", "Controls whether the editor shows CodeLens.")
  },
  "diffEditor.wordWrap": {
    type: "string",
    enum: ["off", "on", "inherit"],
    default: "inherit",
    markdownEnumDescriptions: [
      localize("wordWrap.off", "Lines will never wrap."),
      localize("wordWrap.on", "Lines will wrap at the viewport width."),
      localize("wordWrap.inherit", "Lines will wrap according to the {0} setting.", "`#editor.wordWrap#`")
    ]
  },
  "diffEditor.diffAlgorithm": {
    type: "string",
    enum: ["legacy", "advanced"],
    default: "advanced",
    markdownEnumDescriptions: [
      localize("diffAlgorithm.legacy", "Uses the legacy diffing algorithm."),
      localize("diffAlgorithm.advanced", "Uses the advanced diffing algorithm.")
    ],
    tags: ["experimental"]
  },
  "diffEditor.experimental.collapseUnchangedRegions": {
    type: "boolean",
    default: false,
    markdownDescription: localize("collapseUnchangedRegions", "Controls whether the diff editor shows unchanged regions. Only works when {0} is set.", "`#diffEditor.experimental.useVersion2#`")
  },
  "diffEditor.experimental.showMoves": {
    type: "boolean",
    default: false,
    markdownDescription: localize("showMoves", "Controls whether the diff editor should show detected code moves. Only works when {0} is set.", "`#diffEditor.experimental.useVersion2#`")
  },
  "diffEditor.experimental.useVersion2": {
    type: "boolean",
    default: false,
    description: localize("useVersion2", "Controls whether the diff editor uses the new or the old implementation."),
    tags: ["experimental"]
  },
  "diffEditor.experimental.showEmptyDecorations": {
    type: "boolean",
    default: true,
    description: localize("showEmptyDecorations", "Controls whether the diff editor shows empty decorations to see where characters got inserted or deleted.")
  }
} });
function isConfigurationPropertySchema(x) {
  return typeof x.type !== "undefined" || typeof x.anyOf !== "undefined";
}
for (const editorOption of editorOptionsRegistry) {
  const schema = editorOption.schema;
  if (typeof schema !== "undefined") {
    if (isConfigurationPropertySchema(schema)) {
      editorConfiguration.properties[`editor.${editorOption.name}`] = schema;
    } else {
      for (const key in schema) {
        if (Object.hasOwnProperty.call(schema, key)) {
          editorConfiguration.properties[key] = schema[key];
        }
      }
    }
  }
}
let cachedEditorConfigurationKeys = null;
function getEditorConfigurationKeys() {
  if (cachedEditorConfigurationKeys === null) {
    cachedEditorConfigurationKeys = /* @__PURE__ */ Object.create(null);
    Object.keys(editorConfiguration.properties).forEach((prop) => {
      cachedEditorConfigurationKeys[prop] = true;
    });
  }
  return cachedEditorConfigurationKeys;
}
function isEditorConfigurationKey(key) {
  const editorConfigurationKeys = getEditorConfigurationKeys();
  return editorConfigurationKeys[`editor.${key}`] || false;
}
function isDiffEditorConfigurationKey(key) {
  const editorConfigurationKeys = getEditorConfigurationKeys();
  return editorConfigurationKeys[`diffEditor.${key}`] || false;
}
const configurationRegistry$1 = Registry.as(Extensions$6.Configuration);
configurationRegistry$1.registerConfiguration(editorConfiguration);
const IBulkEditService = createDecorator("IWorkspaceEditService");
class ResourceEdit {
  constructor(metadata) {
    this.metadata = metadata;
  }
  static convert(edit) {
    return edit.edits.map((edit2) => {
      if (ResourceTextEdit.is(edit2)) {
        return ResourceTextEdit.lift(edit2);
      }
      if (ResourceFileEdit.is(edit2)) {
        return ResourceFileEdit.lift(edit2);
      }
      throw new Error("Unsupported edit");
    });
  }
}
class ResourceTextEdit extends ResourceEdit {
  static is(candidate) {
    if (candidate instanceof ResourceTextEdit) {
      return true;
    }
    return isObject$4(candidate) && URI.isUri(candidate.resource) && isObject$4(candidate.textEdit);
  }
  static lift(edit) {
    if (edit instanceof ResourceTextEdit) {
      return edit;
    } else {
      return new ResourceTextEdit(edit.resource, edit.textEdit, edit.versionId, edit.metadata);
    }
  }
  constructor(resource, textEdit, versionId = void 0, metadata) {
    super(metadata);
    this.resource = resource;
    this.textEdit = textEdit;
    this.versionId = versionId;
  }
}
class ResourceFileEdit extends ResourceEdit {
  static is(candidate) {
    if (candidate instanceof ResourceFileEdit) {
      return true;
    } else {
      return isObject$4(candidate) && (Boolean(candidate.newResource) || Boolean(candidate.oldResource));
    }
  }
  static lift(edit) {
    if (edit instanceof ResourceFileEdit) {
      return edit;
    } else {
      return new ResourceFileEdit(edit.oldResource, edit.newResource, edit.options, edit.metadata);
    }
  }
  constructor(oldResource, newResource, options = {}, metadata) {
    super(metadata);
    this.oldResource = oldResource;
    this.newResource = newResource;
    this.options = options;
  }
}
const IEditorCancellationTokens = createDecorator("IEditorCancelService");
const ctxCancellableOperation = new RawContextKey("cancellableOperation", false, localize("cancellableOperation", "Whether the editor runs a cancellable operation, e.g. like 'Peek References'"));
registerSingleton(
  IEditorCancellationTokens,
  class {
    constructor() {
      this._tokens = /* @__PURE__ */ new WeakMap();
    }
    add(editor2, cts) {
      let data = this._tokens.get(editor2);
      if (!data) {
        data = editor2.invokeWithinContext((accessor) => {
          const key = ctxCancellableOperation.bindTo(accessor.get(IContextKeyService));
          const tokens = new LinkedList();
          return { key, tokens };
        });
        this._tokens.set(editor2, data);
      }
      let removeFn;
      data.key.set(true);
      removeFn = data.tokens.push(cts);
      return () => {
        if (removeFn) {
          removeFn();
          data.key.set(!data.tokens.isEmpty());
          removeFn = void 0;
        }
      };
    }
    cancel(editor2) {
      const data = this._tokens.get(editor2);
      if (!data) {
        return;
      }
      const cts = data.tokens.pop();
      if (cts) {
        cts.cancel();
        data.key.set(!data.tokens.isEmpty());
      }
    }
  },
  1
  /* InstantiationType.Delayed */
);
class EditorKeybindingCancellationTokenSource extends CancellationTokenSource$1 {
  constructor(editor2, parent) {
    super(parent);
    this.editor = editor2;
    this._unregister = editor2.invokeWithinContext((accessor) => accessor.get(IEditorCancellationTokens).add(editor2, this));
  }
  dispose() {
    this._unregister();
    super.dispose();
  }
}
registerEditorCommand(new class extends EditorCommand {
  constructor() {
    super({
      id: "editor.cancelOperation",
      kbOpts: {
        weight: 100,
        primary: 9
        /* KeyCode.Escape */
      },
      precondition: ctxCancellableOperation
    });
  }
  runEditorCommand(accessor, editor2) {
    accessor.get(IEditorCancellationTokens).cancel(editor2);
  }
}());
let EditorState$1 = class EditorState {
  constructor(editor2, flags) {
    this.flags = flags;
    if ((this.flags & 1) !== 0) {
      const model = editor2.getModel();
      this.modelVersionId = model ? format$2("{0}#{1}", model.uri.toString(), model.getVersionId()) : null;
    } else {
      this.modelVersionId = null;
    }
    if ((this.flags & 4) !== 0) {
      this.position = editor2.getPosition();
    } else {
      this.position = null;
    }
    if ((this.flags & 2) !== 0) {
      this.selection = editor2.getSelection();
    } else {
      this.selection = null;
    }
    if ((this.flags & 8) !== 0) {
      this.scrollLeft = editor2.getScrollLeft();
      this.scrollTop = editor2.getScrollTop();
    } else {
      this.scrollLeft = -1;
      this.scrollTop = -1;
    }
  }
  _equals(other) {
    if (!(other instanceof EditorState)) {
      return false;
    }
    const state = other;
    if (this.modelVersionId !== state.modelVersionId) {
      return false;
    }
    if (this.scrollLeft !== state.scrollLeft || this.scrollTop !== state.scrollTop) {
      return false;
    }
    if (!this.position && state.position || this.position && !state.position || this.position && state.position && !this.position.equals(state.position)) {
      return false;
    }
    if (!this.selection && state.selection || this.selection && !state.selection || this.selection && state.selection && !this.selection.equalsRange(state.selection)) {
      return false;
    }
    return true;
  }
  validate(editor2) {
    return this._equals(new EditorState(editor2, this.flags));
  }
};
class EditorStateCancellationTokenSource extends EditorKeybindingCancellationTokenSource {
  constructor(editor2, flags, range2, parent) {
    super(editor2, parent);
    this._listener = new DisposableStore();
    if (flags & 4) {
      this._listener.add(editor2.onDidChangeCursorPosition((e) => {
        if (!range2 || !Range$2.containsPosition(range2, e.position)) {
          this.cancel();
        }
      }));
    }
    if (flags & 2) {
      this._listener.add(editor2.onDidChangeCursorSelection((e) => {
        if (!range2 || !Range$2.containsRange(range2, e.selection)) {
          this.cancel();
        }
      }));
    }
    if (flags & 8) {
      this._listener.add(editor2.onDidScrollChange((_) => this.cancel()));
    }
    if (flags & 1) {
      this._listener.add(editor2.onDidChangeModel((_) => this.cancel()));
      this._listener.add(editor2.onDidChangeModelContent((_) => this.cancel()));
    }
  }
  dispose() {
    this._listener.dispose();
    super.dispose();
  }
}
class TextModelCancellationTokenSource extends CancellationTokenSource$1 {
  constructor(model, parent) {
    super(parent);
    this._listener = model.onDidChangeContent(() => this.cancel());
  }
  dispose() {
    this._listener.dispose();
    super.dispose();
  }
}
var __awaiter$1m = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class CodeActionKind {
  constructor(value) {
    this.value = value;
  }
  equals(other) {
    return this.value === other.value;
  }
  contains(other) {
    return this.equals(other) || this.value === "" || other.value.startsWith(this.value + CodeActionKind.sep);
  }
  intersects(other) {
    return this.contains(other) || other.contains(this);
  }
  append(part) {
    return new CodeActionKind(this.value + CodeActionKind.sep + part);
  }
}
CodeActionKind.sep = ".";
CodeActionKind.None = new CodeActionKind("@@none@@");
CodeActionKind.Empty = new CodeActionKind("");
CodeActionKind.QuickFix = new CodeActionKind("quickfix");
CodeActionKind.Refactor = new CodeActionKind("refactor");
CodeActionKind.RefactorExtract = CodeActionKind.Refactor.append("extract");
CodeActionKind.RefactorInline = CodeActionKind.Refactor.append("inline");
CodeActionKind.RefactorMove = CodeActionKind.Refactor.append("move");
CodeActionKind.RefactorRewrite = CodeActionKind.Refactor.append("rewrite");
CodeActionKind.Source = new CodeActionKind("source");
CodeActionKind.SourceOrganizeImports = CodeActionKind.Source.append("organizeImports");
CodeActionKind.SourceFixAll = CodeActionKind.Source.append("fixAll");
CodeActionKind.SurroundWith = CodeActionKind.Refactor.append("surround");
var CodeActionTriggerSource;
(function(CodeActionTriggerSource2) {
  CodeActionTriggerSource2["Refactor"] = "refactor";
  CodeActionTriggerSource2["RefactorPreview"] = "refactor preview";
  CodeActionTriggerSource2["Lightbulb"] = "lightbulb";
  CodeActionTriggerSource2["Default"] = "other (default)";
  CodeActionTriggerSource2["SourceAction"] = "source action";
  CodeActionTriggerSource2["QuickFix"] = "quick fix action";
  CodeActionTriggerSource2["FixAll"] = "fix all";
  CodeActionTriggerSource2["OrganizeImports"] = "organize imports";
  CodeActionTriggerSource2["AutoFix"] = "auto fix";
  CodeActionTriggerSource2["QuickFixHover"] = "quick fix hover window";
  CodeActionTriggerSource2["OnSave"] = "save participants";
  CodeActionTriggerSource2["ProblemsView"] = "problems view";
})(CodeActionTriggerSource || (CodeActionTriggerSource = {}));
function mayIncludeActionsOfKind(filter2, providedKind) {
  if (filter2.include && !filter2.include.intersects(providedKind)) {
    return false;
  }
  if (filter2.excludes) {
    if (filter2.excludes.some((exclude) => excludesAction(providedKind, exclude, filter2.include))) {
      return false;
    }
  }
  if (!filter2.includeSourceActions && CodeActionKind.Source.contains(providedKind)) {
    return false;
  }
  return true;
}
function filtersAction(filter2, action) {
  const actionKind = action.kind ? new CodeActionKind(action.kind) : void 0;
  if (filter2.include) {
    if (!actionKind || !filter2.include.contains(actionKind)) {
      return false;
    }
  }
  if (filter2.excludes) {
    if (actionKind && filter2.excludes.some((exclude) => excludesAction(actionKind, exclude, filter2.include))) {
      return false;
    }
  }
  if (!filter2.includeSourceActions) {
    if (actionKind && CodeActionKind.Source.contains(actionKind)) {
      return false;
    }
  }
  if (filter2.onlyIncludePreferredActions) {
    if (!action.isPreferred) {
      return false;
    }
  }
  return true;
}
function excludesAction(providedKind, exclude, include) {
  if (!exclude.contains(providedKind)) {
    return false;
  }
  if (include && exclude.contains(include)) {
    return false;
  }
  return true;
}
class CodeActionCommandArgs {
  static fromUser(arg, defaults) {
    if (!arg || typeof arg !== "object") {
      return new CodeActionCommandArgs(defaults.kind, defaults.apply, false);
    }
    return new CodeActionCommandArgs(CodeActionCommandArgs.getKindFromUser(arg, defaults.kind), CodeActionCommandArgs.getApplyFromUser(arg, defaults.apply), CodeActionCommandArgs.getPreferredUser(arg));
  }
  static getApplyFromUser(arg, defaultAutoApply) {
    switch (typeof arg.apply === "string" ? arg.apply.toLowerCase() : "") {
      case "first":
        return "first";
      case "never":
        return "never";
      case "ifsingle":
        return "ifSingle";
      default:
        return defaultAutoApply;
    }
  }
  static getKindFromUser(arg, defaultKind) {
    return typeof arg.kind === "string" ? new CodeActionKind(arg.kind) : defaultKind;
  }
  static getPreferredUser(arg) {
    return typeof arg.preferred === "boolean" ? arg.preferred : false;
  }
  constructor(kind, apply2, preferred) {
    this.kind = kind;
    this.apply = apply2;
    this.preferred = preferred;
  }
}
class CodeActionItem {
  constructor(action, provider) {
    this.action = action;
    this.provider = provider;
  }
  resolve(token) {
    var _a2;
    return __awaiter$1m(this, void 0, void 0, function* () {
      if (((_a2 = this.provider) === null || _a2 === void 0 ? void 0 : _a2.resolveCodeAction) && !this.action.edit) {
        let action;
        try {
          action = yield this.provider.resolveCodeAction(this.action, token);
        } catch (err) {
          onUnexpectedExternalError(err);
        }
        if (action) {
          this.action.edit = action.edit;
        }
      }
      return this;
    });
  }
}
var __awaiter$1l = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
const codeActionCommandId = "editor.action.codeAction";
const quickFixCommandId = "editor.action.quickFix";
const autoFixCommandId = "editor.action.autoFix";
const refactorCommandId = "editor.action.refactor";
const sourceActionCommandId = "editor.action.sourceAction";
const organizeImportsCommandId = "editor.action.organizeImports";
const fixAllCommandId = "editor.action.fixAll";
class ManagedCodeActionSet extends Disposable {
  static codeActionsPreferredComparator(a, b) {
    if (a.isPreferred && !b.isPreferred) {
      return -1;
    } else if (!a.isPreferred && b.isPreferred) {
      return 1;
    } else {
      return 0;
    }
  }
  static codeActionsComparator({ action: a }, { action: b }) {
    if (isNonEmptyArray(a.diagnostics)) {
      return isNonEmptyArray(b.diagnostics) ? ManagedCodeActionSet.codeActionsPreferredComparator(a, b) : -1;
    } else if (isNonEmptyArray(b.diagnostics)) {
      return 1;
    } else {
      return ManagedCodeActionSet.codeActionsPreferredComparator(a, b);
    }
  }
  constructor(actions, documentation, disposables) {
    super();
    this.documentation = documentation;
    this._register(disposables);
    this.allActions = [...actions].sort(ManagedCodeActionSet.codeActionsComparator);
    this.validActions = this.allActions.filter(({ action }) => !action.disabled);
  }
  get hasAutoFix() {
    return this.validActions.some(({ action: fix }) => !!fix.kind && CodeActionKind.QuickFix.contains(new CodeActionKind(fix.kind)) && !!fix.isPreferred);
  }
}
const emptyCodeActionsResponse = { actions: [], documentation: void 0 };
function getCodeActions(registry, model, rangeOrSelection, trigger2, progress, token) {
  var _a2;
  return __awaiter$1l(this, void 0, void 0, function* () {
    const filter2 = trigger2.filter || {};
    const codeActionContext = {
      only: (_a2 = filter2.include) === null || _a2 === void 0 ? void 0 : _a2.value,
      trigger: trigger2.type
    };
    const cts = new TextModelCancellationTokenSource(model, token);
    const providers = getCodeActionProviders(registry, model, filter2);
    const disposables = new DisposableStore();
    const promises = providers.map((provider) => __awaiter$1l(this, void 0, void 0, function* () {
      try {
        progress.report(provider);
        const providedCodeActions = yield provider.provideCodeActions(model, rangeOrSelection, codeActionContext, cts.token);
        if (providedCodeActions) {
          disposables.add(providedCodeActions);
        }
        if (cts.token.isCancellationRequested) {
          return emptyCodeActionsResponse;
        }
        const filteredActions = ((providedCodeActions === null || providedCodeActions === void 0 ? void 0 : providedCodeActions.actions) || []).filter((action) => action && filtersAction(filter2, action));
        const documentation = getDocumentationFromProvider(provider, filteredActions, filter2.include);
        return {
          actions: filteredActions.map((action) => new CodeActionItem(action, provider)),
          documentation
        };
      } catch (err) {
        if (isCancellationError(err)) {
          throw err;
        }
        onUnexpectedExternalError(err);
        return emptyCodeActionsResponse;
      }
    }));
    const listener = registry.onDidChange(() => {
      const newProviders = registry.all(model);
      if (!equals$3(newProviders, providers)) {
        cts.cancel();
      }
    });
    try {
      const actions = yield Promise.all(promises);
      const allActions = actions.map((x) => x.actions).flat();
      const allDocumentation = [
        ...coalesce(actions.map((x) => x.documentation)),
        ...getAdditionalDocumentationForShowingActions(registry, model, trigger2, allActions)
      ];
      return new ManagedCodeActionSet(allActions, allDocumentation, disposables);
    } finally {
      listener.dispose();
      cts.dispose();
    }
  });
}
function getCodeActionProviders(registry, model, filter2) {
  return registry.all(model).filter((provider) => {
    if (!provider.providedCodeActionKinds) {
      return true;
    }
    return provider.providedCodeActionKinds.some((kind) => mayIncludeActionsOfKind(filter2, new CodeActionKind(kind)));
  });
}
function* getAdditionalDocumentationForShowingActions(registry, model, trigger2, actionsToShow) {
  var _a2, _b2, _c2;
  if (model && actionsToShow.length) {
    for (const provider of registry.all(model)) {
      if (provider._getAdditionalMenuItems) {
        yield* (_a2 = provider._getAdditionalMenuItems) === null || _a2 === void 0 ? void 0 : _a2.call(provider, { trigger: trigger2.type, only: (_c2 = (_b2 = trigger2.filter) === null || _b2 === void 0 ? void 0 : _b2.include) === null || _c2 === void 0 ? void 0 : _c2.value }, actionsToShow.map((item) => item.action));
      }
    }
  }
}
function getDocumentationFromProvider(provider, providedCodeActions, only) {
  if (!provider.documentation) {
    return void 0;
  }
  const documentation = provider.documentation.map((entry) => ({ kind: new CodeActionKind(entry.kind), command: entry.command }));
  if (only) {
    let currentBest;
    for (const entry of documentation) {
      if (entry.kind.contains(only)) {
        if (!currentBest) {
          currentBest = entry;
        } else {
          if (currentBest.kind.contains(entry.kind)) {
            currentBest = entry;
          }
        }
      }
    }
    if (currentBest) {
      return currentBest === null || currentBest === void 0 ? void 0 : currentBest.command;
    }
  }
  for (const action of providedCodeActions) {
    if (!action.kind) {
      continue;
    }
    for (const entry of documentation) {
      if (entry.kind.contains(new CodeActionKind(action.kind))) {
        return entry.command;
      }
    }
  }
  return void 0;
}
var ApplyCodeActionReason;
(function(ApplyCodeActionReason2) {
  ApplyCodeActionReason2["OnSave"] = "onSave";
  ApplyCodeActionReason2["FromProblemsView"] = "fromProblemsView";
  ApplyCodeActionReason2["FromCodeActions"] = "fromCodeActions";
})(ApplyCodeActionReason || (ApplyCodeActionReason = {}));
function applyCodeAction(accessor, item, codeActionReason, options, token = CancellationToken.None) {
  var _a2;
  return __awaiter$1l(this, void 0, void 0, function* () {
    const bulkEditService = accessor.get(IBulkEditService);
    const commandService = accessor.get(ICommandService);
    const telemetryService = accessor.get(ITelemetryService);
    const notificationService = accessor.get(INotificationService);
    telemetryService.publicLog2("codeAction.applyCodeAction", {
      codeActionTitle: item.action.title,
      codeActionKind: item.action.kind,
      codeActionIsPreferred: !!item.action.isPreferred,
      reason: codeActionReason
    });
    yield item.resolve(token);
    if (token.isCancellationRequested) {
      return;
    }
    if ((_a2 = item.action.edit) === null || _a2 === void 0 ? void 0 : _a2.edits.length) {
      const result2 = yield bulkEditService.apply(item.action.edit, {
        editor: options === null || options === void 0 ? void 0 : options.editor,
        label: item.action.title,
        quotableLabel: item.action.title,
        code: "undoredo.codeAction",
        respectAutoSaveConfig: codeActionReason !== ApplyCodeActionReason.OnSave,
        showPreview: options === null || options === void 0 ? void 0 : options.preview
      });
      if (!result2.isApplied) {
        return;
      }
    }
    if (item.action.command) {
      try {
        yield commandService.executeCommand(item.action.command.id, ...item.action.command.arguments || []);
      } catch (err) {
        const message = asMessage(err);
        notificationService.error(typeof message === "string" ? message : localize("applyCodeActionFailed", "An unknown error occurred while applying the code action"));
      }
    }
  });
}
function asMessage(err) {
  if (typeof err === "string") {
    return err;
  } else if (err instanceof Error && typeof err.message === "string") {
    return err.message;
  } else {
    return void 0;
  }
}
CommandsRegistry.registerCommand("_executeCodeActionProvider", function(accessor, resource, rangeOrSelection, kind, itemResolveCount) {
  return __awaiter$1l(this, void 0, void 0, function* () {
    if (!(resource instanceof URI)) {
      throw illegalArgument();
    }
    const { codeActionProvider } = accessor.get(ILanguageFeaturesService);
    const model = accessor.get(IModelService).getModel(resource);
    if (!model) {
      throw illegalArgument();
    }
    const validatedRangeOrSelection = Selection$1.isISelection(rangeOrSelection) ? Selection$1.liftSelection(rangeOrSelection) : Range$2.isIRange(rangeOrSelection) ? model.validateRange(rangeOrSelection) : void 0;
    if (!validatedRangeOrSelection) {
      throw illegalArgument();
    }
    const include = typeof kind === "string" ? new CodeActionKind(kind) : void 0;
    const codeActionSet = yield getCodeActions(codeActionProvider, model, validatedRangeOrSelection, { type: 1, triggerAction: CodeActionTriggerSource.Default, filter: { includeSourceActions: true, include } }, Progress.None, CancellationToken.None);
    const resolving = [];
    const resolveCount = Math.min(codeActionSet.validActions.length, typeof itemResolveCount === "number" ? itemResolveCount : 0);
    for (let i = 0; i < resolveCount; i++) {
      resolving.push(codeActionSet.validActions[i].resolve(CancellationToken.None));
    }
    try {
      yield Promise.all(resolving);
      return codeActionSet.validActions.map((item) => item.action);
    } finally {
      setTimeout(() => codeActionSet.dispose(), 100);
    }
  });
});
var __decorate$1V = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1S = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let CodeActionKeybindingResolver = class CodeActionKeybindingResolver2 {
  constructor(keybindingService) {
    this.keybindingService = keybindingService;
  }
  getResolver() {
    const allCodeActionBindings = new Lazy(() => this.keybindingService.getKeybindings().filter((item) => CodeActionKeybindingResolver2.codeActionCommands.indexOf(item.command) >= 0).filter((item) => item.resolvedKeybinding).map((item) => {
      let commandArgs = item.commandArgs;
      if (item.command === organizeImportsCommandId) {
        commandArgs = { kind: CodeActionKind.SourceOrganizeImports.value };
      } else if (item.command === fixAllCommandId) {
        commandArgs = { kind: CodeActionKind.SourceFixAll.value };
      }
      return Object.assign({ resolvedKeybinding: item.resolvedKeybinding }, CodeActionCommandArgs.fromUser(commandArgs, {
        kind: CodeActionKind.None,
        apply: "never"
        /* CodeActionAutoApply.Never */
      }));
    }));
    return (action) => {
      if (action.kind) {
        const binding2 = this.bestKeybindingForCodeAction(action, allCodeActionBindings.value);
        return binding2 === null || binding2 === void 0 ? void 0 : binding2.resolvedKeybinding;
      }
      return void 0;
    };
  }
  bestKeybindingForCodeAction(action, candidates) {
    if (!action.kind) {
      return void 0;
    }
    const kind = new CodeActionKind(action.kind);
    return candidates.filter((candidate) => candidate.kind.contains(kind)).filter((candidate) => {
      if (candidate.preferred) {
        return action.isPreferred;
      }
      return true;
    }).reduceRight((currentBest, candidate) => {
      if (!currentBest) {
        return candidate;
      }
      return currentBest.kind.contains(candidate.kind) ? candidate : currentBest;
    }, void 0);
  }
};
CodeActionKeybindingResolver.codeActionCommands = [
  refactorCommandId,
  codeActionCommandId,
  sourceActionCommandId,
  organizeImportsCommandId,
  fixAllCommandId
];
CodeActionKeybindingResolver = __decorate$1V([
  __param$1S(0, IKeybindingService)
], CodeActionKeybindingResolver);
const codicon = "";
const codiconModifiers = "";
const symbolIcons = "";
registerColor("symbolIcon.arrayForeground", {
  dark: foreground,
  light: foreground,
  hcDark: foreground,
  hcLight: foreground
}, localize("symbolIcon.arrayForeground", "The foreground color for array symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.booleanForeground", {
  dark: foreground,
  light: foreground,
  hcDark: foreground,
  hcLight: foreground
}, localize("symbolIcon.booleanForeground", "The foreground color for boolean symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.classForeground", {
  dark: "#EE9D28",
  light: "#D67E00",
  hcDark: "#EE9D28",
  hcLight: "#D67E00"
}, localize("symbolIcon.classForeground", "The foreground color for class symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.colorForeground", {
  dark: foreground,
  light: foreground,
  hcDark: foreground,
  hcLight: foreground
}, localize("symbolIcon.colorForeground", "The foreground color for color symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.constantForeground", {
  dark: foreground,
  light: foreground,
  hcDark: foreground,
  hcLight: foreground
}, localize("symbolIcon.constantForeground", "The foreground color for constant symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.constructorForeground", {
  dark: "#B180D7",
  light: "#652D90",
  hcDark: "#B180D7",
  hcLight: "#652D90"
}, localize("symbolIcon.constructorForeground", "The foreground color for constructor symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.enumeratorForeground", {
  dark: "#EE9D28",
  light: "#D67E00",
  hcDark: "#EE9D28",
  hcLight: "#D67E00"
}, localize("symbolIcon.enumeratorForeground", "The foreground color for enumerator symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.enumeratorMemberForeground", {
  dark: "#75BEFF",
  light: "#007ACC",
  hcDark: "#75BEFF",
  hcLight: "#007ACC"
}, localize("symbolIcon.enumeratorMemberForeground", "The foreground color for enumerator member symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.eventForeground", {
  dark: "#EE9D28",
  light: "#D67E00",
  hcDark: "#EE9D28",
  hcLight: "#D67E00"
}, localize("symbolIcon.eventForeground", "The foreground color for event symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.fieldForeground", {
  dark: "#75BEFF",
  light: "#007ACC",
  hcDark: "#75BEFF",
  hcLight: "#007ACC"
}, localize("symbolIcon.fieldForeground", "The foreground color for field symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.fileForeground", {
  dark: foreground,
  light: foreground,
  hcDark: foreground,
  hcLight: foreground
}, localize("symbolIcon.fileForeground", "The foreground color for file symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.folderForeground", {
  dark: foreground,
  light: foreground,
  hcDark: foreground,
  hcLight: foreground
}, localize("symbolIcon.folderForeground", "The foreground color for folder symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.functionForeground", {
  dark: "#B180D7",
  light: "#652D90",
  hcDark: "#B180D7",
  hcLight: "#652D90"
}, localize("symbolIcon.functionForeground", "The foreground color for function symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.interfaceForeground", {
  dark: "#75BEFF",
  light: "#007ACC",
  hcDark: "#75BEFF",
  hcLight: "#007ACC"
}, localize("symbolIcon.interfaceForeground", "The foreground color for interface symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.keyForeground", {
  dark: foreground,
  light: foreground,
  hcDark: foreground,
  hcLight: foreground
}, localize("symbolIcon.keyForeground", "The foreground color for key symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.keywordForeground", {
  dark: foreground,
  light: foreground,
  hcDark: foreground,
  hcLight: foreground
}, localize("symbolIcon.keywordForeground", "The foreground color for keyword symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.methodForeground", {
  dark: "#B180D7",
  light: "#652D90",
  hcDark: "#B180D7",
  hcLight: "#652D90"
}, localize("symbolIcon.methodForeground", "The foreground color for method symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.moduleForeground", {
  dark: foreground,
  light: foreground,
  hcDark: foreground,
  hcLight: foreground
}, localize("symbolIcon.moduleForeground", "The foreground color for module symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.namespaceForeground", {
  dark: foreground,
  light: foreground,
  hcDark: foreground,
  hcLight: foreground
}, localize("symbolIcon.namespaceForeground", "The foreground color for namespace symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.nullForeground", {
  dark: foreground,
  light: foreground,
  hcDark: foreground,
  hcLight: foreground
}, localize("symbolIcon.nullForeground", "The foreground color for null symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.numberForeground", {
  dark: foreground,
  light: foreground,
  hcDark: foreground,
  hcLight: foreground
}, localize("symbolIcon.numberForeground", "The foreground color for number symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.objectForeground", {
  dark: foreground,
  light: foreground,
  hcDark: foreground,
  hcLight: foreground
}, localize("symbolIcon.objectForeground", "The foreground color for object symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.operatorForeground", {
  dark: foreground,
  light: foreground,
  hcDark: foreground,
  hcLight: foreground
}, localize("symbolIcon.operatorForeground", "The foreground color for operator symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.packageForeground", {
  dark: foreground,
  light: foreground,
  hcDark: foreground,
  hcLight: foreground
}, localize("symbolIcon.packageForeground", "The foreground color for package symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.propertyForeground", {
  dark: foreground,
  light: foreground,
  hcDark: foreground,
  hcLight: foreground
}, localize("symbolIcon.propertyForeground", "The foreground color for property symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.referenceForeground", {
  dark: foreground,
  light: foreground,
  hcDark: foreground,
  hcLight: foreground
}, localize("symbolIcon.referenceForeground", "The foreground color for reference symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.snippetForeground", {
  dark: foreground,
  light: foreground,
  hcDark: foreground,
  hcLight: foreground
}, localize("symbolIcon.snippetForeground", "The foreground color for snippet symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.stringForeground", {
  dark: foreground,
  light: foreground,
  hcDark: foreground,
  hcLight: foreground
}, localize("symbolIcon.stringForeground", "The foreground color for string symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.structForeground", {
  dark: foreground,
  light: foreground,
  hcDark: foreground,
  hcLight: foreground
}, localize("symbolIcon.structForeground", "The foreground color for struct symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.textForeground", {
  dark: foreground,
  light: foreground,
  hcDark: foreground,
  hcLight: foreground
}, localize("symbolIcon.textForeground", "The foreground color for text symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.typeParameterForeground", {
  dark: foreground,
  light: foreground,
  hcDark: foreground,
  hcLight: foreground
}, localize("symbolIcon.typeParameterForeground", "The foreground color for type parameter symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.unitForeground", {
  dark: foreground,
  light: foreground,
  hcDark: foreground,
  hcLight: foreground
}, localize("symbolIcon.unitForeground", "The foreground color for unit symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
registerColor("symbolIcon.variableForeground", {
  dark: "#75BEFF",
  light: "#007ACC",
  hcDark: "#75BEFF",
  hcLight: "#007ACC"
}, localize("symbolIcon.variableForeground", "The foreground color for variable symbols. These symbols appear in the outline, breadcrumb, and suggest widget."));
const uncategorizedCodeActionGroup = Object.freeze({ kind: CodeActionKind.Empty, title: localize("codeAction.widget.id.more", "More Actions...") });
const codeActionGroups = Object.freeze([
  { kind: CodeActionKind.QuickFix, title: localize("codeAction.widget.id.quickfix", "Quick Fix...") },
  { kind: CodeActionKind.RefactorExtract, title: localize("codeAction.widget.id.extract", "Extract..."), icon: Codicon.wrench },
  { kind: CodeActionKind.RefactorInline, title: localize("codeAction.widget.id.inline", "Inline..."), icon: Codicon.wrench },
  { kind: CodeActionKind.RefactorRewrite, title: localize("codeAction.widget.id.convert", "Rewrite..."), icon: Codicon.wrench },
  { kind: CodeActionKind.RefactorMove, title: localize("codeAction.widget.id.move", "Move..."), icon: Codicon.wrench },
  { kind: CodeActionKind.SurroundWith, title: localize("codeAction.widget.id.surround", "Surround With..."), icon: Codicon.symbolSnippet },
  { kind: CodeActionKind.Source, title: localize("codeAction.widget.id.source", "Source Action..."), icon: Codicon.symbolFile },
  uncategorizedCodeActionGroup
]);
function toMenuItems(inputCodeActions, showHeaders, keybindingResolver) {
  if (!showHeaders) {
    return inputCodeActions.map((action) => {
      return {
        kind: "action",
        item: action,
        group: uncategorizedCodeActionGroup,
        disabled: !!action.action.disabled,
        label: action.action.disabled || action.action.title
      };
    });
  }
  const menuEntries = codeActionGroups.map((group2) => ({ group: group2, actions: [] }));
  for (const action of inputCodeActions) {
    const kind = action.action.kind ? new CodeActionKind(action.action.kind) : CodeActionKind.None;
    for (const menuEntry of menuEntries) {
      if (menuEntry.group.kind.contains(kind)) {
        menuEntry.actions.push(action);
        break;
      }
    }
  }
  const allMenuItems = [];
  for (const menuEntry of menuEntries) {
    if (menuEntry.actions.length) {
      allMenuItems.push({ kind: "header", group: menuEntry.group });
      for (const action of menuEntry.actions) {
        allMenuItems.push({
          kind: "action",
          item: action,
          group: menuEntry.group,
          label: action.action.title,
          disabled: !!action.action.disabled,
          keybinding: keybindingResolver(action.action)
        });
      }
    }
  }
  return allMenuItems;
}
const lightBulbWidget = "";
var __decorate$1U = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1R = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var LightBulbState;
(function(LightBulbState2) {
  LightBulbState2.Hidden = {
    type: 0
    /* Type.Hidden */
  };
  class Showing {
    constructor(actions, trigger2, editorPosition, widgetPosition) {
      this.actions = actions;
      this.trigger = trigger2;
      this.editorPosition = editorPosition;
      this.widgetPosition = widgetPosition;
      this.type = 1;
    }
  }
  LightBulbState2.Showing = Showing;
})(LightBulbState || (LightBulbState = {}));
let LightBulbWidget = class LightBulbWidget2 extends Disposable {
  constructor(_editor, keybindingService) {
    super();
    this._editor = _editor;
    this._onClick = this._register(new Emitter$1());
    this.onClick = this._onClick.event;
    this._state = LightBulbState.Hidden;
    this._domNode = $$d("div.lightBulbWidget");
    this._register(Gesture.ignoreTarget(this._domNode));
    this._editor.addContentWidget(this);
    this._register(this._editor.onDidChangeModelContent((_) => {
      const editorModel = this._editor.getModel();
      if (this.state.type !== 1 || !editorModel || this.state.editorPosition.lineNumber >= editorModel.getLineCount()) {
        this.hide();
      }
    }));
    this._register(addStandardDisposableGenericMouseDownListener(this._domNode, (e) => {
      if (this.state.type !== 1) {
        return;
      }
      this._editor.focus();
      e.preventDefault();
      const { top, height } = getDomNodePagePosition(this._domNode);
      const lineHeight = this._editor.getOption(
        65
        /* EditorOption.lineHeight */
      );
      let pad2 = Math.floor(lineHeight / 3);
      if (this.state.widgetPosition.position !== null && this.state.widgetPosition.position.lineNumber < this.state.editorPosition.lineNumber) {
        pad2 += lineHeight;
      }
      this._onClick.fire({
        x: e.posx,
        y: top + height + pad2,
        actions: this.state.actions,
        trigger: this.state.trigger
      });
    }));
    this._register(addDisposableListener(this._domNode, "mouseenter", (e) => {
      if ((e.buttons & 1) !== 1) {
        return;
      }
      this.hide();
    }));
    this._register(this._editor.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        63
        /* EditorOption.lightbulb */
      ) && !this._editor.getOption(
        63
        /* EditorOption.lightbulb */
      ).enabled) {
        this.hide();
      }
    }));
    this._register(Event$1.runAndSubscribe(keybindingService.onDidUpdateKeybindings, () => {
      var _a2, _b2;
      this._preferredKbLabel = withNullAsUndefined((_a2 = keybindingService.lookupKeybinding(autoFixCommandId)) === null || _a2 === void 0 ? void 0 : _a2.getLabel());
      this._quickFixKbLabel = withNullAsUndefined((_b2 = keybindingService.lookupKeybinding(quickFixCommandId)) === null || _b2 === void 0 ? void 0 : _b2.getLabel());
      this._updateLightBulbTitleAndIcon();
    }));
  }
  dispose() {
    super.dispose();
    this._editor.removeContentWidget(this);
  }
  getId() {
    return "LightBulbWidget";
  }
  getDomNode() {
    return this._domNode;
  }
  getPosition() {
    return this._state.type === 1 ? this._state.widgetPosition : null;
  }
  update(actions, trigger2, atPosition) {
    if (actions.validActions.length <= 0) {
      return this.hide();
    }
    const options = this._editor.getOptions();
    if (!options.get(
      63
      /* EditorOption.lightbulb */
    ).enabled) {
      return this.hide();
    }
    const model = this._editor.getModel();
    if (!model) {
      return this.hide();
    }
    const { lineNumber, column } = model.validatePosition(atPosition);
    const tabSize = model.getOptions().tabSize;
    const fontInfo = options.get(
      49
      /* EditorOption.fontInfo */
    );
    const lineContent = model.getLineContent(lineNumber);
    const indent = computeIndentLevel(lineContent, tabSize);
    const lineHasSpace = fontInfo.spaceWidth * indent > 22;
    const isFolded = (lineNumber2) => {
      return lineNumber2 > 2 && this._editor.getTopForLineNumber(lineNumber2) === this._editor.getTopForLineNumber(lineNumber2 - 1);
    };
    let effectiveLineNumber = lineNumber;
    if (!lineHasSpace) {
      if (lineNumber > 1 && !isFolded(lineNumber - 1)) {
        effectiveLineNumber -= 1;
      } else if (!isFolded(lineNumber + 1)) {
        effectiveLineNumber += 1;
      } else if (column * fontInfo.spaceWidth < 22) {
        return this.hide();
      }
    }
    this.state = new LightBulbState.Showing(actions, trigger2, atPosition, {
      position: { lineNumber: effectiveLineNumber, column: 1 },
      preference: LightBulbWidget2._posPref
    });
    this._editor.layoutContentWidget(this);
  }
  hide() {
    if (this.state === LightBulbState.Hidden) {
      return;
    }
    this.state = LightBulbState.Hidden;
    this._editor.layoutContentWidget(this);
  }
  get state() {
    return this._state;
  }
  set state(value) {
    this._state = value;
    this._updateLightBulbTitleAndIcon();
  }
  _updateLightBulbTitleAndIcon() {
    if (this.state.type === 1 && this.state.actions.hasAutoFix) {
      this._domNode.classList.remove(...ThemeIcon.asClassNameArray(Codicon.lightBulb));
      this._domNode.classList.add(...ThemeIcon.asClassNameArray(Codicon.lightbulbAutofix));
      if (this._preferredKbLabel) {
        this.title = localize("preferredcodeActionWithKb", "Show Code Actions. Preferred Quick Fix Available ({0})", this._preferredKbLabel);
        return;
      }
    }
    this._domNode.classList.remove(...ThemeIcon.asClassNameArray(Codicon.lightbulbAutofix));
    this._domNode.classList.add(...ThemeIcon.asClassNameArray(Codicon.lightBulb));
    if (this._quickFixKbLabel) {
      this.title = localize("codeActionWithKb", "Show Code Actions ({0})", this._quickFixKbLabel);
    } else {
      this.title = localize("codeAction", "Show Code Actions");
    }
  }
  set title(value) {
    this._domNode.title = value;
  }
};
LightBulbWidget.ID = "editor.contrib.lightbulbWidget";
LightBulbWidget._posPref = [
  0
  /* ContentWidgetPositionPreference.EXACT */
];
LightBulbWidget = __decorate$1U([
  __param$1R(1, IKeybindingService)
], LightBulbWidget);
const messageController = "";
const renderedMarkdown = "";
const IOpenerService = createDecorator("openerService");
function matchesScheme(target, scheme) {
  if (URI.isUri(target)) {
    return equalsIgnoreCase(target.scheme, scheme);
  } else {
    return startsWithIgnoreCase(target, scheme + ":");
  }
}
function matchesSomeScheme(target, ...schemes) {
  return schemes.some((scheme) => matchesScheme(target, scheme));
}
function extractSelection(uri) {
  let selection = void 0;
  const match2 = /^L?(\d+)(?:,(\d+))?(-L?(\d+)(?:,(\d+))?)?/.exec(uri.fragment);
  if (match2) {
    selection = {
      startLineNumber: parseInt(match2[1]),
      startColumn: match2[2] ? parseInt(match2[2]) : 1,
      endLineNumber: match2[4] ? parseInt(match2[4]) : void 0,
      endColumn: match2[4] ? match2[5] ? parseInt(match2[5]) : 1 : void 0
    };
    uri = uri.with({ fragment: "" });
  }
  return { selection, uri };
}
var __decorate$1T = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1Q = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$1k = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
let MarkdownRenderer = class MarkdownRenderer2 {
  constructor(_options, _languageService, _openerService) {
    this._options = _options;
    this._languageService = _languageService;
    this._openerService = _openerService;
    this._onDidRenderAsync = new Emitter$1();
    this.onDidRenderAsync = this._onDidRenderAsync.event;
  }
  dispose() {
    this._onDidRenderAsync.dispose();
  }
  render(markdown, options, markedOptions) {
    if (!markdown) {
      const element = document.createElement("span");
      return { element, dispose: () => {
      } };
    }
    const disposables = new DisposableStore();
    const rendered = disposables.add(renderMarkdown(markdown, Object.assign(Object.assign({}, this._getRenderOptions(markdown, disposables)), options), markedOptions));
    rendered.element.classList.add("rendered-markdown");
    return {
      element: rendered.element,
      dispose: () => disposables.dispose()
    };
  }
  _getRenderOptions(markdown, disposables) {
    return {
      codeBlockRenderer: (languageAlias, value) => __awaiter$1k(this, void 0, void 0, function* () {
        var _a2, _b2, _c2;
        let languageId;
        if (languageAlias) {
          languageId = this._languageService.getLanguageIdByLanguageName(languageAlias);
        } else if (this._options.editor) {
          languageId = (_a2 = this._options.editor.getModel()) === null || _a2 === void 0 ? void 0 : _a2.getLanguageId();
        }
        if (!languageId) {
          languageId = PLAINTEXT_LANGUAGE_ID;
        }
        const html2 = yield tokenizeToString(this._languageService, value, languageId);
        const element = document.createElement("span");
        element.innerHTML = (_c2 = (_b2 = MarkdownRenderer2._ttpTokenizer) === null || _b2 === void 0 ? void 0 : _b2.createHTML(html2)) !== null && _c2 !== void 0 ? _c2 : html2;
        if (this._options.editor) {
          const fontInfo = this._options.editor.getOption(
            49
            /* EditorOption.fontInfo */
          );
          applyFontInfo(element, fontInfo);
        } else if (this._options.codeBlockFontFamily) {
          element.style.fontFamily = this._options.codeBlockFontFamily;
        }
        if (this._options.codeBlockFontSize !== void 0) {
          element.style.fontSize = this._options.codeBlockFontSize;
        }
        return element;
      }),
      asyncRenderCallback: () => this._onDidRenderAsync.fire(),
      actionHandler: {
        callback: (link2) => openLinkFromMarkdown(this._openerService, link2, markdown.isTrusted),
        disposables
      }
    };
  }
};
MarkdownRenderer._ttpTokenizer = createTrustedTypesPolicy("tokenizeToString", {
  createHTML(html2) {
    return html2;
  }
});
MarkdownRenderer = __decorate$1T([
  __param$1Q(1, ILanguageService),
  __param$1Q(2, IOpenerService)
], MarkdownRenderer);
function openLinkFromMarkdown(openerService, link2, isTrusted) {
  return __awaiter$1k(this, void 0, void 0, function* () {
    try {
      return yield openerService.open(link2, {
        fromUserGesture: true,
        allowContributedOpeners: true,
        allowCommands: toAllowCommandsOption(isTrusted)
      });
    } catch (e) {
      onUnexpectedError(e);
      return false;
    }
  });
}
function toAllowCommandsOption(isTrusted) {
  if (isTrusted === true) {
    return true;
  }
  if (isTrusted && Array.isArray(isTrusted.enabledCommands)) {
    return isTrusted.enabledCommands;
  }
  return false;
}
var __decorate$1S = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1P = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let MessageController = class MessageController2 {
  static get(editor2) {
    return editor2.getContribution(MessageController2.ID);
  }
  constructor(editor2, contextKeyService, _openerService) {
    this._openerService = _openerService;
    this._messageWidget = new MutableDisposable();
    this._messageListeners = new DisposableStore();
    this._mouseOverMessage = false;
    this._editor = editor2;
    this._visible = MessageController2.MESSAGE_VISIBLE.bindTo(contextKeyService);
  }
  dispose() {
    var _a2;
    (_a2 = this._message) === null || _a2 === void 0 ? void 0 : _a2.dispose();
    this._messageListeners.dispose();
    this._messageWidget.dispose();
    this._visible.reset();
  }
  showMessage(message, position) {
    alert(isMarkdownString(message) ? message.value : message);
    this._visible.set(true);
    this._messageWidget.clear();
    this._messageListeners.clear();
    this._message = isMarkdownString(message) ? renderMarkdown(message, {
      actionHandler: {
        callback: (url) => openLinkFromMarkdown(this._openerService, url, isMarkdownString(message) ? message.isTrusted : void 0),
        disposables: this._messageListeners
      }
    }) : void 0;
    this._messageWidget.value = new MessageWidget$1(this._editor, position, typeof message === "string" ? message : this._message.element);
    this._messageListeners.add(Event$1.debounce(this._editor.onDidBlurEditorText, (last2, event) => event, 0)(() => {
      if (this._mouseOverMessage) {
        return;
      }
      if (this._messageWidget.value && isAncestor$1(document.activeElement, this._messageWidget.value.getDomNode())) {
        return;
      }
      this.closeMessage();
    }));
    this._messageListeners.add(this._editor.onDidChangeCursorPosition(() => this.closeMessage()));
    this._messageListeners.add(this._editor.onDidDispose(() => this.closeMessage()));
    this._messageListeners.add(this._editor.onDidChangeModel(() => this.closeMessage()));
    this._messageListeners.add(addDisposableListener(this._messageWidget.value.getDomNode(), EventType$1.MOUSE_ENTER, () => this._mouseOverMessage = true, true));
    this._messageListeners.add(addDisposableListener(this._messageWidget.value.getDomNode(), EventType$1.MOUSE_LEAVE, () => this._mouseOverMessage = false, true));
    let bounds;
    this._messageListeners.add(this._editor.onMouseMove((e) => {
      if (!e.target.position) {
        return;
      }
      if (!bounds) {
        bounds = new Range$2(position.lineNumber - 3, 1, e.target.position.lineNumber + 3, 1);
      } else if (!bounds.containsPosition(e.target.position)) {
        this.closeMessage();
      }
    }));
  }
  closeMessage() {
    this._visible.reset();
    this._messageListeners.clear();
    if (this._messageWidget.value) {
      this._messageListeners.add(MessageWidget$1.fadeOut(this._messageWidget.value));
    }
  }
};
MessageController.ID = "editor.contrib.messageController";
MessageController.MESSAGE_VISIBLE = new RawContextKey("messageVisible", false, localize("messageVisible", "Whether the editor is currently showing an inline message"));
MessageController = __decorate$1S([
  __param$1P(1, IContextKeyService),
  __param$1P(2, IOpenerService)
], MessageController);
const MessageCommand = EditorCommand.bindToContribution(MessageController.get);
registerEditorCommand(new MessageCommand({
  id: "leaveEditorMessage",
  precondition: MessageController.MESSAGE_VISIBLE,
  handler: (c) => c.closeMessage(),
  kbOpts: {
    weight: 100 + 30,
    primary: 9
    /* KeyCode.Escape */
  }
}));
let MessageWidget$1 = class MessageWidget {
  static fadeOut(messageWidget) {
    const dispose2 = () => {
      messageWidget.dispose();
      clearTimeout(handle);
      messageWidget.getDomNode().removeEventListener("animationend", dispose2);
    };
    const handle = setTimeout(dispose2, 110);
    messageWidget.getDomNode().addEventListener("animationend", dispose2);
    messageWidget.getDomNode().classList.add("fadeOut");
    return { dispose: dispose2 };
  }
  constructor(editor2, { lineNumber, column }, text2) {
    this.allowEditorOverflow = true;
    this.suppressMouseDown = false;
    this._editor = editor2;
    this._editor.revealLinesInCenterIfOutsideViewport(
      lineNumber,
      lineNumber,
      0
      /* ScrollType.Smooth */
    );
    this._position = { lineNumber, column };
    this._domNode = document.createElement("div");
    this._domNode.classList.add("monaco-editor-overlaymessage");
    this._domNode.style.marginLeft = "-6px";
    const anchorTop = document.createElement("div");
    anchorTop.classList.add("anchor", "top");
    this._domNode.appendChild(anchorTop);
    const message = document.createElement("div");
    if (typeof text2 === "string") {
      message.classList.add("message");
      message.textContent = text2;
    } else {
      text2.classList.add("message");
      message.appendChild(text2);
    }
    this._domNode.appendChild(message);
    const anchorBottom = document.createElement("div");
    anchorBottom.classList.add("anchor", "below");
    this._domNode.appendChild(anchorBottom);
    this._editor.addContentWidget(this);
    this._domNode.classList.add("fadeIn");
  }
  dispose() {
    this._editor.removeContentWidget(this);
  }
  getId() {
    return "messageoverlay";
  }
  getDomNode() {
    return this._domNode;
  }
  getPosition() {
    return {
      position: this._position,
      preference: [
        1,
        2
      ],
      positionAffinity: 1
    };
  }
  afterRender(position) {
    this._domNode.classList.toggle(
      "below",
      position === 2
      /* ContentWidgetPositionPreference.BELOW */
    );
  }
};
registerEditorContribution(
  MessageController.ID,
  MessageController,
  4
  /* EditorContributionInstantiation.Lazy */
);
const actionWidget = "";
class ModifierLabelProvider {
  constructor(mac, windows, linux = windows) {
    this.modifierLabels = [null];
    this.modifierLabels[
      2
      /* OperatingSystem.Macintosh */
    ] = mac;
    this.modifierLabels[
      1
      /* OperatingSystem.Windows */
    ] = windows;
    this.modifierLabels[
      3
      /* OperatingSystem.Linux */
    ] = linux;
  }
  toLabel(OS2, chords, keyLabelProvider) {
    if (chords.length === 0) {
      return null;
    }
    const result2 = [];
    for (let i = 0, len = chords.length; i < len; i++) {
      const chord = chords[i];
      const keyLabel = keyLabelProvider(chord);
      if (keyLabel === null) {
        return null;
      }
      result2[i] = _simpleAsString(chord, keyLabel, this.modifierLabels[OS2]);
    }
    return result2.join(" ");
  }
}
const UILabelProvider = new ModifierLabelProvider({
  ctrlKey: "⌃",
  shiftKey: "⇧",
  altKey: "⌥",
  metaKey: "⌘",
  separator: ""
}, {
  ctrlKey: localize({ key: "ctrlKey", comment: ["This is the short form for the Control key on the keyboard"] }, "Ctrl"),
  shiftKey: localize({ key: "shiftKey", comment: ["This is the short form for the Shift key on the keyboard"] }, "Shift"),
  altKey: localize({ key: "altKey", comment: ["This is the short form for the Alt key on the keyboard"] }, "Alt"),
  metaKey: localize({ key: "windowsKey", comment: ["This is the short form for the Windows key on the keyboard"] }, "Windows"),
  separator: "+"
}, {
  ctrlKey: localize({ key: "ctrlKey", comment: ["This is the short form for the Control key on the keyboard"] }, "Ctrl"),
  shiftKey: localize({ key: "shiftKey", comment: ["This is the short form for the Shift key on the keyboard"] }, "Shift"),
  altKey: localize({ key: "altKey", comment: ["This is the short form for the Alt key on the keyboard"] }, "Alt"),
  metaKey: localize({ key: "superKey", comment: ["This is the short form for the Super key on the keyboard"] }, "Super"),
  separator: "+"
});
const AriaLabelProvider = new ModifierLabelProvider({
  ctrlKey: localize({ key: "ctrlKey.long", comment: ["This is the long form for the Control key on the keyboard"] }, "Control"),
  shiftKey: localize({ key: "shiftKey.long", comment: ["This is the long form for the Shift key on the keyboard"] }, "Shift"),
  altKey: localize({ key: "optKey.long", comment: ["This is the long form for the Alt/Option key on the keyboard"] }, "Option"),
  metaKey: localize({ key: "cmdKey.long", comment: ["This is the long form for the Command key on the keyboard"] }, "Command"),
  separator: "+"
}, {
  ctrlKey: localize({ key: "ctrlKey.long", comment: ["This is the long form for the Control key on the keyboard"] }, "Control"),
  shiftKey: localize({ key: "shiftKey.long", comment: ["This is the long form for the Shift key on the keyboard"] }, "Shift"),
  altKey: localize({ key: "altKey.long", comment: ["This is the long form for the Alt key on the keyboard"] }, "Alt"),
  metaKey: localize({ key: "windowsKey.long", comment: ["This is the long form for the Windows key on the keyboard"] }, "Windows"),
  separator: "+"
}, {
  ctrlKey: localize({ key: "ctrlKey.long", comment: ["This is the long form for the Control key on the keyboard"] }, "Control"),
  shiftKey: localize({ key: "shiftKey.long", comment: ["This is the long form for the Shift key on the keyboard"] }, "Shift"),
  altKey: localize({ key: "altKey.long", comment: ["This is the long form for the Alt key on the keyboard"] }, "Alt"),
  metaKey: localize({ key: "superKey.long", comment: ["This is the long form for the Super key on the keyboard"] }, "Super"),
  separator: "+"
});
const ElectronAcceleratorLabelProvider = new ModifierLabelProvider({
  ctrlKey: "Ctrl",
  shiftKey: "Shift",
  altKey: "Alt",
  metaKey: "Cmd",
  separator: "+"
}, {
  ctrlKey: "Ctrl",
  shiftKey: "Shift",
  altKey: "Alt",
  metaKey: "Super",
  separator: "+"
});
const UserSettingsLabelProvider = new ModifierLabelProvider({
  ctrlKey: "ctrl",
  shiftKey: "shift",
  altKey: "alt",
  metaKey: "cmd",
  separator: "+"
}, {
  ctrlKey: "ctrl",
  shiftKey: "shift",
  altKey: "alt",
  metaKey: "win",
  separator: "+"
}, {
  ctrlKey: "ctrl",
  shiftKey: "shift",
  altKey: "alt",
  metaKey: "meta",
  separator: "+"
});
function _simpleAsString(modifiers, key, labels) {
  if (key === null) {
    return "";
  }
  const result2 = [];
  if (modifiers.ctrlKey) {
    result2.push(labels.ctrlKey);
  }
  if (modifiers.shiftKey) {
    result2.push(labels.shiftKey);
  }
  if (modifiers.altKey) {
    result2.push(labels.altKey);
  }
  if (modifiers.metaKey) {
    result2.push(labels.metaKey);
  }
  if (key !== "") {
    result2.push(key);
  }
  return result2.join(labels.separator);
}
const keybindingLabel = "";
const $$b = $$d;
const unthemedKeybindingLabelOptions = {
  keybindingLabelBackground: void 0,
  keybindingLabelForeground: void 0,
  keybindingLabelBorder: void 0,
  keybindingLabelBottomBorder: void 0,
  keybindingLabelShadow: void 0
};
class KeybindingLabel {
  constructor(container2, os, options) {
    this.os = os;
    this.keyElements = /* @__PURE__ */ new Set();
    this.options = options || /* @__PURE__ */ Object.create(null);
    const labelForeground = this.options.keybindingLabelForeground;
    this.domNode = append$1(container2, $$b(".monaco-keybinding"));
    if (labelForeground) {
      this.domNode.style.color = labelForeground;
    }
    this.didEverRender = false;
    container2.appendChild(this.domNode);
  }
  get element() {
    return this.domNode;
  }
  set(keybinding, matches) {
    if (this.didEverRender && this.keybinding === keybinding && KeybindingLabel.areSame(this.matches, matches)) {
      return;
    }
    this.keybinding = keybinding;
    this.matches = matches;
    this.render();
  }
  render() {
    var _a2;
    this.clear();
    if (this.keybinding) {
      const chords = this.keybinding.getChords();
      if (chords[0]) {
        this.renderChord(this.domNode, chords[0], this.matches ? this.matches.firstPart : null);
      }
      for (let i = 1; i < chords.length; i++) {
        append$1(this.domNode, $$b("span.monaco-keybinding-key-chord-separator", void 0, " "));
        this.renderChord(this.domNode, chords[i], this.matches ? this.matches.chordPart : null);
      }
      const title2 = ((_a2 = this.options.disableTitle) !== null && _a2 !== void 0 ? _a2 : false) ? void 0 : this.keybinding.getAriaLabel() || void 0;
      if (title2 !== void 0) {
        this.domNode.title = title2;
      } else {
        this.domNode.removeAttribute("title");
      }
    } else if (this.options && this.options.renderUnboundKeybindings) {
      this.renderUnbound(this.domNode);
    }
    this.didEverRender = true;
  }
  clear() {
    clearNode(this.domNode);
    this.keyElements.clear();
  }
  renderChord(parent, chord, match2) {
    const modifierLabels = UILabelProvider.modifierLabels[this.os];
    if (chord.ctrlKey) {
      this.renderKey(parent, modifierLabels.ctrlKey, Boolean(match2 === null || match2 === void 0 ? void 0 : match2.ctrlKey), modifierLabels.separator);
    }
    if (chord.shiftKey) {
      this.renderKey(parent, modifierLabels.shiftKey, Boolean(match2 === null || match2 === void 0 ? void 0 : match2.shiftKey), modifierLabels.separator);
    }
    if (chord.altKey) {
      this.renderKey(parent, modifierLabels.altKey, Boolean(match2 === null || match2 === void 0 ? void 0 : match2.altKey), modifierLabels.separator);
    }
    if (chord.metaKey) {
      this.renderKey(parent, modifierLabels.metaKey, Boolean(match2 === null || match2 === void 0 ? void 0 : match2.metaKey), modifierLabels.separator);
    }
    const keyLabel = chord.keyLabel;
    if (keyLabel) {
      this.renderKey(parent, keyLabel, Boolean(match2 === null || match2 === void 0 ? void 0 : match2.keyCode), "");
    }
  }
  renderKey(parent, label, highlight, separator) {
    append$1(parent, this.createKeyElement(label, highlight ? ".highlight" : ""));
    if (separator) {
      append$1(parent, $$b("span.monaco-keybinding-key-separator", void 0, separator));
    }
  }
  renderUnbound(parent) {
    append$1(parent, this.createKeyElement(localize("unbound", "Unbound")));
  }
  createKeyElement(label, extraClass = "") {
    const keyElement = $$b("span.monaco-keybinding-key" + extraClass, void 0, label);
    this.keyElements.add(keyElement);
    if (this.options.keybindingLabelBackground) {
      keyElement.style.backgroundColor = this.options.keybindingLabelBackground;
    }
    if (this.options.keybindingLabelBorder) {
      keyElement.style.borderColor = this.options.keybindingLabelBorder;
    }
    if (this.options.keybindingLabelBottomBorder) {
      keyElement.style.borderBottomColor = this.options.keybindingLabelBottomBorder;
    }
    if (this.options.keybindingLabelShadow) {
      keyElement.style.boxShadow = `inset 0 -1px 0 ${this.options.keybindingLabelShadow}`;
    }
    return keyElement;
  }
  static areSame(a, b) {
    if (a === b || !a && !b) {
      return true;
    }
    return !!a && !!b && equals$2(a.firstPart, b.firstPart) && equals$2(a.chordPart, b.chordPart);
  }
}
function overrideStyles(override, styles) {
  const result2 = Object.assign({}, styles);
  for (const key in override) {
    const val = override[key];
    result2[key] = val !== void 0 ? asCssVariable(val) : void 0;
  }
  return result2;
}
const defaultKeybindingLabelStyles = {
  keybindingLabelBackground: asCssVariable(keybindingLabelBackground),
  keybindingLabelForeground: asCssVariable(keybindingLabelForeground),
  keybindingLabelBorder: asCssVariable(keybindingLabelBorder),
  keybindingLabelBottomBorder: asCssVariable(keybindingLabelBottomBorder),
  keybindingLabelShadow: asCssVariable(widgetShadow)
};
const defaultButtonStyles = {
  buttonForeground: asCssVariable(buttonForeground),
  buttonSeparator: asCssVariable(buttonSeparator),
  buttonBackground: asCssVariable(buttonBackground),
  buttonHoverBackground: asCssVariable(buttonHoverBackground),
  buttonSecondaryForeground: asCssVariable(buttonSecondaryForeground),
  buttonSecondaryBackground: asCssVariable(buttonSecondaryBackground),
  buttonSecondaryHoverBackground: asCssVariable(buttonSecondaryHoverBackground),
  buttonBorder: asCssVariable(buttonBorder)
};
const defaultProgressBarStyles = {
  progressBarBackground: asCssVariable(progressBarBackground)
};
const defaultToggleStyles = {
  inputActiveOptionBorder: asCssVariable(inputActiveOptionBorder),
  inputActiveOptionForeground: asCssVariable(inputActiveOptionForeground),
  inputActiveOptionBackground: asCssVariable(inputActiveOptionBackground)
};
({
  checkboxBackground: asCssVariable(checkboxBackground),
  checkboxBorder: asCssVariable(checkboxBorder),
  checkboxForeground: asCssVariable(checkboxForeground)
});
({
  dialogBackground: asCssVariable(editorWidgetBackground),
  dialogForeground: asCssVariable(editorWidgetForeground),
  dialogShadow: asCssVariable(widgetShadow),
  dialogBorder: asCssVariable(contrastBorder),
  errorIconForeground: asCssVariable(problemsErrorIconForeground),
  warningIconForeground: asCssVariable(problemsWarningIconForeground),
  infoIconForeground: asCssVariable(problemsInfoIconForeground),
  textLinkForeground: asCssVariable(textLinkForeground)
});
const defaultInputBoxStyles = {
  inputBackground: asCssVariable(inputBackground),
  inputForeground: asCssVariable(inputForeground),
  inputBorder: asCssVariable(inputBorder),
  inputValidationInfoBorder: asCssVariable(inputValidationInfoBorder),
  inputValidationInfoBackground: asCssVariable(inputValidationInfoBackground),
  inputValidationInfoForeground: asCssVariable(inputValidationInfoForeground),
  inputValidationWarningBorder: asCssVariable(inputValidationWarningBorder),
  inputValidationWarningBackground: asCssVariable(inputValidationWarningBackground),
  inputValidationWarningForeground: asCssVariable(inputValidationWarningForeground),
  inputValidationErrorBorder: asCssVariable(inputValidationErrorBorder),
  inputValidationErrorBackground: asCssVariable(inputValidationErrorBackground),
  inputValidationErrorForeground: asCssVariable(inputValidationErrorForeground)
};
const defaultFindWidgetStyles = {
  listFilterWidgetBackground: asCssVariable(listFilterWidgetBackground),
  listFilterWidgetOutline: asCssVariable(listFilterWidgetOutline),
  listFilterWidgetNoMatchesOutline: asCssVariable(listFilterWidgetNoMatchesOutline),
  listFilterWidgetShadow: asCssVariable(listFilterWidgetShadow),
  inputBoxStyles: defaultInputBoxStyles,
  toggleStyles: defaultToggleStyles
};
const defaultCountBadgeStyles = {
  badgeBackground: asCssVariable(badgeBackground),
  badgeForeground: asCssVariable(badgeForeground),
  badgeBorder: asCssVariable(contrastBorder)
};
({
  breadcrumbsBackground: asCssVariable(breadcrumbsBackground),
  breadcrumbsForeground: asCssVariable(breadcrumbsForeground),
  breadcrumbsHoverForeground: asCssVariable(breadcrumbsFocusForeground),
  breadcrumbsFocusForeground: asCssVariable(breadcrumbsFocusForeground),
  breadcrumbsFocusAndSelectionForeground: asCssVariable(breadcrumbsActiveSelectionForeground)
});
const defaultListStyles = {
  listBackground: void 0,
  listInactiveFocusForeground: void 0,
  listFocusBackground: asCssVariable(listFocusBackground),
  listFocusForeground: asCssVariable(listFocusForeground),
  listFocusOutline: asCssVariable(listFocusOutline),
  listActiveSelectionBackground: asCssVariable(listActiveSelectionBackground),
  listActiveSelectionForeground: asCssVariable(listActiveSelectionForeground),
  listActiveSelectionIconForeground: asCssVariable(listActiveSelectionIconForeground),
  listFocusAndSelectionOutline: asCssVariable(listFocusAndSelectionOutline),
  listFocusAndSelectionBackground: asCssVariable(listActiveSelectionBackground),
  listFocusAndSelectionForeground: asCssVariable(listActiveSelectionForeground),
  listInactiveSelectionBackground: asCssVariable(listInactiveSelectionBackground),
  listInactiveSelectionIconForeground: asCssVariable(listInactiveSelectionIconForeground),
  listInactiveSelectionForeground: asCssVariable(listInactiveSelectionForeground),
  listInactiveFocusBackground: asCssVariable(listInactiveFocusBackground),
  listInactiveFocusOutline: asCssVariable(listInactiveFocusOutline),
  listHoverBackground: asCssVariable(listHoverBackground),
  listHoverForeground: asCssVariable(listHoverForeground),
  listDropBackground: asCssVariable(listDropBackground),
  listSelectionOutline: asCssVariable(activeContrastBorder),
  listHoverOutline: asCssVariable(activeContrastBorder),
  treeIndentGuidesStroke: asCssVariable(treeIndentGuidesStroke),
  treeInactiveIndentGuidesStroke: asCssVariable(treeInactiveIndentGuidesStroke),
  tableColumnsBorder: asCssVariable(tableColumnsBorder),
  tableOddRowsBackgroundColor: asCssVariable(tableOddRowsBackgroundColor)
};
function getListStyles(override) {
  return overrideStyles(override, defaultListStyles);
}
const defaultSelectBoxStyles = {
  selectBackground: asCssVariable(selectBackground),
  selectListBackground: asCssVariable(selectListBackground),
  selectForeground: asCssVariable(selectForeground),
  decoratorRightForeground: asCssVariable(pickerGroupForeground),
  selectBorder: asCssVariable(selectBorder),
  focusBorder: asCssVariable(focusBorder),
  listFocusBackground: asCssVariable(quickInputListFocusBackground),
  listInactiveSelectionIconForeground: asCssVariable(quickInputListFocusIconForeground),
  listFocusForeground: asCssVariable(quickInputListFocusForeground),
  listFocusOutline: asCssVariableWithDefault(activeContrastBorder, Color.transparent.toString()),
  listHoverBackground: asCssVariable(listHoverBackground),
  listHoverForeground: asCssVariable(listHoverForeground),
  listHoverOutline: asCssVariable(activeContrastBorder),
  selectListBorder: asCssVariable(editorWidgetBorder),
  listBackground: void 0,
  listActiveSelectionBackground: void 0,
  listActiveSelectionForeground: void 0,
  listActiveSelectionIconForeground: void 0,
  listFocusAndSelectionBackground: void 0,
  listDropBackground: void 0,
  listInactiveSelectionBackground: void 0,
  listInactiveSelectionForeground: void 0,
  listInactiveFocusBackground: void 0,
  listInactiveFocusOutline: void 0,
  listSelectionOutline: void 0,
  listFocusAndSelectionForeground: void 0,
  listFocusAndSelectionOutline: void 0,
  listInactiveFocusForeground: void 0,
  tableColumnsBorder: void 0,
  tableOddRowsBackgroundColor: void 0,
  treeIndentGuidesStroke: void 0,
  treeInactiveIndentGuidesStroke: void 0
};
const defaultMenuStyles = {
  shadowColor: asCssVariable(widgetShadow),
  borderColor: asCssVariable(menuBorder),
  foregroundColor: asCssVariable(menuForeground),
  backgroundColor: asCssVariable(menuBackground),
  selectionForegroundColor: asCssVariable(menuSelectionForeground),
  selectionBackgroundColor: asCssVariable(menuSelectionBackground),
  selectionBorderColor: asCssVariable(menuSelectionBorder),
  separatorColor: asCssVariable(menuSeparatorBackground),
  scrollbarShadow: asCssVariable(scrollbarShadow),
  scrollbarSliderBackground: asCssVariable(scrollbarSliderBackground),
  scrollbarSliderHoverBackground: asCssVariable(scrollbarSliderHoverBackground),
  scrollbarSliderActiveBackground: asCssVariable(scrollbarSliderActiveBackground)
};
var __decorate$1R = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1O = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
const acceptSelectedActionCommand = "acceptSelectedCodeAction";
const previewSelectedActionCommand = "previewSelectedCodeAction";
class HeaderRenderer {
  get templateId() {
    return "header";
  }
  renderTemplate(container2) {
    container2.classList.add("group-header");
    const text2 = document.createElement("span");
    container2.append(text2);
    return { container: container2, text: text2 };
  }
  renderElement(element, _index, templateData) {
    var _a2, _b2;
    templateData.text.textContent = (_b2 = (_a2 = element.group) === null || _a2 === void 0 ? void 0 : _a2.title) !== null && _b2 !== void 0 ? _b2 : "";
  }
  disposeTemplate(_templateData) {
  }
}
let ActionItemRenderer = class ActionItemRenderer2 {
  get templateId() {
    return "action";
  }
  constructor(_supportsPreview, _keybindingService) {
    this._supportsPreview = _supportsPreview;
    this._keybindingService = _keybindingService;
  }
  renderTemplate(container2) {
    container2.classList.add(this.templateId);
    const icon = document.createElement("div");
    icon.className = "icon";
    container2.append(icon);
    const text2 = document.createElement("span");
    text2.className = "title";
    container2.append(text2);
    const keybinding = new KeybindingLabel(container2, OS);
    return { container: container2, icon, text: text2, keybinding };
  }
  renderElement(element, _index, data) {
    var _a2, _b2, _c2;
    if ((_a2 = element.group) === null || _a2 === void 0 ? void 0 : _a2.icon) {
      data.icon.className = ThemeIcon.asClassName(element.group.icon);
      if (element.group.icon.color) {
        data.icon.style.color = asCssVariable(element.group.icon.color.id);
      }
    } else {
      data.icon.className = ThemeIcon.asClassName(Codicon.lightBulb);
      data.icon.style.color = "var(--vscode-editorLightBulb-foreground)";
    }
    if (!element.item || !element.label) {
      return;
    }
    data.text.textContent = stripNewlines(element.label);
    data.keybinding.set(element.keybinding);
    setVisibility(!!element.keybinding, data.keybinding.element);
    const actionTitle = (_b2 = this._keybindingService.lookupKeybinding(acceptSelectedActionCommand)) === null || _b2 === void 0 ? void 0 : _b2.getLabel();
    const previewTitle = (_c2 = this._keybindingService.lookupKeybinding(previewSelectedActionCommand)) === null || _c2 === void 0 ? void 0 : _c2.getLabel();
    data.container.classList.toggle("option-disabled", element.disabled);
    if (element.disabled) {
      data.container.title = element.label;
    } else if (actionTitle && previewTitle) {
      if (this._supportsPreview) {
        data.container.title = localize({ key: "label-preview", comment: ['placeholders are keybindings, e.g "F2 to apply, Shift+F2 to preview"'] }, "{0} to apply, {1} to preview", actionTitle, previewTitle);
      } else {
        data.container.title = localize({ key: "label", comment: ['placeholder is a keybinding, e.g "F2 to apply"'] }, "{0} to apply", actionTitle);
      }
    } else {
      data.container.title = "";
    }
  }
  disposeTemplate(_templateData) {
  }
};
ActionItemRenderer = __decorate$1R([
  __param$1O(1, IKeybindingService)
], ActionItemRenderer);
class AcceptSelectedEvent extends UIEvent {
  constructor() {
    super("acceptSelectedAction");
  }
}
class PreviewSelectedEvent extends UIEvent {
  constructor() {
    super("previewSelectedAction");
  }
}
let ActionList = class ActionList2 extends Disposable {
  constructor(user, preview, items, _delegate, _contextViewService, _keybindingService) {
    super();
    this._delegate = _delegate;
    this._contextViewService = _contextViewService;
    this._keybindingService = _keybindingService;
    this._actionLineHeight = 24;
    this._headerLineHeight = 26;
    this.domNode = document.createElement("div");
    this.domNode.classList.add("actionList");
    const virtualDelegate = {
      getHeight: (element) => element.kind === "header" ? this._headerLineHeight : this._actionLineHeight,
      getTemplateId: (element) => element.kind
    };
    this._list = this._register(new List(user, this.domNode, virtualDelegate, [
      new ActionItemRenderer(preview, this._keybindingService),
      new HeaderRenderer()
    ], {
      keyboardSupport: false,
      accessibilityProvider: {
        getAriaLabel: (element) => {
          if (element.kind === "action") {
            let label = element.label ? stripNewlines(element === null || element === void 0 ? void 0 : element.label) : "";
            if (element.disabled) {
              label = localize({ key: "customQuickFixWidget.labels", comment: [`Action widget labels for accessibility.`] }, "{0}, Disabled Reason: {1}", label, element.disabled);
            }
            return label;
          }
          return null;
        },
        getWidgetAriaLabel: () => localize({ key: "customQuickFixWidget", comment: [`An action widget option`] }, "Action Widget"),
        getRole: (e) => e.kind === "action" ? "option" : "separator",
        getWidgetRole: () => "listbox"
      }
    }));
    this._list.style(defaultListStyles);
    this._register(this._list.onMouseClick((e) => this.onListClick(e)));
    this._register(this._list.onMouseOver((e) => this.onListHover(e)));
    this._register(this._list.onDidChangeFocus(() => this._list.domFocus()));
    this._register(this._list.onDidChangeSelection((e) => this.onListSelection(e)));
    this._allMenuItems = items;
    this._list.splice(0, this._list.length, this._allMenuItems);
    if (this._list.length) {
      this.focusNext();
    }
  }
  focusCondition(element) {
    return !element.disabled && element.kind === "action";
  }
  hide(didCancel) {
    this._delegate.onHide(didCancel);
    this._contextViewService.hideContextView();
  }
  layout(minWidth) {
    const numHeaders = this._allMenuItems.filter((item) => item.kind === "header").length;
    const itemsHeight = this._allMenuItems.length * this._actionLineHeight;
    const heightWithHeaders = itemsHeight + numHeaders * this._headerLineHeight - numHeaders * this._actionLineHeight;
    this._list.layout(heightWithHeaders);
    const itemWidths = this._allMenuItems.map((_, index) => {
      const element = document.getElementById(this._list.getElementID(index));
      if (element) {
        element.style.width = "auto";
        const width2 = element.getBoundingClientRect().width;
        element.style.width = "";
        return width2;
      }
      return 0;
    });
    const width = Math.max(...itemWidths, minWidth);
    const maxVhPrecentage = 0.7;
    const height = Math.min(heightWithHeaders, document.body.clientHeight * maxVhPrecentage);
    this._list.layout(height, width);
    this.domNode.style.height = `${height}px`;
    this._list.domFocus();
    return width;
  }
  focusPrevious() {
    this._list.focusPrevious(1, true, void 0, this.focusCondition);
  }
  focusNext() {
    this._list.focusNext(1, true, void 0, this.focusCondition);
  }
  acceptSelected(preview) {
    const focused = this._list.getFocus();
    if (focused.length === 0) {
      return;
    }
    const focusIndex = focused[0];
    const element = this._list.element(focusIndex);
    if (!this.focusCondition(element)) {
      return;
    }
    const event = preview ? new PreviewSelectedEvent() : new AcceptSelectedEvent();
    this._list.setSelection([focusIndex], event);
  }
  onListSelection(e) {
    if (!e.elements.length) {
      return;
    }
    const element = e.elements[0];
    if (element.item && this.focusCondition(element)) {
      this._delegate.onSelect(element.item, e.browserEvent instanceof PreviewSelectedEvent);
    } else {
      this._list.setSelection([]);
    }
  }
  onListHover(e) {
    this._list.setFocus(typeof e.index === "number" ? [e.index] : []);
  }
  onListClick(e) {
    if (e.element && this.focusCondition(e.element)) {
      this._list.setFocus([]);
    }
  }
};
ActionList = __decorate$1R([
  __param$1O(4, IContextViewService),
  __param$1O(5, IKeybindingService)
], ActionList);
function stripNewlines(str2) {
  return str2.replace(/\r\n|\r|\n/g, " ");
}
var __decorate$1Q = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1N = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
const ActionWidgetContextKeys = {
  Visible: new RawContextKey("codeActionMenuVisible", false, localize("codeActionMenuVisible", "Whether the action widget list is visible"))
};
const IActionWidgetService = createDecorator("actionWidgetService");
let ActionWidgetService = class ActionWidgetService2 extends Disposable {
  get isVisible() {
    return ActionWidgetContextKeys.Visible.getValue(this._contextKeyService) || false;
  }
  constructor(_contextViewService, _contextKeyService, _instantiationService) {
    super();
    this._contextViewService = _contextViewService;
    this._contextKeyService = _contextKeyService;
    this._instantiationService = _instantiationService;
    this._list = this._register(new MutableDisposable());
  }
  show(user, supportsPreview, items, delegate, anchor, container2, actionBarActions) {
    const visibleContext = ActionWidgetContextKeys.Visible.bindTo(this._contextKeyService);
    const list2 = this._instantiationService.createInstance(ActionList, user, supportsPreview, items, delegate);
    this._contextViewService.showContextView({
      getAnchor: () => anchor,
      render: (container3) => {
        visibleContext.set(true);
        return this._renderWidget(container3, list2, actionBarActions !== null && actionBarActions !== void 0 ? actionBarActions : []);
      },
      onHide: (didCancel) => {
        visibleContext.reset();
        this._onWidgetClosed(didCancel);
      }
    }, container2, false);
  }
  acceptSelected(preview) {
    var _a2;
    (_a2 = this._list.value) === null || _a2 === void 0 ? void 0 : _a2.acceptSelected(preview);
  }
  focusPrevious() {
    var _a2, _b2;
    (_b2 = (_a2 = this._list) === null || _a2 === void 0 ? void 0 : _a2.value) === null || _b2 === void 0 ? void 0 : _b2.focusPrevious();
  }
  focusNext() {
    var _a2, _b2;
    (_b2 = (_a2 = this._list) === null || _a2 === void 0 ? void 0 : _a2.value) === null || _b2 === void 0 ? void 0 : _b2.focusNext();
  }
  hide() {
    var _a2;
    (_a2 = this._list.value) === null || _a2 === void 0 ? void 0 : _a2.hide();
    this._list.clear();
  }
  _renderWidget(element, list2, actionBarActions) {
    var _a2;
    const widget = document.createElement("div");
    widget.classList.add("action-widget");
    element.appendChild(widget);
    this._list.value = list2;
    if (this._list.value) {
      widget.appendChild(this._list.value.domNode);
    } else {
      throw new Error("List has no value");
    }
    const renderDisposables = new DisposableStore();
    const menuBlock = document.createElement("div");
    const block = element.appendChild(menuBlock);
    block.classList.add("context-view-block");
    renderDisposables.add(addDisposableListener(block, EventType$1.MOUSE_DOWN, (e) => e.stopPropagation()));
    const pointerBlockDiv = document.createElement("div");
    const pointerBlock = element.appendChild(pointerBlockDiv);
    pointerBlock.classList.add("context-view-pointerBlock");
    renderDisposables.add(addDisposableListener(pointerBlock, EventType$1.POINTER_MOVE, () => pointerBlock.remove()));
    renderDisposables.add(addDisposableListener(pointerBlock, EventType$1.MOUSE_DOWN, () => pointerBlock.remove()));
    let actionBarWidth = 0;
    if (actionBarActions.length) {
      const actionBar = this._createActionBar(".action-widget-action-bar", actionBarActions);
      if (actionBar) {
        widget.appendChild(actionBar.getContainer().parentElement);
        renderDisposables.add(actionBar);
        actionBarWidth = actionBar.getContainer().offsetWidth;
      }
    }
    const width = (_a2 = this._list.value) === null || _a2 === void 0 ? void 0 : _a2.layout(actionBarWidth);
    widget.style.width = `${width}px`;
    const focusTracker = renderDisposables.add(trackFocus(element));
    renderDisposables.add(focusTracker.onDidBlur(() => this.hide()));
    return renderDisposables;
  }
  _createActionBar(className3, actions) {
    if (!actions.length) {
      return void 0;
    }
    const container2 = $$d(className3);
    const actionBar = new ActionBar(container2);
    actionBar.push(actions, { icon: false, label: true });
    return actionBar;
  }
  _onWidgetClosed(didCancel) {
    var _a2;
    (_a2 = this._list.value) === null || _a2 === void 0 ? void 0 : _a2.hide(didCancel);
  }
};
ActionWidgetService = __decorate$1Q([
  __param$1N(0, IContextViewService),
  __param$1N(1, IContextKeyService),
  __param$1N(2, IInstantiationService)
], ActionWidgetService);
registerSingleton(
  IActionWidgetService,
  ActionWidgetService,
  1
  /* InstantiationType.Delayed */
);
const weight$3 = 100 + 1e3;
registerAction2(class extends Action2 {
  constructor() {
    super({
      id: "hideCodeActionWidget",
      title: {
        value: localize("hideCodeActionWidget.title", "Hide action widget"),
        original: "Hide action widget"
      },
      precondition: ActionWidgetContextKeys.Visible,
      keybinding: {
        weight: weight$3,
        primary: 9,
        secondary: [
          1024 | 9
          /* KeyCode.Escape */
        ]
      }
    });
  }
  run(accessor) {
    accessor.get(IActionWidgetService).hide();
  }
});
registerAction2(class extends Action2 {
  constructor() {
    super({
      id: "selectPrevCodeAction",
      title: {
        value: localize("selectPrevCodeAction.title", "Select previous action"),
        original: "Select previous action"
      },
      precondition: ActionWidgetContextKeys.Visible,
      keybinding: {
        weight: weight$3,
        primary: 16,
        secondary: [
          2048 | 16
          /* KeyCode.UpArrow */
        ],
        mac: { primary: 16, secondary: [
          2048 | 16,
          256 | 46
          /* KeyCode.KeyP */
        ] }
      }
    });
  }
  run(accessor) {
    const widgetService = accessor.get(IActionWidgetService);
    if (widgetService instanceof ActionWidgetService) {
      widgetService.focusPrevious();
    }
  }
});
registerAction2(class extends Action2 {
  constructor() {
    super({
      id: "selectNextCodeAction",
      title: {
        value: localize("selectNextCodeAction.title", "Select next action"),
        original: "Select next action"
      },
      precondition: ActionWidgetContextKeys.Visible,
      keybinding: {
        weight: weight$3,
        primary: 18,
        secondary: [
          2048 | 18
          /* KeyCode.DownArrow */
        ],
        mac: { primary: 18, secondary: [
          2048 | 18,
          256 | 44
          /* KeyCode.KeyN */
        ] }
      }
    });
  }
  run(accessor) {
    const widgetService = accessor.get(IActionWidgetService);
    if (widgetService instanceof ActionWidgetService) {
      widgetService.focusNext();
    }
  }
});
registerAction2(class extends Action2 {
  constructor() {
    super({
      id: acceptSelectedActionCommand,
      title: {
        value: localize("acceptSelected.title", "Accept selected action"),
        original: "Accept selected action"
      },
      precondition: ActionWidgetContextKeys.Visible,
      keybinding: {
        weight: weight$3,
        primary: 3,
        secondary: [
          2048 | 89
          /* KeyCode.Period */
        ]
      }
    });
  }
  run(accessor) {
    const widgetService = accessor.get(IActionWidgetService);
    if (widgetService instanceof ActionWidgetService) {
      widgetService.acceptSelected();
    }
  }
});
registerAction2(class extends Action2 {
  constructor() {
    super({
      id: previewSelectedActionCommand,
      title: {
        value: localize("previewSelected.title", "Preview selected action"),
        original: "Preview selected action"
      },
      precondition: ActionWidgetContextKeys.Visible,
      keybinding: {
        weight: weight$3,
        primary: 2048 | 3
      }
    });
  }
  run(accessor) {
    const widgetService = accessor.get(IActionWidgetService);
    if (widgetService instanceof ActionWidgetService) {
      widgetService.acceptSelected(true);
    }
  }
});
var MarkerSeverity$2;
(function(MarkerSeverity2) {
  MarkerSeverity2[MarkerSeverity2["Hint"] = 1] = "Hint";
  MarkerSeverity2[MarkerSeverity2["Info"] = 2] = "Info";
  MarkerSeverity2[MarkerSeverity2["Warning"] = 4] = "Warning";
  MarkerSeverity2[MarkerSeverity2["Error"] = 8] = "Error";
})(MarkerSeverity$2 || (MarkerSeverity$2 = {}));
(function(MarkerSeverity2) {
  function compare4(a, b) {
    return b - a;
  }
  MarkerSeverity2.compare = compare4;
  const _displayStrings = /* @__PURE__ */ Object.create(null);
  _displayStrings[MarkerSeverity2.Error] = localize("sev.error", "Error");
  _displayStrings[MarkerSeverity2.Warning] = localize("sev.warning", "Warning");
  _displayStrings[MarkerSeverity2.Info] = localize("sev.info", "Info");
  function toString3(a) {
    return _displayStrings[a] || "";
  }
  MarkerSeverity2.toString = toString3;
  function fromSeverity(severity) {
    switch (severity) {
      case Severity$2.Error:
        return MarkerSeverity2.Error;
      case Severity$2.Warning:
        return MarkerSeverity2.Warning;
      case Severity$2.Info:
        return MarkerSeverity2.Info;
      case Severity$2.Ignore:
        return MarkerSeverity2.Hint;
    }
  }
  MarkerSeverity2.fromSeverity = fromSeverity;
  function toSeverity(severity) {
    switch (severity) {
      case MarkerSeverity2.Error:
        return Severity$2.Error;
      case MarkerSeverity2.Warning:
        return Severity$2.Warning;
      case MarkerSeverity2.Info:
        return Severity$2.Info;
      case MarkerSeverity2.Hint:
        return Severity$2.Ignore;
    }
  }
  MarkerSeverity2.toSeverity = toSeverity;
})(MarkerSeverity$2 || (MarkerSeverity$2 = {}));
var IMarkerData;
(function(IMarkerData2) {
  const emptyString = "";
  function makeKey(markerData) {
    return makeKeyOptionalMessage(markerData, true);
  }
  IMarkerData2.makeKey = makeKey;
  function makeKeyOptionalMessage(markerData, useMessage) {
    const result2 = [emptyString];
    if (markerData.source) {
      result2.push(markerData.source.replace("¦", "\\¦"));
    } else {
      result2.push(emptyString);
    }
    if (markerData.code) {
      if (typeof markerData.code === "string") {
        result2.push(markerData.code.replace("¦", "\\¦"));
      } else {
        result2.push(markerData.code.value.replace("¦", "\\¦"));
      }
    } else {
      result2.push(emptyString);
    }
    if (markerData.severity !== void 0 && markerData.severity !== null) {
      result2.push(MarkerSeverity$2.toString(markerData.severity));
    } else {
      result2.push(emptyString);
    }
    if (markerData.message && useMessage) {
      result2.push(markerData.message.replace("¦", "\\¦"));
    } else {
      result2.push(emptyString);
    }
    if (markerData.startLineNumber !== void 0 && markerData.startLineNumber !== null) {
      result2.push(markerData.startLineNumber.toString());
    } else {
      result2.push(emptyString);
    }
    if (markerData.startColumn !== void 0 && markerData.startColumn !== null) {
      result2.push(markerData.startColumn.toString());
    } else {
      result2.push(emptyString);
    }
    if (markerData.endLineNumber !== void 0 && markerData.endLineNumber !== null) {
      result2.push(markerData.endLineNumber.toString());
    } else {
      result2.push(emptyString);
    }
    if (markerData.endColumn !== void 0 && markerData.endColumn !== null) {
      result2.push(markerData.endColumn.toString());
    } else {
      result2.push(emptyString);
    }
    result2.push(emptyString);
    return result2.join("¦");
  }
  IMarkerData2.makeKeyOptionalMessage = makeKeyOptionalMessage;
})(IMarkerData || (IMarkerData = {}));
const IMarkerService = createDecorator("markerService");
const SUPPORTED_CODE_ACTIONS = new RawContextKey("supportedCodeAction", "");
class CodeActionOracle extends Disposable {
  constructor(_editor, _markerService, _signalChange, _delay = 250) {
    super();
    this._editor = _editor;
    this._markerService = _markerService;
    this._signalChange = _signalChange;
    this._delay = _delay;
    this._autoTriggerTimer = this._register(new TimeoutTimer());
    this._register(this._markerService.onMarkerChanged((e) => this._onMarkerChanges(e)));
    this._register(this._editor.onDidChangeCursorPosition(() => this._tryAutoTrigger()));
  }
  trigger(trigger2) {
    const selection = this._getRangeOfSelectionUnlessWhitespaceEnclosed(trigger2);
    this._signalChange(selection ? { trigger: trigger2, selection } : void 0);
  }
  _onMarkerChanges(resources) {
    const model = this._editor.getModel();
    if (model && resources.some((resource) => isEqual(resource, model.uri))) {
      this._tryAutoTrigger();
    }
  }
  _tryAutoTrigger() {
    this._autoTriggerTimer.cancelAndSet(() => {
      this.trigger({ type: 2, triggerAction: CodeActionTriggerSource.Default });
    }, this._delay);
  }
  _getRangeOfSelectionUnlessWhitespaceEnclosed(trigger2) {
    if (!this._editor.hasModel()) {
      return void 0;
    }
    const model = this._editor.getModel();
    const selection = this._editor.getSelection();
    if (selection.isEmpty() && trigger2.type === 2) {
      const { lineNumber, column } = selection.getPosition();
      const line = model.getLineContent(lineNumber);
      if (line.length === 0) {
        return void 0;
      } else if (column === 1) {
        if (/\s/.test(line[0])) {
          return void 0;
        }
      } else if (column === model.getLineMaxColumn(lineNumber)) {
        if (/\s/.test(line[line.length - 1])) {
          return void 0;
        }
      } else {
        if (/\s/.test(line[column - 2]) && /\s/.test(line[column - 1])) {
          return void 0;
        }
      }
    }
    return selection;
  }
}
var CodeActionsState;
(function(CodeActionsState2) {
  CodeActionsState2.Empty = {
    type: 0
    /* Type.Empty */
  };
  class Triggered {
    constructor(trigger2, position, _cancellablePromise) {
      this.trigger = trigger2;
      this.position = position;
      this._cancellablePromise = _cancellablePromise;
      this.type = 1;
      this.actions = _cancellablePromise.catch((e) => {
        if (isCancellationError(e)) {
          return emptyCodeActionSet;
        }
        throw e;
      });
    }
    cancel() {
      this._cancellablePromise.cancel();
    }
  }
  CodeActionsState2.Triggered = Triggered;
})(CodeActionsState || (CodeActionsState = {}));
const emptyCodeActionSet = Object.freeze({
  allActions: [],
  validActions: [],
  dispose: () => {
  },
  documentation: [],
  hasAutoFix: false
});
class CodeActionModel extends Disposable {
  constructor(_editor, _registry2, _markerService, contextKeyService, _progressService) {
    super();
    this._editor = _editor;
    this._registry = _registry2;
    this._markerService = _markerService;
    this._progressService = _progressService;
    this._codeActionOracle = this._register(new MutableDisposable());
    this._state = CodeActionsState.Empty;
    this._onDidChangeState = this._register(new Emitter$1());
    this.onDidChangeState = this._onDidChangeState.event;
    this._disposed = false;
    this._supportedCodeActions = SUPPORTED_CODE_ACTIONS.bindTo(contextKeyService);
    this._register(this._editor.onDidChangeModel(() => this._update()));
    this._register(this._editor.onDidChangeModelLanguage(() => this._update()));
    this._register(this._registry.onDidChange(() => this._update()));
    this._update();
  }
  dispose() {
    if (this._disposed) {
      return;
    }
    this._disposed = true;
    super.dispose();
    this.setState(CodeActionsState.Empty, true);
  }
  _update() {
    if (this._disposed) {
      return;
    }
    this._codeActionOracle.value = void 0;
    this.setState(CodeActionsState.Empty);
    const model = this._editor.getModel();
    if (model && this._registry.has(model) && !this._editor.getOption(
      89
      /* EditorOption.readOnly */
    )) {
      const supportedActions = this._registry.all(model).flatMap((provider) => {
        var _a2;
        return (_a2 = provider.providedCodeActionKinds) !== null && _a2 !== void 0 ? _a2 : [];
      });
      this._supportedCodeActions.set(supportedActions.join(" "));
      this._codeActionOracle.value = new CodeActionOracle(this._editor, this._markerService, (trigger2) => {
        var _a2;
        if (!trigger2) {
          this.setState(CodeActionsState.Empty);
          return;
        }
        const actions = createCancelablePromise((token) => getCodeActions(this._registry, model, trigger2.selection, trigger2.trigger, Progress.None, token));
        if (trigger2.trigger.type === 1) {
          (_a2 = this._progressService) === null || _a2 === void 0 ? void 0 : _a2.showWhile(actions, 250);
        }
        this.setState(new CodeActionsState.Triggered(trigger2.trigger, trigger2.selection.getStartPosition(), actions));
      }, void 0);
      this._codeActionOracle.value.trigger({ type: 2, triggerAction: CodeActionTriggerSource.Default });
    } else {
      this._supportedCodeActions.reset();
    }
  }
  trigger(trigger2) {
    var _a2;
    (_a2 = this._codeActionOracle.value) === null || _a2 === void 0 ? void 0 : _a2.trigger(trigger2);
  }
  setState(newState, skipNotify) {
    if (newState === this._state) {
      return;
    }
    if (this._state.type === 1) {
      this._state.cancel();
    }
    this._state = newState;
    if (!skipNotify && !this._disposed) {
      this._onDidChangeState.fire(newState);
    }
  }
}
var __decorate$1P = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1M = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$1j = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
let CodeActionController = class CodeActionController2 extends Disposable {
  static get(editor2) {
    return editor2.getContribution(CodeActionController2.ID);
  }
  constructor(editor2, markerService, contextKeyService, instantiationService, languageFeaturesService, progressService, _commandService, _configurationService, _actionWidgetService, _instantiationService) {
    super();
    this._commandService = _commandService;
    this._configurationService = _configurationService;
    this._actionWidgetService = _actionWidgetService;
    this._instantiationService = _instantiationService;
    this._activeCodeActions = this._register(new MutableDisposable());
    this._showDisabled = false;
    this._disposed = false;
    this._editor = editor2;
    this._model = this._register(new CodeActionModel(this._editor, languageFeaturesService.codeActionProvider, markerService, contextKeyService, progressService));
    this._register(this._model.onDidChangeState((newState) => this.update(newState)));
    this._lightBulbWidget = new Lazy(() => {
      const widget = this._editor.getContribution(LightBulbWidget.ID);
      if (widget) {
        this._register(widget.onClick((e) => this.showCodeActionList(e.actions, e, { includeDisabledActions: false, fromLightbulb: true })));
      }
      return widget;
    });
    this._resolver = instantiationService.createInstance(CodeActionKeybindingResolver);
    this._register(this._editor.onDidLayoutChange(() => this._actionWidgetService.hide()));
  }
  dispose() {
    this._disposed = true;
    super.dispose();
  }
  showCodeActions(_trigger, actions, at2) {
    return this.showCodeActionList(actions, at2, { includeDisabledActions: false, fromLightbulb: false });
  }
  manualTriggerAtCurrentPosition(notAvailableMessage, triggerAction, filter2, autoApply) {
    var _a2;
    if (!this._editor.hasModel()) {
      return;
    }
    (_a2 = MessageController.get(this._editor)) === null || _a2 === void 0 ? void 0 : _a2.closeMessage();
    const triggerPosition = this._editor.getPosition();
    this._trigger({ type: 1, triggerAction, filter: filter2, autoApply, context: { notAvailableMessage, position: triggerPosition } });
  }
  _trigger(trigger2) {
    return this._model.trigger(trigger2);
  }
  _applyCodeAction(action, retrigger, preview) {
    return __awaiter$1j(this, void 0, void 0, function* () {
      try {
        yield this._instantiationService.invokeFunction(applyCodeAction, action, ApplyCodeActionReason.FromCodeActions, { preview, editor: this._editor });
      } finally {
        if (retrigger) {
          this._trigger({ type: 2, triggerAction: CodeActionTriggerSource.QuickFix, filter: {} });
        }
      }
    });
  }
  update(newState) {
    var _a2, _b2, _c2, _d2, _e2, _f2, _g2;
    return __awaiter$1j(this, void 0, void 0, function* () {
      if (newState.type !== 1) {
        (_a2 = this._lightBulbWidget.rawValue) === null || _a2 === void 0 ? void 0 : _a2.hide();
        return;
      }
      let actions;
      try {
        actions = yield newState.actions;
      } catch (e) {
        onUnexpectedError(e);
        return;
      }
      if (this._disposed) {
        return;
      }
      (_b2 = this._lightBulbWidget.value) === null || _b2 === void 0 ? void 0 : _b2.update(actions, newState.trigger, newState.position);
      if (newState.trigger.type === 1) {
        if ((_c2 = newState.trigger.filter) === null || _c2 === void 0 ? void 0 : _c2.include) {
          const validActionToApply = this.tryGetValidActionToApply(newState.trigger, actions);
          if (validActionToApply) {
            try {
              (_d2 = this._lightBulbWidget.value) === null || _d2 === void 0 ? void 0 : _d2.hide();
              yield this._applyCodeAction(validActionToApply, false, false);
            } finally {
              actions.dispose();
            }
            return;
          }
          if (newState.trigger.context) {
            const invalidAction = this.getInvalidActionThatWouldHaveBeenApplied(newState.trigger, actions);
            if (invalidAction && invalidAction.action.disabled) {
              (_e2 = MessageController.get(this._editor)) === null || _e2 === void 0 ? void 0 : _e2.showMessage(invalidAction.action.disabled, newState.trigger.context.position);
              actions.dispose();
              return;
            }
          }
        }
        const includeDisabledActions = !!((_f2 = newState.trigger.filter) === null || _f2 === void 0 ? void 0 : _f2.include);
        if (newState.trigger.context) {
          if (!actions.allActions.length || !includeDisabledActions && !actions.validActions.length) {
            (_g2 = MessageController.get(this._editor)) === null || _g2 === void 0 ? void 0 : _g2.showMessage(newState.trigger.context.notAvailableMessage, newState.trigger.context.position);
            this._activeCodeActions.value = actions;
            actions.dispose();
            return;
          }
        }
        this._activeCodeActions.value = actions;
        this.showCodeActionList(actions, this.toCoords(newState.position), { includeDisabledActions, fromLightbulb: false });
      } else {
        if (this._actionWidgetService.isVisible) {
          actions.dispose();
        } else {
          this._activeCodeActions.value = actions;
        }
      }
    });
  }
  getInvalidActionThatWouldHaveBeenApplied(trigger2, actions) {
    if (!actions.allActions.length) {
      return void 0;
    }
    if (trigger2.autoApply === "first" && actions.validActions.length === 0 || trigger2.autoApply === "ifSingle" && actions.allActions.length === 1) {
      return actions.allActions.find(({ action }) => action.disabled);
    }
    return void 0;
  }
  tryGetValidActionToApply(trigger2, actions) {
    if (!actions.validActions.length) {
      return void 0;
    }
    if (trigger2.autoApply === "first" && actions.validActions.length > 0 || trigger2.autoApply === "ifSingle" && actions.validActions.length === 1) {
      return actions.validActions[0];
    }
    return void 0;
  }
  showCodeActionList(actions, at2, options) {
    return __awaiter$1j(this, void 0, void 0, function* () {
      const editorDom = this._editor.getDomNode();
      if (!editorDom) {
        return;
      }
      const actionsToShow = options.includeDisabledActions && (this._showDisabled || actions.validActions.length === 0) ? actions.allActions : actions.validActions;
      if (!actionsToShow.length) {
        return;
      }
      const anchor = Position$2.isIPosition(at2) ? this.toCoords(at2) : at2;
      const delegate = {
        onSelect: (action, preview) => __awaiter$1j(this, void 0, void 0, function* () {
          this._applyCodeAction(
            action,
            /* retrigger */
            true,
            !!preview
          );
          this._actionWidgetService.hide();
        }),
        onHide: () => {
          var _a2;
          (_a2 = this._editor) === null || _a2 === void 0 ? void 0 : _a2.focus();
        }
      };
      this._actionWidgetService.show("codeActionWidget", true, toMenuItems(actionsToShow, this._shouldShowHeaders(), this._resolver.getResolver()), delegate, anchor, editorDom, this._getActionBarActions(actions, at2, options));
    });
  }
  toCoords(position) {
    if (!this._editor.hasModel()) {
      return { x: 0, y: 0 };
    }
    this._editor.revealPosition(
      position,
      1
      /* ScrollType.Immediate */
    );
    this._editor.render();
    const cursorCoords = this._editor.getScrolledVisiblePosition(position);
    const editorCoords = getDomNodePagePosition(this._editor.getDomNode());
    const x = editorCoords.left + cursorCoords.left;
    const y = editorCoords.top + cursorCoords.top + cursorCoords.height;
    return { x, y };
  }
  _shouldShowHeaders() {
    var _a2;
    const model = (_a2 = this._editor) === null || _a2 === void 0 ? void 0 : _a2.getModel();
    return this._configurationService.getValue("editor.codeActionWidget.showHeaders", { resource: model === null || model === void 0 ? void 0 : model.uri });
  }
  _getActionBarActions(actions, at2, options) {
    if (options.fromLightbulb) {
      return [];
    }
    const resultActions = actions.documentation.map((command) => {
      var _a2;
      return {
        id: command.id,
        label: command.title,
        tooltip: (_a2 = command.tooltip) !== null && _a2 !== void 0 ? _a2 : "",
        class: void 0,
        enabled: true,
        run: () => {
          var _a3;
          return this._commandService.executeCommand(command.id, ...(_a3 = command.arguments) !== null && _a3 !== void 0 ? _a3 : []);
        }
      };
    });
    if (options.includeDisabledActions && actions.validActions.length > 0 && actions.allActions.length !== actions.validActions.length) {
      resultActions.push(this._showDisabled ? {
        id: "hideMoreActions",
        label: localize("hideMoreActions", "Hide Disabled"),
        enabled: true,
        tooltip: "",
        class: void 0,
        run: () => {
          this._showDisabled = false;
          return this.showCodeActionList(actions, at2, options);
        }
      } : {
        id: "showMoreActions",
        label: localize("showMoreActions", "Show Disabled"),
        enabled: true,
        tooltip: "",
        class: void 0,
        run: () => {
          this._showDisabled = true;
          return this.showCodeActionList(actions, at2, options);
        }
      });
    }
    return resultActions;
  }
};
CodeActionController.ID = "editor.contrib.codeActionController";
CodeActionController = __decorate$1P([
  __param$1M(1, IMarkerService),
  __param$1M(2, IContextKeyService),
  __param$1M(3, IInstantiationService),
  __param$1M(4, ILanguageFeaturesService),
  __param$1M(5, IEditorProgressService),
  __param$1M(6, ICommandService),
  __param$1M(7, IConfigurationService),
  __param$1M(8, IActionWidgetService),
  __param$1M(9, IInstantiationService)
], CodeActionController);
function contextKeyForSupportedActions(kind) {
  return ContextKeyExpr.regex(SUPPORTED_CODE_ACTIONS.keys()[0], new RegExp("(\\s|^)" + escapeRegExpCharacters(kind.value) + "\\b"));
}
const argsSchema = {
  type: "object",
  defaultSnippets: [{ body: { kind: "" } }],
  properties: {
    "kind": {
      type: "string",
      description: localize("args.schema.kind", "Kind of the code action to run.")
    },
    "apply": {
      type: "string",
      description: localize("args.schema.apply", "Controls when the returned actions are applied."),
      default: "ifSingle",
      enum: [
        "first",
        "ifSingle",
        "never"
        /* CodeActionAutoApply.Never */
      ],
      enumDescriptions: [
        localize("args.schema.apply.first", "Always apply the first returned code action."),
        localize("args.schema.apply.ifSingle", "Apply the first returned code action if it is the only one."),
        localize("args.schema.apply.never", "Do not apply the returned code actions.")
      ]
    },
    "preferred": {
      type: "boolean",
      default: false,
      description: localize("args.schema.preferred", "Controls if only preferred code actions should be returned.")
    }
  }
};
function triggerCodeActionsForEditorSelection(editor2, notAvailableMessage, filter2, autoApply, triggerAction = CodeActionTriggerSource.Default) {
  if (editor2.hasModel()) {
    const controller = CodeActionController.get(editor2);
    controller === null || controller === void 0 ? void 0 : controller.manualTriggerAtCurrentPosition(notAvailableMessage, triggerAction, filter2, autoApply);
  }
}
class QuickFixAction extends EditorAction {
  constructor() {
    super({
      id: quickFixCommandId,
      label: localize("quickfix.trigger.label", "Quick Fix..."),
      alias: "Quick Fix...",
      precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasCodeActionsProvider),
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 2048 | 89,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(_accessor, editor2) {
    return triggerCodeActionsForEditorSelection(editor2, localize("editor.action.quickFix.noneMessage", "No code actions available"), void 0, void 0, CodeActionTriggerSource.QuickFix);
  }
}
class CodeActionCommand extends EditorCommand {
  constructor() {
    super({
      id: codeActionCommandId,
      precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasCodeActionsProvider),
      description: {
        description: "Trigger a code action",
        args: [{ name: "args", schema: argsSchema }]
      }
    });
  }
  runEditorCommand(_accessor, editor2, userArgs) {
    const args = CodeActionCommandArgs.fromUser(userArgs, {
      kind: CodeActionKind.Empty,
      apply: "ifSingle"
    });
    return triggerCodeActionsForEditorSelection(editor2, typeof (userArgs === null || userArgs === void 0 ? void 0 : userArgs.kind) === "string" ? args.preferred ? localize("editor.action.codeAction.noneMessage.preferred.kind", "No preferred code actions for '{0}' available", userArgs.kind) : localize("editor.action.codeAction.noneMessage.kind", "No code actions for '{0}' available", userArgs.kind) : args.preferred ? localize("editor.action.codeAction.noneMessage.preferred", "No preferred code actions available") : localize("editor.action.codeAction.noneMessage", "No code actions available"), {
      include: args.kind,
      includeSourceActions: true,
      onlyIncludePreferredActions: args.preferred
    }, args.apply);
  }
}
class RefactorAction extends EditorAction {
  constructor() {
    super({
      id: refactorCommandId,
      label: localize("refactor.label", "Refactor..."),
      alias: "Refactor...",
      precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasCodeActionsProvider),
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 2048 | 1024 | 48,
        mac: {
          primary: 256 | 1024 | 48
          /* KeyCode.KeyR */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      contextMenuOpts: {
        group: "1_modification",
        order: 2,
        when: ContextKeyExpr.and(EditorContextKeys.writable, contextKeyForSupportedActions(CodeActionKind.Refactor))
      },
      description: {
        description: "Refactor...",
        args: [{ name: "args", schema: argsSchema }]
      }
    });
  }
  run(_accessor, editor2, userArgs) {
    const args = CodeActionCommandArgs.fromUser(userArgs, {
      kind: CodeActionKind.Refactor,
      apply: "never"
      /* CodeActionAutoApply.Never */
    });
    return triggerCodeActionsForEditorSelection(editor2, typeof (userArgs === null || userArgs === void 0 ? void 0 : userArgs.kind) === "string" ? args.preferred ? localize("editor.action.refactor.noneMessage.preferred.kind", "No preferred refactorings for '{0}' available", userArgs.kind) : localize("editor.action.refactor.noneMessage.kind", "No refactorings for '{0}' available", userArgs.kind) : args.preferred ? localize("editor.action.refactor.noneMessage.preferred", "No preferred refactorings available") : localize("editor.action.refactor.noneMessage", "No refactorings available"), {
      include: CodeActionKind.Refactor.contains(args.kind) ? args.kind : CodeActionKind.None,
      onlyIncludePreferredActions: args.preferred
    }, args.apply, CodeActionTriggerSource.Refactor);
  }
}
class SourceAction extends EditorAction {
  constructor() {
    super({
      id: sourceActionCommandId,
      label: localize("source.label", "Source Action..."),
      alias: "Source Action...",
      precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasCodeActionsProvider),
      contextMenuOpts: {
        group: "1_modification",
        order: 2.1,
        when: ContextKeyExpr.and(EditorContextKeys.writable, contextKeyForSupportedActions(CodeActionKind.Source))
      },
      description: {
        description: "Source Action...",
        args: [{ name: "args", schema: argsSchema }]
      }
    });
  }
  run(_accessor, editor2, userArgs) {
    const args = CodeActionCommandArgs.fromUser(userArgs, {
      kind: CodeActionKind.Source,
      apply: "never"
      /* CodeActionAutoApply.Never */
    });
    return triggerCodeActionsForEditorSelection(editor2, typeof (userArgs === null || userArgs === void 0 ? void 0 : userArgs.kind) === "string" ? args.preferred ? localize("editor.action.source.noneMessage.preferred.kind", "No preferred source actions for '{0}' available", userArgs.kind) : localize("editor.action.source.noneMessage.kind", "No source actions for '{0}' available", userArgs.kind) : args.preferred ? localize("editor.action.source.noneMessage.preferred", "No preferred source actions available") : localize("editor.action.source.noneMessage", "No source actions available"), {
      include: CodeActionKind.Source.contains(args.kind) ? args.kind : CodeActionKind.None,
      includeSourceActions: true,
      onlyIncludePreferredActions: args.preferred
    }, args.apply, CodeActionTriggerSource.SourceAction);
  }
}
class OrganizeImportsAction extends EditorAction {
  constructor() {
    super({
      id: organizeImportsCommandId,
      label: localize("organizeImports.label", "Organize Imports"),
      alias: "Organize Imports",
      precondition: ContextKeyExpr.and(EditorContextKeys.writable, contextKeyForSupportedActions(CodeActionKind.SourceOrganizeImports)),
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 1024 | 512 | 45,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(_accessor, editor2) {
    return triggerCodeActionsForEditorSelection(editor2, localize("editor.action.organize.noneMessage", "No organize imports action available"), { include: CodeActionKind.SourceOrganizeImports, includeSourceActions: true }, "ifSingle", CodeActionTriggerSource.OrganizeImports);
  }
}
class FixAllAction extends EditorAction {
  constructor() {
    super({
      id: fixAllCommandId,
      label: localize("fixAll.label", "Fix All"),
      alias: "Fix All",
      precondition: ContextKeyExpr.and(EditorContextKeys.writable, contextKeyForSupportedActions(CodeActionKind.SourceFixAll))
    });
  }
  run(_accessor, editor2) {
    return triggerCodeActionsForEditorSelection(editor2, localize("fixAll.noneMessage", "No fix all action available"), { include: CodeActionKind.SourceFixAll, includeSourceActions: true }, "ifSingle", CodeActionTriggerSource.FixAll);
  }
}
class AutoFixAction extends EditorAction {
  constructor() {
    super({
      id: autoFixCommandId,
      label: localize("autoFix.label", "Auto Fix..."),
      alias: "Auto Fix...",
      precondition: ContextKeyExpr.and(EditorContextKeys.writable, contextKeyForSupportedActions(CodeActionKind.QuickFix)),
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 512 | 1024 | 89,
        mac: {
          primary: 2048 | 512 | 89
          /* KeyCode.Period */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(_accessor, editor2) {
    return triggerCodeActionsForEditorSelection(editor2, localize("editor.action.autoFix.noneMessage", "No auto fixes available"), {
      include: CodeActionKind.QuickFix,
      onlyIncludePreferredActions: true
    }, "ifSingle", CodeActionTriggerSource.AutoFix);
  }
}
registerEditorContribution(
  CodeActionController.ID,
  CodeActionController,
  3
  /* EditorContributionInstantiation.Eventually */
);
registerEditorContribution(
  LightBulbWidget.ID,
  LightBulbWidget,
  4
  /* EditorContributionInstantiation.Lazy */
);
registerEditorAction(QuickFixAction);
registerEditorAction(RefactorAction);
registerEditorAction(SourceAction);
registerEditorAction(OrganizeImportsAction);
registerEditorAction(AutoFixAction);
registerEditorAction(FixAllAction);
registerEditorCommand(new CodeActionCommand());
Registry.as(Extensions$6.Configuration).registerConfiguration(Object.assign(Object.assign({}, editorConfigurationBaseNode), { properties: {
  "editor.codeActionWidget.showHeaders": {
    type: "boolean",
    scope: 5,
    description: localize("showCodeActionHeaders", "Enable/disable showing group headers in the Code Action menu."),
    default: true
  }
} }));
var __awaiter$1i = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class CodeLensModel {
  constructor() {
    this.lenses = [];
    this._disposables = new DisposableStore();
  }
  dispose() {
    this._disposables.dispose();
  }
  get isDisposed() {
    return this._disposables.isDisposed;
  }
  add(list2, provider) {
    this._disposables.add(list2);
    for (const symbol of list2.lenses) {
      this.lenses.push({ symbol, provider });
    }
  }
}
function getCodeLensModel(registry, model, token) {
  return __awaiter$1i(this, void 0, void 0, function* () {
    const provider = registry.ordered(model);
    const providerRanks = /* @__PURE__ */ new Map();
    const result2 = new CodeLensModel();
    const promises = provider.map((provider2, i) => __awaiter$1i(this, void 0, void 0, function* () {
      providerRanks.set(provider2, i);
      try {
        const list2 = yield Promise.resolve(provider2.provideCodeLenses(model, token));
        if (list2) {
          result2.add(list2, provider2);
        }
      } catch (err) {
        onUnexpectedExternalError(err);
      }
    }));
    yield Promise.all(promises);
    result2.lenses = result2.lenses.sort((a, b) => {
      if (a.symbol.range.startLineNumber < b.symbol.range.startLineNumber) {
        return -1;
      } else if (a.symbol.range.startLineNumber > b.symbol.range.startLineNumber) {
        return 1;
      } else if (providerRanks.get(a.provider) < providerRanks.get(b.provider)) {
        return -1;
      } else if (providerRanks.get(a.provider) > providerRanks.get(b.provider)) {
        return 1;
      } else if (a.symbol.range.startColumn < b.symbol.range.startColumn) {
        return -1;
      } else if (a.symbol.range.startColumn > b.symbol.range.startColumn) {
        return 1;
      } else {
        return 0;
      }
    });
    return result2;
  });
}
CommandsRegistry.registerCommand("_executeCodeLensProvider", function(accessor, ...args) {
  let [uri, itemResolveCount] = args;
  assertType(URI.isUri(uri));
  assertType(typeof itemResolveCount === "number" || !itemResolveCount);
  const { codeLensProvider } = accessor.get(ILanguageFeaturesService);
  const model = accessor.get(IModelService).getModel(uri);
  if (!model) {
    throw illegalArgument();
  }
  const result2 = [];
  const disposables = new DisposableStore();
  return getCodeLensModel(codeLensProvider, model, CancellationToken.None).then((value) => {
    disposables.add(value);
    const resolve2 = [];
    for (const item of value.lenses) {
      if (itemResolveCount === void 0 || itemResolveCount === null || Boolean(item.symbol.command)) {
        result2.push(item.symbol);
      } else if (itemResolveCount-- > 0 && item.provider.resolveCodeLens) {
        resolve2.push(Promise.resolve(item.provider.resolveCodeLens(model, item.symbol, CancellationToken.None)).then((symbol) => result2.push(symbol || item.symbol)));
      }
    }
    return Promise.all(resolve2);
  }).then(() => {
    return result2;
  }).finally(() => {
    setTimeout(() => disposables.dispose(), 100);
  });
});
var __awaiter$1h = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var StorageHint;
(function(StorageHint2) {
  StorageHint2[StorageHint2["STORAGE_DOES_NOT_EXIST"] = 0] = "STORAGE_DOES_NOT_EXIST";
  StorageHint2[StorageHint2["STORAGE_IN_MEMORY"] = 1] = "STORAGE_IN_MEMORY";
})(StorageHint || (StorageHint = {}));
var StorageState;
(function(StorageState2) {
  StorageState2[StorageState2["None"] = 0] = "None";
  StorageState2[StorageState2["Initialized"] = 1] = "Initialized";
  StorageState2[StorageState2["Closed"] = 2] = "Closed";
})(StorageState || (StorageState = {}));
class Storage extends Disposable {
  constructor(database, options = /* @__PURE__ */ Object.create(null)) {
    super();
    this.database = database;
    this.options = options;
    this._onDidChangeStorage = this._register(new PauseableEmitter());
    this.onDidChangeStorage = this._onDidChangeStorage.event;
    this.state = StorageState.None;
    this.cache = /* @__PURE__ */ new Map();
    this.flushDelayer = new ThrottledDelayer(Storage.DEFAULT_FLUSH_DELAY);
    this.pendingDeletes = /* @__PURE__ */ new Set();
    this.pendingInserts = /* @__PURE__ */ new Map();
    this.whenFlushedCallbacks = [];
    this.registerListeners();
  }
  registerListeners() {
    this._register(this.database.onDidChangeItemsExternal((e) => this.onDidChangeItemsExternal(e)));
  }
  onDidChangeItemsExternal(e) {
    var _a2, _b2;
    this._onDidChangeStorage.pause();
    try {
      (_a2 = e.changed) === null || _a2 === void 0 ? void 0 : _a2.forEach((value, key) => this.acceptExternal(key, value));
      (_b2 = e.deleted) === null || _b2 === void 0 ? void 0 : _b2.forEach((key) => this.acceptExternal(key, void 0));
    } finally {
      this._onDidChangeStorage.resume();
    }
  }
  acceptExternal(key, value) {
    if (this.state === StorageState.Closed) {
      return;
    }
    let changed = false;
    if (isUndefinedOrNull(value)) {
      changed = this.cache.delete(key);
    } else {
      const currentValue = this.cache.get(key);
      if (currentValue !== value) {
        this.cache.set(key, value);
        changed = true;
      }
    }
    if (changed) {
      this._onDidChangeStorage.fire({ key, external: true });
    }
  }
  get(key, fallbackValue) {
    const value = this.cache.get(key);
    if (isUndefinedOrNull(value)) {
      return fallbackValue;
    }
    return value;
  }
  getBoolean(key, fallbackValue) {
    const value = this.get(key);
    if (isUndefinedOrNull(value)) {
      return fallbackValue;
    }
    return value === "true";
  }
  getNumber(key, fallbackValue) {
    const value = this.get(key);
    if (isUndefinedOrNull(value)) {
      return fallbackValue;
    }
    return parseInt(value, 10);
  }
  set(key, value, external = false) {
    return __awaiter$1h(this, void 0, void 0, function* () {
      if (this.state === StorageState.Closed) {
        return;
      }
      if (isUndefinedOrNull(value)) {
        return this.delete(key, external);
      }
      const valueStr = isObject$4(value) || Array.isArray(value) ? stringify$6(value) : String(value);
      const currentValue = this.cache.get(key);
      if (currentValue === valueStr) {
        return;
      }
      this.cache.set(key, valueStr);
      this.pendingInserts.set(key, valueStr);
      this.pendingDeletes.delete(key);
      this._onDidChangeStorage.fire({ key, external });
      return this.doFlush();
    });
  }
  delete(key, external = false) {
    return __awaiter$1h(this, void 0, void 0, function* () {
      if (this.state === StorageState.Closed) {
        return;
      }
      const wasDeleted = this.cache.delete(key);
      if (!wasDeleted) {
        return;
      }
      if (!this.pendingDeletes.has(key)) {
        this.pendingDeletes.add(key);
      }
      this.pendingInserts.delete(key);
      this._onDidChangeStorage.fire({ key, external });
      return this.doFlush();
    });
  }
  get hasPending() {
    return this.pendingInserts.size > 0 || this.pendingDeletes.size > 0;
  }
  flushPending() {
    return __awaiter$1h(this, void 0, void 0, function* () {
      if (!this.hasPending) {
        return;
      }
      const updateRequest = { insert: this.pendingInserts, delete: this.pendingDeletes };
      this.pendingDeletes = /* @__PURE__ */ new Set();
      this.pendingInserts = /* @__PURE__ */ new Map();
      return this.database.updateItems(updateRequest).finally(() => {
        var _a2;
        if (!this.hasPending) {
          while (this.whenFlushedCallbacks.length) {
            (_a2 = this.whenFlushedCallbacks.pop()) === null || _a2 === void 0 ? void 0 : _a2();
          }
        }
      });
    });
  }
  doFlush(delay) {
    return __awaiter$1h(this, void 0, void 0, function* () {
      return this.flushDelayer.trigger(() => this.flushPending(), delay);
    });
  }
  dispose() {
    this.flushDelayer.dispose();
    super.dispose();
  }
}
Storage.DEFAULT_FLUSH_DELAY = 100;
class InMemoryStorageDatabase {
  constructor() {
    this.onDidChangeItemsExternal = Event$1.None;
    this.items = /* @__PURE__ */ new Map();
  }
  updateItems(request) {
    var _a2, _b2;
    return __awaiter$1h(this, void 0, void 0, function* () {
      (_a2 = request.insert) === null || _a2 === void 0 ? void 0 : _a2.forEach((value, key) => this.items.set(key, value));
      (_b2 = request.delete) === null || _b2 === void 0 ? void 0 : _b2.forEach((key) => this.items.delete(key));
    });
  }
}
const TARGET_KEY = "__$__targetStorageMarker";
const IStorageService = createDecorator("storageService");
var WillSaveStateReason;
(function(WillSaveStateReason2) {
  WillSaveStateReason2[WillSaveStateReason2["NONE"] = 0] = "NONE";
  WillSaveStateReason2[WillSaveStateReason2["SHUTDOWN"] = 1] = "SHUTDOWN";
})(WillSaveStateReason || (WillSaveStateReason = {}));
function loadKeyTargets(storage) {
  const keysRaw = storage.get(TARGET_KEY);
  if (keysRaw) {
    try {
      return JSON.parse(keysRaw);
    } catch (error2) {
    }
  }
  return /* @__PURE__ */ Object.create(null);
}
class AbstractStorageService extends Disposable {
  constructor(options = { flushInterval: AbstractStorageService.DEFAULT_FLUSH_INTERVAL }) {
    super();
    this.options = options;
    this._onDidChangeValue = this._register(new PauseableEmitter());
    this.onDidChangeValue = this._onDidChangeValue.event;
    this._onDidChangeTarget = this._register(new PauseableEmitter());
    this._onWillSaveState = this._register(new Emitter$1());
    this.onWillSaveState = this._onWillSaveState.event;
    this._workspaceKeyTargets = void 0;
    this._profileKeyTargets = void 0;
    this._applicationKeyTargets = void 0;
  }
  emitDidChangeValue(scope, event) {
    const { key, external } = event;
    if (key === TARGET_KEY) {
      switch (scope) {
        case -1:
          this._applicationKeyTargets = void 0;
          break;
        case 0:
          this._profileKeyTargets = void 0;
          break;
        case 1:
          this._workspaceKeyTargets = void 0;
          break;
      }
      this._onDidChangeTarget.fire({ scope });
    } else {
      this._onDidChangeValue.fire({ scope, key, target: this.getKeyTargets(scope)[key], external });
    }
  }
  get(key, scope, fallbackValue) {
    var _a2;
    return (_a2 = this.getStorage(scope)) === null || _a2 === void 0 ? void 0 : _a2.get(key, fallbackValue);
  }
  getBoolean(key, scope, fallbackValue) {
    var _a2;
    return (_a2 = this.getStorage(scope)) === null || _a2 === void 0 ? void 0 : _a2.getBoolean(key, fallbackValue);
  }
  getNumber(key, scope, fallbackValue) {
    var _a2;
    return (_a2 = this.getStorage(scope)) === null || _a2 === void 0 ? void 0 : _a2.getNumber(key, fallbackValue);
  }
  store(key, value, scope, target, external = false) {
    if (isUndefinedOrNull(value)) {
      this.remove(key, scope, external);
      return;
    }
    this.withPausedEmitters(() => {
      var _a2;
      this.updateKeyTarget(key, scope, target);
      (_a2 = this.getStorage(scope)) === null || _a2 === void 0 ? void 0 : _a2.set(key, value, external);
    });
  }
  remove(key, scope, external = false) {
    this.withPausedEmitters(() => {
      var _a2;
      this.updateKeyTarget(key, scope, void 0);
      (_a2 = this.getStorage(scope)) === null || _a2 === void 0 ? void 0 : _a2.delete(key, external);
    });
  }
  withPausedEmitters(fn) {
    this._onDidChangeValue.pause();
    this._onDidChangeTarget.pause();
    try {
      fn();
    } finally {
      this._onDidChangeValue.resume();
      this._onDidChangeTarget.resume();
    }
  }
  updateKeyTarget(key, scope, target, external = false) {
    var _a2, _b2;
    const keyTargets = this.getKeyTargets(scope);
    if (typeof target === "number") {
      if (keyTargets[key] !== target) {
        keyTargets[key] = target;
        (_a2 = this.getStorage(scope)) === null || _a2 === void 0 ? void 0 : _a2.set(TARGET_KEY, JSON.stringify(keyTargets), external);
      }
    } else {
      if (typeof keyTargets[key] === "number") {
        delete keyTargets[key];
        (_b2 = this.getStorage(scope)) === null || _b2 === void 0 ? void 0 : _b2.set(TARGET_KEY, JSON.stringify(keyTargets), external);
      }
    }
  }
  get workspaceKeyTargets() {
    if (!this._workspaceKeyTargets) {
      this._workspaceKeyTargets = this.loadKeyTargets(
        1
        /* StorageScope.WORKSPACE */
      );
    }
    return this._workspaceKeyTargets;
  }
  get profileKeyTargets() {
    if (!this._profileKeyTargets) {
      this._profileKeyTargets = this.loadKeyTargets(
        0
        /* StorageScope.PROFILE */
      );
    }
    return this._profileKeyTargets;
  }
  get applicationKeyTargets() {
    if (!this._applicationKeyTargets) {
      this._applicationKeyTargets = this.loadKeyTargets(
        -1
        /* StorageScope.APPLICATION */
      );
    }
    return this._applicationKeyTargets;
  }
  getKeyTargets(scope) {
    switch (scope) {
      case -1:
        return this.applicationKeyTargets;
      case 0:
        return this.profileKeyTargets;
      default:
        return this.workspaceKeyTargets;
    }
  }
  loadKeyTargets(scope) {
    const storage = this.getStorage(scope);
    return storage ? loadKeyTargets(storage) : /* @__PURE__ */ Object.create(null);
  }
}
AbstractStorageService.DEFAULT_FLUSH_INTERVAL = 60 * 1e3;
class InMemoryStorageService extends AbstractStorageService {
  constructor() {
    super();
    this.applicationStorage = this._register(new Storage(new InMemoryStorageDatabase(), { hint: StorageHint.STORAGE_IN_MEMORY }));
    this.profileStorage = this._register(new Storage(new InMemoryStorageDatabase(), { hint: StorageHint.STORAGE_IN_MEMORY }));
    this.workspaceStorage = this._register(new Storage(new InMemoryStorageDatabase(), { hint: StorageHint.STORAGE_IN_MEMORY }));
    this._register(this.workspaceStorage.onDidChangeStorage((e) => this.emitDidChangeValue(1, e)));
    this._register(this.profileStorage.onDidChangeStorage((e) => this.emitDidChangeValue(0, e)));
    this._register(this.applicationStorage.onDidChangeStorage((e) => this.emitDidChangeValue(-1, e)));
  }
  getStorage(scope) {
    switch (scope) {
      case -1:
        return this.applicationStorage;
      case 0:
        return this.profileStorage;
      default:
        return this.workspaceStorage;
    }
  }
}
var __decorate$1O = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1L = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
const ICodeLensCache = createDecorator("ICodeLensCache");
class CacheItem {
  constructor(lineCount, data) {
    this.lineCount = lineCount;
    this.data = data;
  }
}
let CodeLensCache = class CodeLensCache2 {
  constructor(storageService) {
    this._fakeProvider = new class {
      provideCodeLenses() {
        throw new Error("not supported");
      }
    }();
    this._cache = new LRUCache$2(20, 0.75);
    const oldkey = "codelens/cache";
    runWhenIdle(() => storageService.remove(
      oldkey,
      1
      /* StorageScope.WORKSPACE */
    ));
    const key = "codelens/cache2";
    const raw = storageService.get(key, 1, "{}");
    this._deserialize(raw);
    once$2(storageService.onWillSaveState)((e) => {
      if (e.reason === WillSaveStateReason.SHUTDOWN) {
        storageService.store(
          key,
          this._serialize(),
          1,
          1
          /* StorageTarget.MACHINE */
        );
      }
    });
  }
  put(model, data) {
    const copyItems = data.lenses.map((item2) => {
      var _a2;
      return {
        range: item2.symbol.range,
        command: item2.symbol.command && { id: "", title: (_a2 = item2.symbol.command) === null || _a2 === void 0 ? void 0 : _a2.title }
      };
    });
    const copyModel = new CodeLensModel();
    copyModel.add({ lenses: copyItems, dispose: () => {
    } }, this._fakeProvider);
    const item = new CacheItem(model.getLineCount(), copyModel);
    this._cache.set(model.uri.toString(), item);
  }
  get(model) {
    const item = this._cache.get(model.uri.toString());
    return item && item.lineCount === model.getLineCount() ? item.data : void 0;
  }
  delete(model) {
    this._cache.delete(model.uri.toString());
  }
  // --- persistence
  _serialize() {
    const data = /* @__PURE__ */ Object.create(null);
    for (const [key, value] of this._cache) {
      const lines = /* @__PURE__ */ new Set();
      for (const d of value.data.lenses) {
        lines.add(d.symbol.range.startLineNumber);
      }
      data[key] = {
        lineCount: value.lineCount,
        lines: [...lines.values()]
      };
    }
    return JSON.stringify(data);
  }
  _deserialize(raw) {
    try {
      const data = JSON.parse(raw);
      for (const key in data) {
        const element = data[key];
        const lenses = [];
        for (const line of element.lines) {
          lenses.push({ range: new Range$2(line, 1, line, 11) });
        }
        const model = new CodeLensModel();
        model.add({ lenses, dispose() {
        } }, this._fakeProvider);
        this._cache.set(key, new CacheItem(element.lineCount, model));
      }
    } catch (_a2) {
    }
  }
};
CodeLensCache = __decorate$1O([
  __param$1L(0, IStorageService)
], CodeLensCache);
registerSingleton(
  ICodeLensCache,
  CodeLensCache,
  1
  /* InstantiationType.Delayed */
);
const codelensWidget = "";
class CodeLensViewZone {
  constructor(afterLineNumber, heightInPx, onHeight) {
    this.afterColumn = 1073741824;
    this.afterLineNumber = afterLineNumber;
    this.heightInPx = heightInPx;
    this._onHeight = onHeight;
    this.suppressMouseDown = true;
    this.domNode = document.createElement("div");
  }
  onComputedHeight(height) {
    if (this._lastHeight === void 0) {
      this._lastHeight = height;
    } else if (this._lastHeight !== height) {
      this._lastHeight = height;
      this._onHeight();
    }
  }
  isVisible() {
    return this._lastHeight !== 0 && this.domNode.hasAttribute("monaco-visible-view-zone");
  }
}
class CodeLensContentWidget {
  constructor(editor2, line) {
    this.allowEditorOverflow = false;
    this.suppressMouseDown = true;
    this._commands = /* @__PURE__ */ new Map();
    this._isEmpty = true;
    this._editor = editor2;
    this._id = `codelens.widget-${CodeLensContentWidget._idPool++}`;
    this.updatePosition(line);
    this._domNode = document.createElement("span");
    this._domNode.className = `codelens-decoration`;
  }
  withCommands(lenses, animate2) {
    this._commands.clear();
    const children = [];
    let hasSymbol = false;
    for (let i = 0; i < lenses.length; i++) {
      const lens = lenses[i];
      if (!lens) {
        continue;
      }
      hasSymbol = true;
      if (lens.command) {
        const title2 = renderLabelWithIcons(lens.command.title.trim());
        if (lens.command.id) {
          children.push($$d("a", { id: String(i), title: lens.command.tooltip, role: "button" }, ...title2));
          this._commands.set(String(i), lens.command);
        } else {
          children.push($$d("span", { title: lens.command.tooltip }, ...title2));
        }
        if (i + 1 < lenses.length) {
          children.push($$d("span", void 0, " | "));
        }
      }
    }
    if (!hasSymbol) {
      reset(this._domNode, $$d("span", void 0, "no commands"));
    } else {
      reset(this._domNode, ...children);
      if (this._isEmpty && animate2) {
        this._domNode.classList.add("fadein");
      }
      this._isEmpty = false;
    }
  }
  getCommand(link2) {
    return link2.parentElement === this._domNode ? this._commands.get(link2.id) : void 0;
  }
  getId() {
    return this._id;
  }
  getDomNode() {
    return this._domNode;
  }
  updatePosition(line) {
    const column = this._editor.getModel().getLineFirstNonWhitespaceColumn(line);
    this._widgetPosition = {
      position: { lineNumber: line, column },
      preference: [
        1
        /* ContentWidgetPositionPreference.ABOVE */
      ]
    };
  }
  getPosition() {
    return this._widgetPosition || null;
  }
}
CodeLensContentWidget._idPool = 0;
class CodeLensHelper {
  constructor() {
    this._removeDecorations = [];
    this._addDecorations = [];
    this._addDecorationsCallbacks = [];
  }
  addDecoration(decoration2, callback) {
    this._addDecorations.push(decoration2);
    this._addDecorationsCallbacks.push(callback);
  }
  removeDecoration(decorationId) {
    this._removeDecorations.push(decorationId);
  }
  commit(changeAccessor) {
    const resultingDecorations = changeAccessor.deltaDecorations(this._removeDecorations, this._addDecorations);
    for (let i = 0, len = resultingDecorations.length; i < len; i++) {
      this._addDecorationsCallbacks[i](resultingDecorations[i]);
    }
  }
}
const codeLensDecorationOptions = ModelDecorationOptions.register({
  collapseOnReplaceEdit: true,
  description: "codelens"
});
class CodeLensWidget {
  constructor(data, editor2, helper, viewZoneChangeAccessor, heightInPx, updateCallback) {
    this._isDisposed = false;
    this._editor = editor2;
    this._data = data;
    this._decorationIds = [];
    let range2;
    const lenses = [];
    this._data.forEach((codeLensData, i) => {
      if (codeLensData.symbol.command) {
        lenses.push(codeLensData.symbol);
      }
      helper.addDecoration({
        range: codeLensData.symbol.range,
        options: codeLensDecorationOptions
      }, (id3) => this._decorationIds[i] = id3);
      if (!range2) {
        range2 = Range$2.lift(codeLensData.symbol.range);
      } else {
        range2 = Range$2.plusRange(range2, codeLensData.symbol.range);
      }
    });
    this._viewZone = new CodeLensViewZone(range2.startLineNumber - 1, heightInPx, updateCallback);
    this._viewZoneId = viewZoneChangeAccessor.addZone(this._viewZone);
    if (lenses.length > 0) {
      this._createContentWidgetIfNecessary();
      this._contentWidget.withCommands(lenses, false);
    }
  }
  _createContentWidgetIfNecessary() {
    if (!this._contentWidget) {
      this._contentWidget = new CodeLensContentWidget(this._editor, this._viewZone.afterLineNumber + 1);
      this._editor.addContentWidget(this._contentWidget);
    } else {
      this._editor.layoutContentWidget(this._contentWidget);
    }
  }
  dispose(helper, viewZoneChangeAccessor) {
    this._decorationIds.forEach(helper.removeDecoration, helper);
    this._decorationIds = [];
    viewZoneChangeAccessor === null || viewZoneChangeAccessor === void 0 ? void 0 : viewZoneChangeAccessor.removeZone(this._viewZoneId);
    if (this._contentWidget) {
      this._editor.removeContentWidget(this._contentWidget);
      this._contentWidget = void 0;
    }
    this._isDisposed = true;
  }
  isDisposed() {
    return this._isDisposed;
  }
  isValid() {
    return this._decorationIds.some((id3, i) => {
      const range2 = this._editor.getModel().getDecorationRange(id3);
      const symbol = this._data[i].symbol;
      return !!(range2 && Range$2.isEmpty(symbol.range) === range2.isEmpty());
    });
  }
  updateCodeLensSymbols(data, helper) {
    this._decorationIds.forEach(helper.removeDecoration, helper);
    this._decorationIds = [];
    this._data = data;
    this._data.forEach((codeLensData, i) => {
      helper.addDecoration({
        range: codeLensData.symbol.range,
        options: codeLensDecorationOptions
      }, (id3) => this._decorationIds[i] = id3);
    });
  }
  updateHeight(height, viewZoneChangeAccessor) {
    this._viewZone.heightInPx = height;
    viewZoneChangeAccessor.layoutZone(this._viewZoneId);
    if (this._contentWidget) {
      this._editor.layoutContentWidget(this._contentWidget);
    }
  }
  computeIfNecessary(model) {
    if (!this._viewZone.isVisible()) {
      return null;
    }
    for (let i = 0; i < this._decorationIds.length; i++) {
      const range2 = model.getDecorationRange(this._decorationIds[i]);
      if (range2) {
        this._data[i].symbol.range = range2;
      }
    }
    return this._data;
  }
  updateCommands(symbols2) {
    this._createContentWidgetIfNecessary();
    this._contentWidget.withCommands(symbols2, true);
    for (let i = 0; i < this._data.length; i++) {
      const resolved = symbols2[i];
      if (resolved) {
        const { symbol } = this._data[i];
        symbol.command = resolved.command || symbol.command;
      }
    }
  }
  getCommand(link2) {
    var _a2;
    return (_a2 = this._contentWidget) === null || _a2 === void 0 ? void 0 : _a2.getCommand(link2);
  }
  getLineNumber() {
    const range2 = this._editor.getModel().getDecorationRange(this._decorationIds[0]);
    if (range2) {
      return range2.startLineNumber;
    }
    return -1;
  }
  update(viewZoneChangeAccessor) {
    if (this.isValid()) {
      const range2 = this._editor.getModel().getDecorationRange(this._decorationIds[0]);
      if (range2) {
        this._viewZone.afterLineNumber = range2.startLineNumber - 1;
        viewZoneChangeAccessor.layoutZone(this._viewZoneId);
        if (this._contentWidget) {
          this._contentWidget.updatePosition(range2.startLineNumber);
          this._editor.layoutContentWidget(this._contentWidget);
        }
      }
    }
  }
}
const NO_KEY_MODS = { ctrlCmd: false, alt: false };
var QuickInputHideReason;
(function(QuickInputHideReason2) {
  QuickInputHideReason2[QuickInputHideReason2["Blur"] = 1] = "Blur";
  QuickInputHideReason2[QuickInputHideReason2["Gesture"] = 2] = "Gesture";
  QuickInputHideReason2[QuickInputHideReason2["Other"] = 3] = "Other";
})(QuickInputHideReason || (QuickInputHideReason = {}));
var ItemActivation;
(function(ItemActivation2) {
  ItemActivation2[ItemActivation2["NONE"] = 0] = "NONE";
  ItemActivation2[ItemActivation2["FIRST"] = 1] = "FIRST";
  ItemActivation2[ItemActivation2["SECOND"] = 2] = "SECOND";
  ItemActivation2[ItemActivation2["LAST"] = 3] = "LAST";
})(ItemActivation || (ItemActivation = {}));
const IQuickInputService = createDecorator("quickInputService");
function hash(obj) {
  return doHash(obj, 0);
}
function doHash(obj, hashVal) {
  switch (typeof obj) {
    case "object":
      if (obj === null) {
        return numberHash(349, hashVal);
      } else if (Array.isArray(obj)) {
        return arrayHash(obj, hashVal);
      }
      return objectHash(obj, hashVal);
    case "string":
      return stringHash(obj, hashVal);
    case "boolean":
      return booleanHash(obj, hashVal);
    case "number":
      return numberHash(obj, hashVal);
    case "undefined":
      return numberHash(937, hashVal);
    default:
      return numberHash(617, hashVal);
  }
}
function numberHash(val, initialHashVal) {
  return (initialHashVal << 5) - initialHashVal + val | 0;
}
function booleanHash(b, initialHashVal) {
  return numberHash(b ? 433 : 863, initialHashVal);
}
function stringHash(s, hashVal) {
  hashVal = numberHash(149417, hashVal);
  for (let i = 0, length2 = s.length; i < length2; i++) {
    hashVal = numberHash(s.charCodeAt(i), hashVal);
  }
  return hashVal;
}
function arrayHash(arr, initialHashVal) {
  initialHashVal = numberHash(104579, initialHashVal);
  return arr.reduce((hashVal, item) => doHash(item, hashVal), initialHashVal);
}
function objectHash(obj, initialHashVal) {
  initialHashVal = numberHash(181387, initialHashVal);
  return Object.keys(obj).sort().reduce((hashVal, key) => {
    hashVal = stringHash(key, hashVal);
    return doHash(obj[key], hashVal);
  }, initialHashVal);
}
function leftRotate(value, bits, totalBits = 32) {
  const delta = totalBits - bits;
  const mask = ~((1 << delta) - 1);
  return (value << bits | (mask & value) >>> delta) >>> 0;
}
function fill(dest, index = 0, count = dest.byteLength, value = 0) {
  for (let i = 0; i < count; i++) {
    dest[index + i] = value;
  }
}
function leftPad(value, length2, char = "0") {
  while (value.length < length2) {
    value = char + value;
  }
  return value;
}
function toHexString(bufferOrValue, bitsize = 32) {
  if (bufferOrValue instanceof ArrayBuffer) {
    return Array.from(new Uint8Array(bufferOrValue)).map((b) => b.toString(16).padStart(2, "0")).join("");
  }
  return leftPad((bufferOrValue >>> 0).toString(16), bitsize / 4);
}
class StringSHA1 {
  constructor() {
    this._h0 = 1732584193;
    this._h1 = 4023233417;
    this._h2 = 2562383102;
    this._h3 = 271733878;
    this._h4 = 3285377520;
    this._buff = new Uint8Array(
      64 + 3
      /* to fit any utf-8 */
    );
    this._buffDV = new DataView(this._buff.buffer);
    this._buffLen = 0;
    this._totalLen = 0;
    this._leftoverHighSurrogate = 0;
    this._finished = false;
  }
  update(str2) {
    const strLen = str2.length;
    if (strLen === 0) {
      return;
    }
    const buff = this._buff;
    let buffLen = this._buffLen;
    let leftoverHighSurrogate = this._leftoverHighSurrogate;
    let charCode;
    let offset;
    if (leftoverHighSurrogate !== 0) {
      charCode = leftoverHighSurrogate;
      offset = -1;
      leftoverHighSurrogate = 0;
    } else {
      charCode = str2.charCodeAt(0);
      offset = 0;
    }
    while (true) {
      let codePoint = charCode;
      if (isHighSurrogate(charCode)) {
        if (offset + 1 < strLen) {
          const nextCharCode = str2.charCodeAt(offset + 1);
          if (isLowSurrogate(nextCharCode)) {
            offset++;
            codePoint = computeCodePoint(charCode, nextCharCode);
          } else {
            codePoint = 65533;
          }
        } else {
          leftoverHighSurrogate = charCode;
          break;
        }
      } else if (isLowSurrogate(charCode)) {
        codePoint = 65533;
      }
      buffLen = this._push(buff, buffLen, codePoint);
      offset++;
      if (offset < strLen) {
        charCode = str2.charCodeAt(offset);
      } else {
        break;
      }
    }
    this._buffLen = buffLen;
    this._leftoverHighSurrogate = leftoverHighSurrogate;
  }
  _push(buff, buffLen, codePoint) {
    if (codePoint < 128) {
      buff[buffLen++] = codePoint;
    } else if (codePoint < 2048) {
      buff[buffLen++] = 192 | (codePoint & 1984) >>> 6;
      buff[buffLen++] = 128 | (codePoint & 63) >>> 0;
    } else if (codePoint < 65536) {
      buff[buffLen++] = 224 | (codePoint & 61440) >>> 12;
      buff[buffLen++] = 128 | (codePoint & 4032) >>> 6;
      buff[buffLen++] = 128 | (codePoint & 63) >>> 0;
    } else {
      buff[buffLen++] = 240 | (codePoint & 1835008) >>> 18;
      buff[buffLen++] = 128 | (codePoint & 258048) >>> 12;
      buff[buffLen++] = 128 | (codePoint & 4032) >>> 6;
      buff[buffLen++] = 128 | (codePoint & 63) >>> 0;
    }
    if (buffLen >= 64) {
      this._step();
      buffLen -= 64;
      this._totalLen += 64;
      buff[0] = buff[64 + 0];
      buff[1] = buff[64 + 1];
      buff[2] = buff[64 + 2];
    }
    return buffLen;
  }
  digest() {
    if (!this._finished) {
      this._finished = true;
      if (this._leftoverHighSurrogate) {
        this._leftoverHighSurrogate = 0;
        this._buffLen = this._push(
          this._buff,
          this._buffLen,
          65533
          /* SHA1Constant.UNICODE_REPLACEMENT */
        );
      }
      this._totalLen += this._buffLen;
      this._wrapUp();
    }
    return toHexString(this._h0) + toHexString(this._h1) + toHexString(this._h2) + toHexString(this._h3) + toHexString(this._h4);
  }
  _wrapUp() {
    this._buff[this._buffLen++] = 128;
    fill(this._buff, this._buffLen);
    if (this._buffLen > 56) {
      this._step();
      fill(this._buff);
    }
    const ml = 8 * this._totalLen;
    this._buffDV.setUint32(56, Math.floor(ml / 4294967296), false);
    this._buffDV.setUint32(60, ml % 4294967296, false);
    this._step();
  }
  _step() {
    const bigBlock32 = StringSHA1._bigBlock32;
    const data = this._buffDV;
    for (let j = 0; j < 64; j += 4) {
      bigBlock32.setUint32(j, data.getUint32(j, false), false);
    }
    for (let j = 64; j < 320; j += 4) {
      bigBlock32.setUint32(j, leftRotate(bigBlock32.getUint32(j - 12, false) ^ bigBlock32.getUint32(j - 32, false) ^ bigBlock32.getUint32(j - 56, false) ^ bigBlock32.getUint32(j - 64, false), 1), false);
    }
    let a = this._h0;
    let b = this._h1;
    let c = this._h2;
    let d = this._h3;
    let e = this._h4;
    let f, k;
    let temp;
    for (let j = 0; j < 80; j++) {
      if (j < 20) {
        f = b & c | ~b & d;
        k = 1518500249;
      } else if (j < 40) {
        f = b ^ c ^ d;
        k = 1859775393;
      } else if (j < 60) {
        f = b & c | b & d | c & d;
        k = 2400959708;
      } else {
        f = b ^ c ^ d;
        k = 3395469782;
      }
      temp = leftRotate(a, 5) + f + e + k + bigBlock32.getUint32(j * 4, false) & 4294967295;
      e = d;
      d = c;
      c = leftRotate(b, 30);
      b = a;
      a = temp;
    }
    this._h0 = this._h0 + a & 4294967295;
    this._h1 = this._h1 + b & 4294967295;
    this._h2 = this._h2 + c & 4294967295;
    this._h3 = this._h3 + d & 4294967295;
    this._h4 = this._h4 + e & 4294967295;
  }
}
StringSHA1._bigBlock32 = new DataView(new ArrayBuffer(320));
const IEnvironmentService = createDecorator("environmentService");
var __decorate$1N = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1K = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
const ILanguageFeatureDebounceService = createDecorator("ILanguageFeatureDebounceService");
var IdentityHash;
(function(IdentityHash2) {
  const _hashes = /* @__PURE__ */ new WeakMap();
  let pool = 0;
  function of(obj) {
    let value = _hashes.get(obj);
    if (value === void 0) {
      value = ++pool;
      _hashes.set(obj, value);
    }
    return value;
  }
  IdentityHash2.of = of;
})(IdentityHash || (IdentityHash = {}));
class NullDebounceInformation {
  constructor(_default) {
    this._default = _default;
  }
  get(_model) {
    return this._default;
  }
  update(_model, _value) {
    return this._default;
  }
  default() {
    return this._default;
  }
}
class FeatureDebounceInformation {
  constructor(_logService, _name, _registry2, _default, _min, _max) {
    this._logService = _logService;
    this._name = _name;
    this._registry = _registry2;
    this._default = _default;
    this._min = _min;
    this._max = _max;
    this._cache = new LRUCache$2(50, 0.7);
  }
  _key(model) {
    return model.id + this._registry.all(model).reduce((hashVal, obj) => doHash(IdentityHash.of(obj), hashVal), 0);
  }
  get(model) {
    const key = this._key(model);
    const avg = this._cache.get(key);
    return avg ? clamp(avg.value, this._min, this._max) : this.default();
  }
  update(model, value) {
    const key = this._key(model);
    let avg = this._cache.get(key);
    if (!avg) {
      avg = new SlidingWindowAverage(6);
      this._cache.set(key, avg);
    }
    const newValue = clamp(avg.update(value), this._min, this._max);
    if (!matchesScheme(model.uri, "output")) {
      this._logService.trace(`[DEBOUNCE: ${this._name}] for ${model.uri.toString()} is ${newValue}ms`);
    }
    return newValue;
  }
  _overall() {
    const result2 = new MovingAverage();
    for (const [, avg] of this._cache) {
      result2.update(avg.value);
    }
    return result2.value;
  }
  default() {
    const value = this._overall() | 0 || this._default;
    return clamp(value, this._min, this._max);
  }
}
let LanguageFeatureDebounceService = class LanguageFeatureDebounceService2 {
  constructor(_logService, envService) {
    this._logService = _logService;
    this._data = /* @__PURE__ */ new Map();
    this._isDev = envService.isExtensionDevelopment || !envService.isBuilt;
  }
  for(feature, name, config2) {
    var _a2, _b2, _c2;
    const min = (_a2 = config2 === null || config2 === void 0 ? void 0 : config2.min) !== null && _a2 !== void 0 ? _a2 : 50;
    const max = (_b2 = config2 === null || config2 === void 0 ? void 0 : config2.max) !== null && _b2 !== void 0 ? _b2 : Math.pow(min, 2);
    const extra = (_c2 = config2 === null || config2 === void 0 ? void 0 : config2.key) !== null && _c2 !== void 0 ? _c2 : void 0;
    const key = `${IdentityHash.of(feature)},${min}${extra ? "," + extra : ""}`;
    let info = this._data.get(key);
    if (!info) {
      if (!this._isDev) {
        this._logService.debug(`[DEBOUNCE: ${name}] is disabled in developed mode`);
        info = new NullDebounceInformation(min * 1.5);
      } else {
        info = new FeatureDebounceInformation(
          this._logService,
          name,
          feature,
          this._overallAverage() | 0 || min * 1.5,
          // default is overall default or derived from min-value
          min,
          max
        );
      }
      this._data.set(key, info);
    }
    return info;
  }
  _overallAverage() {
    const result2 = new MovingAverage();
    for (const info of this._data.values()) {
      result2.update(info.default());
    }
    return result2.value;
  }
};
LanguageFeatureDebounceService = __decorate$1N([
  __param$1K(0, ILogService),
  __param$1K(1, IEnvironmentService)
], LanguageFeatureDebounceService);
registerSingleton(
  ILanguageFeatureDebounceService,
  LanguageFeatureDebounceService,
  1
  /* InstantiationType.Delayed */
);
var __decorate$1M = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1J = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$1g = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
let CodeLensContribution = class CodeLensContribution2 {
  constructor(_editor, _languageFeaturesService, debounceService, _commandService, _notificationService, _codeLensCache) {
    this._editor = _editor;
    this._languageFeaturesService = _languageFeaturesService;
    this._commandService = _commandService;
    this._notificationService = _notificationService;
    this._codeLensCache = _codeLensCache;
    this._disposables = new DisposableStore();
    this._localToDispose = new DisposableStore();
    this._lenses = [];
    this._oldCodeLensModels = new DisposableStore();
    this._provideCodeLensDebounce = debounceService.for(_languageFeaturesService.codeLensProvider, "CodeLensProvide", { min: 250 });
    this._resolveCodeLensesDebounce = debounceService.for(_languageFeaturesService.codeLensProvider, "CodeLensResolve", { min: 250, salt: "resolve" });
    this._resolveCodeLensesScheduler = new RunOnceScheduler(() => this._resolveCodeLensesInViewport(), this._resolveCodeLensesDebounce.default());
    this._disposables.add(this._editor.onDidChangeModel(() => this._onModelChange()));
    this._disposables.add(this._editor.onDidChangeModelLanguage(() => this._onModelChange()));
    this._disposables.add(this._editor.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        49
        /* EditorOption.fontInfo */
      ) || e.hasChanged(
        18
        /* EditorOption.codeLensFontSize */
      ) || e.hasChanged(
        17
        /* EditorOption.codeLensFontFamily */
      )) {
        this._updateLensStyle();
      }
      if (e.hasChanged(
        16
        /* EditorOption.codeLens */
      )) {
        this._onModelChange();
      }
    }));
    this._disposables.add(_languageFeaturesService.codeLensProvider.onDidChange(this._onModelChange, this));
    this._onModelChange();
    this._updateLensStyle();
  }
  dispose() {
    var _a2;
    this._localDispose();
    this._disposables.dispose();
    this._oldCodeLensModels.dispose();
    (_a2 = this._currentCodeLensModel) === null || _a2 === void 0 ? void 0 : _a2.dispose();
  }
  _getLayoutInfo() {
    const lineHeightFactor = Math.max(1.3, this._editor.getOption(
      65
      /* EditorOption.lineHeight */
    ) / this._editor.getOption(
      51
      /* EditorOption.fontSize */
    ));
    let fontSize = this._editor.getOption(
      18
      /* EditorOption.codeLensFontSize */
    );
    if (!fontSize || fontSize < 5) {
      fontSize = this._editor.getOption(
        51
        /* EditorOption.fontSize */
      ) * 0.9 | 0;
    }
    return {
      fontSize,
      codeLensHeight: fontSize * lineHeightFactor | 0
    };
  }
  _updateLensStyle() {
    const { codeLensHeight, fontSize } = this._getLayoutInfo();
    const fontFamily = this._editor.getOption(
      17
      /* EditorOption.codeLensFontFamily */
    );
    const editorFontInfo = this._editor.getOption(
      49
      /* EditorOption.fontInfo */
    );
    const { style: style2 } = this._editor.getContainerDomNode();
    style2.setProperty("--vscode-editorCodeLens-lineHeight", `${codeLensHeight}px`);
    style2.setProperty("--vscode-editorCodeLens-fontSize", `${fontSize}px`);
    style2.setProperty("--vscode-editorCodeLens-fontFeatureSettings", editorFontInfo.fontFeatureSettings);
    if (fontFamily) {
      style2.setProperty("--vscode-editorCodeLens-fontFamily", fontFamily);
      style2.setProperty("--vscode-editorCodeLens-fontFamilyDefault", EDITOR_FONT_DEFAULTS.fontFamily);
    }
    this._editor.changeViewZones((accessor) => {
      for (const lens of this._lenses) {
        lens.updateHeight(codeLensHeight, accessor);
      }
    });
  }
  _localDispose() {
    var _a2, _b2, _c2;
    (_a2 = this._getCodeLensModelPromise) === null || _a2 === void 0 ? void 0 : _a2.cancel();
    this._getCodeLensModelPromise = void 0;
    (_b2 = this._resolveCodeLensesPromise) === null || _b2 === void 0 ? void 0 : _b2.cancel();
    this._resolveCodeLensesPromise = void 0;
    this._localToDispose.clear();
    this._oldCodeLensModels.clear();
    (_c2 = this._currentCodeLensModel) === null || _c2 === void 0 ? void 0 : _c2.dispose();
  }
  _onModelChange() {
    this._localDispose();
    const model = this._editor.getModel();
    if (!model) {
      return;
    }
    if (!this._editor.getOption(
      16
      /* EditorOption.codeLens */
    )) {
      return;
    }
    const cachedLenses = this._codeLensCache.get(model);
    if (cachedLenses) {
      this._renderCodeLensSymbols(cachedLenses);
    }
    if (!this._languageFeaturesService.codeLensProvider.has(model)) {
      if (cachedLenses) {
        this._localToDispose.add(disposableTimeout(() => {
          const cachedLensesNow = this._codeLensCache.get(model);
          if (cachedLenses === cachedLensesNow) {
            this._codeLensCache.delete(model);
            this._onModelChange();
          }
        }, 30 * 1e3));
      }
      return;
    }
    for (const provider of this._languageFeaturesService.codeLensProvider.all(model)) {
      if (typeof provider.onDidChange === "function") {
        const registration = provider.onDidChange(() => scheduler.schedule());
        this._localToDispose.add(registration);
      }
    }
    const scheduler = new RunOnceScheduler(() => {
      var _a2;
      const t1 = Date.now();
      (_a2 = this._getCodeLensModelPromise) === null || _a2 === void 0 ? void 0 : _a2.cancel();
      this._getCodeLensModelPromise = createCancelablePromise((token) => getCodeLensModel(this._languageFeaturesService.codeLensProvider, model, token));
      this._getCodeLensModelPromise.then((result2) => {
        if (this._currentCodeLensModel) {
          this._oldCodeLensModels.add(this._currentCodeLensModel);
        }
        this._currentCodeLensModel = result2;
        this._codeLensCache.put(model, result2);
        const newDelay = this._provideCodeLensDebounce.update(model, Date.now() - t1);
        scheduler.delay = newDelay;
        this._renderCodeLensSymbols(result2);
        this._resolveCodeLensesInViewportSoon();
      }, onUnexpectedError);
    }, this._provideCodeLensDebounce.get(model));
    this._localToDispose.add(scheduler);
    this._localToDispose.add(toDisposable(() => this._resolveCodeLensesScheduler.cancel()));
    this._localToDispose.add(this._editor.onDidChangeModelContent(() => {
      var _a2;
      this._editor.changeDecorations((decorationsAccessor) => {
        this._editor.changeViewZones((viewZonesAccessor) => {
          const toDispose = [];
          let lastLensLineNumber = -1;
          this._lenses.forEach((lens) => {
            if (!lens.isValid() || lastLensLineNumber === lens.getLineNumber()) {
              toDispose.push(lens);
            } else {
              lens.update(viewZonesAccessor);
              lastLensLineNumber = lens.getLineNumber();
            }
          });
          const helper = new CodeLensHelper();
          toDispose.forEach((l) => {
            l.dispose(helper, viewZonesAccessor);
            this._lenses.splice(this._lenses.indexOf(l), 1);
          });
          helper.commit(decorationsAccessor);
        });
      });
      scheduler.schedule();
      this._resolveCodeLensesScheduler.cancel();
      (_a2 = this._resolveCodeLensesPromise) === null || _a2 === void 0 ? void 0 : _a2.cancel();
      this._resolveCodeLensesPromise = void 0;
    }));
    this._localToDispose.add(this._editor.onDidFocusEditorWidget(() => {
      scheduler.schedule();
    }));
    this._localToDispose.add(this._editor.onDidScrollChange((e) => {
      if (e.scrollTopChanged && this._lenses.length > 0) {
        this._resolveCodeLensesInViewportSoon();
      }
    }));
    this._localToDispose.add(this._editor.onDidLayoutChange(() => {
      this._resolveCodeLensesInViewportSoon();
    }));
    this._localToDispose.add(toDisposable(() => {
      if (this._editor.getModel()) {
        const scrollState = StableEditorScrollState.capture(this._editor);
        this._editor.changeDecorations((decorationsAccessor) => {
          this._editor.changeViewZones((viewZonesAccessor) => {
            this._disposeAllLenses(decorationsAccessor, viewZonesAccessor);
          });
        });
        scrollState.restore(this._editor);
      } else {
        this._disposeAllLenses(void 0, void 0);
      }
    }));
    this._localToDispose.add(this._editor.onMouseDown((e) => {
      if (e.target.type !== 9) {
        return;
      }
      let target = e.target.element;
      if ((target === null || target === void 0 ? void 0 : target.tagName) === "SPAN") {
        target = target.parentElement;
      }
      if ((target === null || target === void 0 ? void 0 : target.tagName) === "A") {
        for (const lens of this._lenses) {
          const command = lens.getCommand(target);
          if (command) {
            this._commandService.executeCommand(command.id, ...command.arguments || []).catch((err) => this._notificationService.error(err));
            break;
          }
        }
      }
    }));
    scheduler.schedule();
  }
  _disposeAllLenses(decChangeAccessor, viewZoneChangeAccessor) {
    const helper = new CodeLensHelper();
    for (const lens of this._lenses) {
      lens.dispose(helper, viewZoneChangeAccessor);
    }
    if (decChangeAccessor) {
      helper.commit(decChangeAccessor);
    }
    this._lenses.length = 0;
  }
  _renderCodeLensSymbols(symbols2) {
    if (!this._editor.hasModel()) {
      return;
    }
    const maxLineNumber = this._editor.getModel().getLineCount();
    const groups = [];
    let lastGroup;
    for (const symbol of symbols2.lenses) {
      const line = symbol.symbol.range.startLineNumber;
      if (line < 1 || line > maxLineNumber) {
        continue;
      } else if (lastGroup && lastGroup[lastGroup.length - 1].symbol.range.startLineNumber === line) {
        lastGroup.push(symbol);
      } else {
        lastGroup = [symbol];
        groups.push(lastGroup);
      }
    }
    if (!groups.length && !this._lenses.length) {
      return;
    }
    const scrollState = StableEditorScrollState.capture(this._editor);
    const layoutInfo = this._getLayoutInfo();
    this._editor.changeDecorations((decorationsAccessor) => {
      this._editor.changeViewZones((viewZoneAccessor) => {
        const helper = new CodeLensHelper();
        let codeLensIndex = 0;
        let groupsIndex = 0;
        while (groupsIndex < groups.length && codeLensIndex < this._lenses.length) {
          const symbolsLineNumber = groups[groupsIndex][0].symbol.range.startLineNumber;
          const codeLensLineNumber = this._lenses[codeLensIndex].getLineNumber();
          if (codeLensLineNumber < symbolsLineNumber) {
            this._lenses[codeLensIndex].dispose(helper, viewZoneAccessor);
            this._lenses.splice(codeLensIndex, 1);
          } else if (codeLensLineNumber === symbolsLineNumber) {
            this._lenses[codeLensIndex].updateCodeLensSymbols(groups[groupsIndex], helper);
            groupsIndex++;
            codeLensIndex++;
          } else {
            this._lenses.splice(codeLensIndex, 0, new CodeLensWidget(groups[groupsIndex], this._editor, helper, viewZoneAccessor, layoutInfo.codeLensHeight, () => this._resolveCodeLensesInViewportSoon()));
            codeLensIndex++;
            groupsIndex++;
          }
        }
        while (codeLensIndex < this._lenses.length) {
          this._lenses[codeLensIndex].dispose(helper, viewZoneAccessor);
          this._lenses.splice(codeLensIndex, 1);
        }
        while (groupsIndex < groups.length) {
          this._lenses.push(new CodeLensWidget(groups[groupsIndex], this._editor, helper, viewZoneAccessor, layoutInfo.codeLensHeight, () => this._resolveCodeLensesInViewportSoon()));
          groupsIndex++;
        }
        helper.commit(decorationsAccessor);
      });
    });
    scrollState.restore(this._editor);
  }
  _resolveCodeLensesInViewportSoon() {
    const model = this._editor.getModel();
    if (model) {
      this._resolveCodeLensesScheduler.schedule();
    }
  }
  _resolveCodeLensesInViewport() {
    var _a2;
    (_a2 = this._resolveCodeLensesPromise) === null || _a2 === void 0 ? void 0 : _a2.cancel();
    this._resolveCodeLensesPromise = void 0;
    const model = this._editor.getModel();
    if (!model) {
      return;
    }
    const toResolve = [];
    const lenses = [];
    this._lenses.forEach((lens) => {
      const request = lens.computeIfNecessary(model);
      if (request) {
        toResolve.push(request);
        lenses.push(lens);
      }
    });
    if (toResolve.length === 0) {
      return;
    }
    const t1 = Date.now();
    const resolvePromise = createCancelablePromise((token) => {
      const promises = toResolve.map((request, i) => {
        const resolvedSymbols = new Array(request.length);
        const promises2 = request.map((request2, i2) => {
          if (!request2.symbol.command && typeof request2.provider.resolveCodeLens === "function") {
            return Promise.resolve(request2.provider.resolveCodeLens(model, request2.symbol, token)).then((symbol) => {
              resolvedSymbols[i2] = symbol;
            }, onUnexpectedExternalError);
          } else {
            resolvedSymbols[i2] = request2.symbol;
            return Promise.resolve(void 0);
          }
        });
        return Promise.all(promises2).then(() => {
          if (!token.isCancellationRequested && !lenses[i].isDisposed()) {
            lenses[i].updateCommands(resolvedSymbols);
          }
        });
      });
      return Promise.all(promises);
    });
    this._resolveCodeLensesPromise = resolvePromise;
    this._resolveCodeLensesPromise.then(() => {
      const newDelay = this._resolveCodeLensesDebounce.update(model, Date.now() - t1);
      this._resolveCodeLensesScheduler.delay = newDelay;
      if (this._currentCodeLensModel) {
        this._codeLensCache.put(model, this._currentCodeLensModel);
      }
      this._oldCodeLensModels.clear();
      if (resolvePromise === this._resolveCodeLensesPromise) {
        this._resolveCodeLensesPromise = void 0;
      }
    }, (err) => {
      onUnexpectedError(err);
      if (resolvePromise === this._resolveCodeLensesPromise) {
        this._resolveCodeLensesPromise = void 0;
      }
    });
  }
  getModel() {
    return this._currentCodeLensModel;
  }
};
CodeLensContribution.ID = "css.editor.codeLens";
CodeLensContribution = __decorate$1M([
  __param$1J(1, ILanguageFeaturesService),
  __param$1J(2, ILanguageFeatureDebounceService),
  __param$1J(3, ICommandService),
  __param$1J(4, INotificationService),
  __param$1J(5, ICodeLensCache)
], CodeLensContribution);
registerEditorContribution(
  CodeLensContribution.ID,
  CodeLensContribution,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
registerEditorAction(class ShowLensesInCurrentLine extends EditorAction {
  constructor() {
    super({
      id: "codelens.showLensesInCurrentLine",
      precondition: EditorContextKeys.hasCodeLensProvider,
      label: localize("showLensOnLine", "Show CodeLens Commands For Current Line"),
      alias: "Show CodeLens Commands For Current Line"
    });
  }
  run(accessor, editor2) {
    return __awaiter$1g(this, void 0, void 0, function* () {
      if (!editor2.hasModel()) {
        return;
      }
      const quickInputService = accessor.get(IQuickInputService);
      const commandService = accessor.get(ICommandService);
      const notificationService = accessor.get(INotificationService);
      const lineNumber = editor2.getSelection().positionLineNumber;
      const codelensController = editor2.getContribution(CodeLensContribution.ID);
      if (!codelensController) {
        return;
      }
      const model = codelensController.getModel();
      if (!model) {
        return;
      }
      const items = [];
      for (const lens of model.lenses) {
        if (lens.symbol.command && lens.symbol.range.startLineNumber === lineNumber) {
          items.push({
            label: lens.symbol.command.title,
            command: lens.symbol.command
          });
        }
      }
      if (items.length === 0) {
        return;
      }
      const item = yield quickInputService.pick(items, { canPickMany: false });
      if (!item) {
        return;
      }
      if (model.isDisposed) {
        return yield commandService.executeCommand(this.id);
      }
      try {
        yield commandService.executeCommand(item.command.id, ...item.command.arguments || []);
      } catch (err) {
        notificationService.error(err);
      }
    });
  }
});
const INITIALIZE = "$initialize";
let webWorkerWarningLogged = false;
function logOnceWebWorkerWarning(err) {
  if (!isWeb) {
    return;
  }
  if (!webWorkerWarningLogged) {
    webWorkerWarningLogged = true;
    console.warn("Could not create web worker(s). Falling back to loading web worker code in main thread, which might cause UI freezes. Please see https://github.com/microsoft/monaco-editor#faq");
  }
  console.warn(err.message);
}
class RequestMessage {
  constructor(vsWorker, req, method, args) {
    this.vsWorker = vsWorker;
    this.req = req;
    this.method = method;
    this.args = args;
    this.type = 0;
  }
}
class ReplyMessage {
  constructor(vsWorker, seq, res, err) {
    this.vsWorker = vsWorker;
    this.seq = seq;
    this.res = res;
    this.err = err;
    this.type = 1;
  }
}
class SubscribeEventMessage {
  constructor(vsWorker, req, eventName, arg) {
    this.vsWorker = vsWorker;
    this.req = req;
    this.eventName = eventName;
    this.arg = arg;
    this.type = 2;
  }
}
class EventMessage {
  constructor(vsWorker, req, event) {
    this.vsWorker = vsWorker;
    this.req = req;
    this.event = event;
    this.type = 3;
  }
}
class UnsubscribeEventMessage {
  constructor(vsWorker, req) {
    this.vsWorker = vsWorker;
    this.req = req;
    this.type = 4;
  }
}
class SimpleWorkerProtocol {
  constructor(handler) {
    this._workerId = -1;
    this._handler = handler;
    this._lastSentReq = 0;
    this._pendingReplies = /* @__PURE__ */ Object.create(null);
    this._pendingEmitters = /* @__PURE__ */ new Map();
    this._pendingEvents = /* @__PURE__ */ new Map();
  }
  setWorkerId(workerId) {
    this._workerId = workerId;
  }
  sendMessage(method, args) {
    const req = String(++this._lastSentReq);
    return new Promise((resolve2, reject) => {
      this._pendingReplies[req] = {
        resolve: resolve2,
        reject
      };
      this._send(new RequestMessage(this._workerId, req, method, args));
    });
  }
  listen(eventName, arg) {
    let req = null;
    const emitter = new Emitter$1({
      onWillAddFirstListener: () => {
        req = String(++this._lastSentReq);
        this._pendingEmitters.set(req, emitter);
        this._send(new SubscribeEventMessage(this._workerId, req, eventName, arg));
      },
      onDidRemoveLastListener: () => {
        this._pendingEmitters.delete(req);
        this._send(new UnsubscribeEventMessage(this._workerId, req));
        req = null;
      }
    });
    return emitter.event;
  }
  handleMessage(message) {
    if (!message || !message.vsWorker) {
      return;
    }
    if (this._workerId !== -1 && message.vsWorker !== this._workerId) {
      return;
    }
    this._handleMessage(message);
  }
  _handleMessage(msg) {
    switch (msg.type) {
      case 1:
        return this._handleReplyMessage(msg);
      case 0:
        return this._handleRequestMessage(msg);
      case 2:
        return this._handleSubscribeEventMessage(msg);
      case 3:
        return this._handleEventMessage(msg);
      case 4:
        return this._handleUnsubscribeEventMessage(msg);
    }
  }
  _handleReplyMessage(replyMessage) {
    if (!this._pendingReplies[replyMessage.seq]) {
      console.warn("Got reply to unknown seq");
      return;
    }
    const reply = this._pendingReplies[replyMessage.seq];
    delete this._pendingReplies[replyMessage.seq];
    if (replyMessage.err) {
      let err = replyMessage.err;
      if (replyMessage.err.$isError) {
        err = new Error();
        err.name = replyMessage.err.name;
        err.message = replyMessage.err.message;
        err.stack = replyMessage.err.stack;
      }
      reply.reject(err);
      return;
    }
    reply.resolve(replyMessage.res);
  }
  _handleRequestMessage(requestMessage) {
    const req = requestMessage.req;
    const result2 = this._handler.handleMessage(requestMessage.method, requestMessage.args);
    result2.then((r) => {
      this._send(new ReplyMessage(this._workerId, req, r, void 0));
    }, (e) => {
      if (e.detail instanceof Error) {
        e.detail = transformErrorForSerialization(e.detail);
      }
      this._send(new ReplyMessage(this._workerId, req, void 0, transformErrorForSerialization(e)));
    });
  }
  _handleSubscribeEventMessage(msg) {
    const req = msg.req;
    const disposable = this._handler.handleEvent(msg.eventName, msg.arg)((event) => {
      this._send(new EventMessage(this._workerId, req, event));
    });
    this._pendingEvents.set(req, disposable);
  }
  _handleEventMessage(msg) {
    if (!this._pendingEmitters.has(msg.req)) {
      console.warn("Got event for unknown req");
      return;
    }
    this._pendingEmitters.get(msg.req).fire(msg.event);
  }
  _handleUnsubscribeEventMessage(msg) {
    if (!this._pendingEvents.has(msg.req)) {
      console.warn("Got unsubscribe for unknown req");
      return;
    }
    this._pendingEvents.get(msg.req).dispose();
    this._pendingEvents.delete(msg.req);
  }
  _send(msg) {
    const transfer = [];
    if (msg.type === 0) {
      for (let i = 0; i < msg.args.length; i++) {
        if (msg.args[i] instanceof ArrayBuffer) {
          transfer.push(msg.args[i]);
        }
      }
    } else if (msg.type === 1) {
      if (msg.res instanceof ArrayBuffer) {
        transfer.push(msg.res);
      }
    }
    this._handler.sendMessage(msg, transfer);
  }
}
class SimpleWorkerClient extends Disposable {
  constructor(workerFactory, moduleId, host) {
    super();
    let lazyProxyReject = null;
    this._worker = this._register(workerFactory.create("vs/base/common/worker/simpleWorker", (msg) => {
      this._protocol.handleMessage(msg);
    }, (err) => {
      lazyProxyReject === null || lazyProxyReject === void 0 ? void 0 : lazyProxyReject(err);
    }));
    this._protocol = new SimpleWorkerProtocol({
      sendMessage: (msg, transfer) => {
        this._worker.postMessage(msg, transfer);
      },
      handleMessage: (method, args) => {
        if (typeof host[method] !== "function") {
          return Promise.reject(new Error("Missing method " + method + " on main thread host."));
        }
        try {
          return Promise.resolve(host[method].apply(host, args));
        } catch (e) {
          return Promise.reject(e);
        }
      },
      handleEvent: (eventName, arg) => {
        if (propertyIsDynamicEvent(eventName)) {
          const event = host[eventName].call(host, arg);
          if (typeof event !== "function") {
            throw new Error(`Missing dynamic event ${eventName} on main thread host.`);
          }
          return event;
        }
        if (propertyIsEvent(eventName)) {
          const event = host[eventName];
          if (typeof event !== "function") {
            throw new Error(`Missing event ${eventName} on main thread host.`);
          }
          return event;
        }
        throw new Error(`Malformed event name ${eventName}`);
      }
    });
    this._protocol.setWorkerId(this._worker.getId());
    let loaderConfiguration = null;
    const globalRequire = globalThis.require;
    if (typeof globalRequire !== "undefined" && typeof globalRequire.getConfig === "function") {
      loaderConfiguration = globalRequire.getConfig();
    } else if (typeof globalThis.requirejs !== "undefined") {
      loaderConfiguration = globalThis.requirejs.s.contexts._.config;
    }
    const hostMethods = getAllMethodNames(host);
    this._onModuleLoaded = this._protocol.sendMessage(INITIALIZE, [
      this._worker.getId(),
      JSON.parse(JSON.stringify(loaderConfiguration)),
      moduleId,
      hostMethods
    ]);
    const proxyMethodRequest = (method, args) => {
      return this._request(method, args);
    };
    const proxyListen = (eventName, arg) => {
      return this._protocol.listen(eventName, arg);
    };
    this._lazyProxy = new Promise((resolve2, reject) => {
      lazyProxyReject = reject;
      this._onModuleLoaded.then((availableMethods) => {
        resolve2(createProxyObject(availableMethods, proxyMethodRequest, proxyListen));
      }, (e) => {
        reject(e);
        this._onError("Worker failed to load " + moduleId, e);
      });
    });
  }
  getProxyObject() {
    return this._lazyProxy;
  }
  _request(method, args) {
    return new Promise((resolve2, reject) => {
      this._onModuleLoaded.then(() => {
        this._protocol.sendMessage(method, args).then(resolve2, reject);
      }, reject);
    });
  }
  _onError(message, error2) {
    console.error(message);
    console.info(error2);
  }
}
function propertyIsEvent(name) {
  return name[0] === "o" && name[1] === "n" && isUpperAsciiLetter(name.charCodeAt(2));
}
function propertyIsDynamicEvent(name) {
  return /^onDynamic/.test(name) && isUpperAsciiLetter(name.charCodeAt(9));
}
function createProxyObject(methodNames, invoke, proxyListen) {
  const createProxyMethod = (method) => {
    return function() {
      const args = Array.prototype.slice.call(arguments, 0);
      return invoke(method, args);
    };
  };
  const createProxyDynamicEvent = (eventName) => {
    return function(arg) {
      return proxyListen(eventName, arg);
    };
  };
  const result2 = {};
  for (const methodName of methodNames) {
    if (propertyIsDynamicEvent(methodName)) {
      result2[methodName] = createProxyDynamicEvent(methodName);
      continue;
    }
    if (propertyIsEvent(methodName)) {
      result2[methodName] = proxyListen(methodName, void 0);
      continue;
    }
    result2[methodName] = createProxyMethod(methodName);
  }
  return result2;
}
const ttPolicy$3 = createTrustedTypesPolicy("defaultWorkerFactory", { createScriptURL: (value) => value });
function getWorker(label) {
  const monacoEnvironment2 = globalThis.MonacoEnvironment;
  if (monacoEnvironment2) {
    if (typeof monacoEnvironment2.getWorker === "function") {
      return monacoEnvironment2.getWorker("workerMain.js", label);
    }
    if (typeof monacoEnvironment2.getWorkerUrl === "function") {
      const workerUrl = monacoEnvironment2.getWorkerUrl("workerMain.js", label);
      return new Worker(ttPolicy$3 ? ttPolicy$3.createScriptURL(workerUrl) : workerUrl, { name: label });
    }
  }
  throw new Error(`You must define a function MonacoEnvironment.getWorkerUrl or MonacoEnvironment.getWorker`);
}
function isPromiseLike(obj) {
  if (typeof obj.then === "function") {
    return true;
  }
  return false;
}
class WebWorker {
  constructor(moduleId, id3, label, onMessageCallback, onErrorCallback) {
    this.id = id3;
    const workerOrPromise = getWorker(label);
    if (isPromiseLike(workerOrPromise)) {
      this.worker = workerOrPromise;
    } else {
      this.worker = Promise.resolve(workerOrPromise);
    }
    this.postMessage(moduleId, []);
    this.worker.then((w) => {
      w.onmessage = function(ev) {
        onMessageCallback(ev.data);
      };
      w.onmessageerror = onErrorCallback;
      if (typeof w.addEventListener === "function") {
        w.addEventListener("error", onErrorCallback);
      }
    });
  }
  getId() {
    return this.id;
  }
  postMessage(message, transfer) {
    var _a2;
    (_a2 = this.worker) === null || _a2 === void 0 ? void 0 : _a2.then((w) => w.postMessage(message, transfer));
  }
  dispose() {
    var _a2;
    (_a2 = this.worker) === null || _a2 === void 0 ? void 0 : _a2.then((w) => w.terminate());
    this.worker = null;
  }
}
class DefaultWorkerFactory {
  constructor(label) {
    this._label = label;
    this._webWorkerFailedBeforeError = false;
  }
  create(moduleId, onMessageCallback, onErrorCallback) {
    const workerId = ++DefaultWorkerFactory.LAST_WORKER_ID;
    if (this._webWorkerFailedBeforeError) {
      throw this._webWorkerFailedBeforeError;
    }
    return new WebWorker(moduleId, workerId, this._label || "anonymous" + workerId, onMessageCallback, (err) => {
      logOnceWebWorkerWarning(err);
      this._webWorkerFailedBeforeError = err;
      onErrorCallback(err);
    });
  }
}
DefaultWorkerFactory.LAST_WORKER_ID = 0;
class DiffChange {
  /**
   * Constructs a new DiffChange with the given sequence information
   * and content.
   */
  constructor(originalStart, originalLength, modifiedStart, modifiedLength) {
    this.originalStart = originalStart;
    this.originalLength = originalLength;
    this.modifiedStart = modifiedStart;
    this.modifiedLength = modifiedLength;
  }
  /**
   * The end point (exclusive) of the change in the original sequence.
   */
  getOriginalEnd() {
    return this.originalStart + this.originalLength;
  }
  /**
   * The end point (exclusive) of the change in the modified sequence.
   */
  getModifiedEnd() {
    return this.modifiedStart + this.modifiedLength;
  }
}
class StringDiffSequence {
  constructor(source) {
    this.source = source;
  }
  getElements() {
    const source = this.source;
    const characters = new Int32Array(source.length);
    for (let i = 0, len = source.length; i < len; i++) {
      characters[i] = source.charCodeAt(i);
    }
    return characters;
  }
}
function stringDiff(original, modified, pretty) {
  return new LcsDiff(new StringDiffSequence(original), new StringDiffSequence(modified)).ComputeDiff(pretty).changes;
}
class Debug {
  static Assert(condition, message) {
    if (!condition) {
      throw new Error(message);
    }
  }
}
class MyArray {
  /**
   * Copies a range of elements from an Array starting at the specified source index and pastes
   * them to another Array starting at the specified destination index. The length and the indexes
   * are specified as 64-bit integers.
   * sourceArray:
   *		The Array that contains the data to copy.
   * sourceIndex:
   *		A 64-bit integer that represents the index in the sourceArray at which copying begins.
   * destinationArray:
   *		The Array that receives the data.
   * destinationIndex:
   *		A 64-bit integer that represents the index in the destinationArray at which storing begins.
   * length:
   *		A 64-bit integer that represents the number of elements to copy.
   */
  static Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length2) {
    for (let i = 0; i < length2; i++) {
      destinationArray[destinationIndex + i] = sourceArray[sourceIndex + i];
    }
  }
  static Copy2(sourceArray, sourceIndex, destinationArray, destinationIndex, length2) {
    for (let i = 0; i < length2; i++) {
      destinationArray[destinationIndex + i] = sourceArray[sourceIndex + i];
    }
  }
}
class DiffChangeHelper {
  /**
   * Constructs a new DiffChangeHelper for the given DiffSequences.
   */
  constructor() {
    this.m_changes = [];
    this.m_originalStart = 1073741824;
    this.m_modifiedStart = 1073741824;
    this.m_originalCount = 0;
    this.m_modifiedCount = 0;
  }
  /**
   * Marks the beginning of the next change in the set of differences.
   */
  MarkNextChange() {
    if (this.m_originalCount > 0 || this.m_modifiedCount > 0) {
      this.m_changes.push(new DiffChange(this.m_originalStart, this.m_originalCount, this.m_modifiedStart, this.m_modifiedCount));
    }
    this.m_originalCount = 0;
    this.m_modifiedCount = 0;
    this.m_originalStart = 1073741824;
    this.m_modifiedStart = 1073741824;
  }
  /**
   * Adds the original element at the given position to the elements
   * affected by the current change. The modified index gives context
   * to the change position with respect to the original sequence.
   * @param originalIndex The index of the original element to add.
   * @param modifiedIndex The index of the modified element that provides corresponding position in the modified sequence.
   */
  AddOriginalElement(originalIndex, modifiedIndex) {
    this.m_originalStart = Math.min(this.m_originalStart, originalIndex);
    this.m_modifiedStart = Math.min(this.m_modifiedStart, modifiedIndex);
    this.m_originalCount++;
  }
  /**
   * Adds the modified element at the given position to the elements
   * affected by the current change. The original index gives context
   * to the change position with respect to the modified sequence.
   * @param originalIndex The index of the original element that provides corresponding position in the original sequence.
   * @param modifiedIndex The index of the modified element to add.
   */
  AddModifiedElement(originalIndex, modifiedIndex) {
    this.m_originalStart = Math.min(this.m_originalStart, originalIndex);
    this.m_modifiedStart = Math.min(this.m_modifiedStart, modifiedIndex);
    this.m_modifiedCount++;
  }
  /**
   * Retrieves all of the changes marked by the class.
   */
  getChanges() {
    if (this.m_originalCount > 0 || this.m_modifiedCount > 0) {
      this.MarkNextChange();
    }
    return this.m_changes;
  }
  /**
   * Retrieves all of the changes marked by the class in the reverse order
   */
  getReverseChanges() {
    if (this.m_originalCount > 0 || this.m_modifiedCount > 0) {
      this.MarkNextChange();
    }
    this.m_changes.reverse();
    return this.m_changes;
  }
}
class LcsDiff {
  /**
   * Constructs the DiffFinder
   */
  constructor(originalSequence, modifiedSequence, continueProcessingPredicate = null) {
    this.ContinueProcessingPredicate = continueProcessingPredicate;
    this._originalSequence = originalSequence;
    this._modifiedSequence = modifiedSequence;
    const [originalStringElements, originalElementsOrHash, originalHasStrings] = LcsDiff._getElements(originalSequence);
    const [modifiedStringElements, modifiedElementsOrHash, modifiedHasStrings] = LcsDiff._getElements(modifiedSequence);
    this._hasStrings = originalHasStrings && modifiedHasStrings;
    this._originalStringElements = originalStringElements;
    this._originalElementsOrHash = originalElementsOrHash;
    this._modifiedStringElements = modifiedStringElements;
    this._modifiedElementsOrHash = modifiedElementsOrHash;
    this.m_forwardHistory = [];
    this.m_reverseHistory = [];
  }
  static _isStringArray(arr) {
    return arr.length > 0 && typeof arr[0] === "string";
  }
  static _getElements(sequence) {
    const elements = sequence.getElements();
    if (LcsDiff._isStringArray(elements)) {
      const hashes = new Int32Array(elements.length);
      for (let i = 0, len = elements.length; i < len; i++) {
        hashes[i] = stringHash(elements[i], 0);
      }
      return [elements, hashes, true];
    }
    if (elements instanceof Int32Array) {
      return [[], elements, false];
    }
    return [[], new Int32Array(elements), false];
  }
  ElementsAreEqual(originalIndex, newIndex) {
    if (this._originalElementsOrHash[originalIndex] !== this._modifiedElementsOrHash[newIndex]) {
      return false;
    }
    return this._hasStrings ? this._originalStringElements[originalIndex] === this._modifiedStringElements[newIndex] : true;
  }
  ElementsAreStrictEqual(originalIndex, newIndex) {
    if (!this.ElementsAreEqual(originalIndex, newIndex)) {
      return false;
    }
    const originalElement = LcsDiff._getStrictElement(this._originalSequence, originalIndex);
    const modifiedElement = LcsDiff._getStrictElement(this._modifiedSequence, newIndex);
    return originalElement === modifiedElement;
  }
  static _getStrictElement(sequence, index) {
    if (typeof sequence.getStrictElement === "function") {
      return sequence.getStrictElement(index);
    }
    return null;
  }
  OriginalElementsAreEqual(index1, index2) {
    if (this._originalElementsOrHash[index1] !== this._originalElementsOrHash[index2]) {
      return false;
    }
    return this._hasStrings ? this._originalStringElements[index1] === this._originalStringElements[index2] : true;
  }
  ModifiedElementsAreEqual(index1, index2) {
    if (this._modifiedElementsOrHash[index1] !== this._modifiedElementsOrHash[index2]) {
      return false;
    }
    return this._hasStrings ? this._modifiedStringElements[index1] === this._modifiedStringElements[index2] : true;
  }
  ComputeDiff(pretty) {
    return this._ComputeDiff(0, this._originalElementsOrHash.length - 1, 0, this._modifiedElementsOrHash.length - 1, pretty);
  }
  /**
   * Computes the differences between the original and modified input
   * sequences on the bounded range.
   * @returns An array of the differences between the two input sequences.
   */
  _ComputeDiff(originalStart, originalEnd, modifiedStart, modifiedEnd, pretty) {
    const quitEarlyArr = [false];
    let changes = this.ComputeDiffRecursive(originalStart, originalEnd, modifiedStart, modifiedEnd, quitEarlyArr);
    if (pretty) {
      changes = this.PrettifyChanges(changes);
    }
    return {
      quitEarly: quitEarlyArr[0],
      changes
    };
  }
  /**
   * Private helper method which computes the differences on the bounded range
   * recursively.
   * @returns An array of the differences between the two input sequences.
   */
  ComputeDiffRecursive(originalStart, originalEnd, modifiedStart, modifiedEnd, quitEarlyArr) {
    quitEarlyArr[0] = false;
    while (originalStart <= originalEnd && modifiedStart <= modifiedEnd && this.ElementsAreEqual(originalStart, modifiedStart)) {
      originalStart++;
      modifiedStart++;
    }
    while (originalEnd >= originalStart && modifiedEnd >= modifiedStart && this.ElementsAreEqual(originalEnd, modifiedEnd)) {
      originalEnd--;
      modifiedEnd--;
    }
    if (originalStart > originalEnd || modifiedStart > modifiedEnd) {
      let changes;
      if (modifiedStart <= modifiedEnd) {
        Debug.Assert(originalStart === originalEnd + 1, "originalStart should only be one more than originalEnd");
        changes = [
          new DiffChange(originalStart, 0, modifiedStart, modifiedEnd - modifiedStart + 1)
        ];
      } else if (originalStart <= originalEnd) {
        Debug.Assert(modifiedStart === modifiedEnd + 1, "modifiedStart should only be one more than modifiedEnd");
        changes = [
          new DiffChange(originalStart, originalEnd - originalStart + 1, modifiedStart, 0)
        ];
      } else {
        Debug.Assert(originalStart === originalEnd + 1, "originalStart should only be one more than originalEnd");
        Debug.Assert(modifiedStart === modifiedEnd + 1, "modifiedStart should only be one more than modifiedEnd");
        changes = [];
      }
      return changes;
    }
    const midOriginalArr = [0];
    const midModifiedArr = [0];
    const result2 = this.ComputeRecursionPoint(originalStart, originalEnd, modifiedStart, modifiedEnd, midOriginalArr, midModifiedArr, quitEarlyArr);
    const midOriginal = midOriginalArr[0];
    const midModified = midModifiedArr[0];
    if (result2 !== null) {
      return result2;
    } else if (!quitEarlyArr[0]) {
      const leftChanges = this.ComputeDiffRecursive(originalStart, midOriginal, modifiedStart, midModified, quitEarlyArr);
      let rightChanges = [];
      if (!quitEarlyArr[0]) {
        rightChanges = this.ComputeDiffRecursive(midOriginal + 1, originalEnd, midModified + 1, modifiedEnd, quitEarlyArr);
      } else {
        rightChanges = [
          new DiffChange(midOriginal + 1, originalEnd - (midOriginal + 1) + 1, midModified + 1, modifiedEnd - (midModified + 1) + 1)
        ];
      }
      return this.ConcatenateChanges(leftChanges, rightChanges);
    }
    return [
      new DiffChange(originalStart, originalEnd - originalStart + 1, modifiedStart, modifiedEnd - modifiedStart + 1)
    ];
  }
  WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr) {
    let forwardChanges = null;
    let reverseChanges = null;
    let changeHelper = new DiffChangeHelper();
    let diagonalMin = diagonalForwardStart;
    let diagonalMax = diagonalForwardEnd;
    let diagonalRelative = midOriginalArr[0] - midModifiedArr[0] - diagonalForwardOffset;
    let lastOriginalIndex = -1073741824;
    let historyIndex = this.m_forwardHistory.length - 1;
    do {
      const diagonal = diagonalRelative + diagonalForwardBase;
      if (diagonal === diagonalMin || diagonal < diagonalMax && forwardPoints[diagonal - 1] < forwardPoints[diagonal + 1]) {
        originalIndex = forwardPoints[diagonal + 1];
        modifiedIndex = originalIndex - diagonalRelative - diagonalForwardOffset;
        if (originalIndex < lastOriginalIndex) {
          changeHelper.MarkNextChange();
        }
        lastOriginalIndex = originalIndex;
        changeHelper.AddModifiedElement(originalIndex + 1, modifiedIndex);
        diagonalRelative = diagonal + 1 - diagonalForwardBase;
      } else {
        originalIndex = forwardPoints[diagonal - 1] + 1;
        modifiedIndex = originalIndex - diagonalRelative - diagonalForwardOffset;
        if (originalIndex < lastOriginalIndex) {
          changeHelper.MarkNextChange();
        }
        lastOriginalIndex = originalIndex - 1;
        changeHelper.AddOriginalElement(originalIndex, modifiedIndex + 1);
        diagonalRelative = diagonal - 1 - diagonalForwardBase;
      }
      if (historyIndex >= 0) {
        forwardPoints = this.m_forwardHistory[historyIndex];
        diagonalForwardBase = forwardPoints[0];
        diagonalMin = 1;
        diagonalMax = forwardPoints.length - 1;
      }
    } while (--historyIndex >= -1);
    forwardChanges = changeHelper.getReverseChanges();
    if (quitEarlyArr[0]) {
      let originalStartPoint = midOriginalArr[0] + 1;
      let modifiedStartPoint = midModifiedArr[0] + 1;
      if (forwardChanges !== null && forwardChanges.length > 0) {
        const lastForwardChange = forwardChanges[forwardChanges.length - 1];
        originalStartPoint = Math.max(originalStartPoint, lastForwardChange.getOriginalEnd());
        modifiedStartPoint = Math.max(modifiedStartPoint, lastForwardChange.getModifiedEnd());
      }
      reverseChanges = [
        new DiffChange(originalStartPoint, originalEnd - originalStartPoint + 1, modifiedStartPoint, modifiedEnd - modifiedStartPoint + 1)
      ];
    } else {
      changeHelper = new DiffChangeHelper();
      diagonalMin = diagonalReverseStart;
      diagonalMax = diagonalReverseEnd;
      diagonalRelative = midOriginalArr[0] - midModifiedArr[0] - diagonalReverseOffset;
      lastOriginalIndex = 1073741824;
      historyIndex = deltaIsEven ? this.m_reverseHistory.length - 1 : this.m_reverseHistory.length - 2;
      do {
        const diagonal = diagonalRelative + diagonalReverseBase;
        if (diagonal === diagonalMin || diagonal < diagonalMax && reversePoints[diagonal - 1] >= reversePoints[diagonal + 1]) {
          originalIndex = reversePoints[diagonal + 1] - 1;
          modifiedIndex = originalIndex - diagonalRelative - diagonalReverseOffset;
          if (originalIndex > lastOriginalIndex) {
            changeHelper.MarkNextChange();
          }
          lastOriginalIndex = originalIndex + 1;
          changeHelper.AddOriginalElement(originalIndex + 1, modifiedIndex + 1);
          diagonalRelative = diagonal + 1 - diagonalReverseBase;
        } else {
          originalIndex = reversePoints[diagonal - 1];
          modifiedIndex = originalIndex - diagonalRelative - diagonalReverseOffset;
          if (originalIndex > lastOriginalIndex) {
            changeHelper.MarkNextChange();
          }
          lastOriginalIndex = originalIndex;
          changeHelper.AddModifiedElement(originalIndex + 1, modifiedIndex + 1);
          diagonalRelative = diagonal - 1 - diagonalReverseBase;
        }
        if (historyIndex >= 0) {
          reversePoints = this.m_reverseHistory[historyIndex];
          diagonalReverseBase = reversePoints[0];
          diagonalMin = 1;
          diagonalMax = reversePoints.length - 1;
        }
      } while (--historyIndex >= -1);
      reverseChanges = changeHelper.getChanges();
    }
    return this.ConcatenateChanges(forwardChanges, reverseChanges);
  }
  /**
   * Given the range to compute the diff on, this method finds the point:
   * (midOriginal, midModified)
   * that exists in the middle of the LCS of the two sequences and
   * is the point at which the LCS problem may be broken down recursively.
   * This method will try to keep the LCS trace in memory. If the LCS recursion
   * point is calculated and the full trace is available in memory, then this method
   * will return the change list.
   * @param originalStart The start bound of the original sequence range
   * @param originalEnd The end bound of the original sequence range
   * @param modifiedStart The start bound of the modified sequence range
   * @param modifiedEnd The end bound of the modified sequence range
   * @param midOriginal The middle point of the original sequence range
   * @param midModified The middle point of the modified sequence range
   * @returns The diff changes, if available, otherwise null
   */
  ComputeRecursionPoint(originalStart, originalEnd, modifiedStart, modifiedEnd, midOriginalArr, midModifiedArr, quitEarlyArr) {
    let originalIndex = 0, modifiedIndex = 0;
    let diagonalForwardStart = 0, diagonalForwardEnd = 0;
    let diagonalReverseStart = 0, diagonalReverseEnd = 0;
    originalStart--;
    modifiedStart--;
    midOriginalArr[0] = 0;
    midModifiedArr[0] = 0;
    this.m_forwardHistory = [];
    this.m_reverseHistory = [];
    const maxDifferences = originalEnd - originalStart + (modifiedEnd - modifiedStart);
    const numDiagonals = maxDifferences + 1;
    const forwardPoints = new Int32Array(numDiagonals);
    const reversePoints = new Int32Array(numDiagonals);
    const diagonalForwardBase = modifiedEnd - modifiedStart;
    const diagonalReverseBase = originalEnd - originalStart;
    const diagonalForwardOffset = originalStart - modifiedStart;
    const diagonalReverseOffset = originalEnd - modifiedEnd;
    const delta = diagonalReverseBase - diagonalForwardBase;
    const deltaIsEven = delta % 2 === 0;
    forwardPoints[diagonalForwardBase] = originalStart;
    reversePoints[diagonalReverseBase] = originalEnd;
    quitEarlyArr[0] = false;
    for (let numDifferences = 1; numDifferences <= maxDifferences / 2 + 1; numDifferences++) {
      let furthestOriginalIndex = 0;
      let furthestModifiedIndex = 0;
      diagonalForwardStart = this.ClipDiagonalBound(diagonalForwardBase - numDifferences, numDifferences, diagonalForwardBase, numDiagonals);
      diagonalForwardEnd = this.ClipDiagonalBound(diagonalForwardBase + numDifferences, numDifferences, diagonalForwardBase, numDiagonals);
      for (let diagonal = diagonalForwardStart; diagonal <= diagonalForwardEnd; diagonal += 2) {
        if (diagonal === diagonalForwardStart || diagonal < diagonalForwardEnd && forwardPoints[diagonal - 1] < forwardPoints[diagonal + 1]) {
          originalIndex = forwardPoints[diagonal + 1];
        } else {
          originalIndex = forwardPoints[diagonal - 1] + 1;
        }
        modifiedIndex = originalIndex - (diagonal - diagonalForwardBase) - diagonalForwardOffset;
        const tempOriginalIndex = originalIndex;
        while (originalIndex < originalEnd && modifiedIndex < modifiedEnd && this.ElementsAreEqual(originalIndex + 1, modifiedIndex + 1)) {
          originalIndex++;
          modifiedIndex++;
        }
        forwardPoints[diagonal] = originalIndex;
        if (originalIndex + modifiedIndex > furthestOriginalIndex + furthestModifiedIndex) {
          furthestOriginalIndex = originalIndex;
          furthestModifiedIndex = modifiedIndex;
        }
        if (!deltaIsEven && Math.abs(diagonal - diagonalReverseBase) <= numDifferences - 1) {
          if (originalIndex >= reversePoints[diagonal]) {
            midOriginalArr[0] = originalIndex;
            midModifiedArr[0] = modifiedIndex;
            if (tempOriginalIndex <= reversePoints[diagonal] && 1447 > 0 && numDifferences <= 1447 + 1) {
              return this.WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr);
            } else {
              return null;
            }
          }
        }
      }
      const matchLengthOfLongest = (furthestOriginalIndex - originalStart + (furthestModifiedIndex - modifiedStart) - numDifferences) / 2;
      if (this.ContinueProcessingPredicate !== null && !this.ContinueProcessingPredicate(furthestOriginalIndex, matchLengthOfLongest)) {
        quitEarlyArr[0] = true;
        midOriginalArr[0] = furthestOriginalIndex;
        midModifiedArr[0] = furthestModifiedIndex;
        if (matchLengthOfLongest > 0 && 1447 > 0 && numDifferences <= 1447 + 1) {
          return this.WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr);
        } else {
          originalStart++;
          modifiedStart++;
          return [
            new DiffChange(originalStart, originalEnd - originalStart + 1, modifiedStart, modifiedEnd - modifiedStart + 1)
          ];
        }
      }
      diagonalReverseStart = this.ClipDiagonalBound(diagonalReverseBase - numDifferences, numDifferences, diagonalReverseBase, numDiagonals);
      diagonalReverseEnd = this.ClipDiagonalBound(diagonalReverseBase + numDifferences, numDifferences, diagonalReverseBase, numDiagonals);
      for (let diagonal = diagonalReverseStart; diagonal <= diagonalReverseEnd; diagonal += 2) {
        if (diagonal === diagonalReverseStart || diagonal < diagonalReverseEnd && reversePoints[diagonal - 1] >= reversePoints[diagonal + 1]) {
          originalIndex = reversePoints[diagonal + 1] - 1;
        } else {
          originalIndex = reversePoints[diagonal - 1];
        }
        modifiedIndex = originalIndex - (diagonal - diagonalReverseBase) - diagonalReverseOffset;
        const tempOriginalIndex = originalIndex;
        while (originalIndex > originalStart && modifiedIndex > modifiedStart && this.ElementsAreEqual(originalIndex, modifiedIndex)) {
          originalIndex--;
          modifiedIndex--;
        }
        reversePoints[diagonal] = originalIndex;
        if (deltaIsEven && Math.abs(diagonal - diagonalForwardBase) <= numDifferences) {
          if (originalIndex <= forwardPoints[diagonal]) {
            midOriginalArr[0] = originalIndex;
            midModifiedArr[0] = modifiedIndex;
            if (tempOriginalIndex >= forwardPoints[diagonal] && 1447 > 0 && numDifferences <= 1447 + 1) {
              return this.WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr);
            } else {
              return null;
            }
          }
        }
      }
      if (numDifferences <= 1447) {
        let temp = new Int32Array(diagonalForwardEnd - diagonalForwardStart + 2);
        temp[0] = diagonalForwardBase - diagonalForwardStart + 1;
        MyArray.Copy2(forwardPoints, diagonalForwardStart, temp, 1, diagonalForwardEnd - diagonalForwardStart + 1);
        this.m_forwardHistory.push(temp);
        temp = new Int32Array(diagonalReverseEnd - diagonalReverseStart + 2);
        temp[0] = diagonalReverseBase - diagonalReverseStart + 1;
        MyArray.Copy2(reversePoints, diagonalReverseStart, temp, 1, diagonalReverseEnd - diagonalReverseStart + 1);
        this.m_reverseHistory.push(temp);
      }
    }
    return this.WALKTRACE(diagonalForwardBase, diagonalForwardStart, diagonalForwardEnd, diagonalForwardOffset, diagonalReverseBase, diagonalReverseStart, diagonalReverseEnd, diagonalReverseOffset, forwardPoints, reversePoints, originalIndex, originalEnd, midOriginalArr, modifiedIndex, modifiedEnd, midModifiedArr, deltaIsEven, quitEarlyArr);
  }
  /**
   * Shifts the given changes to provide a more intuitive diff.
   * While the first element in a diff matches the first element after the diff,
   * we shift the diff down.
   *
   * @param changes The list of changes to shift
   * @returns The shifted changes
   */
  PrettifyChanges(changes) {
    for (let i = 0; i < changes.length; i++) {
      const change = changes[i];
      const originalStop = i < changes.length - 1 ? changes[i + 1].originalStart : this._originalElementsOrHash.length;
      const modifiedStop = i < changes.length - 1 ? changes[i + 1].modifiedStart : this._modifiedElementsOrHash.length;
      const checkOriginal = change.originalLength > 0;
      const checkModified = change.modifiedLength > 0;
      while (change.originalStart + change.originalLength < originalStop && change.modifiedStart + change.modifiedLength < modifiedStop && (!checkOriginal || this.OriginalElementsAreEqual(change.originalStart, change.originalStart + change.originalLength)) && (!checkModified || this.ModifiedElementsAreEqual(change.modifiedStart, change.modifiedStart + change.modifiedLength))) {
        const startStrictEqual = this.ElementsAreStrictEqual(change.originalStart, change.modifiedStart);
        const endStrictEqual = this.ElementsAreStrictEqual(change.originalStart + change.originalLength, change.modifiedStart + change.modifiedLength);
        if (endStrictEqual && !startStrictEqual) {
          break;
        }
        change.originalStart++;
        change.modifiedStart++;
      }
      const mergedChangeArr = [null];
      if (i < changes.length - 1 && this.ChangesOverlap(changes[i], changes[i + 1], mergedChangeArr)) {
        changes[i] = mergedChangeArr[0];
        changes.splice(i + 1, 1);
        i--;
        continue;
      }
    }
    for (let i = changes.length - 1; i >= 0; i--) {
      const change = changes[i];
      let originalStop = 0;
      let modifiedStop = 0;
      if (i > 0) {
        const prevChange = changes[i - 1];
        originalStop = prevChange.originalStart + prevChange.originalLength;
        modifiedStop = prevChange.modifiedStart + prevChange.modifiedLength;
      }
      const checkOriginal = change.originalLength > 0;
      const checkModified = change.modifiedLength > 0;
      let bestDelta = 0;
      let bestScore = this._boundaryScore(change.originalStart, change.originalLength, change.modifiedStart, change.modifiedLength);
      for (let delta = 1; ; delta++) {
        const originalStart = change.originalStart - delta;
        const modifiedStart = change.modifiedStart - delta;
        if (originalStart < originalStop || modifiedStart < modifiedStop) {
          break;
        }
        if (checkOriginal && !this.OriginalElementsAreEqual(originalStart, originalStart + change.originalLength)) {
          break;
        }
        if (checkModified && !this.ModifiedElementsAreEqual(modifiedStart, modifiedStart + change.modifiedLength)) {
          break;
        }
        const touchingPreviousChange = originalStart === originalStop && modifiedStart === modifiedStop;
        const score2 = (touchingPreviousChange ? 5 : 0) + this._boundaryScore(originalStart, change.originalLength, modifiedStart, change.modifiedLength);
        if (score2 > bestScore) {
          bestScore = score2;
          bestDelta = delta;
        }
      }
      change.originalStart -= bestDelta;
      change.modifiedStart -= bestDelta;
      const mergedChangeArr = [null];
      if (i > 0 && this.ChangesOverlap(changes[i - 1], changes[i], mergedChangeArr)) {
        changes[i - 1] = mergedChangeArr[0];
        changes.splice(i, 1);
        i++;
        continue;
      }
    }
    if (this._hasStrings) {
      for (let i = 1, len = changes.length; i < len; i++) {
        const aChange = changes[i - 1];
        const bChange = changes[i];
        const matchedLength = bChange.originalStart - aChange.originalStart - aChange.originalLength;
        const aOriginalStart = aChange.originalStart;
        const bOriginalEnd = bChange.originalStart + bChange.originalLength;
        const abOriginalLength = bOriginalEnd - aOriginalStart;
        const aModifiedStart = aChange.modifiedStart;
        const bModifiedEnd = bChange.modifiedStart + bChange.modifiedLength;
        const abModifiedLength = bModifiedEnd - aModifiedStart;
        if (matchedLength < 5 && abOriginalLength < 20 && abModifiedLength < 20) {
          const t = this._findBetterContiguousSequence(aOriginalStart, abOriginalLength, aModifiedStart, abModifiedLength, matchedLength);
          if (t) {
            const [originalMatchStart, modifiedMatchStart] = t;
            if (originalMatchStart !== aChange.originalStart + aChange.originalLength || modifiedMatchStart !== aChange.modifiedStart + aChange.modifiedLength) {
              aChange.originalLength = originalMatchStart - aChange.originalStart;
              aChange.modifiedLength = modifiedMatchStart - aChange.modifiedStart;
              bChange.originalStart = originalMatchStart + matchedLength;
              bChange.modifiedStart = modifiedMatchStart + matchedLength;
              bChange.originalLength = bOriginalEnd - bChange.originalStart;
              bChange.modifiedLength = bModifiedEnd - bChange.modifiedStart;
            }
          }
        }
      }
    }
    return changes;
  }
  _findBetterContiguousSequence(originalStart, originalLength, modifiedStart, modifiedLength, desiredLength) {
    if (originalLength < desiredLength || modifiedLength < desiredLength) {
      return null;
    }
    const originalMax = originalStart + originalLength - desiredLength + 1;
    const modifiedMax = modifiedStart + modifiedLength - desiredLength + 1;
    let bestScore = 0;
    let bestOriginalStart = 0;
    let bestModifiedStart = 0;
    for (let i = originalStart; i < originalMax; i++) {
      for (let j = modifiedStart; j < modifiedMax; j++) {
        const score2 = this._contiguousSequenceScore(i, j, desiredLength);
        if (score2 > 0 && score2 > bestScore) {
          bestScore = score2;
          bestOriginalStart = i;
          bestModifiedStart = j;
        }
      }
    }
    if (bestScore > 0) {
      return [bestOriginalStart, bestModifiedStart];
    }
    return null;
  }
  _contiguousSequenceScore(originalStart, modifiedStart, length2) {
    let score2 = 0;
    for (let l = 0; l < length2; l++) {
      if (!this.ElementsAreEqual(originalStart + l, modifiedStart + l)) {
        return 0;
      }
      score2 += this._originalStringElements[originalStart + l].length;
    }
    return score2;
  }
  _OriginalIsBoundary(index) {
    if (index <= 0 || index >= this._originalElementsOrHash.length - 1) {
      return true;
    }
    return this._hasStrings && /^\s*$/.test(this._originalStringElements[index]);
  }
  _OriginalRegionIsBoundary(originalStart, originalLength) {
    if (this._OriginalIsBoundary(originalStart) || this._OriginalIsBoundary(originalStart - 1)) {
      return true;
    }
    if (originalLength > 0) {
      const originalEnd = originalStart + originalLength;
      if (this._OriginalIsBoundary(originalEnd - 1) || this._OriginalIsBoundary(originalEnd)) {
        return true;
      }
    }
    return false;
  }
  _ModifiedIsBoundary(index) {
    if (index <= 0 || index >= this._modifiedElementsOrHash.length - 1) {
      return true;
    }
    return this._hasStrings && /^\s*$/.test(this._modifiedStringElements[index]);
  }
  _ModifiedRegionIsBoundary(modifiedStart, modifiedLength) {
    if (this._ModifiedIsBoundary(modifiedStart) || this._ModifiedIsBoundary(modifiedStart - 1)) {
      return true;
    }
    if (modifiedLength > 0) {
      const modifiedEnd = modifiedStart + modifiedLength;
      if (this._ModifiedIsBoundary(modifiedEnd - 1) || this._ModifiedIsBoundary(modifiedEnd)) {
        return true;
      }
    }
    return false;
  }
  _boundaryScore(originalStart, originalLength, modifiedStart, modifiedLength) {
    const originalScore = this._OriginalRegionIsBoundary(originalStart, originalLength) ? 1 : 0;
    const modifiedScore = this._ModifiedRegionIsBoundary(modifiedStart, modifiedLength) ? 1 : 0;
    return originalScore + modifiedScore;
  }
  /**
   * Concatenates the two input DiffChange lists and returns the resulting
   * list.
   * @param The left changes
   * @param The right changes
   * @returns The concatenated list
   */
  ConcatenateChanges(left, right) {
    const mergedChangeArr = [];
    if (left.length === 0 || right.length === 0) {
      return right.length > 0 ? right : left;
    } else if (this.ChangesOverlap(left[left.length - 1], right[0], mergedChangeArr)) {
      const result2 = new Array(left.length + right.length - 1);
      MyArray.Copy(left, 0, result2, 0, left.length - 1);
      result2[left.length - 1] = mergedChangeArr[0];
      MyArray.Copy(right, 1, result2, left.length, right.length - 1);
      return result2;
    } else {
      const result2 = new Array(left.length + right.length);
      MyArray.Copy(left, 0, result2, 0, left.length);
      MyArray.Copy(right, 0, result2, left.length, right.length);
      return result2;
    }
  }
  /**
   * Returns true if the two changes overlap and can be merged into a single
   * change
   * @param left The left change
   * @param right The right change
   * @param mergedChange The merged change if the two overlap, null otherwise
   * @returns True if the two changes overlap
   */
  ChangesOverlap(left, right, mergedChangeArr) {
    Debug.Assert(left.originalStart <= right.originalStart, "Left change is not less than or equal to right change");
    Debug.Assert(left.modifiedStart <= right.modifiedStart, "Left change is not less than or equal to right change");
    if (left.originalStart + left.originalLength >= right.originalStart || left.modifiedStart + left.modifiedLength >= right.modifiedStart) {
      const originalStart = left.originalStart;
      let originalLength = left.originalLength;
      const modifiedStart = left.modifiedStart;
      let modifiedLength = left.modifiedLength;
      if (left.originalStart + left.originalLength >= right.originalStart) {
        originalLength = right.originalStart + right.originalLength - left.originalStart;
      }
      if (left.modifiedStart + left.modifiedLength >= right.modifiedStart) {
        modifiedLength = right.modifiedStart + right.modifiedLength - left.modifiedStart;
      }
      mergedChangeArr[0] = new DiffChange(originalStart, originalLength, modifiedStart, modifiedLength);
      return true;
    } else {
      mergedChangeArr[0] = null;
      return false;
    }
  }
  /**
   * Helper method used to clip a diagonal index to the range of valid
   * diagonals. This also decides whether or not the diagonal index,
   * if it exceeds the boundary, should be clipped to the boundary or clipped
   * one inside the boundary depending on the Even/Odd status of the boundary
   * and numDifferences.
   * @param diagonal The index of the diagonal to clip.
   * @param numDifferences The current number of differences being iterated upon.
   * @param diagonalBaseIndex The base reference diagonal.
   * @param numDiagonals The total number of diagonals.
   * @returns The clipped diagonal index.
   */
  ClipDiagonalBound(diagonal, numDifferences, diagonalBaseIndex, numDiagonals) {
    if (diagonal >= 0 && diagonal < numDiagonals) {
      return diagonal;
    }
    const diagonalsBelow = diagonalBaseIndex;
    const diagonalsAbove = numDiagonals - diagonalBaseIndex - 1;
    const diffEven = numDifferences % 2 === 0;
    if (diagonal < 0) {
      const lowerBoundEven = diagonalsBelow % 2 === 0;
      return diffEven === lowerBoundEven ? 0 : 1;
    } else {
      const upperBoundEven = diagonalsAbove % 2 === 0;
      return diffEven === upperBoundEven ? numDiagonals - 1 : numDiagonals - 2;
    }
  }
}
class MirrorTextModel {
  constructor(uri, lines, eol, versionId) {
    this._uri = uri;
    this._lines = lines;
    this._eol = eol;
    this._versionId = versionId;
    this._lineStarts = null;
    this._cachedTextValue = null;
  }
  dispose() {
    this._lines.length = 0;
  }
  get version() {
    return this._versionId;
  }
  getText() {
    if (this._cachedTextValue === null) {
      this._cachedTextValue = this._lines.join(this._eol);
    }
    return this._cachedTextValue;
  }
  onEvents(e) {
    if (e.eol && e.eol !== this._eol) {
      this._eol = e.eol;
      this._lineStarts = null;
    }
    const changes = e.changes;
    for (const change of changes) {
      this._acceptDeleteRange(change.range);
      this._acceptInsertText(new Position$2(change.range.startLineNumber, change.range.startColumn), change.text);
    }
    this._versionId = e.versionId;
    this._cachedTextValue = null;
  }
  _ensureLineStarts() {
    if (!this._lineStarts) {
      const eolLength = this._eol.length;
      const linesLength = this._lines.length;
      const lineStartValues = new Uint32Array(linesLength);
      for (let i = 0; i < linesLength; i++) {
        lineStartValues[i] = this._lines[i].length + eolLength;
      }
      this._lineStarts = new PrefixSumComputer(lineStartValues);
    }
  }
  /**
   * All changes to a line's text go through this method
   */
  _setLineText(lineIndex, newValue) {
    this._lines[lineIndex] = newValue;
    if (this._lineStarts) {
      this._lineStarts.setValue(lineIndex, this._lines[lineIndex].length + this._eol.length);
    }
  }
  _acceptDeleteRange(range2) {
    if (range2.startLineNumber === range2.endLineNumber) {
      if (range2.startColumn === range2.endColumn) {
        return;
      }
      this._setLineText(range2.startLineNumber - 1, this._lines[range2.startLineNumber - 1].substring(0, range2.startColumn - 1) + this._lines[range2.startLineNumber - 1].substring(range2.endColumn - 1));
      return;
    }
    this._setLineText(range2.startLineNumber - 1, this._lines[range2.startLineNumber - 1].substring(0, range2.startColumn - 1) + this._lines[range2.endLineNumber - 1].substring(range2.endColumn - 1));
    this._lines.splice(range2.startLineNumber, range2.endLineNumber - range2.startLineNumber);
    if (this._lineStarts) {
      this._lineStarts.removeValues(range2.startLineNumber, range2.endLineNumber - range2.startLineNumber);
    }
  }
  _acceptInsertText(position, insertText) {
    if (insertText.length === 0) {
      return;
    }
    const insertLines = splitLines(insertText);
    if (insertLines.length === 1) {
      this._setLineText(position.lineNumber - 1, this._lines[position.lineNumber - 1].substring(0, position.column - 1) + insertLines[0] + this._lines[position.lineNumber - 1].substring(position.column - 1));
      return;
    }
    insertLines[insertLines.length - 1] += this._lines[position.lineNumber - 1].substring(position.column - 1);
    this._setLineText(position.lineNumber - 1, this._lines[position.lineNumber - 1].substring(0, position.column - 1) + insertLines[0]);
    const newLengths = new Uint32Array(insertLines.length - 1);
    for (let i = 1; i < insertLines.length; i++) {
      this._lines.splice(position.lineNumber + i - 1, 0, insertLines[i]);
      newLengths[i - 1] = insertLines[i].length + this._eol.length;
    }
    if (this._lineStarts) {
      this._lineStarts.insertValues(position.lineNumber, newLengths);
    }
  }
}
class Uint8Matrix {
  constructor(rows, cols, defaultValue) {
    const data = new Uint8Array(rows * cols);
    for (let i = 0, len = rows * cols; i < len; i++) {
      data[i] = defaultValue;
    }
    this._data = data;
    this.rows = rows;
    this.cols = cols;
  }
  get(row, col) {
    return this._data[row * this.cols + col];
  }
  set(row, col, value) {
    this._data[row * this.cols + col] = value;
  }
}
class StateMachine {
  constructor(edges) {
    let maxCharCode = 0;
    let maxState = 0;
    for (let i = 0, len = edges.length; i < len; i++) {
      const [from2, chCode, to] = edges[i];
      if (chCode > maxCharCode) {
        maxCharCode = chCode;
      }
      if (from2 > maxState) {
        maxState = from2;
      }
      if (to > maxState) {
        maxState = to;
      }
    }
    maxCharCode++;
    maxState++;
    const states = new Uint8Matrix(
      maxState,
      maxCharCode,
      0
      /* State.Invalid */
    );
    for (let i = 0, len = edges.length; i < len; i++) {
      const [from2, chCode, to] = edges[i];
      states.set(from2, chCode, to);
    }
    this._states = states;
    this._maxCharCode = maxCharCode;
  }
  nextState(currentState, chCode) {
    if (chCode < 0 || chCode >= this._maxCharCode) {
      return 0;
    }
    return this._states.get(currentState, chCode);
  }
}
let _stateMachine = null;
function getStateMachine() {
  if (_stateMachine === null) {
    _stateMachine = new StateMachine([
      [
        1,
        104,
        2
        /* State.H */
      ],
      [
        1,
        72,
        2
        /* State.H */
      ],
      [
        1,
        102,
        6
        /* State.F */
      ],
      [
        1,
        70,
        6
        /* State.F */
      ],
      [
        2,
        116,
        3
        /* State.HT */
      ],
      [
        2,
        84,
        3
        /* State.HT */
      ],
      [
        3,
        116,
        4
        /* State.HTT */
      ],
      [
        3,
        84,
        4
        /* State.HTT */
      ],
      [
        4,
        112,
        5
        /* State.HTTP */
      ],
      [
        4,
        80,
        5
        /* State.HTTP */
      ],
      [
        5,
        115,
        9
        /* State.BeforeColon */
      ],
      [
        5,
        83,
        9
        /* State.BeforeColon */
      ],
      [
        5,
        58,
        10
        /* State.AfterColon */
      ],
      [
        6,
        105,
        7
        /* State.FI */
      ],
      [
        6,
        73,
        7
        /* State.FI */
      ],
      [
        7,
        108,
        8
        /* State.FIL */
      ],
      [
        7,
        76,
        8
        /* State.FIL */
      ],
      [
        8,
        101,
        9
        /* State.BeforeColon */
      ],
      [
        8,
        69,
        9
        /* State.BeforeColon */
      ],
      [
        9,
        58,
        10
        /* State.AfterColon */
      ],
      [
        10,
        47,
        11
        /* State.AlmostThere */
      ],
      [
        11,
        47,
        12
        /* State.End */
      ]
    ]);
  }
  return _stateMachine;
}
let _classifier = null;
function getClassifier() {
  if (_classifier === null) {
    _classifier = new CharacterClassifier(
      0
      /* CharacterClass.None */
    );
    const FORCE_TERMINATION_CHARACTERS = ` 	<>'"、。｡､，．：；‘〈「『〔（［｛｢｣｝］）〕』」〉’｀～…`;
    for (let i = 0; i < FORCE_TERMINATION_CHARACTERS.length; i++) {
      _classifier.set(
        FORCE_TERMINATION_CHARACTERS.charCodeAt(i),
        1
        /* CharacterClass.ForceTermination */
      );
    }
    const CANNOT_END_WITH_CHARACTERS = ".,;:";
    for (let i = 0; i < CANNOT_END_WITH_CHARACTERS.length; i++) {
      _classifier.set(
        CANNOT_END_WITH_CHARACTERS.charCodeAt(i),
        2
        /* CharacterClass.CannotEndIn */
      );
    }
  }
  return _classifier;
}
class LinkComputer {
  static _createLink(classifier, line, lineNumber, linkBeginIndex, linkEndIndex) {
    let lastIncludedCharIndex = linkEndIndex - 1;
    do {
      const chCode = line.charCodeAt(lastIncludedCharIndex);
      const chClass = classifier.get(chCode);
      if (chClass !== 2) {
        break;
      }
      lastIncludedCharIndex--;
    } while (lastIncludedCharIndex > linkBeginIndex);
    if (linkBeginIndex > 0) {
      const charCodeBeforeLink = line.charCodeAt(linkBeginIndex - 1);
      const lastCharCodeInLink = line.charCodeAt(lastIncludedCharIndex);
      if (charCodeBeforeLink === 40 && lastCharCodeInLink === 41 || charCodeBeforeLink === 91 && lastCharCodeInLink === 93 || charCodeBeforeLink === 123 && lastCharCodeInLink === 125) {
        lastIncludedCharIndex--;
      }
    }
    return {
      range: {
        startLineNumber: lineNumber,
        startColumn: linkBeginIndex + 1,
        endLineNumber: lineNumber,
        endColumn: lastIncludedCharIndex + 2
      },
      url: line.substring(linkBeginIndex, lastIncludedCharIndex + 1)
    };
  }
  static computeLinks(model, stateMachine = getStateMachine()) {
    const classifier = getClassifier();
    const result2 = [];
    for (let i = 1, lineCount = model.getLineCount(); i <= lineCount; i++) {
      const line = model.getLineContent(i);
      const len = line.length;
      let j = 0;
      let linkBeginIndex = 0;
      let linkBeginChCode = 0;
      let state = 1;
      let hasOpenParens = false;
      let hasOpenSquareBracket = false;
      let inSquareBrackets = false;
      let hasOpenCurlyBracket = false;
      while (j < len) {
        let resetStateMachine = false;
        const chCode = line.charCodeAt(j);
        if (state === 13) {
          let chClass;
          switch (chCode) {
            case 40:
              hasOpenParens = true;
              chClass = 0;
              break;
            case 41:
              chClass = hasOpenParens ? 0 : 1;
              break;
            case 91:
              inSquareBrackets = true;
              hasOpenSquareBracket = true;
              chClass = 0;
              break;
            case 93:
              inSquareBrackets = false;
              chClass = hasOpenSquareBracket ? 0 : 1;
              break;
            case 123:
              hasOpenCurlyBracket = true;
              chClass = 0;
              break;
            case 125:
              chClass = hasOpenCurlyBracket ? 0 : 1;
              break;
            case 39:
            case 34:
            case 96:
              if (linkBeginChCode === chCode) {
                chClass = 1;
              } else if (linkBeginChCode === 39 || linkBeginChCode === 34 || linkBeginChCode === 96) {
                chClass = 0;
              } else {
                chClass = 1;
              }
              break;
            case 42:
              chClass = linkBeginChCode === 42 ? 1 : 0;
              break;
            case 124:
              chClass = linkBeginChCode === 124 ? 1 : 0;
              break;
            case 32:
              chClass = inSquareBrackets ? 0 : 1;
              break;
            default:
              chClass = classifier.get(chCode);
          }
          if (chClass === 1) {
            result2.push(LinkComputer._createLink(classifier, line, i, linkBeginIndex, j));
            resetStateMachine = true;
          }
        } else if (state === 12) {
          let chClass;
          if (chCode === 91) {
            hasOpenSquareBracket = true;
            chClass = 0;
          } else {
            chClass = classifier.get(chCode);
          }
          if (chClass === 1) {
            resetStateMachine = true;
          } else {
            state = 13;
          }
        } else {
          state = stateMachine.nextState(state, chCode);
          if (state === 0) {
            resetStateMachine = true;
          }
        }
        if (resetStateMachine) {
          state = 1;
          hasOpenParens = false;
          hasOpenSquareBracket = false;
          hasOpenCurlyBracket = false;
          linkBeginIndex = j + 1;
          linkBeginChCode = chCode;
        }
        j++;
      }
      if (state === 13) {
        result2.push(LinkComputer._createLink(classifier, line, i, linkBeginIndex, len));
      }
    }
    return result2;
  }
}
function computeLinks(model) {
  if (!model || typeof model.getLineCount !== "function" || typeof model.getLineContent !== "function") {
    return [];
  }
  return LinkComputer.computeLinks(model);
}
class BasicInplaceReplace {
  constructor() {
    this._defaultValueSet = [
      ["true", "false"],
      ["True", "False"],
      ["Private", "Public", "Friend", "ReadOnly", "Partial", "Protected", "WriteOnly"],
      ["public", "protected", "private"]
    ];
  }
  navigateValueSet(range1, text1, range2, text2, up) {
    if (range1 && text1) {
      const result2 = this.doNavigateValueSet(text1, up);
      if (result2) {
        return {
          range: range1,
          value: result2
        };
      }
    }
    if (range2 && text2) {
      const result2 = this.doNavigateValueSet(text2, up);
      if (result2) {
        return {
          range: range2,
          value: result2
        };
      }
    }
    return null;
  }
  doNavigateValueSet(text2, up) {
    const numberResult = this.numberReplace(text2, up);
    if (numberResult !== null) {
      return numberResult;
    }
    return this.textReplace(text2, up);
  }
  numberReplace(value, up) {
    const precision = Math.pow(10, value.length - (value.lastIndexOf(".") + 1));
    let n1 = Number(value);
    const n2 = parseFloat(value);
    if (!isNaN(n1) && !isNaN(n2) && n1 === n2) {
      if (n1 === 0 && !up) {
        return null;
      } else {
        n1 = Math.floor(n1 * precision);
        n1 += up ? precision : -precision;
        return String(n1 / precision);
      }
    }
    return null;
  }
  textReplace(value, up) {
    return this.valueSetsReplace(this._defaultValueSet, value, up);
  }
  valueSetsReplace(valueSets, value, up) {
    let result2 = null;
    for (let i = 0, len = valueSets.length; result2 === null && i < len; i++) {
      result2 = this.valueSetReplace(valueSets[i], value, up);
    }
    return result2;
  }
  valueSetReplace(valueSet, value, up) {
    let idx = valueSet.indexOf(value);
    if (idx >= 0) {
      idx += up ? 1 : -1;
      if (idx < 0) {
        idx = valueSet.length - 1;
      } else {
        idx %= valueSet.length;
      }
      return valueSet[idx];
    }
    return null;
  }
}
BasicInplaceReplace.INSTANCE = new BasicInplaceReplace();
var AccessibilitySupport;
(function(AccessibilitySupport2) {
  AccessibilitySupport2[AccessibilitySupport2["Unknown"] = 0] = "Unknown";
  AccessibilitySupport2[AccessibilitySupport2["Disabled"] = 1] = "Disabled";
  AccessibilitySupport2[AccessibilitySupport2["Enabled"] = 2] = "Enabled";
})(AccessibilitySupport || (AccessibilitySupport = {}));
var CodeActionTriggerType;
(function(CodeActionTriggerType2) {
  CodeActionTriggerType2[CodeActionTriggerType2["Invoke"] = 1] = "Invoke";
  CodeActionTriggerType2[CodeActionTriggerType2["Auto"] = 2] = "Auto";
})(CodeActionTriggerType || (CodeActionTriggerType = {}));
var CompletionItemInsertTextRule;
(function(CompletionItemInsertTextRule2) {
  CompletionItemInsertTextRule2[CompletionItemInsertTextRule2["None"] = 0] = "None";
  CompletionItemInsertTextRule2[CompletionItemInsertTextRule2["KeepWhitespace"] = 1] = "KeepWhitespace";
  CompletionItemInsertTextRule2[CompletionItemInsertTextRule2["InsertAsSnippet"] = 4] = "InsertAsSnippet";
})(CompletionItemInsertTextRule || (CompletionItemInsertTextRule = {}));
var CompletionItemKind;
(function(CompletionItemKind2) {
  CompletionItemKind2[CompletionItemKind2["Method"] = 0] = "Method";
  CompletionItemKind2[CompletionItemKind2["Function"] = 1] = "Function";
  CompletionItemKind2[CompletionItemKind2["Constructor"] = 2] = "Constructor";
  CompletionItemKind2[CompletionItemKind2["Field"] = 3] = "Field";
  CompletionItemKind2[CompletionItemKind2["Variable"] = 4] = "Variable";
  CompletionItemKind2[CompletionItemKind2["Class"] = 5] = "Class";
  CompletionItemKind2[CompletionItemKind2["Struct"] = 6] = "Struct";
  CompletionItemKind2[CompletionItemKind2["Interface"] = 7] = "Interface";
  CompletionItemKind2[CompletionItemKind2["Module"] = 8] = "Module";
  CompletionItemKind2[CompletionItemKind2["Property"] = 9] = "Property";
  CompletionItemKind2[CompletionItemKind2["Event"] = 10] = "Event";
  CompletionItemKind2[CompletionItemKind2["Operator"] = 11] = "Operator";
  CompletionItemKind2[CompletionItemKind2["Unit"] = 12] = "Unit";
  CompletionItemKind2[CompletionItemKind2["Value"] = 13] = "Value";
  CompletionItemKind2[CompletionItemKind2["Constant"] = 14] = "Constant";
  CompletionItemKind2[CompletionItemKind2["Enum"] = 15] = "Enum";
  CompletionItemKind2[CompletionItemKind2["EnumMember"] = 16] = "EnumMember";
  CompletionItemKind2[CompletionItemKind2["Keyword"] = 17] = "Keyword";
  CompletionItemKind2[CompletionItemKind2["Text"] = 18] = "Text";
  CompletionItemKind2[CompletionItemKind2["Color"] = 19] = "Color";
  CompletionItemKind2[CompletionItemKind2["File"] = 20] = "File";
  CompletionItemKind2[CompletionItemKind2["Reference"] = 21] = "Reference";
  CompletionItemKind2[CompletionItemKind2["Customcolor"] = 22] = "Customcolor";
  CompletionItemKind2[CompletionItemKind2["Folder"] = 23] = "Folder";
  CompletionItemKind2[CompletionItemKind2["TypeParameter"] = 24] = "TypeParameter";
  CompletionItemKind2[CompletionItemKind2["User"] = 25] = "User";
  CompletionItemKind2[CompletionItemKind2["Issue"] = 26] = "Issue";
  CompletionItemKind2[CompletionItemKind2["Snippet"] = 27] = "Snippet";
})(CompletionItemKind || (CompletionItemKind = {}));
var CompletionItemTag;
(function(CompletionItemTag2) {
  CompletionItemTag2[CompletionItemTag2["Deprecated"] = 1] = "Deprecated";
})(CompletionItemTag || (CompletionItemTag = {}));
var CompletionTriggerKind;
(function(CompletionTriggerKind2) {
  CompletionTriggerKind2[CompletionTriggerKind2["Invoke"] = 0] = "Invoke";
  CompletionTriggerKind2[CompletionTriggerKind2["TriggerCharacter"] = 1] = "TriggerCharacter";
  CompletionTriggerKind2[CompletionTriggerKind2["TriggerForIncompleteCompletions"] = 2] = "TriggerForIncompleteCompletions";
})(CompletionTriggerKind || (CompletionTriggerKind = {}));
var ContentWidgetPositionPreference;
(function(ContentWidgetPositionPreference2) {
  ContentWidgetPositionPreference2[ContentWidgetPositionPreference2["EXACT"] = 0] = "EXACT";
  ContentWidgetPositionPreference2[ContentWidgetPositionPreference2["ABOVE"] = 1] = "ABOVE";
  ContentWidgetPositionPreference2[ContentWidgetPositionPreference2["BELOW"] = 2] = "BELOW";
})(ContentWidgetPositionPreference || (ContentWidgetPositionPreference = {}));
var CursorChangeReason;
(function(CursorChangeReason2) {
  CursorChangeReason2[CursorChangeReason2["NotSet"] = 0] = "NotSet";
  CursorChangeReason2[CursorChangeReason2["ContentFlush"] = 1] = "ContentFlush";
  CursorChangeReason2[CursorChangeReason2["RecoverFromMarkers"] = 2] = "RecoverFromMarkers";
  CursorChangeReason2[CursorChangeReason2["Explicit"] = 3] = "Explicit";
  CursorChangeReason2[CursorChangeReason2["Paste"] = 4] = "Paste";
  CursorChangeReason2[CursorChangeReason2["Undo"] = 5] = "Undo";
  CursorChangeReason2[CursorChangeReason2["Redo"] = 6] = "Redo";
})(CursorChangeReason || (CursorChangeReason = {}));
var DefaultEndOfLine;
(function(DefaultEndOfLine2) {
  DefaultEndOfLine2[DefaultEndOfLine2["LF"] = 1] = "LF";
  DefaultEndOfLine2[DefaultEndOfLine2["CRLF"] = 2] = "CRLF";
})(DefaultEndOfLine || (DefaultEndOfLine = {}));
var DocumentHighlightKind;
(function(DocumentHighlightKind2) {
  DocumentHighlightKind2[DocumentHighlightKind2["Text"] = 0] = "Text";
  DocumentHighlightKind2[DocumentHighlightKind2["Read"] = 1] = "Read";
  DocumentHighlightKind2[DocumentHighlightKind2["Write"] = 2] = "Write";
})(DocumentHighlightKind || (DocumentHighlightKind = {}));
var EditorAutoIndentStrategy;
(function(EditorAutoIndentStrategy2) {
  EditorAutoIndentStrategy2[EditorAutoIndentStrategy2["None"] = 0] = "None";
  EditorAutoIndentStrategy2[EditorAutoIndentStrategy2["Keep"] = 1] = "Keep";
  EditorAutoIndentStrategy2[EditorAutoIndentStrategy2["Brackets"] = 2] = "Brackets";
  EditorAutoIndentStrategy2[EditorAutoIndentStrategy2["Advanced"] = 3] = "Advanced";
  EditorAutoIndentStrategy2[EditorAutoIndentStrategy2["Full"] = 4] = "Full";
})(EditorAutoIndentStrategy || (EditorAutoIndentStrategy = {}));
var EditorOption;
(function(EditorOption2) {
  EditorOption2[EditorOption2["acceptSuggestionOnCommitCharacter"] = 0] = "acceptSuggestionOnCommitCharacter";
  EditorOption2[EditorOption2["acceptSuggestionOnEnter"] = 1] = "acceptSuggestionOnEnter";
  EditorOption2[EditorOption2["accessibilitySupport"] = 2] = "accessibilitySupport";
  EditorOption2[EditorOption2["accessibilityPageSize"] = 3] = "accessibilityPageSize";
  EditorOption2[EditorOption2["ariaLabel"] = 4] = "ariaLabel";
  EditorOption2[EditorOption2["ariaRequired"] = 5] = "ariaRequired";
  EditorOption2[EditorOption2["autoClosingBrackets"] = 6] = "autoClosingBrackets";
  EditorOption2[EditorOption2["screenReaderAnnounceInlineSuggestion"] = 7] = "screenReaderAnnounceInlineSuggestion";
  EditorOption2[EditorOption2["autoClosingDelete"] = 8] = "autoClosingDelete";
  EditorOption2[EditorOption2["autoClosingOvertype"] = 9] = "autoClosingOvertype";
  EditorOption2[EditorOption2["autoClosingQuotes"] = 10] = "autoClosingQuotes";
  EditorOption2[EditorOption2["autoIndent"] = 11] = "autoIndent";
  EditorOption2[EditorOption2["automaticLayout"] = 12] = "automaticLayout";
  EditorOption2[EditorOption2["autoSurround"] = 13] = "autoSurround";
  EditorOption2[EditorOption2["bracketPairColorization"] = 14] = "bracketPairColorization";
  EditorOption2[EditorOption2["guides"] = 15] = "guides";
  EditorOption2[EditorOption2["codeLens"] = 16] = "codeLens";
  EditorOption2[EditorOption2["codeLensFontFamily"] = 17] = "codeLensFontFamily";
  EditorOption2[EditorOption2["codeLensFontSize"] = 18] = "codeLensFontSize";
  EditorOption2[EditorOption2["colorDecorators"] = 19] = "colorDecorators";
  EditorOption2[EditorOption2["colorDecoratorsLimit"] = 20] = "colorDecoratorsLimit";
  EditorOption2[EditorOption2["columnSelection"] = 21] = "columnSelection";
  EditorOption2[EditorOption2["comments"] = 22] = "comments";
  EditorOption2[EditorOption2["contextmenu"] = 23] = "contextmenu";
  EditorOption2[EditorOption2["copyWithSyntaxHighlighting"] = 24] = "copyWithSyntaxHighlighting";
  EditorOption2[EditorOption2["cursorBlinking"] = 25] = "cursorBlinking";
  EditorOption2[EditorOption2["cursorSmoothCaretAnimation"] = 26] = "cursorSmoothCaretAnimation";
  EditorOption2[EditorOption2["cursorStyle"] = 27] = "cursorStyle";
  EditorOption2[EditorOption2["cursorSurroundingLines"] = 28] = "cursorSurroundingLines";
  EditorOption2[EditorOption2["cursorSurroundingLinesStyle"] = 29] = "cursorSurroundingLinesStyle";
  EditorOption2[EditorOption2["cursorWidth"] = 30] = "cursorWidth";
  EditorOption2[EditorOption2["disableLayerHinting"] = 31] = "disableLayerHinting";
  EditorOption2[EditorOption2["disableMonospaceOptimizations"] = 32] = "disableMonospaceOptimizations";
  EditorOption2[EditorOption2["domReadOnly"] = 33] = "domReadOnly";
  EditorOption2[EditorOption2["dragAndDrop"] = 34] = "dragAndDrop";
  EditorOption2[EditorOption2["dropIntoEditor"] = 35] = "dropIntoEditor";
  EditorOption2[EditorOption2["emptySelectionClipboard"] = 36] = "emptySelectionClipboard";
  EditorOption2[EditorOption2["experimentalWhitespaceRendering"] = 37] = "experimentalWhitespaceRendering";
  EditorOption2[EditorOption2["extraEditorClassName"] = 38] = "extraEditorClassName";
  EditorOption2[EditorOption2["fastScrollSensitivity"] = 39] = "fastScrollSensitivity";
  EditorOption2[EditorOption2["find"] = 40] = "find";
  EditorOption2[EditorOption2["fixedOverflowWidgets"] = 41] = "fixedOverflowWidgets";
  EditorOption2[EditorOption2["folding"] = 42] = "folding";
  EditorOption2[EditorOption2["foldingStrategy"] = 43] = "foldingStrategy";
  EditorOption2[EditorOption2["foldingHighlight"] = 44] = "foldingHighlight";
  EditorOption2[EditorOption2["foldingImportsByDefault"] = 45] = "foldingImportsByDefault";
  EditorOption2[EditorOption2["foldingMaximumRegions"] = 46] = "foldingMaximumRegions";
  EditorOption2[EditorOption2["unfoldOnClickAfterEndOfLine"] = 47] = "unfoldOnClickAfterEndOfLine";
  EditorOption2[EditorOption2["fontFamily"] = 48] = "fontFamily";
  EditorOption2[EditorOption2["fontInfo"] = 49] = "fontInfo";
  EditorOption2[EditorOption2["fontLigatures"] = 50] = "fontLigatures";
  EditorOption2[EditorOption2["fontSize"] = 51] = "fontSize";
  EditorOption2[EditorOption2["fontWeight"] = 52] = "fontWeight";
  EditorOption2[EditorOption2["fontVariations"] = 53] = "fontVariations";
  EditorOption2[EditorOption2["formatOnPaste"] = 54] = "formatOnPaste";
  EditorOption2[EditorOption2["formatOnType"] = 55] = "formatOnType";
  EditorOption2[EditorOption2["glyphMargin"] = 56] = "glyphMargin";
  EditorOption2[EditorOption2["gotoLocation"] = 57] = "gotoLocation";
  EditorOption2[EditorOption2["hideCursorInOverviewRuler"] = 58] = "hideCursorInOverviewRuler";
  EditorOption2[EditorOption2["hover"] = 59] = "hover";
  EditorOption2[EditorOption2["inDiffEditor"] = 60] = "inDiffEditor";
  EditorOption2[EditorOption2["inlineSuggest"] = 61] = "inlineSuggest";
  EditorOption2[EditorOption2["letterSpacing"] = 62] = "letterSpacing";
  EditorOption2[EditorOption2["lightbulb"] = 63] = "lightbulb";
  EditorOption2[EditorOption2["lineDecorationsWidth"] = 64] = "lineDecorationsWidth";
  EditorOption2[EditorOption2["lineHeight"] = 65] = "lineHeight";
  EditorOption2[EditorOption2["lineNumbers"] = 66] = "lineNumbers";
  EditorOption2[EditorOption2["lineNumbersMinChars"] = 67] = "lineNumbersMinChars";
  EditorOption2[EditorOption2["linkedEditing"] = 68] = "linkedEditing";
  EditorOption2[EditorOption2["links"] = 69] = "links";
  EditorOption2[EditorOption2["matchBrackets"] = 70] = "matchBrackets";
  EditorOption2[EditorOption2["minimap"] = 71] = "minimap";
  EditorOption2[EditorOption2["mouseStyle"] = 72] = "mouseStyle";
  EditorOption2[EditorOption2["mouseWheelScrollSensitivity"] = 73] = "mouseWheelScrollSensitivity";
  EditorOption2[EditorOption2["mouseWheelZoom"] = 74] = "mouseWheelZoom";
  EditorOption2[EditorOption2["multiCursorMergeOverlapping"] = 75] = "multiCursorMergeOverlapping";
  EditorOption2[EditorOption2["multiCursorModifier"] = 76] = "multiCursorModifier";
  EditorOption2[EditorOption2["multiCursorPaste"] = 77] = "multiCursorPaste";
  EditorOption2[EditorOption2["multiCursorLimit"] = 78] = "multiCursorLimit";
  EditorOption2[EditorOption2["occurrencesHighlight"] = 79] = "occurrencesHighlight";
  EditorOption2[EditorOption2["overviewRulerBorder"] = 80] = "overviewRulerBorder";
  EditorOption2[EditorOption2["overviewRulerLanes"] = 81] = "overviewRulerLanes";
  EditorOption2[EditorOption2["padding"] = 82] = "padding";
  EditorOption2[EditorOption2["pasteAs"] = 83] = "pasteAs";
  EditorOption2[EditorOption2["parameterHints"] = 84] = "parameterHints";
  EditorOption2[EditorOption2["peekWidgetDefaultFocus"] = 85] = "peekWidgetDefaultFocus";
  EditorOption2[EditorOption2["definitionLinkOpensInPeek"] = 86] = "definitionLinkOpensInPeek";
  EditorOption2[EditorOption2["quickSuggestions"] = 87] = "quickSuggestions";
  EditorOption2[EditorOption2["quickSuggestionsDelay"] = 88] = "quickSuggestionsDelay";
  EditorOption2[EditorOption2["readOnly"] = 89] = "readOnly";
  EditorOption2[EditorOption2["readOnlyMessage"] = 90] = "readOnlyMessage";
  EditorOption2[EditorOption2["renameOnType"] = 91] = "renameOnType";
  EditorOption2[EditorOption2["renderControlCharacters"] = 92] = "renderControlCharacters";
  EditorOption2[EditorOption2["renderFinalNewline"] = 93] = "renderFinalNewline";
  EditorOption2[EditorOption2["renderLineHighlight"] = 94] = "renderLineHighlight";
  EditorOption2[EditorOption2["renderLineHighlightOnlyWhenFocus"] = 95] = "renderLineHighlightOnlyWhenFocus";
  EditorOption2[EditorOption2["renderValidationDecorations"] = 96] = "renderValidationDecorations";
  EditorOption2[EditorOption2["renderWhitespace"] = 97] = "renderWhitespace";
  EditorOption2[EditorOption2["revealHorizontalRightPadding"] = 98] = "revealHorizontalRightPadding";
  EditorOption2[EditorOption2["roundedSelection"] = 99] = "roundedSelection";
  EditorOption2[EditorOption2["rulers"] = 100] = "rulers";
  EditorOption2[EditorOption2["scrollbar"] = 101] = "scrollbar";
  EditorOption2[EditorOption2["scrollBeyondLastColumn"] = 102] = "scrollBeyondLastColumn";
  EditorOption2[EditorOption2["scrollBeyondLastLine"] = 103] = "scrollBeyondLastLine";
  EditorOption2[EditorOption2["scrollPredominantAxis"] = 104] = "scrollPredominantAxis";
  EditorOption2[EditorOption2["selectionClipboard"] = 105] = "selectionClipboard";
  EditorOption2[EditorOption2["selectionHighlight"] = 106] = "selectionHighlight";
  EditorOption2[EditorOption2["selectOnLineNumbers"] = 107] = "selectOnLineNumbers";
  EditorOption2[EditorOption2["showFoldingControls"] = 108] = "showFoldingControls";
  EditorOption2[EditorOption2["showUnused"] = 109] = "showUnused";
  EditorOption2[EditorOption2["snippetSuggestions"] = 110] = "snippetSuggestions";
  EditorOption2[EditorOption2["smartSelect"] = 111] = "smartSelect";
  EditorOption2[EditorOption2["smoothScrolling"] = 112] = "smoothScrolling";
  EditorOption2[EditorOption2["stickyScroll"] = 113] = "stickyScroll";
  EditorOption2[EditorOption2["stickyTabStops"] = 114] = "stickyTabStops";
  EditorOption2[EditorOption2["stopRenderingLineAfter"] = 115] = "stopRenderingLineAfter";
  EditorOption2[EditorOption2["suggest"] = 116] = "suggest";
  EditorOption2[EditorOption2["suggestFontSize"] = 117] = "suggestFontSize";
  EditorOption2[EditorOption2["suggestLineHeight"] = 118] = "suggestLineHeight";
  EditorOption2[EditorOption2["suggestOnTriggerCharacters"] = 119] = "suggestOnTriggerCharacters";
  EditorOption2[EditorOption2["suggestSelection"] = 120] = "suggestSelection";
  EditorOption2[EditorOption2["tabCompletion"] = 121] = "tabCompletion";
  EditorOption2[EditorOption2["tabIndex"] = 122] = "tabIndex";
  EditorOption2[EditorOption2["unicodeHighlighting"] = 123] = "unicodeHighlighting";
  EditorOption2[EditorOption2["unusualLineTerminators"] = 124] = "unusualLineTerminators";
  EditorOption2[EditorOption2["useShadowDOM"] = 125] = "useShadowDOM";
  EditorOption2[EditorOption2["useTabStops"] = 126] = "useTabStops";
  EditorOption2[EditorOption2["wordBreak"] = 127] = "wordBreak";
  EditorOption2[EditorOption2["wordSeparators"] = 128] = "wordSeparators";
  EditorOption2[EditorOption2["wordWrap"] = 129] = "wordWrap";
  EditorOption2[EditorOption2["wordWrapBreakAfterCharacters"] = 130] = "wordWrapBreakAfterCharacters";
  EditorOption2[EditorOption2["wordWrapBreakBeforeCharacters"] = 131] = "wordWrapBreakBeforeCharacters";
  EditorOption2[EditorOption2["wordWrapColumn"] = 132] = "wordWrapColumn";
  EditorOption2[EditorOption2["wordWrapOverride1"] = 133] = "wordWrapOverride1";
  EditorOption2[EditorOption2["wordWrapOverride2"] = 134] = "wordWrapOverride2";
  EditorOption2[EditorOption2["wrappingIndent"] = 135] = "wrappingIndent";
  EditorOption2[EditorOption2["wrappingStrategy"] = 136] = "wrappingStrategy";
  EditorOption2[EditorOption2["showDeprecated"] = 137] = "showDeprecated";
  EditorOption2[EditorOption2["inlayHints"] = 138] = "inlayHints";
  EditorOption2[EditorOption2["editorClassName"] = 139] = "editorClassName";
  EditorOption2[EditorOption2["pixelRatio"] = 140] = "pixelRatio";
  EditorOption2[EditorOption2["tabFocusMode"] = 141] = "tabFocusMode";
  EditorOption2[EditorOption2["layoutInfo"] = 142] = "layoutInfo";
  EditorOption2[EditorOption2["wrappingInfo"] = 143] = "wrappingInfo";
  EditorOption2[EditorOption2["defaultColorDecorators"] = 144] = "defaultColorDecorators";
  EditorOption2[EditorOption2["colorDecoratorsActivatedOn"] = 145] = "colorDecoratorsActivatedOn";
})(EditorOption || (EditorOption = {}));
var EndOfLinePreference;
(function(EndOfLinePreference2) {
  EndOfLinePreference2[EndOfLinePreference2["TextDefined"] = 0] = "TextDefined";
  EndOfLinePreference2[EndOfLinePreference2["LF"] = 1] = "LF";
  EndOfLinePreference2[EndOfLinePreference2["CRLF"] = 2] = "CRLF";
})(EndOfLinePreference || (EndOfLinePreference = {}));
var EndOfLineSequence;
(function(EndOfLineSequence2) {
  EndOfLineSequence2[EndOfLineSequence2["LF"] = 0] = "LF";
  EndOfLineSequence2[EndOfLineSequence2["CRLF"] = 1] = "CRLF";
})(EndOfLineSequence || (EndOfLineSequence = {}));
var GlyphMarginLane;
(function(GlyphMarginLane2) {
  GlyphMarginLane2[GlyphMarginLane2["Left"] = 1] = "Left";
  GlyphMarginLane2[GlyphMarginLane2["Right"] = 2] = "Right";
})(GlyphMarginLane || (GlyphMarginLane = {}));
var IndentAction;
(function(IndentAction2) {
  IndentAction2[IndentAction2["None"] = 0] = "None";
  IndentAction2[IndentAction2["Indent"] = 1] = "Indent";
  IndentAction2[IndentAction2["IndentOutdent"] = 2] = "IndentOutdent";
  IndentAction2[IndentAction2["Outdent"] = 3] = "Outdent";
})(IndentAction || (IndentAction = {}));
var InjectedTextCursorStops;
(function(InjectedTextCursorStops2) {
  InjectedTextCursorStops2[InjectedTextCursorStops2["Both"] = 0] = "Both";
  InjectedTextCursorStops2[InjectedTextCursorStops2["Right"] = 1] = "Right";
  InjectedTextCursorStops2[InjectedTextCursorStops2["Left"] = 2] = "Left";
  InjectedTextCursorStops2[InjectedTextCursorStops2["None"] = 3] = "None";
})(InjectedTextCursorStops || (InjectedTextCursorStops = {}));
var InlayHintKind;
(function(InlayHintKind2) {
  InlayHintKind2[InlayHintKind2["Type"] = 1] = "Type";
  InlayHintKind2[InlayHintKind2["Parameter"] = 2] = "Parameter";
})(InlayHintKind || (InlayHintKind = {}));
var InlineCompletionTriggerKind;
(function(InlineCompletionTriggerKind2) {
  InlineCompletionTriggerKind2[InlineCompletionTriggerKind2["Automatic"] = 0] = "Automatic";
  InlineCompletionTriggerKind2[InlineCompletionTriggerKind2["Explicit"] = 1] = "Explicit";
})(InlineCompletionTriggerKind || (InlineCompletionTriggerKind = {}));
var KeyCode$1;
(function(KeyCode2) {
  KeyCode2[KeyCode2["DependsOnKbLayout"] = -1] = "DependsOnKbLayout";
  KeyCode2[KeyCode2["Unknown"] = 0] = "Unknown";
  KeyCode2[KeyCode2["Backspace"] = 1] = "Backspace";
  KeyCode2[KeyCode2["Tab"] = 2] = "Tab";
  KeyCode2[KeyCode2["Enter"] = 3] = "Enter";
  KeyCode2[KeyCode2["Shift"] = 4] = "Shift";
  KeyCode2[KeyCode2["Ctrl"] = 5] = "Ctrl";
  KeyCode2[KeyCode2["Alt"] = 6] = "Alt";
  KeyCode2[KeyCode2["PauseBreak"] = 7] = "PauseBreak";
  KeyCode2[KeyCode2["CapsLock"] = 8] = "CapsLock";
  KeyCode2[KeyCode2["Escape"] = 9] = "Escape";
  KeyCode2[KeyCode2["Space"] = 10] = "Space";
  KeyCode2[KeyCode2["PageUp"] = 11] = "PageUp";
  KeyCode2[KeyCode2["PageDown"] = 12] = "PageDown";
  KeyCode2[KeyCode2["End"] = 13] = "End";
  KeyCode2[KeyCode2["Home"] = 14] = "Home";
  KeyCode2[KeyCode2["LeftArrow"] = 15] = "LeftArrow";
  KeyCode2[KeyCode2["UpArrow"] = 16] = "UpArrow";
  KeyCode2[KeyCode2["RightArrow"] = 17] = "RightArrow";
  KeyCode2[KeyCode2["DownArrow"] = 18] = "DownArrow";
  KeyCode2[KeyCode2["Insert"] = 19] = "Insert";
  KeyCode2[KeyCode2["Delete"] = 20] = "Delete";
  KeyCode2[KeyCode2["Digit0"] = 21] = "Digit0";
  KeyCode2[KeyCode2["Digit1"] = 22] = "Digit1";
  KeyCode2[KeyCode2["Digit2"] = 23] = "Digit2";
  KeyCode2[KeyCode2["Digit3"] = 24] = "Digit3";
  KeyCode2[KeyCode2["Digit4"] = 25] = "Digit4";
  KeyCode2[KeyCode2["Digit5"] = 26] = "Digit5";
  KeyCode2[KeyCode2["Digit6"] = 27] = "Digit6";
  KeyCode2[KeyCode2["Digit7"] = 28] = "Digit7";
  KeyCode2[KeyCode2["Digit8"] = 29] = "Digit8";
  KeyCode2[KeyCode2["Digit9"] = 30] = "Digit9";
  KeyCode2[KeyCode2["KeyA"] = 31] = "KeyA";
  KeyCode2[KeyCode2["KeyB"] = 32] = "KeyB";
  KeyCode2[KeyCode2["KeyC"] = 33] = "KeyC";
  KeyCode2[KeyCode2["KeyD"] = 34] = "KeyD";
  KeyCode2[KeyCode2["KeyE"] = 35] = "KeyE";
  KeyCode2[KeyCode2["KeyF"] = 36] = "KeyF";
  KeyCode2[KeyCode2["KeyG"] = 37] = "KeyG";
  KeyCode2[KeyCode2["KeyH"] = 38] = "KeyH";
  KeyCode2[KeyCode2["KeyI"] = 39] = "KeyI";
  KeyCode2[KeyCode2["KeyJ"] = 40] = "KeyJ";
  KeyCode2[KeyCode2["KeyK"] = 41] = "KeyK";
  KeyCode2[KeyCode2["KeyL"] = 42] = "KeyL";
  KeyCode2[KeyCode2["KeyM"] = 43] = "KeyM";
  KeyCode2[KeyCode2["KeyN"] = 44] = "KeyN";
  KeyCode2[KeyCode2["KeyO"] = 45] = "KeyO";
  KeyCode2[KeyCode2["KeyP"] = 46] = "KeyP";
  KeyCode2[KeyCode2["KeyQ"] = 47] = "KeyQ";
  KeyCode2[KeyCode2["KeyR"] = 48] = "KeyR";
  KeyCode2[KeyCode2["KeyS"] = 49] = "KeyS";
  KeyCode2[KeyCode2["KeyT"] = 50] = "KeyT";
  KeyCode2[KeyCode2["KeyU"] = 51] = "KeyU";
  KeyCode2[KeyCode2["KeyV"] = 52] = "KeyV";
  KeyCode2[KeyCode2["KeyW"] = 53] = "KeyW";
  KeyCode2[KeyCode2["KeyX"] = 54] = "KeyX";
  KeyCode2[KeyCode2["KeyY"] = 55] = "KeyY";
  KeyCode2[KeyCode2["KeyZ"] = 56] = "KeyZ";
  KeyCode2[KeyCode2["Meta"] = 57] = "Meta";
  KeyCode2[KeyCode2["ContextMenu"] = 58] = "ContextMenu";
  KeyCode2[KeyCode2["F1"] = 59] = "F1";
  KeyCode2[KeyCode2["F2"] = 60] = "F2";
  KeyCode2[KeyCode2["F3"] = 61] = "F3";
  KeyCode2[KeyCode2["F4"] = 62] = "F4";
  KeyCode2[KeyCode2["F5"] = 63] = "F5";
  KeyCode2[KeyCode2["F6"] = 64] = "F6";
  KeyCode2[KeyCode2["F7"] = 65] = "F7";
  KeyCode2[KeyCode2["F8"] = 66] = "F8";
  KeyCode2[KeyCode2["F9"] = 67] = "F9";
  KeyCode2[KeyCode2["F10"] = 68] = "F10";
  KeyCode2[KeyCode2["F11"] = 69] = "F11";
  KeyCode2[KeyCode2["F12"] = 70] = "F12";
  KeyCode2[KeyCode2["F13"] = 71] = "F13";
  KeyCode2[KeyCode2["F14"] = 72] = "F14";
  KeyCode2[KeyCode2["F15"] = 73] = "F15";
  KeyCode2[KeyCode2["F16"] = 74] = "F16";
  KeyCode2[KeyCode2["F17"] = 75] = "F17";
  KeyCode2[KeyCode2["F18"] = 76] = "F18";
  KeyCode2[KeyCode2["F19"] = 77] = "F19";
  KeyCode2[KeyCode2["F20"] = 78] = "F20";
  KeyCode2[KeyCode2["F21"] = 79] = "F21";
  KeyCode2[KeyCode2["F22"] = 80] = "F22";
  KeyCode2[KeyCode2["F23"] = 81] = "F23";
  KeyCode2[KeyCode2["F24"] = 82] = "F24";
  KeyCode2[KeyCode2["NumLock"] = 83] = "NumLock";
  KeyCode2[KeyCode2["ScrollLock"] = 84] = "ScrollLock";
  KeyCode2[KeyCode2["Semicolon"] = 85] = "Semicolon";
  KeyCode2[KeyCode2["Equal"] = 86] = "Equal";
  KeyCode2[KeyCode2["Comma"] = 87] = "Comma";
  KeyCode2[KeyCode2["Minus"] = 88] = "Minus";
  KeyCode2[KeyCode2["Period"] = 89] = "Period";
  KeyCode2[KeyCode2["Slash"] = 90] = "Slash";
  KeyCode2[KeyCode2["Backquote"] = 91] = "Backquote";
  KeyCode2[KeyCode2["BracketLeft"] = 92] = "BracketLeft";
  KeyCode2[KeyCode2["Backslash"] = 93] = "Backslash";
  KeyCode2[KeyCode2["BracketRight"] = 94] = "BracketRight";
  KeyCode2[KeyCode2["Quote"] = 95] = "Quote";
  KeyCode2[KeyCode2["OEM_8"] = 96] = "OEM_8";
  KeyCode2[KeyCode2["IntlBackslash"] = 97] = "IntlBackslash";
  KeyCode2[KeyCode2["Numpad0"] = 98] = "Numpad0";
  KeyCode2[KeyCode2["Numpad1"] = 99] = "Numpad1";
  KeyCode2[KeyCode2["Numpad2"] = 100] = "Numpad2";
  KeyCode2[KeyCode2["Numpad3"] = 101] = "Numpad3";
  KeyCode2[KeyCode2["Numpad4"] = 102] = "Numpad4";
  KeyCode2[KeyCode2["Numpad5"] = 103] = "Numpad5";
  KeyCode2[KeyCode2["Numpad6"] = 104] = "Numpad6";
  KeyCode2[KeyCode2["Numpad7"] = 105] = "Numpad7";
  KeyCode2[KeyCode2["Numpad8"] = 106] = "Numpad8";
  KeyCode2[KeyCode2["Numpad9"] = 107] = "Numpad9";
  KeyCode2[KeyCode2["NumpadMultiply"] = 108] = "NumpadMultiply";
  KeyCode2[KeyCode2["NumpadAdd"] = 109] = "NumpadAdd";
  KeyCode2[KeyCode2["NUMPAD_SEPARATOR"] = 110] = "NUMPAD_SEPARATOR";
  KeyCode2[KeyCode2["NumpadSubtract"] = 111] = "NumpadSubtract";
  KeyCode2[KeyCode2["NumpadDecimal"] = 112] = "NumpadDecimal";
  KeyCode2[KeyCode2["NumpadDivide"] = 113] = "NumpadDivide";
  KeyCode2[KeyCode2["KEY_IN_COMPOSITION"] = 114] = "KEY_IN_COMPOSITION";
  KeyCode2[KeyCode2["ABNT_C1"] = 115] = "ABNT_C1";
  KeyCode2[KeyCode2["ABNT_C2"] = 116] = "ABNT_C2";
  KeyCode2[KeyCode2["AudioVolumeMute"] = 117] = "AudioVolumeMute";
  KeyCode2[KeyCode2["AudioVolumeUp"] = 118] = "AudioVolumeUp";
  KeyCode2[KeyCode2["AudioVolumeDown"] = 119] = "AudioVolumeDown";
  KeyCode2[KeyCode2["BrowserSearch"] = 120] = "BrowserSearch";
  KeyCode2[KeyCode2["BrowserHome"] = 121] = "BrowserHome";
  KeyCode2[KeyCode2["BrowserBack"] = 122] = "BrowserBack";
  KeyCode2[KeyCode2["BrowserForward"] = 123] = "BrowserForward";
  KeyCode2[KeyCode2["MediaTrackNext"] = 124] = "MediaTrackNext";
  KeyCode2[KeyCode2["MediaTrackPrevious"] = 125] = "MediaTrackPrevious";
  KeyCode2[KeyCode2["MediaStop"] = 126] = "MediaStop";
  KeyCode2[KeyCode2["MediaPlayPause"] = 127] = "MediaPlayPause";
  KeyCode2[KeyCode2["LaunchMediaPlayer"] = 128] = "LaunchMediaPlayer";
  KeyCode2[KeyCode2["LaunchMail"] = 129] = "LaunchMail";
  KeyCode2[KeyCode2["LaunchApp2"] = 130] = "LaunchApp2";
  KeyCode2[KeyCode2["Clear"] = 131] = "Clear";
  KeyCode2[KeyCode2["MAX_VALUE"] = 132] = "MAX_VALUE";
})(KeyCode$1 || (KeyCode$1 = {}));
var MarkerSeverity$1;
(function(MarkerSeverity2) {
  MarkerSeverity2[MarkerSeverity2["Hint"] = 1] = "Hint";
  MarkerSeverity2[MarkerSeverity2["Info"] = 2] = "Info";
  MarkerSeverity2[MarkerSeverity2["Warning"] = 4] = "Warning";
  MarkerSeverity2[MarkerSeverity2["Error"] = 8] = "Error";
})(MarkerSeverity$1 || (MarkerSeverity$1 = {}));
var MarkerTag$1;
(function(MarkerTag2) {
  MarkerTag2[MarkerTag2["Unnecessary"] = 1] = "Unnecessary";
  MarkerTag2[MarkerTag2["Deprecated"] = 2] = "Deprecated";
})(MarkerTag$1 || (MarkerTag$1 = {}));
var MinimapPosition;
(function(MinimapPosition2) {
  MinimapPosition2[MinimapPosition2["Inline"] = 1] = "Inline";
  MinimapPosition2[MinimapPosition2["Gutter"] = 2] = "Gutter";
})(MinimapPosition || (MinimapPosition = {}));
var MouseTargetType;
(function(MouseTargetType2) {
  MouseTargetType2[MouseTargetType2["UNKNOWN"] = 0] = "UNKNOWN";
  MouseTargetType2[MouseTargetType2["TEXTAREA"] = 1] = "TEXTAREA";
  MouseTargetType2[MouseTargetType2["GUTTER_GLYPH_MARGIN"] = 2] = "GUTTER_GLYPH_MARGIN";
  MouseTargetType2[MouseTargetType2["GUTTER_LINE_NUMBERS"] = 3] = "GUTTER_LINE_NUMBERS";
  MouseTargetType2[MouseTargetType2["GUTTER_LINE_DECORATIONS"] = 4] = "GUTTER_LINE_DECORATIONS";
  MouseTargetType2[MouseTargetType2["GUTTER_VIEW_ZONE"] = 5] = "GUTTER_VIEW_ZONE";
  MouseTargetType2[MouseTargetType2["CONTENT_TEXT"] = 6] = "CONTENT_TEXT";
  MouseTargetType2[MouseTargetType2["CONTENT_EMPTY"] = 7] = "CONTENT_EMPTY";
  MouseTargetType2[MouseTargetType2["CONTENT_VIEW_ZONE"] = 8] = "CONTENT_VIEW_ZONE";
  MouseTargetType2[MouseTargetType2["CONTENT_WIDGET"] = 9] = "CONTENT_WIDGET";
  MouseTargetType2[MouseTargetType2["OVERVIEW_RULER"] = 10] = "OVERVIEW_RULER";
  MouseTargetType2[MouseTargetType2["SCROLLBAR"] = 11] = "SCROLLBAR";
  MouseTargetType2[MouseTargetType2["OVERLAY_WIDGET"] = 12] = "OVERLAY_WIDGET";
  MouseTargetType2[MouseTargetType2["OUTSIDE_EDITOR"] = 13] = "OUTSIDE_EDITOR";
})(MouseTargetType || (MouseTargetType = {}));
var OverlayWidgetPositionPreference;
(function(OverlayWidgetPositionPreference2) {
  OverlayWidgetPositionPreference2[OverlayWidgetPositionPreference2["TOP_RIGHT_CORNER"] = 0] = "TOP_RIGHT_CORNER";
  OverlayWidgetPositionPreference2[OverlayWidgetPositionPreference2["BOTTOM_RIGHT_CORNER"] = 1] = "BOTTOM_RIGHT_CORNER";
  OverlayWidgetPositionPreference2[OverlayWidgetPositionPreference2["TOP_CENTER"] = 2] = "TOP_CENTER";
})(OverlayWidgetPositionPreference || (OverlayWidgetPositionPreference = {}));
var OverviewRulerLane;
(function(OverviewRulerLane2) {
  OverviewRulerLane2[OverviewRulerLane2["Left"] = 1] = "Left";
  OverviewRulerLane2[OverviewRulerLane2["Center"] = 2] = "Center";
  OverviewRulerLane2[OverviewRulerLane2["Right"] = 4] = "Right";
  OverviewRulerLane2[OverviewRulerLane2["Full"] = 7] = "Full";
})(OverviewRulerLane || (OverviewRulerLane = {}));
var PositionAffinity;
(function(PositionAffinity2) {
  PositionAffinity2[PositionAffinity2["Left"] = 0] = "Left";
  PositionAffinity2[PositionAffinity2["Right"] = 1] = "Right";
  PositionAffinity2[PositionAffinity2["None"] = 2] = "None";
  PositionAffinity2[PositionAffinity2["LeftOfInjectedText"] = 3] = "LeftOfInjectedText";
  PositionAffinity2[PositionAffinity2["RightOfInjectedText"] = 4] = "RightOfInjectedText";
})(PositionAffinity || (PositionAffinity = {}));
var RenderLineNumbersType;
(function(RenderLineNumbersType2) {
  RenderLineNumbersType2[RenderLineNumbersType2["Off"] = 0] = "Off";
  RenderLineNumbersType2[RenderLineNumbersType2["On"] = 1] = "On";
  RenderLineNumbersType2[RenderLineNumbersType2["Relative"] = 2] = "Relative";
  RenderLineNumbersType2[RenderLineNumbersType2["Interval"] = 3] = "Interval";
  RenderLineNumbersType2[RenderLineNumbersType2["Custom"] = 4] = "Custom";
})(RenderLineNumbersType || (RenderLineNumbersType = {}));
var RenderMinimap;
(function(RenderMinimap2) {
  RenderMinimap2[RenderMinimap2["None"] = 0] = "None";
  RenderMinimap2[RenderMinimap2["Text"] = 1] = "Text";
  RenderMinimap2[RenderMinimap2["Blocks"] = 2] = "Blocks";
})(RenderMinimap || (RenderMinimap = {}));
var ScrollType;
(function(ScrollType2) {
  ScrollType2[ScrollType2["Smooth"] = 0] = "Smooth";
  ScrollType2[ScrollType2["Immediate"] = 1] = "Immediate";
})(ScrollType || (ScrollType = {}));
var ScrollbarVisibility;
(function(ScrollbarVisibility2) {
  ScrollbarVisibility2[ScrollbarVisibility2["Auto"] = 1] = "Auto";
  ScrollbarVisibility2[ScrollbarVisibility2["Hidden"] = 2] = "Hidden";
  ScrollbarVisibility2[ScrollbarVisibility2["Visible"] = 3] = "Visible";
})(ScrollbarVisibility || (ScrollbarVisibility = {}));
var SelectionDirection$1;
(function(SelectionDirection2) {
  SelectionDirection2[SelectionDirection2["LTR"] = 0] = "LTR";
  SelectionDirection2[SelectionDirection2["RTL"] = 1] = "RTL";
})(SelectionDirection$1 || (SelectionDirection$1 = {}));
var SignatureHelpTriggerKind;
(function(SignatureHelpTriggerKind2) {
  SignatureHelpTriggerKind2[SignatureHelpTriggerKind2["Invoke"] = 1] = "Invoke";
  SignatureHelpTriggerKind2[SignatureHelpTriggerKind2["TriggerCharacter"] = 2] = "TriggerCharacter";
  SignatureHelpTriggerKind2[SignatureHelpTriggerKind2["ContentChange"] = 3] = "ContentChange";
})(SignatureHelpTriggerKind || (SignatureHelpTriggerKind = {}));
var SymbolKind;
(function(SymbolKind2) {
  SymbolKind2[SymbolKind2["File"] = 0] = "File";
  SymbolKind2[SymbolKind2["Module"] = 1] = "Module";
  SymbolKind2[SymbolKind2["Namespace"] = 2] = "Namespace";
  SymbolKind2[SymbolKind2["Package"] = 3] = "Package";
  SymbolKind2[SymbolKind2["Class"] = 4] = "Class";
  SymbolKind2[SymbolKind2["Method"] = 5] = "Method";
  SymbolKind2[SymbolKind2["Property"] = 6] = "Property";
  SymbolKind2[SymbolKind2["Field"] = 7] = "Field";
  SymbolKind2[SymbolKind2["Constructor"] = 8] = "Constructor";
  SymbolKind2[SymbolKind2["Enum"] = 9] = "Enum";
  SymbolKind2[SymbolKind2["Interface"] = 10] = "Interface";
  SymbolKind2[SymbolKind2["Function"] = 11] = "Function";
  SymbolKind2[SymbolKind2["Variable"] = 12] = "Variable";
  SymbolKind2[SymbolKind2["Constant"] = 13] = "Constant";
  SymbolKind2[SymbolKind2["String"] = 14] = "String";
  SymbolKind2[SymbolKind2["Number"] = 15] = "Number";
  SymbolKind2[SymbolKind2["Boolean"] = 16] = "Boolean";
  SymbolKind2[SymbolKind2["Array"] = 17] = "Array";
  SymbolKind2[SymbolKind2["Object"] = 18] = "Object";
  SymbolKind2[SymbolKind2["Key"] = 19] = "Key";
  SymbolKind2[SymbolKind2["Null"] = 20] = "Null";
  SymbolKind2[SymbolKind2["EnumMember"] = 21] = "EnumMember";
  SymbolKind2[SymbolKind2["Struct"] = 22] = "Struct";
  SymbolKind2[SymbolKind2["Event"] = 23] = "Event";
  SymbolKind2[SymbolKind2["Operator"] = 24] = "Operator";
  SymbolKind2[SymbolKind2["TypeParameter"] = 25] = "TypeParameter";
})(SymbolKind || (SymbolKind = {}));
var SymbolTag;
(function(SymbolTag2) {
  SymbolTag2[SymbolTag2["Deprecated"] = 1] = "Deprecated";
})(SymbolTag || (SymbolTag = {}));
var TextEditorCursorBlinkingStyle;
(function(TextEditorCursorBlinkingStyle2) {
  TextEditorCursorBlinkingStyle2[TextEditorCursorBlinkingStyle2["Hidden"] = 0] = "Hidden";
  TextEditorCursorBlinkingStyle2[TextEditorCursorBlinkingStyle2["Blink"] = 1] = "Blink";
  TextEditorCursorBlinkingStyle2[TextEditorCursorBlinkingStyle2["Smooth"] = 2] = "Smooth";
  TextEditorCursorBlinkingStyle2[TextEditorCursorBlinkingStyle2["Phase"] = 3] = "Phase";
  TextEditorCursorBlinkingStyle2[TextEditorCursorBlinkingStyle2["Expand"] = 4] = "Expand";
  TextEditorCursorBlinkingStyle2[TextEditorCursorBlinkingStyle2["Solid"] = 5] = "Solid";
})(TextEditorCursorBlinkingStyle || (TextEditorCursorBlinkingStyle = {}));
var TextEditorCursorStyle;
(function(TextEditorCursorStyle2) {
  TextEditorCursorStyle2[TextEditorCursorStyle2["Line"] = 1] = "Line";
  TextEditorCursorStyle2[TextEditorCursorStyle2["Block"] = 2] = "Block";
  TextEditorCursorStyle2[TextEditorCursorStyle2["Underline"] = 3] = "Underline";
  TextEditorCursorStyle2[TextEditorCursorStyle2["LineThin"] = 4] = "LineThin";
  TextEditorCursorStyle2[TextEditorCursorStyle2["BlockOutline"] = 5] = "BlockOutline";
  TextEditorCursorStyle2[TextEditorCursorStyle2["UnderlineThin"] = 6] = "UnderlineThin";
})(TextEditorCursorStyle || (TextEditorCursorStyle = {}));
var TrackedRangeStickiness;
(function(TrackedRangeStickiness2) {
  TrackedRangeStickiness2[TrackedRangeStickiness2["AlwaysGrowsWhenTypingAtEdges"] = 0] = "AlwaysGrowsWhenTypingAtEdges";
  TrackedRangeStickiness2[TrackedRangeStickiness2["NeverGrowsWhenTypingAtEdges"] = 1] = "NeverGrowsWhenTypingAtEdges";
  TrackedRangeStickiness2[TrackedRangeStickiness2["GrowsOnlyWhenTypingBefore"] = 2] = "GrowsOnlyWhenTypingBefore";
  TrackedRangeStickiness2[TrackedRangeStickiness2["GrowsOnlyWhenTypingAfter"] = 3] = "GrowsOnlyWhenTypingAfter";
})(TrackedRangeStickiness || (TrackedRangeStickiness = {}));
var WrappingIndent;
(function(WrappingIndent2) {
  WrappingIndent2[WrappingIndent2["None"] = 0] = "None";
  WrappingIndent2[WrappingIndent2["Same"] = 1] = "Same";
  WrappingIndent2[WrappingIndent2["Indent"] = 2] = "Indent";
  WrappingIndent2[WrappingIndent2["DeepIndent"] = 3] = "DeepIndent";
})(WrappingIndent || (WrappingIndent = {}));
let KeyMod$1 = class KeyMod {
  static chord(firstPart, secondPart) {
    return KeyChord(firstPart, secondPart);
  }
};
KeyMod$1.CtrlCmd = 2048;
KeyMod$1.Shift = 1024;
KeyMod$1.Alt = 512;
KeyMod$1.WinCtrl = 256;
function createMonacoBaseAPI() {
  return {
    editor: void 0,
    languages: void 0,
    CancellationTokenSource: CancellationTokenSource$1,
    Emitter: Emitter$1,
    KeyCode: KeyCode$1,
    KeyMod: KeyMod$1,
    Position: Position$2,
    Range: Range$2,
    Selection: Selection$1,
    SelectionDirection: SelectionDirection$1,
    MarkerSeverity: MarkerSeverity$1,
    MarkerTag: MarkerTag$1,
    Uri: URI,
    Token: Token$3
  };
}
class UnicodeTextModelHighlighter {
  static computeUnicodeHighlights(model, options, range2) {
    const startLine = range2 ? range2.startLineNumber : 1;
    const endLine = range2 ? range2.endLineNumber : model.getLineCount();
    const codePointHighlighter = new CodePointHighlighter(options);
    const candidates = codePointHighlighter.getCandidateCodePoints();
    let regex;
    if (candidates === "allNonBasicAscii") {
      regex = new RegExp("[^\\t\\n\\r\\x20-\\x7E]", "g");
    } else {
      regex = new RegExp(`${buildRegExpCharClassExpr(Array.from(candidates))}`, "g");
    }
    const searcher = new Searcher(null, regex);
    const ranges = [];
    let hasMore = false;
    let m;
    let ambiguousCharacterCount = 0;
    let invisibleCharacterCount = 0;
    let nonBasicAsciiCharacterCount = 0;
    forLoop:
      for (let lineNumber = startLine, lineCount = endLine; lineNumber <= lineCount; lineNumber++) {
        const lineContent = model.getLineContent(lineNumber);
        const lineLength = lineContent.length;
        searcher.reset(0);
        do {
          m = searcher.next(lineContent);
          if (m) {
            let startIndex = m.index;
            let endIndex = m.index + m[0].length;
            if (startIndex > 0) {
              const charCodeBefore = lineContent.charCodeAt(startIndex - 1);
              if (isHighSurrogate(charCodeBefore)) {
                startIndex--;
              }
            }
            if (endIndex + 1 < lineLength) {
              const charCodeBefore = lineContent.charCodeAt(endIndex - 1);
              if (isHighSurrogate(charCodeBefore)) {
                endIndex++;
              }
            }
            const str2 = lineContent.substring(startIndex, endIndex);
            let word2 = getWordAtText(startIndex + 1, DEFAULT_WORD_REGEXP, lineContent, 0);
            if (word2 && word2.endColumn <= startIndex + 1) {
              word2 = null;
            }
            const highlightReason = codePointHighlighter.shouldHighlightNonBasicASCII(str2, word2 ? word2.word : null);
            if (highlightReason !== 0) {
              if (highlightReason === 3) {
                ambiguousCharacterCount++;
              } else if (highlightReason === 2) {
                invisibleCharacterCount++;
              } else if (highlightReason === 1) {
                nonBasicAsciiCharacterCount++;
              } else {
                assertNever();
              }
              const MAX_RESULT_LENGTH = 1e3;
              if (ranges.length >= MAX_RESULT_LENGTH) {
                hasMore = true;
                break forLoop;
              }
              ranges.push(new Range$2(lineNumber, startIndex + 1, lineNumber, endIndex + 1));
            }
          }
        } while (m);
      }
    return {
      ranges,
      hasMore,
      ambiguousCharacterCount,
      invisibleCharacterCount,
      nonBasicAsciiCharacterCount
    };
  }
  static computeUnicodeHighlightReason(char, options) {
    const codePointHighlighter = new CodePointHighlighter(options);
    const reason = codePointHighlighter.shouldHighlightNonBasicASCII(char, null);
    switch (reason) {
      case 0:
        return null;
      case 2:
        return {
          kind: 1
          /* UnicodeHighlighterReasonKind.Invisible */
        };
      case 3: {
        const codePoint = char.codePointAt(0);
        const primaryConfusable = codePointHighlighter.ambiguousCharacters.getPrimaryConfusable(codePoint);
        const notAmbiguousInLocales = AmbiguousCharacters.getLocales().filter((l) => !AmbiguousCharacters.getInstance(/* @__PURE__ */ new Set([...options.allowedLocales, l])).isAmbiguous(codePoint));
        return { kind: 0, confusableWith: String.fromCodePoint(primaryConfusable), notAmbiguousInLocales };
      }
      case 1:
        return {
          kind: 2
          /* UnicodeHighlighterReasonKind.NonBasicAscii */
        };
    }
  }
}
function buildRegExpCharClassExpr(codePoints, flags) {
  const src = `[${escapeRegExpCharacters(codePoints.map((i) => String.fromCodePoint(i)).join(""))}]`;
  return src;
}
class CodePointHighlighter {
  constructor(options) {
    this.options = options;
    this.allowedCodePoints = new Set(options.allowedCodePoints);
    this.ambiguousCharacters = AmbiguousCharacters.getInstance(new Set(options.allowedLocales));
  }
  getCandidateCodePoints() {
    if (this.options.nonBasicASCII) {
      return "allNonBasicAscii";
    }
    const set2 = /* @__PURE__ */ new Set();
    if (this.options.invisibleCharacters) {
      for (const cp of InvisibleCharacters.codePoints) {
        if (!isAllowedInvisibleCharacter(String.fromCodePoint(cp))) {
          set2.add(cp);
        }
      }
    }
    if (this.options.ambiguousCharacters) {
      for (const cp of this.ambiguousCharacters.getConfusableCodePoints()) {
        set2.add(cp);
      }
    }
    for (const cp of this.allowedCodePoints) {
      set2.delete(cp);
    }
    return set2;
  }
  shouldHighlightNonBasicASCII(character, wordContext) {
    const codePoint = character.codePointAt(0);
    if (this.allowedCodePoints.has(codePoint)) {
      return 0;
    }
    if (this.options.nonBasicASCII) {
      return 1;
    }
    let hasBasicASCIICharacters = false;
    let hasNonConfusableNonBasicAsciiCharacter = false;
    if (wordContext) {
      for (const char of wordContext) {
        const codePoint2 = char.codePointAt(0);
        const isBasicASCII$1 = isBasicASCII(char);
        hasBasicASCIICharacters = hasBasicASCIICharacters || isBasicASCII$1;
        if (!isBasicASCII$1 && !this.ambiguousCharacters.isAmbiguous(codePoint2) && !InvisibleCharacters.isInvisibleCharacter(codePoint2)) {
          hasNonConfusableNonBasicAsciiCharacter = true;
        }
      }
    }
    if (
      /* Don't allow mixing weird looking characters with ASCII */
      !hasBasicASCIICharacters && /* Is there an obviously weird looking character? */
      hasNonConfusableNonBasicAsciiCharacter
    ) {
      return 0;
    }
    if (this.options.invisibleCharacters) {
      if (!isAllowedInvisibleCharacter(character) && InvisibleCharacters.isInvisibleCharacter(codePoint)) {
        return 2;
      }
    }
    if (this.options.ambiguousCharacters) {
      if (this.ambiguousCharacters.isAmbiguous(codePoint)) {
        return 3;
      }
    }
    return 0;
  }
}
function isAllowedInvisibleCharacter(character) {
  return character === " " || character === "\n" || character === "	";
}
const MINIMUM_MATCHING_CHARACTER_LENGTH = 3;
class SmartLinesDiffComputer {
  computeDiff(originalLines, modifiedLines, options) {
    var _a2;
    const diffComputer = new DiffComputer(originalLines, modifiedLines, {
      maxComputationTime: options.maxComputationTimeMs,
      shouldIgnoreTrimWhitespace: options.ignoreTrimWhitespace,
      shouldComputeCharChanges: true,
      shouldMakePrettyDiff: true,
      shouldPostProcessCharChanges: true
    });
    const result2 = diffComputer.computeDiff();
    const changes = [];
    let lastChange = null;
    for (const c of result2.changes) {
      let originalRange;
      if (c.originalEndLineNumber === 0) {
        originalRange = new LineRange2(c.originalStartLineNumber + 1, c.originalStartLineNumber + 1);
      } else {
        originalRange = new LineRange2(c.originalStartLineNumber, c.originalEndLineNumber + 1);
      }
      let modifiedRange;
      if (c.modifiedEndLineNumber === 0) {
        modifiedRange = new LineRange2(c.modifiedStartLineNumber + 1, c.modifiedStartLineNumber + 1);
      } else {
        modifiedRange = new LineRange2(c.modifiedStartLineNumber, c.modifiedEndLineNumber + 1);
      }
      let change = new LineRangeMapping(originalRange, modifiedRange, (_a2 = c.charChanges) === null || _a2 === void 0 ? void 0 : _a2.map((c2) => new RangeMapping(new Range$2(c2.originalStartLineNumber, c2.originalStartColumn, c2.originalEndLineNumber, c2.originalEndColumn), new Range$2(c2.modifiedStartLineNumber, c2.modifiedStartColumn, c2.modifiedEndLineNumber, c2.modifiedEndColumn))));
      if (lastChange) {
        if (lastChange.modifiedRange.endLineNumberExclusive === change.modifiedRange.startLineNumber || lastChange.originalRange.endLineNumberExclusive === change.originalRange.startLineNumber) {
          change = new LineRangeMapping(lastChange.originalRange.join(change.originalRange), lastChange.modifiedRange.join(change.modifiedRange), lastChange.innerChanges && change.innerChanges ? lastChange.innerChanges.concat(change.innerChanges) : void 0);
          changes.pop();
        }
      }
      changes.push(change);
      lastChange = change;
    }
    assertFn(() => {
      return checkAdjacentItems(changes, (m1, m2) => m2.originalRange.startLineNumber - m1.originalRange.endLineNumberExclusive === m2.modifiedRange.startLineNumber - m1.modifiedRange.endLineNumberExclusive && // There has to be an unchanged line in between (otherwise both diffs should have been joined)
      m1.originalRange.endLineNumberExclusive < m2.originalRange.startLineNumber && m1.modifiedRange.endLineNumberExclusive < m2.modifiedRange.startLineNumber);
    });
    return new LinesDiff(changes, [], result2.quitEarly);
  }
}
function computeDiff(originalSequence, modifiedSequence, continueProcessingPredicate, pretty) {
  const diffAlgo = new LcsDiff(originalSequence, modifiedSequence, continueProcessingPredicate);
  return diffAlgo.ComputeDiff(pretty);
}
let LineSequence$1 = class LineSequence {
  constructor(lines) {
    const startColumns = [];
    const endColumns = [];
    for (let i = 0, length2 = lines.length; i < length2; i++) {
      startColumns[i] = getFirstNonBlankColumn(lines[i], 1);
      endColumns[i] = getLastNonBlankColumn(lines[i], 1);
    }
    this.lines = lines;
    this._startColumns = startColumns;
    this._endColumns = endColumns;
  }
  getElements() {
    const elements = [];
    for (let i = 0, len = this.lines.length; i < len; i++) {
      elements[i] = this.lines[i].substring(this._startColumns[i] - 1, this._endColumns[i] - 1);
    }
    return elements;
  }
  getStrictElement(index) {
    return this.lines[index];
  }
  getStartLineNumber(i) {
    return i + 1;
  }
  getEndLineNumber(i) {
    return i + 1;
  }
  createCharSequence(shouldIgnoreTrimWhitespace, startIndex, endIndex) {
    const charCodes = [];
    const lineNumbers2 = [];
    const columns = [];
    let len = 0;
    for (let index = startIndex; index <= endIndex; index++) {
      const lineContent = this.lines[index];
      const startColumn = shouldIgnoreTrimWhitespace ? this._startColumns[index] : 1;
      const endColumn = shouldIgnoreTrimWhitespace ? this._endColumns[index] : lineContent.length + 1;
      for (let col = startColumn; col < endColumn; col++) {
        charCodes[len] = lineContent.charCodeAt(col - 1);
        lineNumbers2[len] = index + 1;
        columns[len] = col;
        len++;
      }
      if (!shouldIgnoreTrimWhitespace && index < endIndex) {
        charCodes[len] = 10;
        lineNumbers2[len] = index + 1;
        columns[len] = lineContent.length + 1;
        len++;
      }
    }
    return new CharSequence(charCodes, lineNumbers2, columns);
  }
};
class CharSequence {
  constructor(charCodes, lineNumbers2, columns) {
    this._charCodes = charCodes;
    this._lineNumbers = lineNumbers2;
    this._columns = columns;
  }
  toString() {
    return "[" + this._charCodes.map((s, idx) => (s === 10 ? "\\n" : String.fromCharCode(s)) + `-(${this._lineNumbers[idx]},${this._columns[idx]})`).join(", ") + "]";
  }
  _assertIndex(index, arr) {
    if (index < 0 || index >= arr.length) {
      throw new Error(`Illegal index`);
    }
  }
  getElements() {
    return this._charCodes;
  }
  getStartLineNumber(i) {
    if (i > 0 && i === this._lineNumbers.length) {
      return this.getEndLineNumber(i - 1);
    }
    this._assertIndex(i, this._lineNumbers);
    return this._lineNumbers[i];
  }
  getEndLineNumber(i) {
    if (i === -1) {
      return this.getStartLineNumber(i + 1);
    }
    this._assertIndex(i, this._lineNumbers);
    if (this._charCodes[i] === 10) {
      return this._lineNumbers[i] + 1;
    }
    return this._lineNumbers[i];
  }
  getStartColumn(i) {
    if (i > 0 && i === this._columns.length) {
      return this.getEndColumn(i - 1);
    }
    this._assertIndex(i, this._columns);
    return this._columns[i];
  }
  getEndColumn(i) {
    if (i === -1) {
      return this.getStartColumn(i + 1);
    }
    this._assertIndex(i, this._columns);
    if (this._charCodes[i] === 10) {
      return 1;
    }
    return this._columns[i] + 1;
  }
}
class CharChange {
  constructor(originalStartLineNumber, originalStartColumn, originalEndLineNumber, originalEndColumn, modifiedStartLineNumber, modifiedStartColumn, modifiedEndLineNumber, modifiedEndColumn) {
    this.originalStartLineNumber = originalStartLineNumber;
    this.originalStartColumn = originalStartColumn;
    this.originalEndLineNumber = originalEndLineNumber;
    this.originalEndColumn = originalEndColumn;
    this.modifiedStartLineNumber = modifiedStartLineNumber;
    this.modifiedStartColumn = modifiedStartColumn;
    this.modifiedEndLineNumber = modifiedEndLineNumber;
    this.modifiedEndColumn = modifiedEndColumn;
  }
  static createFromDiffChange(diffChange, originalCharSequence, modifiedCharSequence) {
    const originalStartLineNumber = originalCharSequence.getStartLineNumber(diffChange.originalStart);
    const originalStartColumn = originalCharSequence.getStartColumn(diffChange.originalStart);
    const originalEndLineNumber = originalCharSequence.getEndLineNumber(diffChange.originalStart + diffChange.originalLength - 1);
    const originalEndColumn = originalCharSequence.getEndColumn(diffChange.originalStart + diffChange.originalLength - 1);
    const modifiedStartLineNumber = modifiedCharSequence.getStartLineNumber(diffChange.modifiedStart);
    const modifiedStartColumn = modifiedCharSequence.getStartColumn(diffChange.modifiedStart);
    const modifiedEndLineNumber = modifiedCharSequence.getEndLineNumber(diffChange.modifiedStart + diffChange.modifiedLength - 1);
    const modifiedEndColumn = modifiedCharSequence.getEndColumn(diffChange.modifiedStart + diffChange.modifiedLength - 1);
    return new CharChange(originalStartLineNumber, originalStartColumn, originalEndLineNumber, originalEndColumn, modifiedStartLineNumber, modifiedStartColumn, modifiedEndLineNumber, modifiedEndColumn);
  }
}
function postProcessCharChanges(rawChanges) {
  if (rawChanges.length <= 1) {
    return rawChanges;
  }
  const result2 = [rawChanges[0]];
  let prevChange = result2[0];
  for (let i = 1, len = rawChanges.length; i < len; i++) {
    const currChange = rawChanges[i];
    const originalMatchingLength = currChange.originalStart - (prevChange.originalStart + prevChange.originalLength);
    const modifiedMatchingLength = currChange.modifiedStart - (prevChange.modifiedStart + prevChange.modifiedLength);
    const matchingLength = Math.min(originalMatchingLength, modifiedMatchingLength);
    if (matchingLength < MINIMUM_MATCHING_CHARACTER_LENGTH) {
      prevChange.originalLength = currChange.originalStart + currChange.originalLength - prevChange.originalStart;
      prevChange.modifiedLength = currChange.modifiedStart + currChange.modifiedLength - prevChange.modifiedStart;
    } else {
      result2.push(currChange);
      prevChange = currChange;
    }
  }
  return result2;
}
class LineChange {
  constructor(originalStartLineNumber, originalEndLineNumber, modifiedStartLineNumber, modifiedEndLineNumber, charChanges) {
    this.originalStartLineNumber = originalStartLineNumber;
    this.originalEndLineNumber = originalEndLineNumber;
    this.modifiedStartLineNumber = modifiedStartLineNumber;
    this.modifiedEndLineNumber = modifiedEndLineNumber;
    this.charChanges = charChanges;
  }
  static createFromDiffResult(shouldIgnoreTrimWhitespace, diffChange, originalLineSequence, modifiedLineSequence, continueCharDiff, shouldComputeCharChanges, shouldPostProcessCharChanges) {
    let originalStartLineNumber;
    let originalEndLineNumber;
    let modifiedStartLineNumber;
    let modifiedEndLineNumber;
    let charChanges = void 0;
    if (diffChange.originalLength === 0) {
      originalStartLineNumber = originalLineSequence.getStartLineNumber(diffChange.originalStart) - 1;
      originalEndLineNumber = 0;
    } else {
      originalStartLineNumber = originalLineSequence.getStartLineNumber(diffChange.originalStart);
      originalEndLineNumber = originalLineSequence.getEndLineNumber(diffChange.originalStart + diffChange.originalLength - 1);
    }
    if (diffChange.modifiedLength === 0) {
      modifiedStartLineNumber = modifiedLineSequence.getStartLineNumber(diffChange.modifiedStart) - 1;
      modifiedEndLineNumber = 0;
    } else {
      modifiedStartLineNumber = modifiedLineSequence.getStartLineNumber(diffChange.modifiedStart);
      modifiedEndLineNumber = modifiedLineSequence.getEndLineNumber(diffChange.modifiedStart + diffChange.modifiedLength - 1);
    }
    if (shouldComputeCharChanges && diffChange.originalLength > 0 && diffChange.originalLength < 20 && diffChange.modifiedLength > 0 && diffChange.modifiedLength < 20 && continueCharDiff()) {
      const originalCharSequence = originalLineSequence.createCharSequence(shouldIgnoreTrimWhitespace, diffChange.originalStart, diffChange.originalStart + diffChange.originalLength - 1);
      const modifiedCharSequence = modifiedLineSequence.createCharSequence(shouldIgnoreTrimWhitespace, diffChange.modifiedStart, diffChange.modifiedStart + diffChange.modifiedLength - 1);
      if (originalCharSequence.getElements().length > 0 && modifiedCharSequence.getElements().length > 0) {
        let rawChanges = computeDiff(originalCharSequence, modifiedCharSequence, continueCharDiff, true).changes;
        if (shouldPostProcessCharChanges) {
          rawChanges = postProcessCharChanges(rawChanges);
        }
        charChanges = [];
        for (let i = 0, length2 = rawChanges.length; i < length2; i++) {
          charChanges.push(CharChange.createFromDiffChange(rawChanges[i], originalCharSequence, modifiedCharSequence));
        }
      }
    }
    return new LineChange(originalStartLineNumber, originalEndLineNumber, modifiedStartLineNumber, modifiedEndLineNumber, charChanges);
  }
}
class DiffComputer {
  constructor(originalLines, modifiedLines, opts) {
    this.shouldComputeCharChanges = opts.shouldComputeCharChanges;
    this.shouldPostProcessCharChanges = opts.shouldPostProcessCharChanges;
    this.shouldIgnoreTrimWhitespace = opts.shouldIgnoreTrimWhitespace;
    this.shouldMakePrettyDiff = opts.shouldMakePrettyDiff;
    this.originalLines = originalLines;
    this.modifiedLines = modifiedLines;
    this.original = new LineSequence$1(originalLines);
    this.modified = new LineSequence$1(modifiedLines);
    this.continueLineDiff = createContinueProcessingPredicate(opts.maxComputationTime);
    this.continueCharDiff = createContinueProcessingPredicate(opts.maxComputationTime === 0 ? 0 : Math.min(opts.maxComputationTime, 5e3));
  }
  computeDiff() {
    if (this.original.lines.length === 1 && this.original.lines[0].length === 0) {
      if (this.modified.lines.length === 1 && this.modified.lines[0].length === 0) {
        return {
          quitEarly: false,
          changes: []
        };
      }
      return {
        quitEarly: false,
        changes: [{
          originalStartLineNumber: 1,
          originalEndLineNumber: 1,
          modifiedStartLineNumber: 1,
          modifiedEndLineNumber: this.modified.lines.length,
          charChanges: void 0
        }]
      };
    }
    if (this.modified.lines.length === 1 && this.modified.lines[0].length === 0) {
      return {
        quitEarly: false,
        changes: [{
          originalStartLineNumber: 1,
          originalEndLineNumber: this.original.lines.length,
          modifiedStartLineNumber: 1,
          modifiedEndLineNumber: 1,
          charChanges: void 0
        }]
      };
    }
    const diffResult = computeDiff(this.original, this.modified, this.continueLineDiff, this.shouldMakePrettyDiff);
    const rawChanges = diffResult.changes;
    const quitEarly = diffResult.quitEarly;
    if (this.shouldIgnoreTrimWhitespace) {
      const lineChanges = [];
      for (let i = 0, length2 = rawChanges.length; i < length2; i++) {
        lineChanges.push(LineChange.createFromDiffResult(this.shouldIgnoreTrimWhitespace, rawChanges[i], this.original, this.modified, this.continueCharDiff, this.shouldComputeCharChanges, this.shouldPostProcessCharChanges));
      }
      return {
        quitEarly,
        changes: lineChanges
      };
    }
    const result2 = [];
    let originalLineIndex = 0;
    let modifiedLineIndex = 0;
    for (let i = -1, len = rawChanges.length; i < len; i++) {
      const nextChange = i + 1 < len ? rawChanges[i + 1] : null;
      const originalStop = nextChange ? nextChange.originalStart : this.originalLines.length;
      const modifiedStop = nextChange ? nextChange.modifiedStart : this.modifiedLines.length;
      while (originalLineIndex < originalStop && modifiedLineIndex < modifiedStop) {
        const originalLine = this.originalLines[originalLineIndex];
        const modifiedLine = this.modifiedLines[modifiedLineIndex];
        if (originalLine !== modifiedLine) {
          {
            let originalStartColumn = getFirstNonBlankColumn(originalLine, 1);
            let modifiedStartColumn = getFirstNonBlankColumn(modifiedLine, 1);
            while (originalStartColumn > 1 && modifiedStartColumn > 1) {
              const originalChar = originalLine.charCodeAt(originalStartColumn - 2);
              const modifiedChar = modifiedLine.charCodeAt(modifiedStartColumn - 2);
              if (originalChar !== modifiedChar) {
                break;
              }
              originalStartColumn--;
              modifiedStartColumn--;
            }
            if (originalStartColumn > 1 || modifiedStartColumn > 1) {
              this._pushTrimWhitespaceCharChange(result2, originalLineIndex + 1, 1, originalStartColumn, modifiedLineIndex + 1, 1, modifiedStartColumn);
            }
          }
          {
            let originalEndColumn = getLastNonBlankColumn(originalLine, 1);
            let modifiedEndColumn = getLastNonBlankColumn(modifiedLine, 1);
            const originalMaxColumn = originalLine.length + 1;
            const modifiedMaxColumn = modifiedLine.length + 1;
            while (originalEndColumn < originalMaxColumn && modifiedEndColumn < modifiedMaxColumn) {
              const originalChar = originalLine.charCodeAt(originalEndColumn - 1);
              const modifiedChar = originalLine.charCodeAt(modifiedEndColumn - 1);
              if (originalChar !== modifiedChar) {
                break;
              }
              originalEndColumn++;
              modifiedEndColumn++;
            }
            if (originalEndColumn < originalMaxColumn || modifiedEndColumn < modifiedMaxColumn) {
              this._pushTrimWhitespaceCharChange(result2, originalLineIndex + 1, originalEndColumn, originalMaxColumn, modifiedLineIndex + 1, modifiedEndColumn, modifiedMaxColumn);
            }
          }
        }
        originalLineIndex++;
        modifiedLineIndex++;
      }
      if (nextChange) {
        result2.push(LineChange.createFromDiffResult(this.shouldIgnoreTrimWhitespace, nextChange, this.original, this.modified, this.continueCharDiff, this.shouldComputeCharChanges, this.shouldPostProcessCharChanges));
        originalLineIndex += nextChange.originalLength;
        modifiedLineIndex += nextChange.modifiedLength;
      }
    }
    return {
      quitEarly,
      changes: result2
    };
  }
  _pushTrimWhitespaceCharChange(result2, originalLineNumber, originalStartColumn, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedEndColumn) {
    if (this._mergeTrimWhitespaceCharChange(result2, originalLineNumber, originalStartColumn, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedEndColumn)) {
      return;
    }
    let charChanges = void 0;
    if (this.shouldComputeCharChanges) {
      charChanges = [new CharChange(originalLineNumber, originalStartColumn, originalLineNumber, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedLineNumber, modifiedEndColumn)];
    }
    result2.push(new LineChange(originalLineNumber, originalLineNumber, modifiedLineNumber, modifiedLineNumber, charChanges));
  }
  _mergeTrimWhitespaceCharChange(result2, originalLineNumber, originalStartColumn, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedEndColumn) {
    const len = result2.length;
    if (len === 0) {
      return false;
    }
    const prevChange = result2[len - 1];
    if (prevChange.originalEndLineNumber === 0 || prevChange.modifiedEndLineNumber === 0) {
      return false;
    }
    if (prevChange.originalEndLineNumber === originalLineNumber && prevChange.modifiedEndLineNumber === modifiedLineNumber) {
      if (this.shouldComputeCharChanges && prevChange.charChanges) {
        prevChange.charChanges.push(new CharChange(originalLineNumber, originalStartColumn, originalLineNumber, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedLineNumber, modifiedEndColumn));
      }
      return true;
    }
    if (prevChange.originalEndLineNumber + 1 === originalLineNumber && prevChange.modifiedEndLineNumber + 1 === modifiedLineNumber) {
      prevChange.originalEndLineNumber = originalLineNumber;
      prevChange.modifiedEndLineNumber = modifiedLineNumber;
      if (this.shouldComputeCharChanges && prevChange.charChanges) {
        prevChange.charChanges.push(new CharChange(originalLineNumber, originalStartColumn, originalLineNumber, originalEndColumn, modifiedLineNumber, modifiedStartColumn, modifiedLineNumber, modifiedEndColumn));
      }
      return true;
    }
    return false;
  }
}
function getFirstNonBlankColumn(txt, defaultValue) {
  const r = firstNonWhitespaceIndex(txt);
  if (r === -1) {
    return defaultValue;
  }
  return r + 1;
}
function getLastNonBlankColumn(txt, defaultValue) {
  const r = lastNonWhitespaceIndex(txt);
  if (r === -1) {
    return defaultValue;
  }
  return r + 2;
}
function createContinueProcessingPredicate(maximumRuntime) {
  if (maximumRuntime === 0) {
    return () => true;
  }
  const startTime2 = Date.now();
  return () => {
    return Date.now() - startTime2 < maximumRuntime;
  };
}
class DiffAlgorithmResult {
  static trivial(seq1, seq2) {
    return new DiffAlgorithmResult([new SequenceDiff(new OffsetRange(0, seq1.length), new OffsetRange(0, seq2.length))], false);
  }
  static trivialTimedOut(seq1, seq2) {
    return new DiffAlgorithmResult([new SequenceDiff(new OffsetRange(0, seq1.length), new OffsetRange(0, seq2.length))], true);
  }
  constructor(diffs, hitTimeout) {
    this.diffs = diffs;
    this.hitTimeout = hitTimeout;
  }
}
class SequenceDiff {
  constructor(seq1Range, seq2Range) {
    this.seq1Range = seq1Range;
    this.seq2Range = seq2Range;
  }
  reverse() {
    return new SequenceDiff(this.seq2Range, this.seq1Range);
  }
  toString() {
    return `${this.seq1Range} <-> ${this.seq2Range}`;
  }
  join(other) {
    return new SequenceDiff(this.seq1Range.join(other.seq1Range), this.seq2Range.join(other.seq2Range));
  }
  delta(offset) {
    if (offset === 0) {
      return this;
    }
    return new SequenceDiff(this.seq1Range.delta(offset), this.seq2Range.delta(offset));
  }
}
class InfiniteTimeout {
  isValid() {
    return true;
  }
}
InfiniteTimeout.instance = new InfiniteTimeout();
class DateTimeout {
  constructor(timeout2) {
    this.timeout = timeout2;
    this.startTime = Date.now();
    this.valid = true;
    if (timeout2 <= 0) {
      throw new BugIndicatingError("timeout must be positive");
    }
  }
  // Recommendation: Set a log-point `{this.disable()}` in the body
  isValid() {
    const valid = Date.now() - this.startTime < this.timeout;
    if (!valid && this.valid) {
      this.valid = false;
      debugger;
    }
    return this.valid;
  }
}
class Array2D {
  constructor(width, height) {
    this.width = width;
    this.height = height;
    this.array = [];
    this.array = new Array(width * height);
  }
  get(x, y) {
    return this.array[x + y * this.width];
  }
  set(x, y, value) {
    this.array[x + y * this.width] = value;
  }
}
class DynamicProgrammingDiffing {
  compute(sequence1, sequence2, timeout2 = InfiniteTimeout.instance, equalityScore) {
    if (sequence1.length === 0 || sequence2.length === 0) {
      return DiffAlgorithmResult.trivial(sequence1, sequence2);
    }
    const lcsLengths = new Array2D(sequence1.length, sequence2.length);
    const directions = new Array2D(sequence1.length, sequence2.length);
    const lengths = new Array2D(sequence1.length, sequence2.length);
    for (let s12 = 0; s12 < sequence1.length; s12++) {
      for (let s22 = 0; s22 < sequence2.length; s22++) {
        if (!timeout2.isValid()) {
          return DiffAlgorithmResult.trivialTimedOut(sequence1, sequence2);
        }
        const horizontalLen = s12 === 0 ? 0 : lcsLengths.get(s12 - 1, s22);
        const verticalLen = s22 === 0 ? 0 : lcsLengths.get(s12, s22 - 1);
        let extendedSeqScore;
        if (sequence1.getElement(s12) === sequence2.getElement(s22)) {
          if (s12 === 0 || s22 === 0) {
            extendedSeqScore = 0;
          } else {
            extendedSeqScore = lcsLengths.get(s12 - 1, s22 - 1);
          }
          if (s12 > 0 && s22 > 0 && directions.get(s12 - 1, s22 - 1) === 3) {
            extendedSeqScore += lengths.get(s12 - 1, s22 - 1);
          }
          extendedSeqScore += equalityScore ? equalityScore(s12, s22) : 1;
        } else {
          extendedSeqScore = -1;
        }
        const newValue = Math.max(horizontalLen, verticalLen, extendedSeqScore);
        if (newValue === extendedSeqScore) {
          const prevLen = s12 > 0 && s22 > 0 ? lengths.get(s12 - 1, s22 - 1) : 0;
          lengths.set(s12, s22, prevLen + 1);
          directions.set(s12, s22, 3);
        } else if (newValue === horizontalLen) {
          lengths.set(s12, s22, 0);
          directions.set(s12, s22, 1);
        } else if (newValue === verticalLen) {
          lengths.set(s12, s22, 0);
          directions.set(s12, s22, 2);
        }
        lcsLengths.set(s12, s22, newValue);
      }
    }
    const result2 = [];
    let lastAligningPosS1 = sequence1.length;
    let lastAligningPosS2 = sequence2.length;
    function reportDecreasingAligningPositions(s12, s22) {
      if (s12 + 1 !== lastAligningPosS1 || s22 + 1 !== lastAligningPosS2) {
        result2.push(new SequenceDiff(new OffsetRange(s12 + 1, lastAligningPosS1), new OffsetRange(s22 + 1, lastAligningPosS2)));
      }
      lastAligningPosS1 = s12;
      lastAligningPosS2 = s22;
    }
    let s1 = sequence1.length - 1;
    let s2 = sequence2.length - 1;
    while (s1 >= 0 && s2 >= 0) {
      if (directions.get(s1, s2) === 3) {
        reportDecreasingAligningPositions(s1, s2);
        s1--;
        s2--;
      } else {
        if (directions.get(s1, s2) === 1) {
          s1--;
        } else {
          s2--;
        }
      }
    }
    reportDecreasingAligningPositions(-1, -1);
    result2.reverse();
    return new DiffAlgorithmResult(result2, false);
  }
}
function optimizeSequenceDiffs(sequence1, sequence2, sequenceDiffs) {
  let result2 = sequenceDiffs;
  result2 = joinSequenceDiffs(sequence1, sequence2, result2);
  result2 = shiftSequenceDiffs(sequence1, sequence2, result2);
  return result2;
}
function smoothenSequenceDiffs(sequence1, sequence2, sequenceDiffs) {
  const result2 = [];
  for (const s of sequenceDiffs) {
    const last2 = result2[result2.length - 1];
    if (!last2) {
      result2.push(s);
      continue;
    }
    if (s.seq1Range.start - last2.seq1Range.endExclusive <= 2 || s.seq2Range.start - last2.seq2Range.endExclusive <= 2) {
      result2[result2.length - 1] = new SequenceDiff(last2.seq1Range.join(s.seq1Range), last2.seq2Range.join(s.seq2Range));
    } else {
      result2.push(s);
    }
  }
  return result2;
}
function removeRandomMatches(sequence1, sequence2, sequenceDiffs) {
  let diffs = sequenceDiffs;
  if (diffs.length === 0) {
    return diffs;
  }
  let counter = 0;
  let shouldRepeat;
  do {
    shouldRepeat = false;
    const result2 = [
      diffs[0]
    ];
    for (let i = 1; i < diffs.length; i++) {
      let shouldJoinDiffs = function(before, after) {
        const unchangedRange = new OffsetRange(lastResult.seq1Range.endExclusive, cur.seq1Range.start);
        const unchangedLineCount = sequence1.countLinesIn(unchangedRange);
        if (unchangedLineCount > 5 || unchangedRange.length > 500) {
          return false;
        }
        const unchangedText = sequence1.getText(unchangedRange).trim();
        if (unchangedText.length > 20 || unchangedText.split(/\r\n|\r|\n/).length > 1) {
          return false;
        }
        const beforeLineCount1 = sequence1.countLinesIn(before.seq1Range);
        const beforeSeq1Length = before.seq1Range.length;
        const beforeLineCount2 = sequence2.countLinesIn(before.seq2Range);
        const beforeSeq2Length = before.seq2Range.length;
        const afterLineCount1 = sequence1.countLinesIn(after.seq1Range);
        const afterSeq1Length = after.seq1Range.length;
        const afterLineCount2 = sequence2.countLinesIn(after.seq2Range);
        const afterSeq2Length = after.seq2Range.length;
        const max = 2 * 40 + 50;
        function cap(v) {
          return Math.min(v, max);
        }
        if (Math.pow(Math.pow(cap(beforeLineCount1 * 40 + beforeSeq1Length), 1.5) + Math.pow(cap(beforeLineCount2 * 40 + beforeSeq2Length), 1.5), 1.5) + Math.pow(Math.pow(cap(afterLineCount1 * 40 + afterSeq1Length), 1.5) + Math.pow(cap(afterLineCount2 * 40 + afterSeq2Length), 1.5), 1.5) > Math.pow(Math.pow(max, 1.5), 1.5) * 1.3) {
          return true;
        }
        return false;
      };
      const cur = diffs[i];
      const lastResult = result2[result2.length - 1];
      const shouldJoin = shouldJoinDiffs(lastResult, cur);
      if (shouldJoin) {
        shouldRepeat = true;
        result2[result2.length - 1] = result2[result2.length - 1].join(cur);
      } else {
        result2.push(cur);
      }
    }
    diffs = result2;
  } while (counter++ < 10 && shouldRepeat);
  return diffs;
}
function joinSequenceDiffs(sequence1, sequence2, sequenceDiffs) {
  if (sequenceDiffs.length === 0) {
    return sequenceDiffs;
  }
  const result2 = [];
  result2.push(sequenceDiffs[0]);
  for (let i = 1; i < sequenceDiffs.length; i++) {
    const prevResult = result2[result2.length - 1];
    let cur = sequenceDiffs[i];
    if (cur.seq1Range.isEmpty || cur.seq2Range.isEmpty) {
      const length2 = cur.seq1Range.start - prevResult.seq1Range.endExclusive;
      let d;
      for (d = 1; d <= length2; d++) {
        if (sequence1.getElement(cur.seq1Range.start - d) !== sequence1.getElement(cur.seq1Range.endExclusive - d) || sequence2.getElement(cur.seq2Range.start - d) !== sequence2.getElement(cur.seq2Range.endExclusive - d)) {
          break;
        }
      }
      d--;
      if (d === length2) {
        result2[result2.length - 1] = new SequenceDiff(new OffsetRange(prevResult.seq1Range.start, cur.seq1Range.endExclusive - length2), new OffsetRange(prevResult.seq2Range.start, cur.seq2Range.endExclusive - length2));
        continue;
      }
      cur = cur.delta(-d);
    }
    result2.push(cur);
  }
  const result22 = [];
  for (let i = 0; i < result2.length - 1; i++) {
    const nextResult = result2[i + 1];
    let cur = result2[i];
    if (cur.seq1Range.isEmpty || cur.seq2Range.isEmpty) {
      const length2 = nextResult.seq1Range.start - cur.seq1Range.endExclusive;
      let d;
      for (d = 0; d < length2; d++) {
        if (sequence1.getElement(cur.seq1Range.start + d) !== sequence1.getElement(cur.seq1Range.endExclusive + d) || sequence2.getElement(cur.seq2Range.start + d) !== sequence2.getElement(cur.seq2Range.endExclusive + d)) {
          break;
        }
      }
      if (d === length2) {
        result2[i + 1] = new SequenceDiff(new OffsetRange(cur.seq1Range.start + length2, nextResult.seq1Range.endExclusive), new OffsetRange(cur.seq2Range.start + length2, nextResult.seq2Range.endExclusive));
        continue;
      }
      if (d > 0) {
        cur = cur.delta(d);
      }
    }
    result22.push(cur);
  }
  if (result2.length > 0) {
    result22.push(result2[result2.length - 1]);
  }
  return result22;
}
function shiftSequenceDiffs(sequence1, sequence2, sequenceDiffs) {
  if (!sequence1.getBoundaryScore || !sequence2.getBoundaryScore) {
    return sequenceDiffs;
  }
  for (let i = 0; i < sequenceDiffs.length; i++) {
    const prevDiff = i > 0 ? sequenceDiffs[i - 1] : void 0;
    const diff = sequenceDiffs[i];
    const nextDiff = i + 1 < sequenceDiffs.length ? sequenceDiffs[i + 1] : void 0;
    const seq1ValidRange = new OffsetRange(prevDiff ? prevDiff.seq1Range.start + 1 : 0, nextDiff ? nextDiff.seq1Range.endExclusive - 1 : sequence1.length);
    const seq2ValidRange = new OffsetRange(prevDiff ? prevDiff.seq2Range.start + 1 : 0, nextDiff ? nextDiff.seq2Range.endExclusive - 1 : sequence2.length);
    if (diff.seq1Range.isEmpty) {
      sequenceDiffs[i] = shiftDiffToBetterPosition(diff, sequence1, sequence2, seq1ValidRange, seq2ValidRange);
    } else if (diff.seq2Range.isEmpty) {
      sequenceDiffs[i] = shiftDiffToBetterPosition(diff.reverse(), sequence2, sequence1, seq2ValidRange, seq1ValidRange).reverse();
    }
  }
  return sequenceDiffs;
}
function shiftDiffToBetterPosition(diff, sequence1, sequence2, seq1ValidRange, seq2ValidRange) {
  const maxShiftLimit = 100;
  let deltaBefore = 1;
  while (diff.seq1Range.start - deltaBefore >= seq1ValidRange.start && diff.seq2Range.start - deltaBefore >= seq2ValidRange.start && sequence2.getElement(diff.seq2Range.start - deltaBefore) === sequence2.getElement(diff.seq2Range.endExclusive - deltaBefore) && deltaBefore < maxShiftLimit) {
    deltaBefore++;
  }
  deltaBefore--;
  let deltaAfter = 0;
  while (diff.seq1Range.start + deltaAfter < seq1ValidRange.endExclusive && diff.seq2Range.endExclusive + deltaAfter < seq2ValidRange.endExclusive && sequence2.getElement(diff.seq2Range.start + deltaAfter) === sequence2.getElement(diff.seq2Range.endExclusive + deltaAfter) && deltaAfter < maxShiftLimit) {
    deltaAfter++;
  }
  if (deltaBefore === 0 && deltaAfter === 0) {
    return diff;
  }
  let bestDelta = 0;
  let bestScore = -1;
  for (let delta = -deltaBefore; delta <= deltaAfter; delta++) {
    const seq2OffsetStart = diff.seq2Range.start + delta;
    const seq2OffsetEndExclusive = diff.seq2Range.endExclusive + delta;
    const seq1Offset = diff.seq1Range.start + delta;
    const score2 = sequence1.getBoundaryScore(seq1Offset) + sequence2.getBoundaryScore(seq2OffsetStart) + sequence2.getBoundaryScore(seq2OffsetEndExclusive);
    if (score2 > bestScore) {
      bestScore = score2;
      bestDelta = delta;
    }
  }
  return diff.delta(bestDelta);
}
class MyersDiffAlgorithm {
  compute(seq1, seq2, timeout2 = InfiniteTimeout.instance) {
    if (seq1.length === 0 || seq2.length === 0) {
      return DiffAlgorithmResult.trivial(seq1, seq2);
    }
    function getXAfterSnake(x, y) {
      while (x < seq1.length && y < seq2.length && seq1.getElement(x) === seq2.getElement(y)) {
        x++;
        y++;
      }
      return x;
    }
    let d = 0;
    const V = new FastInt32Array();
    V.set(0, getXAfterSnake(0, 0));
    const paths = new FastArrayNegativeIndices();
    paths.set(0, V.get(0) === 0 ? null : new SnakePath(null, 0, 0, V.get(0)));
    let k = 0;
    loop:
      while (true) {
        d++;
        if (!timeout2.isValid()) {
          return DiffAlgorithmResult.trivialTimedOut(seq1, seq2);
        }
        const lowerBound = -Math.min(d, seq2.length + d % 2);
        const upperBound = Math.min(d, seq1.length + d % 2);
        for (k = lowerBound; k <= upperBound; k += 2) {
          const maxXofDLineTop = k === upperBound ? -1 : V.get(k + 1);
          const maxXofDLineLeft = k === lowerBound ? -1 : V.get(k - 1) + 1;
          const x = Math.min(Math.max(maxXofDLineTop, maxXofDLineLeft), seq1.length);
          const y = x - k;
          if (x > seq1.length || y > seq2.length) {
            continue;
          }
          const newMaxX = getXAfterSnake(x, y);
          V.set(k, newMaxX);
          const lastPath = x === maxXofDLineTop ? paths.get(k + 1) : paths.get(k - 1);
          paths.set(k, newMaxX !== x ? new SnakePath(lastPath, x, y, newMaxX - x) : lastPath);
          if (V.get(k) === seq1.length && V.get(k) - k === seq2.length) {
            break loop;
          }
        }
      }
    let path2 = paths.get(k);
    const result2 = [];
    let lastAligningPosS1 = seq1.length;
    let lastAligningPosS2 = seq2.length;
    while (true) {
      const endX = path2 ? path2.x + path2.length : 0;
      const endY = path2 ? path2.y + path2.length : 0;
      if (endX !== lastAligningPosS1 || endY !== lastAligningPosS2) {
        result2.push(new SequenceDiff(new OffsetRange(endX, lastAligningPosS1), new OffsetRange(endY, lastAligningPosS2)));
      }
      if (!path2) {
        break;
      }
      lastAligningPosS1 = path2.x;
      lastAligningPosS2 = path2.y;
      path2 = path2.prev;
    }
    result2.reverse();
    return new DiffAlgorithmResult(result2, false);
  }
}
class SnakePath {
  constructor(prev, x, y, length2) {
    this.prev = prev;
    this.x = x;
    this.y = y;
    this.length = length2;
  }
}
class FastInt32Array {
  constructor() {
    this.positiveArr = new Int32Array(10);
    this.negativeArr = new Int32Array(10);
  }
  get(idx) {
    if (idx < 0) {
      idx = -idx - 1;
      return this.negativeArr[idx];
    } else {
      return this.positiveArr[idx];
    }
  }
  set(idx, value) {
    if (idx < 0) {
      idx = -idx - 1;
      if (idx >= this.negativeArr.length) {
        const arr = this.negativeArr;
        this.negativeArr = new Int32Array(arr.length * 2);
        this.negativeArr.set(arr);
      }
      this.negativeArr[idx] = value;
    } else {
      if (idx >= this.positiveArr.length) {
        const arr = this.positiveArr;
        this.positiveArr = new Int32Array(arr.length * 2);
        this.positiveArr.set(arr);
      }
      this.positiveArr[idx] = value;
    }
  }
}
class FastArrayNegativeIndices {
  constructor() {
    this.positiveArr = [];
    this.negativeArr = [];
  }
  get(idx) {
    if (idx < 0) {
      idx = -idx - 1;
      return this.negativeArr[idx];
    } else {
      return this.positiveArr[idx];
    }
  }
  set(idx, value) {
    if (idx < 0) {
      idx = -idx - 1;
      this.negativeArr[idx] = value;
    } else {
      this.positiveArr[idx] = value;
    }
  }
}
class StandardLinesDiffComputer {
  constructor() {
    this.dynamicProgrammingDiffing = new DynamicProgrammingDiffing();
    this.myersDiffingAlgorithm = new MyersDiffAlgorithm();
  }
  computeDiff(originalLines, modifiedLines, options) {
    if (originalLines.length === 1 && originalLines[0].length === 0 || modifiedLines.length === 1 && modifiedLines[0].length === 0) {
      return {
        changes: [
          new LineRangeMapping(new LineRange2(1, originalLines.length + 1), new LineRange2(1, modifiedLines.length + 1), [
            new RangeMapping(new Range$2(1, 1, originalLines.length, originalLines[0].length + 1), new Range$2(1, 1, modifiedLines.length, modifiedLines[0].length + 1))
          ])
        ],
        hitTimeout: false,
        moves: []
      };
    }
    const timeout2 = options.maxComputationTimeMs === 0 ? InfiniteTimeout.instance : new DateTimeout(options.maxComputationTimeMs);
    const considerWhitespaceChanges = !options.ignoreTrimWhitespace;
    const perfectHashes = /* @__PURE__ */ new Map();
    function getOrCreateHash(text2) {
      let hash2 = perfectHashes.get(text2);
      if (hash2 === void 0) {
        hash2 = perfectHashes.size;
        perfectHashes.set(text2, hash2);
      }
      return hash2;
    }
    const srcDocLines = originalLines.map((l) => getOrCreateHash(l.trim()));
    const tgtDocLines = modifiedLines.map((l) => getOrCreateHash(l.trim()));
    const sequence1 = new LineSequence2(srcDocLines, originalLines);
    const sequence2 = new LineSequence2(tgtDocLines, modifiedLines);
    const lineAlignmentResult = (() => {
      if (sequence1.length + sequence2.length < 1500) {
        return this.dynamicProgrammingDiffing.compute(sequence1, sequence2, timeout2, (offset1, offset2) => originalLines[offset1] === modifiedLines[offset2] ? modifiedLines[offset2].length === 0 ? 0.1 : 1 + Math.log(1 + modifiedLines[offset2].length) : 0.99);
      }
      return this.myersDiffingAlgorithm.compute(sequence1, sequence2);
    })();
    let lineAlignments = lineAlignmentResult.diffs;
    let hitTimeout = lineAlignmentResult.hitTimeout;
    lineAlignments = optimizeSequenceDiffs(sequence1, sequence2, lineAlignments);
    const alignments = [];
    const scanForWhitespaceChanges = (equalLinesCount) => {
      if (!considerWhitespaceChanges) {
        return;
      }
      for (let i = 0; i < equalLinesCount; i++) {
        const seq1Offset = seq1LastStart + i;
        const seq2Offset = seq2LastStart + i;
        if (originalLines[seq1Offset] !== modifiedLines[seq2Offset]) {
          const characterDiffs = this.refineDiff(originalLines, modifiedLines, new SequenceDiff(new OffsetRange(seq1Offset, seq1Offset + 1), new OffsetRange(seq2Offset, seq2Offset + 1)), timeout2, considerWhitespaceChanges);
          for (const a of characterDiffs.mappings) {
            alignments.push(a);
          }
          if (characterDiffs.hitTimeout) {
            hitTimeout = true;
          }
        }
      }
    };
    let seq1LastStart = 0;
    let seq2LastStart = 0;
    for (const diff of lineAlignments) {
      assertFn(() => diff.seq1Range.start - seq1LastStart === diff.seq2Range.start - seq2LastStart);
      const equalLinesCount = diff.seq1Range.start - seq1LastStart;
      scanForWhitespaceChanges(equalLinesCount);
      seq1LastStart = diff.seq1Range.endExclusive;
      seq2LastStart = diff.seq2Range.endExclusive;
      const characterDiffs = this.refineDiff(originalLines, modifiedLines, diff, timeout2, considerWhitespaceChanges);
      if (characterDiffs.hitTimeout) {
        hitTimeout = true;
      }
      for (const a of characterDiffs.mappings) {
        alignments.push(a);
      }
    }
    scanForWhitespaceChanges(originalLines.length - seq1LastStart);
    const changes = lineRangeMappingFromRangeMappings(alignments, originalLines, modifiedLines);
    const moves = [];
    if (options.computeMoves) {
      const deletions = changes.filter((c) => c.modifiedRange.isEmpty && c.originalRange.length >= 3).map((d) => new LineRangeFragment(d.originalRange, originalLines));
      const insertions = new Set(changes.filter((c) => c.originalRange.isEmpty && c.modifiedRange.length >= 3).map((d) => new LineRangeFragment(d.modifiedRange, modifiedLines)));
      for (const deletion of deletions) {
        let highestSimilarity = -1;
        let best;
        for (const insertion of insertions) {
          const similarity = deletion.computeSimilarity(insertion);
          if (similarity > highestSimilarity) {
            highestSimilarity = similarity;
            best = insertion;
          }
        }
        if (highestSimilarity > 0.9 && best) {
          const moveChanges = this.refineDiff(originalLines, modifiedLines, new SequenceDiff(new OffsetRange(deletion.range.startLineNumber - 1, deletion.range.endLineNumberExclusive - 1), new OffsetRange(best.range.startLineNumber - 1, best.range.endLineNumberExclusive - 1)), timeout2, considerWhitespaceChanges);
          const mappings = lineRangeMappingFromRangeMappings(moveChanges.mappings, originalLines, modifiedLines, true);
          insertions.delete(best);
          moves.push(new MovedText(new SimpleLineRangeMapping(deletion.range, best.range), mappings));
        }
      }
    }
    assertFn(() => {
      function validatePosition(pos, lines) {
        if (pos.lineNumber < 1 || pos.lineNumber > lines.length) {
          return false;
        }
        const line = lines[pos.lineNumber - 1];
        if (pos.column < 1 || pos.column > line.length + 1) {
          return false;
        }
        return true;
      }
      function validateRange(range2, lines) {
        if (range2.startLineNumber < 1 || range2.startLineNumber > lines.length + 1) {
          return false;
        }
        if (range2.endLineNumberExclusive < 1 || range2.endLineNumberExclusive > lines.length + 1) {
          return false;
        }
        return true;
      }
      for (const c of changes) {
        if (!c.innerChanges) {
          return false;
        }
        for (const ic of c.innerChanges) {
          const valid = validatePosition(ic.modifiedRange.getStartPosition(), modifiedLines) && validatePosition(ic.modifiedRange.getEndPosition(), modifiedLines) && validatePosition(ic.originalRange.getStartPosition(), originalLines) && validatePosition(ic.originalRange.getEndPosition(), originalLines);
          if (!valid) {
            return false;
          }
        }
        if (!validateRange(c.modifiedRange, modifiedLines) || !validateRange(c.originalRange, originalLines)) {
          return false;
        }
      }
      return true;
    });
    return new LinesDiff(changes, moves, hitTimeout);
  }
  refineDiff(originalLines, modifiedLines, diff, timeout2, considerWhitespaceChanges) {
    const slice1 = new LinesSliceCharSequence(originalLines, diff.seq1Range, considerWhitespaceChanges);
    const slice2 = new LinesSliceCharSequence(modifiedLines, diff.seq2Range, considerWhitespaceChanges);
    const diffResult = slice1.length + slice2.length < 500 ? this.dynamicProgrammingDiffing.compute(slice1, slice2, timeout2) : this.myersDiffingAlgorithm.compute(slice1, slice2, timeout2);
    let diffs = diffResult.diffs;
    diffs = optimizeSequenceDiffs(slice1, slice2, diffs);
    diffs = coverFullWords(slice1, slice2, diffs);
    diffs = smoothenSequenceDiffs(slice1, slice2, diffs);
    diffs = removeRandomMatches(slice1, slice2, diffs);
    const result2 = diffs.map((d) => new RangeMapping(slice1.translateRange(d.seq1Range), slice2.translateRange(d.seq2Range)));
    return {
      mappings: result2,
      hitTimeout: diffResult.hitTimeout
    };
  }
}
function coverFullWords(sequence1, sequence2, sequenceDiffs) {
  const additional = [];
  let lastModifiedWord = void 0;
  function maybePushWordToAdditional() {
    if (!lastModifiedWord) {
      return;
    }
    const originalLength1 = lastModifiedWord.s1Range.length - lastModifiedWord.deleted;
    lastModifiedWord.s2Range.length - lastModifiedWord.added;
    if (Math.max(lastModifiedWord.deleted, lastModifiedWord.added) + (lastModifiedWord.count - 1) > originalLength1) {
      additional.push(new SequenceDiff(lastModifiedWord.s1Range, lastModifiedWord.s2Range));
    }
    lastModifiedWord = void 0;
  }
  for (const s of sequenceDiffs) {
    let processWord = function(s1Range, s2Range) {
      var _a2, _b2, _c2, _d2;
      if (!lastModifiedWord || !lastModifiedWord.s1Range.containsRange(s1Range) || !lastModifiedWord.s2Range.containsRange(s2Range)) {
        if (lastModifiedWord && !(lastModifiedWord.s1Range.endExclusive < s1Range.start && lastModifiedWord.s2Range.endExclusive < s2Range.start)) {
          const s1Added = OffsetRange.tryCreate(lastModifiedWord.s1Range.endExclusive, s1Range.start);
          const s2Added = OffsetRange.tryCreate(lastModifiedWord.s2Range.endExclusive, s2Range.start);
          lastModifiedWord.deleted += (_a2 = s1Added === null || s1Added === void 0 ? void 0 : s1Added.length) !== null && _a2 !== void 0 ? _a2 : 0;
          lastModifiedWord.added += (_b2 = s2Added === null || s2Added === void 0 ? void 0 : s2Added.length) !== null && _b2 !== void 0 ? _b2 : 0;
          lastModifiedWord.s1Range = lastModifiedWord.s1Range.join(s1Range);
          lastModifiedWord.s2Range = lastModifiedWord.s2Range.join(s2Range);
        } else {
          maybePushWordToAdditional();
          lastModifiedWord = { added: 0, deleted: 0, count: 0, s1Range, s2Range };
        }
      }
      const changedS1 = s1Range.intersect(s.seq1Range);
      const changedS2 = s2Range.intersect(s.seq2Range);
      lastModifiedWord.count++;
      lastModifiedWord.deleted += (_c2 = changedS1 === null || changedS1 === void 0 ? void 0 : changedS1.length) !== null && _c2 !== void 0 ? _c2 : 0;
      lastModifiedWord.added += (_d2 = changedS2 === null || changedS2 === void 0 ? void 0 : changedS2.length) !== null && _d2 !== void 0 ? _d2 : 0;
    };
    const w1Before = sequence1.findWordContaining(s.seq1Range.start - 1);
    const w2Before = sequence2.findWordContaining(s.seq2Range.start - 1);
    const w1After = sequence1.findWordContaining(s.seq1Range.endExclusive);
    const w2After = sequence2.findWordContaining(s.seq2Range.endExclusive);
    if (w1Before && w1After && w2Before && w2After && w1Before.equals(w1After) && w2Before.equals(w2After)) {
      processWord(w1Before, w2Before);
    } else {
      if (w1Before && w2Before) {
        processWord(w1Before, w2Before);
      }
      if (w1After && w2After) {
        processWord(w1After, w2After);
      }
    }
  }
  maybePushWordToAdditional();
  const merged = mergeSequenceDiffs(sequenceDiffs, additional);
  return merged;
}
function mergeSequenceDiffs(sequenceDiffs1, sequenceDiffs2) {
  const result2 = [];
  while (sequenceDiffs1.length > 0 || sequenceDiffs2.length > 0) {
    const sd1 = sequenceDiffs1[0];
    const sd2 = sequenceDiffs2[0];
    let next;
    if (sd1 && (!sd2 || sd1.seq1Range.start < sd2.seq1Range.start)) {
      next = sequenceDiffs1.shift();
    } else {
      next = sequenceDiffs2.shift();
    }
    if (result2.length > 0 && result2[result2.length - 1].seq1Range.endExclusive >= next.seq1Range.start) {
      result2[result2.length - 1] = result2[result2.length - 1].join(next);
    } else {
      result2.push(next);
    }
  }
  return result2;
}
function lineRangeMappingFromRangeMappings(alignments, originalLines, modifiedLines, dontAssertStartLine = false) {
  const changes = [];
  for (const g of group$1(alignments.map((a) => getLineRangeMapping(a, originalLines, modifiedLines)), (a1, a2) => a1.originalRange.overlapOrTouch(a2.originalRange) || a1.modifiedRange.overlapOrTouch(a2.modifiedRange))) {
    const first2 = g[0];
    const last2 = g[g.length - 1];
    changes.push(new LineRangeMapping(first2.originalRange.join(last2.originalRange), first2.modifiedRange.join(last2.modifiedRange), g.map((a) => a.innerChanges[0])));
  }
  assertFn(() => {
    if (!dontAssertStartLine) {
      if (changes.length > 0 && changes[0].originalRange.startLineNumber !== changes[0].modifiedRange.startLineNumber) {
        return false;
      }
    }
    return checkAdjacentItems(changes, (m1, m2) => m2.originalRange.startLineNumber - m1.originalRange.endLineNumberExclusive === m2.modifiedRange.startLineNumber - m1.modifiedRange.endLineNumberExclusive && // There has to be an unchanged line in between (otherwise both diffs should have been joined)
    m1.originalRange.endLineNumberExclusive < m2.originalRange.startLineNumber && m1.modifiedRange.endLineNumberExclusive < m2.modifiedRange.startLineNumber);
  });
  return changes;
}
function getLineRangeMapping(rangeMapping, originalLines, modifiedLines) {
  let lineStartDelta = 0;
  let lineEndDelta = 0;
  if (rangeMapping.modifiedRange.endColumn === 1 && rangeMapping.originalRange.endColumn === 1 && rangeMapping.originalRange.startLineNumber + lineStartDelta <= rangeMapping.originalRange.endLineNumber && rangeMapping.modifiedRange.startLineNumber + lineStartDelta <= rangeMapping.modifiedRange.endLineNumber) {
    lineEndDelta = -1;
  }
  if (rangeMapping.modifiedRange.startColumn - 1 >= modifiedLines[rangeMapping.modifiedRange.startLineNumber - 1].length && rangeMapping.originalRange.startColumn - 1 >= originalLines[rangeMapping.originalRange.startLineNumber - 1].length && rangeMapping.originalRange.startLineNumber <= rangeMapping.originalRange.endLineNumber + lineEndDelta && rangeMapping.modifiedRange.startLineNumber <= rangeMapping.modifiedRange.endLineNumber + lineEndDelta) {
    lineStartDelta = 1;
  }
  const originalLineRange = new LineRange2(rangeMapping.originalRange.startLineNumber + lineStartDelta, rangeMapping.originalRange.endLineNumber + 1 + lineEndDelta);
  const modifiedLineRange = new LineRange2(rangeMapping.modifiedRange.startLineNumber + lineStartDelta, rangeMapping.modifiedRange.endLineNumber + 1 + lineEndDelta);
  return new LineRangeMapping(originalLineRange, modifiedLineRange, [rangeMapping]);
}
function* group$1(items, shouldBeGrouped) {
  let currentGroup;
  let last2;
  for (const item of items) {
    if (last2 !== void 0 && shouldBeGrouped(last2, item)) {
      currentGroup.push(item);
    } else {
      if (currentGroup) {
        yield currentGroup;
      }
      currentGroup = [item];
    }
    last2 = item;
  }
  if (currentGroup) {
    yield currentGroup;
  }
}
class LineSequence2 {
  constructor(trimmedHash, lines) {
    this.trimmedHash = trimmedHash;
    this.lines = lines;
  }
  getElement(offset) {
    return this.trimmedHash[offset];
  }
  get length() {
    return this.trimmedHash.length;
  }
  getBoundaryScore(length2) {
    const indentationBefore = length2 === 0 ? 0 : getIndentation(this.lines[length2 - 1]);
    const indentationAfter = length2 === this.lines.length ? 0 : getIndentation(this.lines[length2]);
    return 1e3 - (indentationBefore + indentationAfter);
  }
}
function getIndentation(str2) {
  let i = 0;
  while (i < str2.length && (str2.charCodeAt(i) === 32 || str2.charCodeAt(i) === 9)) {
    i++;
  }
  return i;
}
class LinesSliceCharSequence {
  constructor(lines, lineRange, considerWhitespaceChanges) {
    this.lines = lines;
    this.considerWhitespaceChanges = considerWhitespaceChanges;
    this.elements = [];
    this.firstCharOffsetByLineMinusOne = [];
    this.offsetByLine = [];
    let trimFirstLineFully = false;
    if (lineRange.start > 0 && lineRange.endExclusive >= lines.length) {
      lineRange = new OffsetRange(lineRange.start - 1, lineRange.endExclusive);
      trimFirstLineFully = true;
    }
    this.lineRange = lineRange;
    for (let i = this.lineRange.start; i < this.lineRange.endExclusive; i++) {
      let line = lines[i];
      let offset = 0;
      if (trimFirstLineFully) {
        offset = line.length;
        line = "";
        trimFirstLineFully = false;
      } else if (!considerWhitespaceChanges) {
        const trimmedStartLine = line.trimStart();
        offset = line.length - trimmedStartLine.length;
        line = trimmedStartLine.trimEnd();
      }
      this.offsetByLine.push(offset);
      for (let i2 = 0; i2 < line.length; i2++) {
        this.elements.push(line.charCodeAt(i2));
      }
      if (i < lines.length - 1) {
        this.elements.push("\n".charCodeAt(0));
        this.firstCharOffsetByLineMinusOne[i - this.lineRange.start] = this.elements.length;
      }
    }
    this.offsetByLine.push(0);
  }
  toString() {
    return `Slice: "${this.text}"`;
  }
  get text() {
    return this.getText(new OffsetRange(0, this.length));
  }
  getText(range2) {
    return this.elements.slice(range2.start, range2.endExclusive).map((e) => String.fromCharCode(e)).join("");
  }
  getElement(offset) {
    return this.elements[offset];
  }
  get length() {
    return this.elements.length;
  }
  getBoundaryScore(length2) {
    const prevCategory = getCategory(length2 > 0 ? this.elements[length2 - 1] : -1);
    const nextCategory = getCategory(length2 < this.elements.length ? this.elements[length2] : -1);
    if (prevCategory === 6 && nextCategory === 7) {
      return 0;
    }
    let score2 = 0;
    if (prevCategory !== nextCategory) {
      score2 += 10;
      if (nextCategory === 1) {
        score2 += 1;
      }
    }
    score2 += getCategoryBoundaryScore(prevCategory);
    score2 += getCategoryBoundaryScore(nextCategory);
    return score2;
  }
  translateOffset(offset) {
    if (this.lineRange.isEmpty) {
      return new Position$2(this.lineRange.start + 1, 1);
    }
    let i = 0;
    let j = this.firstCharOffsetByLineMinusOne.length;
    while (i < j) {
      const k = Math.floor((i + j) / 2);
      if (this.firstCharOffsetByLineMinusOne[k] > offset) {
        j = k;
      } else {
        i = k + 1;
      }
    }
    const offsetOfFirstCharInLine = i === 0 ? 0 : this.firstCharOffsetByLineMinusOne[i - 1];
    return new Position$2(this.lineRange.start + i + 1, offset - offsetOfFirstCharInLine + 1 + this.offsetByLine[i]);
  }
  translateRange(range2) {
    return Range$2.fromPositions(this.translateOffset(range2.start), this.translateOffset(range2.endExclusive));
  }
  /**
   * Finds the word that contains the character at the given offset
   */
  findWordContaining(offset) {
    if (offset < 0 || offset >= this.elements.length) {
      return void 0;
    }
    if (!isWordChar(this.elements[offset])) {
      return void 0;
    }
    let start = offset;
    while (start > 0 && isWordChar(this.elements[start - 1])) {
      start--;
    }
    let end = offset;
    while (end < this.elements.length && isWordChar(this.elements[end])) {
      end++;
    }
    return new OffsetRange(start, end);
  }
  countLinesIn(range2) {
    return this.translateOffset(range2.endExclusive).lineNumber - this.translateOffset(range2.start).lineNumber;
  }
}
function isWordChar(charCode) {
  return charCode >= 97 && charCode <= 122 || charCode >= 65 && charCode <= 90 || charCode >= 48 && charCode <= 57;
}
const score$1 = {
  [
    0
    /* CharBoundaryCategory.WordLower */
  ]: 0,
  [
    1
    /* CharBoundaryCategory.WordUpper */
  ]: 0,
  [
    2
    /* CharBoundaryCategory.WordNumber */
  ]: 0,
  [
    3
    /* CharBoundaryCategory.End */
  ]: 10,
  [
    4
    /* CharBoundaryCategory.Other */
  ]: 2,
  [
    5
    /* CharBoundaryCategory.Space */
  ]: 3,
  [
    6
    /* CharBoundaryCategory.LineBreakCR */
  ]: 10,
  [
    7
    /* CharBoundaryCategory.LineBreakLF */
  ]: 10
};
function getCategoryBoundaryScore(category) {
  return score$1[category];
}
function getCategory(charCode) {
  if (charCode === 10) {
    return 7;
  } else if (charCode === 13) {
    return 6;
  } else if (isSpace(charCode)) {
    return 5;
  } else if (charCode >= 97 && charCode <= 122) {
    return 0;
  } else if (charCode >= 65 && charCode <= 90) {
    return 1;
  } else if (charCode >= 48 && charCode <= 57) {
    return 2;
  } else if (charCode === -1) {
    return 3;
  } else {
    return 4;
  }
}
function isSpace(charCode) {
  return charCode === 32 || charCode === 9;
}
const chrKeys = /* @__PURE__ */ new Map();
function getKey(chr) {
  let key = chrKeys.get(chr);
  if (key === void 0) {
    key = chrKeys.size;
    chrKeys.set(chr, key);
  }
  return key;
}
class LineRangeFragment {
  constructor(range2, lines) {
    this.range = range2;
    this.lines = lines;
    this.histogram = [];
    let counter = 0;
    for (let i = range2.startLineNumber - 1; i < range2.endLineNumberExclusive - 1; i++) {
      const line = lines[i];
      for (let j = 0; j < line.length; j++) {
        counter++;
        const chr = line[j];
        const key2 = getKey(chr);
        this.histogram[key2] = (this.histogram[key2] || 0) + 1;
      }
      counter++;
      const key = getKey("\n");
      this.histogram[key] = (this.histogram[key] || 0) + 1;
    }
    this.totalCount = counter;
  }
  computeSimilarity(other) {
    var _a2, _b2;
    let sumDifferences = 0;
    const maxLength = Math.max(this.histogram.length, other.histogram.length);
    for (let i = 0; i < maxLength; i++) {
      sumDifferences += Math.abs(((_a2 = this.histogram[i]) !== null && _a2 !== void 0 ? _a2 : 0) - ((_b2 = other.histogram[i]) !== null && _b2 !== void 0 ? _b2 : 0));
    }
    return 1 - sumDifferences / (this.totalCount + other.totalCount);
  }
}
const linesDiffComputers = {
  getLegacy: () => new SmartLinesDiffComputer(),
  getAdvanced: () => new StandardLinesDiffComputer()
};
function _parseCaptureGroups(captureGroups) {
  const values = [];
  for (const captureGroup of captureGroups) {
    const parsedNumber = Number(captureGroup);
    if (parsedNumber || parsedNumber === 0 && captureGroup.replace(/\s/g, "") !== "") {
      values.push(parsedNumber);
    }
  }
  return values;
}
function _toIColor(r, g, b, a) {
  return {
    red: r / 255,
    blue: b / 255,
    green: g / 255,
    alpha: a
  };
}
function _findRange(model, match2) {
  const index = match2.index;
  const length2 = match2[0].length;
  if (!index) {
    return;
  }
  const startPosition = model.positionAt(index);
  const range2 = {
    startLineNumber: startPosition.lineNumber,
    startColumn: startPosition.column,
    endLineNumber: startPosition.lineNumber,
    endColumn: startPosition.column + length2
  };
  return range2;
}
function _findHexColorInformation(range2, hexValue) {
  if (!range2) {
    return;
  }
  const parsedHexColor = Color.Format.CSS.parseHex(hexValue);
  if (!parsedHexColor) {
    return;
  }
  return {
    range: range2,
    color: _toIColor(parsedHexColor.rgba.r, parsedHexColor.rgba.g, parsedHexColor.rgba.b, parsedHexColor.rgba.a)
  };
}
function _findRGBColorInformation(range2, matches, isAlpha) {
  if (!range2 || matches.length !== 1) {
    return;
  }
  const match2 = matches[0];
  const captureGroups = match2.values();
  const parsedRegex = _parseCaptureGroups(captureGroups);
  return {
    range: range2,
    color: _toIColor(parsedRegex[0], parsedRegex[1], parsedRegex[2], isAlpha ? parsedRegex[3] : 1)
  };
}
function _findHSLColorInformation(range2, matches, isAlpha) {
  if (!range2 || matches.length !== 1) {
    return;
  }
  const match2 = matches[0];
  const captureGroups = match2.values();
  const parsedRegex = _parseCaptureGroups(captureGroups);
  const colorEquivalent = new Color(new HSLA(parsedRegex[0], parsedRegex[1] / 100, parsedRegex[2] / 100, isAlpha ? parsedRegex[3] : 1));
  return {
    range: range2,
    color: _toIColor(colorEquivalent.rgba.r, colorEquivalent.rgba.g, colorEquivalent.rgba.b, colorEquivalent.rgba.a)
  };
}
function _findMatches(model, regex) {
  if (typeof model === "string") {
    return [...model.matchAll(regex)];
  } else {
    return model.findMatches(regex);
  }
}
function computeColors(model) {
  const result2 = [];
  const initialValidationRegex = /\b(rgb|rgba|hsl|hsla)(\([0-9\s,.\%]*\))|(#)([A-Fa-f0-9]{3})\b|(#)([A-Fa-f0-9]{4})\b|(#)([A-Fa-f0-9]{6})\b|(#)([A-Fa-f0-9]{8})\b/gm;
  const initialValidationMatches = _findMatches(model, initialValidationRegex);
  if (initialValidationMatches.length > 0) {
    for (const initialMatch of initialValidationMatches) {
      const initialCaptureGroups = initialMatch.filter((captureGroup) => captureGroup !== void 0);
      const colorScheme = initialCaptureGroups[1];
      const colorParameters = initialCaptureGroups[2];
      if (!colorParameters) {
        continue;
      }
      let colorInformation;
      if (colorScheme === "rgb") {
        const regexParameters = /^\(\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*,\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*,\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*\)$/gm;
        colorInformation = _findRGBColorInformation(_findRange(model, initialMatch), _findMatches(colorParameters, regexParameters), false);
      } else if (colorScheme === "rgba") {
        const regexParameters = /^\(\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*,\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*,\s*(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\s*,\s*(0[.][0-9]+|[.][0-9]+|[01][.]|[01])\s*\)$/gm;
        colorInformation = _findRGBColorInformation(_findRange(model, initialMatch), _findMatches(colorParameters, regexParameters), true);
      } else if (colorScheme === "hsl") {
        const regexParameters = /^\(\s*(36[0]|3[0-5][0-9]|[12][0-9][0-9]|[1-9]?[0-9])\s*,\s*(100|\d{1,2}[.]\d*|\d{1,2})%\s*,\s*(100|\d{1,2}[.]\d*|\d{1,2})%\s*\)$/gm;
        colorInformation = _findHSLColorInformation(_findRange(model, initialMatch), _findMatches(colorParameters, regexParameters), false);
      } else if (colorScheme === "hsla") {
        const regexParameters = /^\(\s*(36[0]|3[0-5][0-9]|[12][0-9][0-9]|[1-9]?[0-9])\s*,\s*(100|\d{1,2}[.]\d*|\d{1,2})%\s*,\s*(100|\d{1,2}[.]\d*|\d{1,2})%\s*,\s*(0[.][0-9]+|[.][0-9]+|[01][.]|[01])\s*\)$/gm;
        colorInformation = _findHSLColorInformation(_findRange(model, initialMatch), _findMatches(colorParameters, regexParameters), true);
      } else if (colorScheme === "#") {
        colorInformation = _findHexColorInformation(_findRange(model, initialMatch), colorScheme + colorParameters);
      }
      if (colorInformation) {
        result2.push(colorInformation);
      }
    }
  }
  return result2;
}
function computeDefaultDocumentColors(model) {
  if (!model || typeof model.getValue !== "function" || typeof model.positionAt !== "function") {
    return [];
  }
  return computeColors(model);
}
var __awaiter$1f = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class MirrorModel extends MirrorTextModel {
  get uri() {
    return this._uri;
  }
  get eol() {
    return this._eol;
  }
  getValue() {
    return this.getText();
  }
  findMatches(regex) {
    const matches = [];
    for (let i = 0; i < this._lines.length; i++) {
      const line = this._lines[i];
      const offsetToAdd = this.offsetAt(new Position$2(i + 1, 1));
      const iteratorOverMatches = line.matchAll(regex);
      for (const match2 of iteratorOverMatches) {
        if (match2.index || match2.index === 0) {
          match2.index = match2.index + offsetToAdd;
        }
        matches.push(match2);
      }
    }
    return matches;
  }
  getLinesContent() {
    return this._lines.slice(0);
  }
  getLineCount() {
    return this._lines.length;
  }
  getLineContent(lineNumber) {
    return this._lines[lineNumber - 1];
  }
  getWordAtPosition(position, wordDefinition) {
    const wordAtText = getWordAtText(position.column, ensureValidWordDefinition(wordDefinition), this._lines[position.lineNumber - 1], 0);
    if (wordAtText) {
      return new Range$2(position.lineNumber, wordAtText.startColumn, position.lineNumber, wordAtText.endColumn);
    }
    return null;
  }
  words(wordDefinition) {
    const lines = this._lines;
    const wordenize = this._wordenize.bind(this);
    let lineNumber = 0;
    let lineText = "";
    let wordRangesIdx = 0;
    let wordRanges = [];
    return {
      *[Symbol.iterator]() {
        while (true) {
          if (wordRangesIdx < wordRanges.length) {
            const value = lineText.substring(wordRanges[wordRangesIdx].start, wordRanges[wordRangesIdx].end);
            wordRangesIdx += 1;
            yield value;
          } else {
            if (lineNumber < lines.length) {
              lineText = lines[lineNumber];
              wordRanges = wordenize(lineText, wordDefinition);
              wordRangesIdx = 0;
              lineNumber += 1;
            } else {
              break;
            }
          }
        }
      }
    };
  }
  getLineWords(lineNumber, wordDefinition) {
    const content = this._lines[lineNumber - 1];
    const ranges = this._wordenize(content, wordDefinition);
    const words = [];
    for (const range2 of ranges) {
      words.push({
        word: content.substring(range2.start, range2.end),
        startColumn: range2.start + 1,
        endColumn: range2.end + 1
      });
    }
    return words;
  }
  _wordenize(content, wordDefinition) {
    const result2 = [];
    let match2;
    wordDefinition.lastIndex = 0;
    while (match2 = wordDefinition.exec(content)) {
      if (match2[0].length === 0) {
        break;
      }
      result2.push({ start: match2.index, end: match2.index + match2[0].length });
    }
    return result2;
  }
  getValueInRange(range2) {
    range2 = this._validateRange(range2);
    if (range2.startLineNumber === range2.endLineNumber) {
      return this._lines[range2.startLineNumber - 1].substring(range2.startColumn - 1, range2.endColumn - 1);
    }
    const lineEnding = this._eol;
    const startLineIndex = range2.startLineNumber - 1;
    const endLineIndex = range2.endLineNumber - 1;
    const resultLines = [];
    resultLines.push(this._lines[startLineIndex].substring(range2.startColumn - 1));
    for (let i = startLineIndex + 1; i < endLineIndex; i++) {
      resultLines.push(this._lines[i]);
    }
    resultLines.push(this._lines[endLineIndex].substring(0, range2.endColumn - 1));
    return resultLines.join(lineEnding);
  }
  offsetAt(position) {
    position = this._validatePosition(position);
    this._ensureLineStarts();
    return this._lineStarts.getPrefixSum(position.lineNumber - 2) + (position.column - 1);
  }
  positionAt(offset) {
    offset = Math.floor(offset);
    offset = Math.max(0, offset);
    this._ensureLineStarts();
    const out = this._lineStarts.getIndexOf(offset);
    const lineLength = this._lines[out.index].length;
    return {
      lineNumber: 1 + out.index,
      column: 1 + Math.min(out.remainder, lineLength)
    };
  }
  _validateRange(range2) {
    const start = this._validatePosition({ lineNumber: range2.startLineNumber, column: range2.startColumn });
    const end = this._validatePosition({ lineNumber: range2.endLineNumber, column: range2.endColumn });
    if (start.lineNumber !== range2.startLineNumber || start.column !== range2.startColumn || end.lineNumber !== range2.endLineNumber || end.column !== range2.endColumn) {
      return {
        startLineNumber: start.lineNumber,
        startColumn: start.column,
        endLineNumber: end.lineNumber,
        endColumn: end.column
      };
    }
    return range2;
  }
  _validatePosition(position) {
    if (!Position$2.isIPosition(position)) {
      throw new Error("bad position");
    }
    let { lineNumber, column } = position;
    let hasChanged2 = false;
    if (lineNumber < 1) {
      lineNumber = 1;
      column = 1;
      hasChanged2 = true;
    } else if (lineNumber > this._lines.length) {
      lineNumber = this._lines.length;
      column = this._lines[lineNumber - 1].length + 1;
      hasChanged2 = true;
    } else {
      const maxCharacter = this._lines[lineNumber - 1].length + 1;
      if (column < 1) {
        column = 1;
        hasChanged2 = true;
      } else if (column > maxCharacter) {
        column = maxCharacter;
        hasChanged2 = true;
      }
    }
    if (!hasChanged2) {
      return position;
    } else {
      return { lineNumber, column };
    }
  }
}
class EditorSimpleWorker {
  constructor(host, foreignModuleFactory) {
    this._host = host;
    this._models = /* @__PURE__ */ Object.create(null);
    this._foreignModuleFactory = foreignModuleFactory;
    this._foreignModule = null;
  }
  dispose() {
    this._models = /* @__PURE__ */ Object.create(null);
  }
  _getModel(uri) {
    return this._models[uri];
  }
  _getModels() {
    const all = [];
    Object.keys(this._models).forEach((key) => all.push(this._models[key]));
    return all;
  }
  acceptNewModel(data) {
    this._models[data.url] = new MirrorModel(URI.parse(data.url), data.lines, data.EOL, data.versionId);
  }
  acceptModelChanged(strURL, e) {
    if (!this._models[strURL]) {
      return;
    }
    const model = this._models[strURL];
    model.onEvents(e);
  }
  acceptRemovedModel(strURL) {
    if (!this._models[strURL]) {
      return;
    }
    delete this._models[strURL];
  }
  computeUnicodeHighlights(url, options, range2) {
    return __awaiter$1f(this, void 0, void 0, function* () {
      const model = this._getModel(url);
      if (!model) {
        return { ranges: [], hasMore: false, ambiguousCharacterCount: 0, invisibleCharacterCount: 0, nonBasicAsciiCharacterCount: 0 };
      }
      return UnicodeTextModelHighlighter.computeUnicodeHighlights(model, options, range2);
    });
  }
  // ---- BEGIN diff --------------------------------------------------------------------------
  computeDiff(originalUrl, modifiedUrl, options, algorithm) {
    return __awaiter$1f(this, void 0, void 0, function* () {
      const original = this._getModel(originalUrl);
      const modified = this._getModel(modifiedUrl);
      if (!original || !modified) {
        return null;
      }
      return EditorSimpleWorker.computeDiff(original, modified, options, algorithm);
    });
  }
  static computeDiff(originalTextModel, modifiedTextModel, options, algorithm) {
    const diffAlgorithm = algorithm === "advanced" ? linesDiffComputers.getAdvanced() : linesDiffComputers.getLegacy();
    const originalLines = originalTextModel.getLinesContent();
    const modifiedLines = modifiedTextModel.getLinesContent();
    const result2 = diffAlgorithm.computeDiff(originalLines, modifiedLines, options);
    const identical = result2.changes.length > 0 ? false : this._modelsAreIdentical(originalTextModel, modifiedTextModel);
    function getLineChanges(changes) {
      return changes.map((m) => {
        var _a2;
        return [m.originalRange.startLineNumber, m.originalRange.endLineNumberExclusive, m.modifiedRange.startLineNumber, m.modifiedRange.endLineNumberExclusive, (_a2 = m.innerChanges) === null || _a2 === void 0 ? void 0 : _a2.map((m2) => [
          m2.originalRange.startLineNumber,
          m2.originalRange.startColumn,
          m2.originalRange.endLineNumber,
          m2.originalRange.endColumn,
          m2.modifiedRange.startLineNumber,
          m2.modifiedRange.startColumn,
          m2.modifiedRange.endLineNumber,
          m2.modifiedRange.endColumn
        ])];
      });
    }
    return {
      identical,
      quitEarly: result2.hitTimeout,
      changes: getLineChanges(result2.changes),
      moves: result2.moves.map((m) => [
        m.lineRangeMapping.original.startLineNumber,
        m.lineRangeMapping.original.endLineNumberExclusive,
        m.lineRangeMapping.modified.startLineNumber,
        m.lineRangeMapping.modified.endLineNumberExclusive,
        getLineChanges(m.changes)
      ])
    };
  }
  static _modelsAreIdentical(original, modified) {
    const originalLineCount = original.getLineCount();
    const modifiedLineCount = modified.getLineCount();
    if (originalLineCount !== modifiedLineCount) {
      return false;
    }
    for (let line = 1; line <= originalLineCount; line++) {
      const originalLine = original.getLineContent(line);
      const modifiedLine = modified.getLineContent(line);
      if (originalLine !== modifiedLine) {
        return false;
      }
    }
    return true;
  }
  computeMoreMinimalEdits(modelUrl, edits, pretty) {
    return __awaiter$1f(this, void 0, void 0, function* () {
      const model = this._getModel(modelUrl);
      if (!model) {
        return edits;
      }
      const result2 = [];
      let lastEol = void 0;
      edits = edits.slice(0).sort((a, b) => {
        if (a.range && b.range) {
          return Range$2.compareRangesUsingStarts(a.range, b.range);
        }
        const aRng = a.range ? 0 : 1;
        const bRng = b.range ? 0 : 1;
        return aRng - bRng;
      });
      for (let { range: range2, text: text2, eol } of edits) {
        if (typeof eol === "number") {
          lastEol = eol;
        }
        if (Range$2.isEmpty(range2) && !text2) {
          continue;
        }
        const original = model.getValueInRange(range2);
        text2 = text2.replace(/\r\n|\n|\r/g, model.eol);
        if (original === text2) {
          continue;
        }
        if (Math.max(text2.length, original.length) > EditorSimpleWorker._diffLimit) {
          result2.push({ range: range2, text: text2 });
          continue;
        }
        const changes = stringDiff(original, text2, pretty);
        const editOffset = model.offsetAt(Range$2.lift(range2).getStartPosition());
        for (const change of changes) {
          const start = model.positionAt(editOffset + change.originalStart);
          const end = model.positionAt(editOffset + change.originalStart + change.originalLength);
          const newEdit = {
            text: text2.substr(change.modifiedStart, change.modifiedLength),
            range: { startLineNumber: start.lineNumber, startColumn: start.column, endLineNumber: end.lineNumber, endColumn: end.column }
          };
          if (model.getValueInRange(newEdit.range) !== newEdit.text) {
            result2.push(newEdit);
          }
        }
      }
      if (typeof lastEol === "number") {
        result2.push({ eol: lastEol, text: "", range: { startLineNumber: 0, startColumn: 0, endLineNumber: 0, endColumn: 0 } });
      }
      return result2;
    });
  }
  // ---- END minimal edits ---------------------------------------------------------------
  computeLinks(modelUrl) {
    return __awaiter$1f(this, void 0, void 0, function* () {
      const model = this._getModel(modelUrl);
      if (!model) {
        return null;
      }
      return computeLinks(model);
    });
  }
  // --- BEGIN default document colors -----------------------------------------------------------
  computeDefaultDocumentColors(modelUrl) {
    return __awaiter$1f(this, void 0, void 0, function* () {
      const model = this._getModel(modelUrl);
      if (!model) {
        return null;
      }
      return computeDefaultDocumentColors(model);
    });
  }
  textualSuggest(modelUrls, leadingWord, wordDef, wordDefFlags) {
    return __awaiter$1f(this, void 0, void 0, function* () {
      const sw = new StopWatch();
      const wordDefRegExp = new RegExp(wordDef, wordDefFlags);
      const seen2 = /* @__PURE__ */ new Set();
      outer:
        for (const url of modelUrls) {
          const model = this._getModel(url);
          if (!model) {
            continue;
          }
          for (const word2 of model.words(wordDefRegExp)) {
            if (word2 === leadingWord || !isNaN(Number(word2))) {
              continue;
            }
            seen2.add(word2);
            if (seen2.size > EditorSimpleWorker._suggestionsLimit) {
              break outer;
            }
          }
        }
      return { words: Array.from(seen2), duration: sw.elapsed() };
    });
  }
  // ---- END suggest --------------------------------------------------------------------------
  //#region -- word ranges --
  computeWordRanges(modelUrl, range2, wordDef, wordDefFlags) {
    return __awaiter$1f(this, void 0, void 0, function* () {
      const model = this._getModel(modelUrl);
      if (!model) {
        return /* @__PURE__ */ Object.create(null);
      }
      const wordDefRegExp = new RegExp(wordDef, wordDefFlags);
      const result2 = /* @__PURE__ */ Object.create(null);
      for (let line = range2.startLineNumber; line < range2.endLineNumber; line++) {
        const words = model.getLineWords(line, wordDefRegExp);
        for (const word2 of words) {
          if (!isNaN(Number(word2.word))) {
            continue;
          }
          let array2 = result2[word2.word];
          if (!array2) {
            array2 = [];
            result2[word2.word] = array2;
          }
          array2.push({
            startLineNumber: line,
            startColumn: word2.startColumn,
            endLineNumber: line,
            endColumn: word2.endColumn
          });
        }
      }
      return result2;
    });
  }
  //#endregion
  navigateValueSet(modelUrl, range2, up, wordDef, wordDefFlags) {
    return __awaiter$1f(this, void 0, void 0, function* () {
      const model = this._getModel(modelUrl);
      if (!model) {
        return null;
      }
      const wordDefRegExp = new RegExp(wordDef, wordDefFlags);
      if (range2.startColumn === range2.endColumn) {
        range2 = {
          startLineNumber: range2.startLineNumber,
          startColumn: range2.startColumn,
          endLineNumber: range2.endLineNumber,
          endColumn: range2.endColumn + 1
        };
      }
      const selectionText = model.getValueInRange(range2);
      const wordRange = model.getWordAtPosition({ lineNumber: range2.startLineNumber, column: range2.startColumn }, wordDefRegExp);
      if (!wordRange) {
        return null;
      }
      const word2 = model.getValueInRange(wordRange);
      const result2 = BasicInplaceReplace.INSTANCE.navigateValueSet(range2, selectionText, wordRange, word2, up);
      return result2;
    });
  }
  // ---- BEGIN foreign module support --------------------------------------------------------------------------
  loadForeignModule(moduleId, createData, foreignHostMethods) {
    const proxyMethodRequest = (method, args) => {
      return this._host.fhr(method, args);
    };
    const foreignHost = createProxyObject$1(foreignHostMethods, proxyMethodRequest);
    const ctx = {
      host: foreignHost,
      getMirrorModels: () => {
        return this._getModels();
      }
    };
    if (this._foreignModuleFactory) {
      this._foreignModule = this._foreignModuleFactory(ctx, createData);
      return Promise.resolve(getAllMethodNames(this._foreignModule));
    }
    return Promise.reject(new Error(`Unexpected usage`));
  }
  // foreign method request
  fmr(method, args) {
    if (!this._foreignModule || typeof this._foreignModule[method] !== "function") {
      return Promise.reject(new Error("Missing requestHandler or method: " + method));
    }
    try {
      return Promise.resolve(this._foreignModule[method].apply(this._foreignModule, args));
    } catch (e) {
      return Promise.reject(e);
    }
  }
}
EditorSimpleWorker._diffLimit = 1e5;
EditorSimpleWorker._suggestionsLimit = 1e4;
if (typeof importScripts === "function") {
  globalThis.monaco = createMonacoBaseAPI();
}
const ITextResourceConfigurationService = createDecorator("textResourceConfigurationService");
const ITextResourcePropertiesService = createDecorator("textResourcePropertiesService");
var __decorate$1L = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1I = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$1e = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
const STOP_SYNC_MODEL_DELTA_TIME_MS = 60 * 1e3;
const STOP_WORKER_DELTA_TIME_MS = 5 * 60 * 1e3;
function canSyncModel(modelService, resource) {
  const model = modelService.getModel(resource);
  if (!model) {
    return false;
  }
  if (model.isTooLargeForSyncing()) {
    return false;
  }
  return true;
}
let EditorWorkerService = class EditorWorkerService2 extends Disposable {
  constructor(modelService, configurationService, logService, languageConfigurationService, languageFeaturesService) {
    super();
    this._modelService = modelService;
    this._workerManager = this._register(new WorkerManager(this._modelService, languageConfigurationService));
    this._logService = logService;
    this._register(languageFeaturesService.linkProvider.register({ language: "*", hasAccessToAllModels: true }, {
      provideLinks: (model, token) => {
        if (!canSyncModel(this._modelService, model.uri)) {
          return Promise.resolve({ links: [] });
        }
        return this._workerManager.withWorker().then((client) => client.computeLinks(model.uri)).then((links2) => {
          return links2 && { links: links2 };
        });
      }
    }));
    this._register(languageFeaturesService.completionProvider.register("*", new WordBasedCompletionItemProvider(this._workerManager, configurationService, this._modelService, languageConfigurationService)));
  }
  dispose() {
    super.dispose();
  }
  canComputeUnicodeHighlights(uri) {
    return canSyncModel(this._modelService, uri);
  }
  computedUnicodeHighlights(uri, options, range2) {
    return this._workerManager.withWorker().then((client) => client.computedUnicodeHighlights(uri, options, range2));
  }
  computeDiff(original, modified, options, algorithm) {
    return __awaiter$1e(this, void 0, void 0, function* () {
      const result2 = yield this._workerManager.withWorker().then((client) => client.computeDiff(original, modified, options, algorithm));
      if (!result2) {
        return null;
      }
      const diff = {
        identical: result2.identical,
        quitEarly: result2.quitEarly,
        changes: toLineRangeMappings(result2.changes),
        moves: result2.moves.map((m) => new MovedText(new SimpleLineRangeMapping(new LineRange2(m[0], m[1]), new LineRange2(m[2], m[3])), toLineRangeMappings(m[4])))
      };
      return diff;
      function toLineRangeMappings(changes) {
        return changes.map((c) => {
          var _a2;
          return new LineRangeMapping(new LineRange2(c[0], c[1]), new LineRange2(c[2], c[3]), (_a2 = c[4]) === null || _a2 === void 0 ? void 0 : _a2.map((c2) => new RangeMapping(new Range$2(c2[0], c2[1], c2[2], c2[3]), new Range$2(c2[4], c2[5], c2[6], c2[7]))));
        });
      }
    });
  }
  computeMoreMinimalEdits(resource, edits, pretty = false) {
    if (isNonEmptyArray(edits)) {
      if (!canSyncModel(this._modelService, resource)) {
        return Promise.resolve(edits);
      }
      const sw = StopWatch.create();
      const result2 = this._workerManager.withWorker().then((client) => client.computeMoreMinimalEdits(resource, edits, pretty));
      result2.finally(() => this._logService.trace("FORMAT#computeMoreMinimalEdits", resource.toString(true), sw.elapsed()));
      return Promise.race([result2, timeout(1e3).then(() => edits)]);
    } else {
      return Promise.resolve(void 0);
    }
  }
  canNavigateValueSet(resource) {
    return canSyncModel(this._modelService, resource);
  }
  navigateValueSet(resource, range2, up) {
    return this._workerManager.withWorker().then((client) => client.navigateValueSet(resource, range2, up));
  }
  canComputeWordRanges(resource) {
    return canSyncModel(this._modelService, resource);
  }
  computeWordRanges(resource, range2) {
    return this._workerManager.withWorker().then((client) => client.computeWordRanges(resource, range2));
  }
};
EditorWorkerService = __decorate$1L([
  __param$1I(0, IModelService),
  __param$1I(1, ITextResourceConfigurationService),
  __param$1I(2, ILogService),
  __param$1I(3, ILanguageConfigurationService),
  __param$1I(4, ILanguageFeaturesService)
], EditorWorkerService);
class WordBasedCompletionItemProvider {
  constructor(workerManager, configurationService, modelService, languageConfigurationService) {
    this.languageConfigurationService = languageConfigurationService;
    this._debugDisplayName = "wordbasedCompletions";
    this._workerManager = workerManager;
    this._configurationService = configurationService;
    this._modelService = modelService;
  }
  provideCompletionItems(model, position) {
    return __awaiter$1e(this, void 0, void 0, function* () {
      const config2 = this._configurationService.getValue(model.uri, position, "editor");
      if (!config2.wordBasedSuggestions) {
        return void 0;
      }
      const models = [];
      if (config2.wordBasedSuggestionsMode === "currentDocument") {
        if (canSyncModel(this._modelService, model.uri)) {
          models.push(model.uri);
        }
      } else {
        for (const candidate of this._modelService.getModels()) {
          if (!canSyncModel(this._modelService, candidate.uri)) {
            continue;
          }
          if (candidate === model) {
            models.unshift(candidate.uri);
          } else if (config2.wordBasedSuggestionsMode === "allDocuments" || candidate.getLanguageId() === model.getLanguageId()) {
            models.push(candidate.uri);
          }
        }
      }
      if (models.length === 0) {
        return void 0;
      }
      const wordDefRegExp = this.languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).getWordDefinition();
      const word2 = model.getWordAtPosition(position);
      const replace = !word2 ? Range$2.fromPositions(position) : new Range$2(position.lineNumber, word2.startColumn, position.lineNumber, word2.endColumn);
      const insert2 = replace.setEndPosition(position.lineNumber, position.column);
      const client = yield this._workerManager.withWorker();
      const data = yield client.textualSuggest(models, word2 === null || word2 === void 0 ? void 0 : word2.word, wordDefRegExp);
      if (!data) {
        return void 0;
      }
      return {
        duration: data.duration,
        suggestions: data.words.map((word3) => {
          return {
            kind: 18,
            label: word3,
            insertText: word3,
            range: { insert: insert2, replace }
          };
        })
      };
    });
  }
}
class WorkerManager extends Disposable {
  constructor(modelService, languageConfigurationService) {
    super();
    this.languageConfigurationService = languageConfigurationService;
    this._modelService = modelService;
    this._editorWorkerClient = null;
    this._lastWorkerUsedTime = (/* @__PURE__ */ new Date()).getTime();
    const stopWorkerInterval = this._register(new IntervalTimer());
    stopWorkerInterval.cancelAndSet(() => this._checkStopIdleWorker(), Math.round(STOP_WORKER_DELTA_TIME_MS / 2));
    this._register(this._modelService.onModelRemoved((_) => this._checkStopEmptyWorker()));
  }
  dispose() {
    if (this._editorWorkerClient) {
      this._editorWorkerClient.dispose();
      this._editorWorkerClient = null;
    }
    super.dispose();
  }
  /**
   * Check if the model service has no more models and stop the worker if that is the case.
   */
  _checkStopEmptyWorker() {
    if (!this._editorWorkerClient) {
      return;
    }
    const models = this._modelService.getModels();
    if (models.length === 0) {
      this._editorWorkerClient.dispose();
      this._editorWorkerClient = null;
    }
  }
  /**
   * Check if the worker has been idle for a while and then stop it.
   */
  _checkStopIdleWorker() {
    if (!this._editorWorkerClient) {
      return;
    }
    const timeSinceLastWorkerUsedTime = (/* @__PURE__ */ new Date()).getTime() - this._lastWorkerUsedTime;
    if (timeSinceLastWorkerUsedTime > STOP_WORKER_DELTA_TIME_MS) {
      this._editorWorkerClient.dispose();
      this._editorWorkerClient = null;
    }
  }
  withWorker() {
    this._lastWorkerUsedTime = (/* @__PURE__ */ new Date()).getTime();
    if (!this._editorWorkerClient) {
      this._editorWorkerClient = new EditorWorkerClient(this._modelService, false, "editorWorkerService", this.languageConfigurationService);
    }
    return Promise.resolve(this._editorWorkerClient);
  }
}
class EditorModelManager extends Disposable {
  constructor(proxy, modelService, keepIdleModels) {
    super();
    this._syncedModels = /* @__PURE__ */ Object.create(null);
    this._syncedModelsLastUsedTime = /* @__PURE__ */ Object.create(null);
    this._proxy = proxy;
    this._modelService = modelService;
    if (!keepIdleModels) {
      const timer = new IntervalTimer();
      timer.cancelAndSet(() => this._checkStopModelSync(), Math.round(STOP_SYNC_MODEL_DELTA_TIME_MS / 2));
      this._register(timer);
    }
  }
  dispose() {
    for (const modelUrl in this._syncedModels) {
      dispose(this._syncedModels[modelUrl]);
    }
    this._syncedModels = /* @__PURE__ */ Object.create(null);
    this._syncedModelsLastUsedTime = /* @__PURE__ */ Object.create(null);
    super.dispose();
  }
  ensureSyncedResources(resources, forceLargeModels) {
    for (const resource of resources) {
      const resourceStr = resource.toString();
      if (!this._syncedModels[resourceStr]) {
        this._beginModelSync(resource, forceLargeModels);
      }
      if (this._syncedModels[resourceStr]) {
        this._syncedModelsLastUsedTime[resourceStr] = (/* @__PURE__ */ new Date()).getTime();
      }
    }
  }
  _checkStopModelSync() {
    const currentTime = (/* @__PURE__ */ new Date()).getTime();
    const toRemove = [];
    for (const modelUrl in this._syncedModelsLastUsedTime) {
      const elapsedTime = currentTime - this._syncedModelsLastUsedTime[modelUrl];
      if (elapsedTime > STOP_SYNC_MODEL_DELTA_TIME_MS) {
        toRemove.push(modelUrl);
      }
    }
    for (const e of toRemove) {
      this._stopModelSync(e);
    }
  }
  _beginModelSync(resource, forceLargeModels) {
    const model = this._modelService.getModel(resource);
    if (!model) {
      return;
    }
    if (!forceLargeModels && model.isTooLargeForSyncing()) {
      return;
    }
    const modelUrl = resource.toString();
    this._proxy.acceptNewModel({
      url: model.uri.toString(),
      lines: model.getLinesContent(),
      EOL: model.getEOL(),
      versionId: model.getVersionId()
    });
    const toDispose = new DisposableStore();
    toDispose.add(model.onDidChangeContent((e) => {
      this._proxy.acceptModelChanged(modelUrl.toString(), e);
    }));
    toDispose.add(model.onWillDispose(() => {
      this._stopModelSync(modelUrl);
    }));
    toDispose.add(toDisposable(() => {
      this._proxy.acceptRemovedModel(modelUrl);
    }));
    this._syncedModels[modelUrl] = toDispose;
  }
  _stopModelSync(modelUrl) {
    const toDispose = this._syncedModels[modelUrl];
    delete this._syncedModels[modelUrl];
    delete this._syncedModelsLastUsedTime[modelUrl];
    dispose(toDispose);
  }
}
class SynchronousWorkerClient {
  constructor(instance) {
    this._instance = instance;
    this._proxyObj = Promise.resolve(this._instance);
  }
  dispose() {
    this._instance.dispose();
  }
  getProxyObject() {
    return this._proxyObj;
  }
}
class EditorWorkerHost {
  constructor(workerClient) {
    this._workerClient = workerClient;
  }
  // foreign host request
  fhr(method, args) {
    return this._workerClient.fhr(method, args);
  }
}
class EditorWorkerClient extends Disposable {
  constructor(modelService, keepIdleModels, label, languageConfigurationService) {
    super();
    this.languageConfigurationService = languageConfigurationService;
    this._disposed = false;
    this._modelService = modelService;
    this._keepIdleModels = keepIdleModels;
    this._workerFactory = new DefaultWorkerFactory(label);
    this._worker = null;
    this._modelManager = null;
  }
  // foreign host request
  fhr(method, args) {
    throw new Error(`Not implemented!`);
  }
  _getOrCreateWorker() {
    if (!this._worker) {
      try {
        this._worker = this._register(new SimpleWorkerClient(this._workerFactory, "vs/editor/common/services/editorSimpleWorker", new EditorWorkerHost(this)));
      } catch (err) {
        logOnceWebWorkerWarning(err);
        this._worker = new SynchronousWorkerClient(new EditorSimpleWorker(new EditorWorkerHost(this), null));
      }
    }
    return this._worker;
  }
  _getProxy() {
    return this._getOrCreateWorker().getProxyObject().then(void 0, (err) => {
      logOnceWebWorkerWarning(err);
      this._worker = new SynchronousWorkerClient(new EditorSimpleWorker(new EditorWorkerHost(this), null));
      return this._getOrCreateWorker().getProxyObject();
    });
  }
  _getOrCreateModelManager(proxy) {
    if (!this._modelManager) {
      this._modelManager = this._register(new EditorModelManager(proxy, this._modelService, this._keepIdleModels));
    }
    return this._modelManager;
  }
  _withSyncedResources(resources, forceLargeModels = false) {
    return __awaiter$1e(this, void 0, void 0, function* () {
      if (this._disposed) {
        return Promise.reject(canceled());
      }
      return this._getProxy().then((proxy) => {
        this._getOrCreateModelManager(proxy).ensureSyncedResources(resources, forceLargeModels);
        return proxy;
      });
    });
  }
  computedUnicodeHighlights(uri, options, range2) {
    return this._withSyncedResources([uri]).then((proxy) => {
      return proxy.computeUnicodeHighlights(uri.toString(), options, range2);
    });
  }
  computeDiff(original, modified, options, algorithm) {
    return this._withSyncedResources(
      [original, modified],
      /* forceLargeModels */
      true
    ).then((proxy) => {
      return proxy.computeDiff(original.toString(), modified.toString(), options, algorithm);
    });
  }
  computeMoreMinimalEdits(resource, edits, pretty) {
    return this._withSyncedResources([resource]).then((proxy) => {
      return proxy.computeMoreMinimalEdits(resource.toString(), edits, pretty);
    });
  }
  computeLinks(resource) {
    return this._withSyncedResources([resource]).then((proxy) => {
      return proxy.computeLinks(resource.toString());
    });
  }
  computeDefaultDocumentColors(resource) {
    return this._withSyncedResources([resource]).then((proxy) => {
      return proxy.computeDefaultDocumentColors(resource.toString());
    });
  }
  textualSuggest(resources, leadingWord, wordDefRegExp) {
    return __awaiter$1e(this, void 0, void 0, function* () {
      const proxy = yield this._withSyncedResources(resources);
      const wordDef = wordDefRegExp.source;
      const wordDefFlags = regExpFlags(wordDefRegExp);
      return proxy.textualSuggest(resources.map((r) => r.toString()), leadingWord, wordDef, wordDefFlags);
    });
  }
  computeWordRanges(resource, range2) {
    return this._withSyncedResources([resource]).then((proxy) => {
      const model = this._modelService.getModel(resource);
      if (!model) {
        return Promise.resolve(null);
      }
      const wordDefRegExp = this.languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).getWordDefinition();
      const wordDef = wordDefRegExp.source;
      const wordDefFlags = regExpFlags(wordDefRegExp);
      return proxy.computeWordRanges(resource.toString(), range2, wordDef, wordDefFlags);
    });
  }
  navigateValueSet(resource, range2, up) {
    return this._withSyncedResources([resource]).then((proxy) => {
      const model = this._modelService.getModel(resource);
      if (!model) {
        return null;
      }
      const wordDefRegExp = this.languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).getWordDefinition();
      const wordDef = wordDefRegExp.source;
      const wordDefFlags = regExpFlags(wordDefRegExp);
      return proxy.navigateValueSet(resource.toString(), range2, up, wordDef, wordDefFlags);
    });
  }
  dispose() {
    super.dispose();
    this._disposed = true;
  }
}
const editorFeatures = [];
function registerEditorFeature(ctor) {
  editorFeatures.push(ctor);
}
function getEditorFeatures() {
  return editorFeatures.slice(0);
}
var __decorate$1K = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1H = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$1d = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class DefaultDocumentColorProvider {
  constructor(modelService, languageConfigurationService) {
    this._editorWorkerClient = new EditorWorkerClient(modelService, false, "editorWorkerService", languageConfigurationService);
  }
  provideDocumentColors(model, _token) {
    return __awaiter$1d(this, void 0, void 0, function* () {
      return this._editorWorkerClient.computeDefaultDocumentColors(model.uri);
    });
  }
  provideColorPresentations(_model, colorInfo, _token) {
    const range2 = colorInfo.range;
    const colorFromInfo = colorInfo.color;
    const alpha = colorFromInfo.alpha;
    const color = new Color(new RGBA(Math.round(255 * colorFromInfo.red), Math.round(255 * colorFromInfo.green), Math.round(255 * colorFromInfo.blue), alpha));
    const rgb = alpha ? Color.Format.CSS.formatRGB(color) : Color.Format.CSS.formatRGBA(color);
    const hsl = alpha ? Color.Format.CSS.formatHSL(color) : Color.Format.CSS.formatHSLA(color);
    const hex = alpha ? Color.Format.CSS.formatHex(color) : Color.Format.CSS.formatHexA(color);
    const colorPresentations = [];
    colorPresentations.push({ label: rgb, textEdit: { range: range2, text: rgb } });
    colorPresentations.push({ label: hsl, textEdit: { range: range2, text: hsl } });
    colorPresentations.push({ label: hex, textEdit: { range: range2, text: hex } });
    return colorPresentations;
  }
}
let DefaultDocumentColorProviderFeature = class DefaultDocumentColorProviderFeature2 extends Disposable {
  constructor(_modelService, _languageConfigurationService, _languageFeaturesService) {
    super();
    this._register(_languageFeaturesService.colorProvider.register("*", new DefaultDocumentColorProvider(_modelService, _languageConfigurationService)));
  }
};
DefaultDocumentColorProviderFeature = __decorate$1K([
  __param$1H(0, IModelService),
  __param$1H(1, ILanguageConfigurationService),
  __param$1H(2, ILanguageFeaturesService)
], DefaultDocumentColorProviderFeature);
registerEditorFeature(DefaultDocumentColorProviderFeature);
var __awaiter$1c = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
function getColors(colorProviderRegistry, model, token, isDefaultColorDecoratorsEnabled = true) {
  return __awaiter$1c(this, void 0, void 0, function* () {
    return _findColorData(new ColorDataCollector(), colorProviderRegistry, model, token, isDefaultColorDecoratorsEnabled);
  });
}
function getColorPresentations(model, colorInfo, provider, token) {
  return Promise.resolve(provider.provideColorPresentations(model, colorInfo, token));
}
class ColorDataCollector {
  constructor() {
  }
  compute(provider, model, token, colors) {
    return __awaiter$1c(this, void 0, void 0, function* () {
      const documentColors = yield provider.provideDocumentColors(model, token);
      if (Array.isArray(documentColors)) {
        for (const colorInfo of documentColors) {
          colors.push({ colorInfo, provider });
        }
      }
      return Array.isArray(documentColors);
    });
  }
}
class ExtColorDataCollector {
  constructor() {
  }
  compute(provider, model, token, colors) {
    return __awaiter$1c(this, void 0, void 0, function* () {
      const documentColors = yield provider.provideDocumentColors(model, token);
      if (Array.isArray(documentColors)) {
        for (const colorInfo of documentColors) {
          colors.push({ range: colorInfo.range, color: [colorInfo.color.red, colorInfo.color.green, colorInfo.color.blue, colorInfo.color.alpha] });
        }
      }
      return Array.isArray(documentColors);
    });
  }
}
class ColorPresentationsCollector {
  constructor(colorInfo) {
    this.colorInfo = colorInfo;
  }
  compute(provider, model, _token, colors) {
    return __awaiter$1c(this, void 0, void 0, function* () {
      const documentColors = yield provider.provideColorPresentations(model, this.colorInfo, CancellationToken.None);
      if (Array.isArray(documentColors)) {
        colors.push(...documentColors);
      }
      return Array.isArray(documentColors);
    });
  }
}
function _findColorData(collector, colorProviderRegistry, model, token, isDefaultColorDecoratorsEnabled) {
  return __awaiter$1c(this, void 0, void 0, function* () {
    let validDocumentColorProviderFound = false;
    let defaultProvider;
    const colorData = [];
    const documentColorProviders = colorProviderRegistry.ordered(model);
    for (let i = documentColorProviders.length - 1; i >= 0; i--) {
      const provider = documentColorProviders[i];
      if (provider instanceof DefaultDocumentColorProvider) {
        defaultProvider = provider;
      } else {
        try {
          if (yield collector.compute(provider, model, token, colorData)) {
            validDocumentColorProviderFound = true;
          }
        } catch (e) {
          onUnexpectedExternalError(e);
        }
      }
    }
    if (validDocumentColorProviderFound) {
      return colorData;
    }
    if (defaultProvider && isDefaultColorDecoratorsEnabled) {
      yield collector.compute(defaultProvider, model, token, colorData);
      return colorData;
    }
    return [];
  });
}
function _setupColorCommand(accessor, resource) {
  const { colorProvider: colorProviderRegistry } = accessor.get(ILanguageFeaturesService);
  const model = accessor.get(IModelService).getModel(resource);
  if (!model) {
    throw illegalArgument();
  }
  const isDefaultColorDecoratorsEnabled = accessor.get(IConfigurationService).getValue("editor.defaultColorDecorators", { resource });
  return { model, colorProviderRegistry, isDefaultColorDecoratorsEnabled };
}
CommandsRegistry.registerCommand("_executeDocumentColorProvider", function(accessor, ...args) {
  const [resource] = args;
  if (!(resource instanceof URI)) {
    throw illegalArgument();
  }
  const { model, colorProviderRegistry, isDefaultColorDecoratorsEnabled } = _setupColorCommand(accessor, resource);
  return _findColorData(new ExtColorDataCollector(), colorProviderRegistry, model, CancellationToken.None, isDefaultColorDecoratorsEnabled);
});
CommandsRegistry.registerCommand("_executeColorPresentationProvider", function(accessor, ...args) {
  const [color, context] = args;
  const { uri, range: range2 } = context;
  if (!(uri instanceof URI) || !Array.isArray(color) || color.length !== 4 || !Range$2.isIRange(range2)) {
    throw illegalArgument();
  }
  const { model, colorProviderRegistry, isDefaultColorDecoratorsEnabled } = _setupColorCommand(accessor, uri);
  const [red, green, blue, alpha] = color;
  return _findColorData(new ColorPresentationsCollector({ range: range2, color: { red, green, blue, alpha } }), colorProviderRegistry, model, CancellationToken.None, isDefaultColorDecoratorsEnabled);
});
var __decorate$1J = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1G = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$1b = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
const ColorDecorationInjectedTextMarker = /* @__PURE__ */ Object.create({});
let ColorDetector = class ColorDetector2 extends Disposable {
  constructor(_editor, _configurationService, _languageFeaturesService, languageFeatureDebounceService) {
    super();
    this._editor = _editor;
    this._configurationService = _configurationService;
    this._languageFeaturesService = _languageFeaturesService;
    this._localToDispose = this._register(new DisposableStore());
    this._decorationsIds = [];
    this._colorDatas = /* @__PURE__ */ new Map();
    this._colorDecoratorIds = this._editor.createDecorationsCollection();
    this._ruleFactory = new DynamicCssRules(this._editor);
    this._decoratorLimitReporter = new DecoratorLimitReporter();
    this._colorDecorationClassRefs = this._register(new DisposableStore());
    this._debounceInformation = languageFeatureDebounceService.for(_languageFeaturesService.colorProvider, "Document Colors", { min: ColorDetector2.RECOMPUTE_TIME });
    this._register(_editor.onDidChangeModel(() => {
      this._isColorDecoratorsEnabled = this.isEnabled();
      this.updateColors();
    }));
    this._register(_editor.onDidChangeModelLanguage(() => this.updateColors()));
    this._register(_languageFeaturesService.colorProvider.onDidChange(() => this.updateColors()));
    this._register(_editor.onDidChangeConfiguration((e) => {
      const prevIsEnabled = this._isColorDecoratorsEnabled;
      this._isColorDecoratorsEnabled = this.isEnabled();
      this._isDefaultColorDecoratorsEnabled = this._editor.getOption(
        144
        /* EditorOption.defaultColorDecorators */
      );
      const updatedColorDecoratorsSetting = prevIsEnabled !== this._isColorDecoratorsEnabled || e.hasChanged(
        20
        /* EditorOption.colorDecoratorsLimit */
      );
      const updatedDefaultColorDecoratorsSetting = e.hasChanged(
        144
        /* EditorOption.defaultColorDecorators */
      );
      if (updatedColorDecoratorsSetting || updatedDefaultColorDecoratorsSetting) {
        if (this._isColorDecoratorsEnabled) {
          this.updateColors();
        } else {
          this.removeAllDecorations();
        }
      }
    }));
    this._timeoutTimer = null;
    this._computePromise = null;
    this._isColorDecoratorsEnabled = this.isEnabled();
    this._isDefaultColorDecoratorsEnabled = this._editor.getOption(
      144
      /* EditorOption.defaultColorDecorators */
    );
    this.updateColors();
  }
  isEnabled() {
    const model = this._editor.getModel();
    if (!model) {
      return false;
    }
    const languageId = model.getLanguageId();
    const deprecatedConfig = this._configurationService.getValue(languageId);
    if (deprecatedConfig && typeof deprecatedConfig === "object") {
      const colorDecorators = deprecatedConfig["colorDecorators"];
      if (colorDecorators && colorDecorators["enable"] !== void 0 && !colorDecorators["enable"]) {
        return colorDecorators["enable"];
      }
    }
    return this._editor.getOption(
      19
      /* EditorOption.colorDecorators */
    );
  }
  static get(editor2) {
    return editor2.getContribution(this.ID);
  }
  dispose() {
    this.stop();
    this.removeAllDecorations();
    super.dispose();
  }
  updateColors() {
    this.stop();
    if (!this._isColorDecoratorsEnabled) {
      return;
    }
    const model = this._editor.getModel();
    if (!model || !this._languageFeaturesService.colorProvider.has(model)) {
      return;
    }
    this._localToDispose.add(this._editor.onDidChangeModelContent(() => {
      if (!this._timeoutTimer) {
        this._timeoutTimer = new TimeoutTimer();
        this._timeoutTimer.cancelAndSet(() => {
          this._timeoutTimer = null;
          this.beginCompute();
        }, this._debounceInformation.get(model));
      }
    }));
    this.beginCompute();
  }
  beginCompute() {
    return __awaiter$1b(this, void 0, void 0, function* () {
      this._computePromise = createCancelablePromise((token) => __awaiter$1b(this, void 0, void 0, function* () {
        const model = this._editor.getModel();
        if (!model) {
          return [];
        }
        const sw = new StopWatch(false);
        const colors = yield getColors(this._languageFeaturesService.colorProvider, model, token, this._isDefaultColorDecoratorsEnabled);
        this._debounceInformation.update(model, sw.elapsed());
        return colors;
      }));
      try {
        const colors = yield this._computePromise;
        this.updateDecorations(colors);
        this.updateColorDecorators(colors);
        this._computePromise = null;
      } catch (e) {
        onUnexpectedError(e);
      }
    });
  }
  stop() {
    if (this._timeoutTimer) {
      this._timeoutTimer.cancel();
      this._timeoutTimer = null;
    }
    if (this._computePromise) {
      this._computePromise.cancel();
      this._computePromise = null;
    }
    this._localToDispose.clear();
  }
  updateDecorations(colorDatas) {
    const decorations2 = colorDatas.map((c) => ({
      range: {
        startLineNumber: c.colorInfo.range.startLineNumber,
        startColumn: c.colorInfo.range.startColumn,
        endLineNumber: c.colorInfo.range.endLineNumber,
        endColumn: c.colorInfo.range.endColumn
      },
      options: ModelDecorationOptions.EMPTY
    }));
    this._editor.changeDecorations((changeAccessor) => {
      this._decorationsIds = changeAccessor.deltaDecorations(this._decorationsIds, decorations2);
      this._colorDatas = /* @__PURE__ */ new Map();
      this._decorationsIds.forEach((id3, i) => this._colorDatas.set(id3, colorDatas[i]));
    });
  }
  updateColorDecorators(colorData) {
    this._colorDecorationClassRefs.clear();
    const decorations2 = [];
    const limit = this._editor.getOption(
      20
      /* EditorOption.colorDecoratorsLimit */
    );
    for (let i = 0; i < colorData.length && decorations2.length < limit; i++) {
      const { red, green, blue, alpha } = colorData[i].colorInfo.color;
      const rgba = new RGBA(Math.round(red * 255), Math.round(green * 255), Math.round(blue * 255), alpha);
      const color = `rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${rgba.a})`;
      const ref2 = this._colorDecorationClassRefs.add(this._ruleFactory.createClassNameRef({
        backgroundColor: color
      }));
      decorations2.push({
        range: {
          startLineNumber: colorData[i].colorInfo.range.startLineNumber,
          startColumn: colorData[i].colorInfo.range.startColumn,
          endLineNumber: colorData[i].colorInfo.range.endLineNumber,
          endColumn: colorData[i].colorInfo.range.endColumn
        },
        options: {
          description: "colorDetector",
          before: {
            content: noBreakWhitespace,
            inlineClassName: `${ref2.className} colorpicker-color-decoration`,
            inlineClassNameAffectsLetterSpacing: true,
            attachedData: ColorDecorationInjectedTextMarker
          }
        }
      });
    }
    const limited = limit < colorData.length ? limit : false;
    this._decoratorLimitReporter.update(colorData.length, limited);
    this._colorDecoratorIds.set(decorations2);
  }
  removeAllDecorations() {
    this._editor.removeDecorations(this._decorationsIds);
    this._decorationsIds = [];
    this._colorDecoratorIds.clear();
    this._colorDecorationClassRefs.clear();
  }
  getColorData(position) {
    const model = this._editor.getModel();
    if (!model) {
      return null;
    }
    const decorations2 = model.getDecorationsInRange(Range$2.fromPositions(position, position)).filter((d) => this._colorDatas.has(d.id));
    if (decorations2.length === 0) {
      return null;
    }
    return this._colorDatas.get(decorations2[0].id);
  }
  isColorDecoration(decoration2) {
    return this._colorDecoratorIds.has(decoration2);
  }
};
ColorDetector.ID = "editor.contrib.colorDetector";
ColorDetector.RECOMPUTE_TIME = 1e3;
ColorDetector = __decorate$1J([
  __param$1G(1, IConfigurationService),
  __param$1G(2, ILanguageFeaturesService),
  __param$1G(3, ILanguageFeatureDebounceService)
], ColorDetector);
class DecoratorLimitReporter {
  constructor() {
    this._onDidChange = new Emitter$1();
    this._computed = 0;
    this._limited = false;
  }
  update(computed2, limited) {
    if (computed2 !== this._computed || limited !== this._limited) {
      this._computed = computed2;
      this._limited = limited;
      this._onDidChange.fire();
    }
  }
}
registerEditorContribution(
  ColorDetector.ID,
  ColorDetector,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
class ColorPickerModel {
  get color() {
    return this._color;
  }
  set color(color) {
    if (this._color.equals(color)) {
      return;
    }
    this._color = color;
    this._onDidChangeColor.fire(color);
  }
  get presentation() {
    return this.colorPresentations[this.presentationIndex];
  }
  get colorPresentations() {
    return this._colorPresentations;
  }
  set colorPresentations(colorPresentations) {
    this._colorPresentations = colorPresentations;
    if (this.presentationIndex > colorPresentations.length - 1) {
      this.presentationIndex = 0;
    }
    this._onDidChangePresentation.fire(this.presentation);
  }
  constructor(color, availableColorPresentations, presentationIndex) {
    this.presentationIndex = presentationIndex;
    this._onColorFlushed = new Emitter$1();
    this.onColorFlushed = this._onColorFlushed.event;
    this._onDidChangeColor = new Emitter$1();
    this.onDidChangeColor = this._onDidChangeColor.event;
    this._onDidChangePresentation = new Emitter$1();
    this.onDidChangePresentation = this._onDidChangePresentation.event;
    this.originalColor = color;
    this._color = color;
    this._colorPresentations = availableColorPresentations;
  }
  selectNextColorPresentation() {
    this.presentationIndex = (this.presentationIndex + 1) % this.colorPresentations.length;
    this.flushColor();
    this._onDidChangePresentation.fire(this.presentation);
  }
  guessColorPresentation(color, originalText) {
    let presentationIndex = -1;
    for (let i = 0; i < this.colorPresentations.length; i++) {
      if (originalText.toLowerCase() === this.colorPresentations[i].label) {
        presentationIndex = i;
        break;
      }
    }
    if (presentationIndex === -1) {
      const originalTextPrefix = originalText.split("(")[0].toLowerCase();
      for (let i = 0; i < this.colorPresentations.length; i++) {
        if (this.colorPresentations[i].label.toLowerCase().startsWith(originalTextPrefix)) {
          presentationIndex = i;
          break;
        }
      }
    }
    if (presentationIndex !== -1 && presentationIndex !== this.presentationIndex) {
      this.presentationIndex = presentationIndex;
      this._onDidChangePresentation.fire(this.presentation);
    }
  }
  flushColor() {
    this._onColorFlushed.fire(this._color);
  }
}
const colorPicker = "";
const $$a = $$d;
class ColorPickerHeader extends Disposable {
  constructor(container2, model, themeService, showingStandaloneColorPicker = false) {
    super();
    this.model = model;
    this.showingStandaloneColorPicker = showingStandaloneColorPicker;
    this._closeButton = null;
    this._domNode = $$a(".colorpicker-header");
    append$1(container2, this._domNode);
    this._pickedColorNode = append$1(this._domNode, $$a(".picked-color"));
    append$1(this._pickedColorNode, $$a("span.codicon.codicon-color-mode"));
    this._pickedColorPresentation = append$1(this._pickedColorNode, document.createElement("span"));
    this._pickedColorPresentation.classList.add("picked-color-presentation");
    const tooltip = localize("clickToToggleColorOptions", "Click to toggle color options (rgb/hsl/hex)");
    this._pickedColorNode.setAttribute("title", tooltip);
    this._originalColorNode = append$1(this._domNode, $$a(".original-color"));
    this._originalColorNode.style.backgroundColor = Color.Format.CSS.format(this.model.originalColor) || "";
    this.backgroundColor = themeService.getColorTheme().getColor(editorHoverBackground) || Color.white;
    this._register(themeService.onDidColorThemeChange((theme) => {
      this.backgroundColor = theme.getColor(editorHoverBackground) || Color.white;
    }));
    this._register(addDisposableListener(this._pickedColorNode, EventType$1.CLICK, () => this.model.selectNextColorPresentation()));
    this._register(addDisposableListener(this._originalColorNode, EventType$1.CLICK, () => {
      this.model.color = this.model.originalColor;
      this.model.flushColor();
    }));
    this._register(model.onDidChangeColor(this.onDidChangeColor, this));
    this._register(model.onDidChangePresentation(this.onDidChangePresentation, this));
    this._pickedColorNode.style.backgroundColor = Color.Format.CSS.format(model.color) || "";
    this._pickedColorNode.classList.toggle("light", model.color.rgba.a < 0.5 ? this.backgroundColor.isLighter() : model.color.isLighter());
    this.onDidChangeColor(this.model.color);
    if (this.showingStandaloneColorPicker) {
      this._domNode.classList.add("standalone-colorpicker");
      this._closeButton = this._register(new CloseButton(this._domNode));
    }
  }
  get closeButton() {
    return this._closeButton;
  }
  get pickedColorNode() {
    return this._pickedColorNode;
  }
  get originalColorNode() {
    return this._originalColorNode;
  }
  onDidChangeColor(color) {
    this._pickedColorNode.style.backgroundColor = Color.Format.CSS.format(color) || "";
    this._pickedColorNode.classList.toggle("light", color.rgba.a < 0.5 ? this.backgroundColor.isLighter() : color.isLighter());
    this.onDidChangePresentation();
  }
  onDidChangePresentation() {
    this._pickedColorPresentation.textContent = this.model.presentation ? this.model.presentation.label : "";
  }
}
class CloseButton extends Disposable {
  constructor(container2) {
    super();
    this._onClicked = this._register(new Emitter$1());
    this.onClicked = this._onClicked.event;
    this._button = document.createElement("div");
    this._button.classList.add("close-button");
    append$1(container2, this._button);
    const innerDiv = document.createElement("div");
    innerDiv.classList.add("close-button-inner-div");
    append$1(this._button, innerDiv);
    const closeButton = append$1(innerDiv, $$a(".button" + ThemeIcon.asCSSSelector(registerIcon("color-picker-close", Codicon.close, localize("closeIcon", "Icon to close the color picker")))));
    closeButton.classList.add("close-icon");
    this._button.onclick = () => {
      this._onClicked.fire();
    };
  }
}
class ColorPickerBody extends Disposable {
  constructor(container2, model, pixelRatio, isStandaloneColorPicker = false) {
    super();
    this.model = model;
    this.pixelRatio = pixelRatio;
    this._insertButton = null;
    this._domNode = $$a(".colorpicker-body");
    append$1(container2, this._domNode);
    this._saturationBox = new SaturationBox(this._domNode, this.model, this.pixelRatio);
    this._register(this._saturationBox);
    this._register(this._saturationBox.onDidChange(this.onDidSaturationValueChange, this));
    this._register(this._saturationBox.onColorFlushed(this.flushColor, this));
    this._opacityStrip = new OpacityStrip(this._domNode, this.model, isStandaloneColorPicker);
    this._register(this._opacityStrip);
    this._register(this._opacityStrip.onDidChange(this.onDidOpacityChange, this));
    this._register(this._opacityStrip.onColorFlushed(this.flushColor, this));
    this._hueStrip = new HueStrip(this._domNode, this.model, isStandaloneColorPicker);
    this._register(this._hueStrip);
    this._register(this._hueStrip.onDidChange(this.onDidHueChange, this));
    this._register(this._hueStrip.onColorFlushed(this.flushColor, this));
    if (isStandaloneColorPicker) {
      this._insertButton = this._register(new InsertButton(this._domNode));
      this._domNode.classList.add("standalone-colorpicker");
    }
  }
  flushColor() {
    this.model.flushColor();
  }
  onDidSaturationValueChange({ s, v }) {
    const hsva = this.model.color.hsva;
    this.model.color = new Color(new HSVA(hsva.h, s, v, hsva.a));
  }
  onDidOpacityChange(a) {
    const hsva = this.model.color.hsva;
    this.model.color = new Color(new HSVA(hsva.h, hsva.s, hsva.v, a));
  }
  onDidHueChange(value) {
    const hsva = this.model.color.hsva;
    const h2 = (1 - value) * 360;
    this.model.color = new Color(new HSVA(h2 === 360 ? 0 : h2, hsva.s, hsva.v, hsva.a));
  }
  get domNode() {
    return this._domNode;
  }
  get saturationBox() {
    return this._saturationBox;
  }
  get enterButton() {
    return this._insertButton;
  }
  layout() {
    this._saturationBox.layout();
    this._opacityStrip.layout();
    this._hueStrip.layout();
  }
}
class SaturationBox extends Disposable {
  constructor(container2, model, pixelRatio) {
    super();
    this.model = model;
    this.pixelRatio = pixelRatio;
    this._onDidChange = new Emitter$1();
    this.onDidChange = this._onDidChange.event;
    this._onColorFlushed = new Emitter$1();
    this.onColorFlushed = this._onColorFlushed.event;
    this._domNode = $$a(".saturation-wrap");
    append$1(container2, this._domNode);
    this._canvas = document.createElement("canvas");
    this._canvas.className = "saturation-box";
    append$1(this._domNode, this._canvas);
    this.selection = $$a(".saturation-selection");
    append$1(this._domNode, this.selection);
    this.layout();
    this._register(addDisposableListener(this._domNode, EventType$1.POINTER_DOWN, (e) => this.onPointerDown(e)));
    this._register(this.model.onDidChangeColor(this.onDidChangeColor, this));
    this.monitor = null;
  }
  get domNode() {
    return this._domNode;
  }
  onPointerDown(e) {
    if (!e.target || !(e.target instanceof Element)) {
      return;
    }
    this.monitor = this._register(new GlobalPointerMoveMonitor());
    const origin = getDomNodePagePosition(this._domNode);
    if (e.target !== this.selection) {
      this.onDidChangePosition(e.offsetX, e.offsetY);
    }
    this.monitor.startMonitoring(e.target, e.pointerId, e.buttons, (event) => this.onDidChangePosition(event.pageX - origin.left, event.pageY - origin.top), () => null);
    const pointerUpListener = addDisposableListener(document, EventType$1.POINTER_UP, () => {
      this._onColorFlushed.fire();
      pointerUpListener.dispose();
      if (this.monitor) {
        this.monitor.stopMonitoring(true);
        this.monitor = null;
      }
    }, true);
  }
  onDidChangePosition(left, top) {
    const s = Math.max(0, Math.min(1, left / this.width));
    const v = Math.max(0, Math.min(1, 1 - top / this.height));
    this.paintSelection(s, v);
    this._onDidChange.fire({ s, v });
  }
  layout() {
    this.width = this._domNode.offsetWidth;
    this.height = this._domNode.offsetHeight;
    this._canvas.width = this.width * this.pixelRatio;
    this._canvas.height = this.height * this.pixelRatio;
    this.paint();
    const hsva = this.model.color.hsva;
    this.paintSelection(hsva.s, hsva.v);
  }
  paint() {
    const hsva = this.model.color.hsva;
    const saturatedColor = new Color(new HSVA(hsva.h, 1, 1, 1));
    const ctx = this._canvas.getContext("2d");
    const whiteGradient = ctx.createLinearGradient(0, 0, this._canvas.width, 0);
    whiteGradient.addColorStop(0, "rgba(255, 255, 255, 1)");
    whiteGradient.addColorStop(0.5, "rgba(255, 255, 255, 0.5)");
    whiteGradient.addColorStop(1, "rgba(255, 255, 255, 0)");
    const blackGradient = ctx.createLinearGradient(0, 0, 0, this._canvas.height);
    blackGradient.addColorStop(0, "rgba(0, 0, 0, 0)");
    blackGradient.addColorStop(1, "rgba(0, 0, 0, 1)");
    ctx.rect(0, 0, this._canvas.width, this._canvas.height);
    ctx.fillStyle = Color.Format.CSS.format(saturatedColor);
    ctx.fill();
    ctx.fillStyle = whiteGradient;
    ctx.fill();
    ctx.fillStyle = blackGradient;
    ctx.fill();
  }
  paintSelection(s, v) {
    this.selection.style.left = `${s * this.width}px`;
    this.selection.style.top = `${this.height - v * this.height}px`;
  }
  onDidChangeColor() {
    if (this.monitor && this.monitor.isMonitoring()) {
      return;
    }
    this.paint();
  }
}
class Strip extends Disposable {
  constructor(container2, model, showingStandaloneColorPicker = false) {
    super();
    this.model = model;
    this._onDidChange = new Emitter$1();
    this.onDidChange = this._onDidChange.event;
    this._onColorFlushed = new Emitter$1();
    this.onColorFlushed = this._onColorFlushed.event;
    if (showingStandaloneColorPicker) {
      this.domNode = append$1(container2, $$a(".standalone-strip"));
      this.overlay = append$1(this.domNode, $$a(".standalone-overlay"));
    } else {
      this.domNode = append$1(container2, $$a(".strip"));
      this.overlay = append$1(this.domNode, $$a(".overlay"));
    }
    this.slider = append$1(this.domNode, $$a(".slider"));
    this.slider.style.top = `0px`;
    this._register(addDisposableListener(this.domNode, EventType$1.POINTER_DOWN, (e) => this.onPointerDown(e)));
    this.layout();
  }
  layout() {
    this.height = this.domNode.offsetHeight - this.slider.offsetHeight;
    const value = this.getValue(this.model.color);
    this.updateSliderPosition(value);
  }
  onPointerDown(e) {
    if (!e.target || !(e.target instanceof Element)) {
      return;
    }
    const monitor = this._register(new GlobalPointerMoveMonitor());
    const origin = getDomNodePagePosition(this.domNode);
    this.domNode.classList.add("grabbing");
    if (e.target !== this.slider) {
      this.onDidChangeTop(e.offsetY);
    }
    monitor.startMonitoring(e.target, e.pointerId, e.buttons, (event) => this.onDidChangeTop(event.pageY - origin.top), () => null);
    const pointerUpListener = addDisposableListener(document, EventType$1.POINTER_UP, () => {
      this._onColorFlushed.fire();
      pointerUpListener.dispose();
      monitor.stopMonitoring(true);
      this.domNode.classList.remove("grabbing");
    }, true);
  }
  onDidChangeTop(top) {
    const value = Math.max(0, Math.min(1, 1 - top / this.height));
    this.updateSliderPosition(value);
    this._onDidChange.fire(value);
  }
  updateSliderPosition(value) {
    this.slider.style.top = `${(1 - value) * this.height}px`;
  }
}
class OpacityStrip extends Strip {
  constructor(container2, model, showingStandaloneColorPicker = false) {
    super(container2, model, showingStandaloneColorPicker);
    this.domNode.classList.add("opacity-strip");
    this._register(model.onDidChangeColor(this.onDidChangeColor, this));
    this.onDidChangeColor(this.model.color);
  }
  onDidChangeColor(color) {
    const { r, g, b } = color.rgba;
    const opaque = new Color(new RGBA(r, g, b, 1));
    const transparent2 = new Color(new RGBA(r, g, b, 0));
    this.overlay.style.background = `linear-gradient(to bottom, ${opaque} 0%, ${transparent2} 100%)`;
  }
  getValue(color) {
    return color.hsva.a;
  }
}
class HueStrip extends Strip {
  constructor(container2, model, showingStandaloneColorPicker = false) {
    super(container2, model, showingStandaloneColorPicker);
    this.domNode.classList.add("hue-strip");
  }
  getValue(color) {
    return 1 - color.hsva.h / 360;
  }
}
class InsertButton extends Disposable {
  constructor(container2) {
    super();
    this._onClicked = this._register(new Emitter$1());
    this.onClicked = this._onClicked.event;
    this._button = append$1(container2, document.createElement("button"));
    this._button.classList.add("insert-button");
    this._button.textContent = "Insert";
    this._button.onclick = (e) => {
      this._onClicked.fire();
    };
  }
  get button() {
    return this._button;
  }
}
class ColorPickerWidget extends Widget$1 {
  constructor(container2, model, pixelRatio, themeService, standaloneColorPicker = false) {
    super();
    this.model = model;
    this.pixelRatio = pixelRatio;
    this._register(PixelRatio.onDidChange(() => this.layout()));
    const element = $$a(".colorpicker-widget");
    container2.appendChild(element);
    this.header = this._register(new ColorPickerHeader(element, this.model, themeService, standaloneColorPicker));
    this.body = this._register(new ColorPickerBody(element, this.model, this.pixelRatio, standaloneColorPicker));
  }
  layout() {
    this.body.layout();
  }
}
var __decorate$1I = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1F = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$1a = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class ColorHover {
  constructor(owner, range2, model, provider) {
    this.owner = owner;
    this.range = range2;
    this.model = model;
    this.provider = provider;
    this.forceShowAtRange = true;
  }
  isValidForHoverAnchor(anchor) {
    return anchor.type === 1 && this.range.startColumn <= anchor.range.startColumn && this.range.endColumn >= anchor.range.endColumn;
  }
}
let ColorHoverParticipant = class ColorHoverParticipant2 {
  constructor(_editor, _themeService) {
    this._editor = _editor;
    this._themeService = _themeService;
    this.hoverOrdinal = 2;
  }
  computeSync(_anchor, _lineDecorations) {
    return [];
  }
  computeAsync(anchor, lineDecorations, token) {
    return AsyncIterableObject.fromPromise(this._computeAsync(anchor, lineDecorations, token));
  }
  _computeAsync(_anchor, lineDecorations, _token) {
    return __awaiter$1a(this, void 0, void 0, function* () {
      if (!this._editor.hasModel()) {
        return [];
      }
      const colorDetector = ColorDetector.get(this._editor);
      if (!colorDetector) {
        return [];
      }
      for (const d of lineDecorations) {
        if (!colorDetector.isColorDecoration(d)) {
          continue;
        }
        const colorData = colorDetector.getColorData(d.range.getStartPosition());
        if (colorData) {
          const colorHover = yield _createColorHover(this, this._editor.getModel(), colorData.colorInfo, colorData.provider);
          return [colorHover];
        }
      }
      return [];
    });
  }
  renderHoverParts(context, hoverParts) {
    return renderHoverParts(this, this._editor, this._themeService, hoverParts, context);
  }
};
ColorHoverParticipant = __decorate$1I([
  __param$1F(1, IThemeService)
], ColorHoverParticipant);
class StandaloneColorPickerHover {
  constructor(owner, range2, model, provider) {
    this.owner = owner;
    this.range = range2;
    this.model = model;
    this.provider = provider;
  }
}
let StandaloneColorPickerParticipant = class StandaloneColorPickerParticipant2 {
  constructor(_editor, _themeService) {
    this._editor = _editor;
    this._themeService = _themeService;
    this._color = null;
  }
  createColorHover(defaultColorInfo, defaultColorProvider, colorProviderRegistry) {
    return __awaiter$1a(this, void 0, void 0, function* () {
      if (!this._editor.hasModel()) {
        return null;
      }
      const colorDetector = ColorDetector.get(this._editor);
      if (!colorDetector) {
        return null;
      }
      const colors = yield getColors(colorProviderRegistry, this._editor.getModel(), CancellationToken.None);
      let foundColorInfo = null;
      let foundColorProvider = null;
      for (const colorData of colors) {
        const colorInfo2 = colorData.colorInfo;
        if (Range$2.containsRange(colorInfo2.range, defaultColorInfo.range)) {
          foundColorInfo = colorInfo2;
          foundColorProvider = colorData.provider;
        }
      }
      const colorInfo = foundColorInfo !== null && foundColorInfo !== void 0 ? foundColorInfo : defaultColorInfo;
      const colorProvider = foundColorProvider !== null && foundColorProvider !== void 0 ? foundColorProvider : defaultColorProvider;
      const foundInEditor = !!foundColorInfo;
      return { colorHover: yield _createColorHover(this, this._editor.getModel(), colorInfo, colorProvider), foundInEditor };
    });
  }
  updateEditorModel(colorHoverData) {
    return __awaiter$1a(this, void 0, void 0, function* () {
      if (!this._editor.hasModel()) {
        return;
      }
      const colorPickerModel = colorHoverData.model;
      let range2 = new Range$2(colorHoverData.range.startLineNumber, colorHoverData.range.startColumn, colorHoverData.range.endLineNumber, colorHoverData.range.endColumn);
      if (this._color) {
        yield _updateColorPresentations(this._editor.getModel(), colorPickerModel, this._color, range2, colorHoverData);
        range2 = _updateEditorModel(this._editor, range2, colorPickerModel);
      }
    });
  }
  renderHoverParts(context, hoverParts) {
    return renderHoverParts(this, this._editor, this._themeService, hoverParts, context);
  }
  set color(color) {
    this._color = color;
  }
  get color() {
    return this._color;
  }
};
StandaloneColorPickerParticipant = __decorate$1I([
  __param$1F(1, IThemeService)
], StandaloneColorPickerParticipant);
function _createColorHover(participant, editorModel, colorInfo, provider) {
  return __awaiter$1a(this, void 0, void 0, function* () {
    const originalText = editorModel.getValueInRange(colorInfo.range);
    const { red, green, blue, alpha } = colorInfo.color;
    const rgba = new RGBA(Math.round(red * 255), Math.round(green * 255), Math.round(blue * 255), alpha);
    const color = new Color(rgba);
    const colorPresentations = yield getColorPresentations(editorModel, colorInfo, provider, CancellationToken.None);
    const model = new ColorPickerModel(color, [], 0);
    model.colorPresentations = colorPresentations || [];
    model.guessColorPresentation(color, originalText);
    if (participant instanceof ColorHoverParticipant) {
      return new ColorHover(participant, Range$2.lift(colorInfo.range), model, provider);
    } else {
      return new StandaloneColorPickerHover(participant, Range$2.lift(colorInfo.range), model, provider);
    }
  });
}
function renderHoverParts(participant, editor2, themeService, hoverParts, context) {
  if (hoverParts.length === 0 || !editor2.hasModel()) {
    return Disposable.None;
  }
  if (context.setMinimumDimensions) {
    const minimumHeight = editor2.getOption(
      65
      /* EditorOption.lineHeight */
    ) + 8;
    context.setMinimumDimensions(new Dimension(302, minimumHeight));
  }
  const disposables = new DisposableStore();
  const colorHover = hoverParts[0];
  const editorModel = editor2.getModel();
  const model = colorHover.model;
  const widget = disposables.add(new ColorPickerWidget(context.fragment, model, editor2.getOption(
    140
    /* EditorOption.pixelRatio */
  ), themeService, participant instanceof StandaloneColorPickerParticipant));
  context.setColorPicker(widget);
  let editorUpdatedByColorPicker = false;
  let range2 = new Range$2(colorHover.range.startLineNumber, colorHover.range.startColumn, colorHover.range.endLineNumber, colorHover.range.endColumn);
  if (participant instanceof StandaloneColorPickerParticipant) {
    const color = hoverParts[0].model.color;
    participant.color = color;
    _updateColorPresentations(editorModel, model, color, range2, colorHover);
    disposables.add(model.onColorFlushed((color2) => {
      participant.color = color2;
    }));
  } else {
    disposables.add(model.onColorFlushed((color) => __awaiter$1a(this, void 0, void 0, function* () {
      yield _updateColorPresentations(editorModel, model, color, range2, colorHover);
      editorUpdatedByColorPicker = true;
      range2 = _updateEditorModel(editor2, range2, model, context);
    })));
  }
  disposables.add(model.onDidChangeColor((color) => {
    _updateColorPresentations(editorModel, model, color, range2, colorHover);
  }));
  disposables.add(editor2.onDidChangeModelContent((e) => {
    if (editorUpdatedByColorPicker) {
      editorUpdatedByColorPicker = false;
    } else {
      context.hide();
      editor2.focus();
    }
  }));
  return disposables;
}
function _updateEditorModel(editor2, range2, model, context) {
  let textEdits;
  let newRange;
  if (model.presentation.textEdit) {
    textEdits = [model.presentation.textEdit];
    newRange = new Range$2(model.presentation.textEdit.range.startLineNumber, model.presentation.textEdit.range.startColumn, model.presentation.textEdit.range.endLineNumber, model.presentation.textEdit.range.endColumn);
    const trackedRange = editor2.getModel()._setTrackedRange(
      null,
      newRange,
      3
      /* TrackedRangeStickiness.GrowsOnlyWhenTypingAfter */
    );
    editor2.pushUndoStop();
    editor2.executeEdits("colorpicker", textEdits);
    newRange = editor2.getModel()._getTrackedRange(trackedRange) || newRange;
  } else {
    textEdits = [{ range: range2, text: model.presentation.label, forceMoveMarkers: false }];
    newRange = range2.setEndPosition(range2.endLineNumber, range2.startColumn + model.presentation.label.length);
    editor2.pushUndoStop();
    editor2.executeEdits("colorpicker", textEdits);
  }
  if (model.presentation.additionalTextEdits) {
    textEdits = [...model.presentation.additionalTextEdits];
    editor2.executeEdits("colorpicker", textEdits);
    if (context) {
      context.hide();
    }
  }
  editor2.pushUndoStop();
  return newRange;
}
function _updateColorPresentations(editorModel, colorPickerModel, color, range2, colorHover) {
  return __awaiter$1a(this, void 0, void 0, function* () {
    const colorPresentations = yield getColorPresentations(editorModel, {
      range: range2,
      color: {
        red: color.rgba.r / 255,
        green: color.rgba.g / 255,
        blue: color.rgba.b / 255,
        alpha: color.rgba.a
      }
    }, colorHover.provider, CancellationToken.None);
    colorPickerModel.colorPresentations = colorPresentations || [];
  });
}
const goToDefinitionAtPosition = "";
function hasModifier(e, modifier) {
  return !!e[modifier];
}
class ClickLinkMouseEvent {
  constructor(source, opts) {
    this.target = source.target;
    this.isLeftClick = source.event.leftButton;
    this.isMiddleClick = source.event.middleButton;
    this.isRightClick = source.event.rightButton;
    this.hasTriggerModifier = hasModifier(source.event, opts.triggerModifier);
    this.hasSideBySideModifier = hasModifier(source.event, opts.triggerSideBySideModifier);
    this.isNoneOrSingleMouseDown = source.event.detail <= 1;
  }
}
class ClickLinkKeyboardEvent {
  constructor(source, opts) {
    this.keyCodeIsTriggerKey = source.keyCode === opts.triggerKey;
    this.keyCodeIsSideBySideKey = source.keyCode === opts.triggerSideBySideKey;
    this.hasTriggerModifier = hasModifier(source, opts.triggerModifier);
  }
}
class ClickLinkOptions {
  constructor(triggerKey, triggerModifier, triggerSideBySideKey, triggerSideBySideModifier) {
    this.triggerKey = triggerKey;
    this.triggerModifier = triggerModifier;
    this.triggerSideBySideKey = triggerSideBySideKey;
    this.triggerSideBySideModifier = triggerSideBySideModifier;
  }
  equals(other) {
    return this.triggerKey === other.triggerKey && this.triggerModifier === other.triggerModifier && this.triggerSideBySideKey === other.triggerSideBySideKey && this.triggerSideBySideModifier === other.triggerSideBySideModifier;
  }
}
function createOptions(multiCursorModifier) {
  if (multiCursorModifier === "altKey") {
    if (isMacintosh) {
      return new ClickLinkOptions(57, "metaKey", 6, "altKey");
    }
    return new ClickLinkOptions(5, "ctrlKey", 6, "altKey");
  }
  if (isMacintosh) {
    return new ClickLinkOptions(6, "altKey", 57, "metaKey");
  }
  return new ClickLinkOptions(6, "altKey", 5, "ctrlKey");
}
class ClickLinkGesture extends Disposable {
  constructor(editor2, alwaysFireOnMouseUp) {
    super();
    this._onMouseMoveOrRelevantKeyDown = this._register(new Emitter$1());
    this.onMouseMoveOrRelevantKeyDown = this._onMouseMoveOrRelevantKeyDown.event;
    this._onExecute = this._register(new Emitter$1());
    this.onExecute = this._onExecute.event;
    this._onCancel = this._register(new Emitter$1());
    this.onCancel = this._onCancel.event;
    this._editor = editor2;
    this._alwaysFireExecuteOnMouseUp = alwaysFireOnMouseUp;
    this._opts = createOptions(this._editor.getOption(
      76
      /* EditorOption.multiCursorModifier */
    ));
    this._lastMouseMoveEvent = null;
    this._hasTriggerKeyOnMouseDown = false;
    this._lineNumberOnMouseDown = 0;
    this._register(this._editor.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        76
        /* EditorOption.multiCursorModifier */
      )) {
        const newOpts = createOptions(this._editor.getOption(
          76
          /* EditorOption.multiCursorModifier */
        ));
        if (this._opts.equals(newOpts)) {
          return;
        }
        this._opts = newOpts;
        this._lastMouseMoveEvent = null;
        this._hasTriggerKeyOnMouseDown = false;
        this._lineNumberOnMouseDown = 0;
        this._onCancel.fire();
      }
    }));
    this._register(this._editor.onMouseMove((e) => this._onEditorMouseMove(new ClickLinkMouseEvent(e, this._opts))));
    this._register(this._editor.onMouseDown((e) => this._onEditorMouseDown(new ClickLinkMouseEvent(e, this._opts))));
    this._register(this._editor.onMouseUp((e) => this._onEditorMouseUp(new ClickLinkMouseEvent(e, this._opts))));
    this._register(this._editor.onKeyDown((e) => this._onEditorKeyDown(new ClickLinkKeyboardEvent(e, this._opts))));
    this._register(this._editor.onKeyUp((e) => this._onEditorKeyUp(new ClickLinkKeyboardEvent(e, this._opts))));
    this._register(this._editor.onMouseDrag(() => this._resetHandler()));
    this._register(this._editor.onDidChangeCursorSelection((e) => this._onDidChangeCursorSelection(e)));
    this._register(this._editor.onDidChangeModel((e) => this._resetHandler()));
    this._register(this._editor.onDidChangeModelContent(() => this._resetHandler()));
    this._register(this._editor.onDidScrollChange((e) => {
      if (e.scrollTopChanged || e.scrollLeftChanged) {
        this._resetHandler();
      }
    }));
  }
  _onDidChangeCursorSelection(e) {
    if (e.selection && e.selection.startColumn !== e.selection.endColumn) {
      this._resetHandler();
    }
  }
  _onEditorMouseMove(mouseEvent) {
    this._lastMouseMoveEvent = mouseEvent;
    this._onMouseMoveOrRelevantKeyDown.fire([mouseEvent, null]);
  }
  _onEditorMouseDown(mouseEvent) {
    this._hasTriggerKeyOnMouseDown = mouseEvent.hasTriggerModifier;
    this._lineNumberOnMouseDown = mouseEvent.target.position ? mouseEvent.target.position.lineNumber : 0;
  }
  _onEditorMouseUp(mouseEvent) {
    const currentLineNumber = mouseEvent.target.position ? mouseEvent.target.position.lineNumber : 0;
    if (this._hasTriggerKeyOnMouseDown && this._lineNumberOnMouseDown && this._lineNumberOnMouseDown === currentLineNumber || this._alwaysFireExecuteOnMouseUp) {
      this._onExecute.fire(mouseEvent);
    }
  }
  _onEditorKeyDown(e) {
    if (this._lastMouseMoveEvent && (e.keyCodeIsTriggerKey || e.keyCodeIsSideBySideKey && e.hasTriggerModifier)) {
      this._onMouseMoveOrRelevantKeyDown.fire([this._lastMouseMoveEvent, e]);
    } else if (e.hasTriggerModifier) {
      this._onCancel.fire();
    }
  }
  _onEditorKeyUp(e) {
    if (e.keyCodeIsTriggerKey) {
      this._onCancel.fire();
    }
  }
  _resetHandler() {
    this._lastMouseMoveEvent = null;
    this._hasTriggerKeyOnMouseDown = false;
    this._onCancel.fire();
  }
}
const peekViewWidget = "";
var __decorate$1H = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1E = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let EmbeddedCodeEditorWidget = class EmbeddedCodeEditorWidget2 extends CodeEditorWidget {
  constructor(domElement, options, codeEditorWidgetOptions, parentEditor, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService, languageConfigurationService, languageFeaturesService) {
    super(domElement, Object.assign(Object.assign({}, parentEditor.getRawOptions()), { overflowWidgetsDomNode: parentEditor.getOverflowWidgetsDomNode() }), codeEditorWidgetOptions, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService, languageConfigurationService, languageFeaturesService);
    this._parentEditor = parentEditor;
    this._overwriteOptions = options;
    super.updateOptions(this._overwriteOptions);
    this._register(parentEditor.onDidChangeConfiguration((e) => this._onParentConfigurationChanged(e)));
  }
  getParentEditor() {
    return this._parentEditor;
  }
  _onParentConfigurationChanged(e) {
    super.updateOptions(this._parentEditor.getRawOptions());
    super.updateOptions(this._overwriteOptions);
  }
  updateOptions(newOptions) {
    mixin(this._overwriteOptions, newOptions, true);
    super.updateOptions(this._overwriteOptions);
  }
};
EmbeddedCodeEditorWidget = __decorate$1H([
  __param$1E(4, IInstantiationService),
  __param$1E(5, ICodeEditorService),
  __param$1E(6, ICommandService),
  __param$1E(7, IContextKeyService),
  __param$1E(8, IThemeService),
  __param$1E(9, INotificationService),
  __param$1E(10, IAccessibilityService),
  __param$1E(11, ILanguageConfigurationService),
  __param$1E(12, ILanguageFeaturesService)
], EmbeddedCodeEditorWidget);
const zoneWidget = "";
const defaultColor = new Color(new RGBA(0, 122, 204));
const defaultOptions$2 = {
  showArrow: true,
  showFrame: true,
  className: "",
  frameColor: defaultColor,
  arrowColor: defaultColor,
  keepEditorSelection: false
};
const WIDGET_ID = "vs.editor.contrib.zoneWidget";
class ViewZoneDelegate {
  constructor(domNode, afterLineNumber, afterColumn, heightInLines, onDomNodeTop, onComputedHeight, showInHiddenAreas, ordinal) {
    this.id = "";
    this.domNode = domNode;
    this.afterLineNumber = afterLineNumber;
    this.afterColumn = afterColumn;
    this.heightInLines = heightInLines;
    this.showInHiddenAreas = showInHiddenAreas;
    this.ordinal = ordinal;
    this._onDomNodeTop = onDomNodeTop;
    this._onComputedHeight = onComputedHeight;
  }
  onDomNodeTop(top) {
    this._onDomNodeTop(top);
  }
  onComputedHeight(height) {
    this._onComputedHeight(height);
  }
}
class OverlayWidgetDelegate {
  constructor(id3, domNode) {
    this._id = id3;
    this._domNode = domNode;
  }
  getId() {
    return this._id;
  }
  getDomNode() {
    return this._domNode;
  }
  getPosition() {
    return null;
  }
}
class Arrow {
  constructor(_editor) {
    this._editor = _editor;
    this._ruleName = Arrow._IdGenerator.nextId();
    this._decorations = this._editor.createDecorationsCollection();
    this._color = null;
    this._height = -1;
  }
  dispose() {
    this.hide();
    removeCSSRulesContainingSelector(this._ruleName);
  }
  set color(value) {
    if (this._color !== value) {
      this._color = value;
      this._updateStyle();
    }
  }
  set height(value) {
    if (this._height !== value) {
      this._height = value;
      this._updateStyle();
    }
  }
  _updateStyle() {
    removeCSSRulesContainingSelector(this._ruleName);
    createCSSRule(`.monaco-editor ${this._ruleName}`, `border-style: solid; border-color: transparent; border-bottom-color: ${this._color}; border-width: ${this._height}px; bottom: -${this._height}px; margin-left: -${this._height}px; `);
  }
  show(where) {
    if (where.column === 1) {
      where = { lineNumber: where.lineNumber, column: 2 };
    }
    this._decorations.set([{
      range: Range$2.fromPositions(where),
      options: {
        description: "zone-widget-arrow",
        className: this._ruleName,
        stickiness: 1
        /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
      }
    }]);
  }
  hide() {
    this._decorations.clear();
  }
}
Arrow._IdGenerator = new IdGenerator(".arrow-decoration-");
class ZoneWidget {
  constructor(editor2, options = {}) {
    this._arrow = null;
    this._overlayWidget = null;
    this._resizeSash = null;
    this._viewZone = null;
    this._disposables = new DisposableStore();
    this.container = null;
    this._isShowing = false;
    this.editor = editor2;
    this._positionMarkerId = this.editor.createDecorationsCollection();
    this.options = deepClone(options);
    mixin(this.options, defaultOptions$2, false);
    this.domNode = document.createElement("div");
    if (!this.options.isAccessible) {
      this.domNode.setAttribute("aria-hidden", "true");
      this.domNode.setAttribute("role", "presentation");
    }
    this._disposables.add(this.editor.onDidLayoutChange((info) => {
      const width = this._getWidth(info);
      this.domNode.style.width = width + "px";
      this.domNode.style.left = this._getLeft(info) + "px";
      this._onWidth(width);
    }));
  }
  dispose() {
    if (this._overlayWidget) {
      this.editor.removeOverlayWidget(this._overlayWidget);
      this._overlayWidget = null;
    }
    if (this._viewZone) {
      this.editor.changeViewZones((accessor) => {
        if (this._viewZone) {
          accessor.removeZone(this._viewZone.id);
        }
        this._viewZone = null;
      });
    }
    this._positionMarkerId.clear();
    this._disposables.dispose();
  }
  create() {
    this.domNode.classList.add("zone-widget");
    if (this.options.className) {
      this.domNode.classList.add(this.options.className);
    }
    this.container = document.createElement("div");
    this.container.classList.add("zone-widget-container");
    this.domNode.appendChild(this.container);
    if (this.options.showArrow) {
      this._arrow = new Arrow(this.editor);
      this._disposables.add(this._arrow);
    }
    this._fillContainer(this.container);
    this._initSash();
    this._applyStyles();
  }
  style(styles) {
    if (styles.frameColor) {
      this.options.frameColor = styles.frameColor;
    }
    if (styles.arrowColor) {
      this.options.arrowColor = styles.arrowColor;
    }
    this._applyStyles();
  }
  _applyStyles() {
    if (this.container && this.options.frameColor) {
      const frameColor = this.options.frameColor.toString();
      this.container.style.borderTopColor = frameColor;
      this.container.style.borderBottomColor = frameColor;
    }
    if (this._arrow && this.options.arrowColor) {
      const arrowColor = this.options.arrowColor.toString();
      this._arrow.color = arrowColor;
    }
  }
  _getWidth(info) {
    return info.width - info.minimap.minimapWidth - info.verticalScrollbarWidth;
  }
  _getLeft(info) {
    if (info.minimap.minimapWidth > 0 && info.minimap.minimapLeft === 0) {
      return info.minimap.minimapWidth;
    }
    return 0;
  }
  _onViewZoneTop(top) {
    this.domNode.style.top = top + "px";
  }
  _onViewZoneHeight(height) {
    var _a2;
    this.domNode.style.height = `${height}px`;
    if (this.container) {
      const containerHeight = height - this._decoratingElementsHeight();
      this.container.style.height = `${containerHeight}px`;
      const layoutInfo = this.editor.getLayoutInfo();
      this._doLayout(containerHeight, this._getWidth(layoutInfo));
    }
    (_a2 = this._resizeSash) === null || _a2 === void 0 ? void 0 : _a2.layout();
  }
  get position() {
    const range2 = this._positionMarkerId.getRange(0);
    if (!range2) {
      return void 0;
    }
    return range2.getStartPosition();
  }
  show(rangeOrPos, heightInLines) {
    const range2 = Range$2.isIRange(rangeOrPos) ? Range$2.lift(rangeOrPos) : Range$2.fromPositions(rangeOrPos);
    this._isShowing = true;
    this._showImpl(range2, heightInLines);
    this._isShowing = false;
    this._positionMarkerId.set([{ range: range2, options: ModelDecorationOptions.EMPTY }]);
  }
  hide() {
    var _a2;
    if (this._viewZone) {
      this.editor.changeViewZones((accessor) => {
        if (this._viewZone) {
          accessor.removeZone(this._viewZone.id);
        }
      });
      this._viewZone = null;
    }
    if (this._overlayWidget) {
      this.editor.removeOverlayWidget(this._overlayWidget);
      this._overlayWidget = null;
    }
    (_a2 = this._arrow) === null || _a2 === void 0 ? void 0 : _a2.hide();
    this._positionMarkerId.clear();
  }
  _decoratingElementsHeight() {
    const lineHeight = this.editor.getOption(
      65
      /* EditorOption.lineHeight */
    );
    let result2 = 0;
    if (this.options.showArrow) {
      const arrowHeight = Math.round(lineHeight / 3);
      result2 += 2 * arrowHeight;
    }
    if (this.options.showFrame) {
      const frameThickness = Math.round(lineHeight / 9);
      result2 += 2 * frameThickness;
    }
    return result2;
  }
  _showImpl(where, heightInLines) {
    const position = where.getStartPosition();
    const layoutInfo = this.editor.getLayoutInfo();
    const width = this._getWidth(layoutInfo);
    this.domNode.style.width = `${width}px`;
    this.domNode.style.left = this._getLeft(layoutInfo) + "px";
    const viewZoneDomNode = document.createElement("div");
    viewZoneDomNode.style.overflow = "hidden";
    const lineHeight = this.editor.getOption(
      65
      /* EditorOption.lineHeight */
    );
    if (!this.options.allowUnlimitedHeight) {
      const maxHeightInLines = Math.max(12, this.editor.getLayoutInfo().height / lineHeight * 0.8);
      heightInLines = Math.min(heightInLines, maxHeightInLines);
    }
    let arrowHeight = 0;
    let frameThickness = 0;
    if (this._arrow && this.options.showArrow) {
      arrowHeight = Math.round(lineHeight / 3);
      this._arrow.height = arrowHeight;
      this._arrow.show(position);
    }
    if (this.options.showFrame) {
      frameThickness = Math.round(lineHeight / 9);
    }
    this.editor.changeViewZones((accessor) => {
      if (this._viewZone) {
        accessor.removeZone(this._viewZone.id);
      }
      if (this._overlayWidget) {
        this.editor.removeOverlayWidget(this._overlayWidget);
        this._overlayWidget = null;
      }
      this.domNode.style.top = "-1000px";
      this._viewZone = new ViewZoneDelegate(viewZoneDomNode, position.lineNumber, position.column, heightInLines, (top) => this._onViewZoneTop(top), (height) => this._onViewZoneHeight(height), this.options.showInHiddenAreas, this.options.ordinal);
      this._viewZone.id = accessor.addZone(this._viewZone);
      this._overlayWidget = new OverlayWidgetDelegate(WIDGET_ID + this._viewZone.id, this.domNode);
      this.editor.addOverlayWidget(this._overlayWidget);
    });
    if (this.container && this.options.showFrame) {
      const width2 = this.options.frameWidth ? this.options.frameWidth : frameThickness;
      this.container.style.borderTopWidth = width2 + "px";
      this.container.style.borderBottomWidth = width2 + "px";
    }
    const containerHeight = heightInLines * lineHeight - this._decoratingElementsHeight();
    if (this.container) {
      this.container.style.top = arrowHeight + "px";
      this.container.style.height = containerHeight + "px";
      this.container.style.overflow = "hidden";
    }
    this._doLayout(containerHeight, width);
    if (!this.options.keepEditorSelection) {
      this.editor.setSelection(where);
    }
    const model = this.editor.getModel();
    if (model) {
      const range2 = model.validateRange(new Range$2(where.startLineNumber, 1, where.endLineNumber + 1, 1));
      this.revealRange(range2, range2.startLineNumber === model.getLineCount());
    }
  }
  revealRange(range2, isLastLine) {
    if (isLastLine) {
      this.editor.revealLineNearTop(
        range2.endLineNumber,
        0
        /* ScrollType.Smooth */
      );
    } else {
      this.editor.revealRange(
        range2,
        0
        /* ScrollType.Smooth */
      );
    }
  }
  setCssClass(className3, classToReplace) {
    if (!this.container) {
      return;
    }
    if (classToReplace) {
      this.container.classList.remove(classToReplace);
    }
    this.container.classList.add(className3);
  }
  _onWidth(widthInPixel) {
  }
  _doLayout(heightInPixel, widthInPixel) {
  }
  _relayout(newHeightInLines) {
    if (this._viewZone && this._viewZone.heightInLines !== newHeightInLines) {
      this.editor.changeViewZones((accessor) => {
        if (this._viewZone) {
          this._viewZone.heightInLines = newHeightInLines;
          accessor.layoutZone(this._viewZone.id);
        }
      });
    }
  }
  // --- sash
  _initSash() {
    if (this._resizeSash) {
      return;
    }
    this._resizeSash = this._disposables.add(new Sash(this.domNode, this, {
      orientation: 1
      /* Orientation.HORIZONTAL */
    }));
    if (!this.options.isResizeable) {
      this._resizeSash.state = 0;
    }
    let data;
    this._disposables.add(this._resizeSash.onDidStart((e) => {
      if (this._viewZone) {
        data = {
          startY: e.startY,
          heightInLines: this._viewZone.heightInLines
        };
      }
    }));
    this._disposables.add(this._resizeSash.onDidEnd(() => {
      data = void 0;
    }));
    this._disposables.add(this._resizeSash.onDidChange((evt) => {
      if (data) {
        const lineDelta = (evt.currentY - data.startY) / this.editor.getOption(
          65
          /* EditorOption.lineHeight */
        );
        const roundedLineDelta = lineDelta < 0 ? Math.ceil(lineDelta) : Math.floor(lineDelta);
        const newHeightInLines = data.heightInLines + roundedLineDelta;
        if (newHeightInLines > 5 && newHeightInLines < 35) {
          this._relayout(newHeightInLines);
        }
      }
    }));
  }
  getHorizontalSashLeft() {
    return 0;
  }
  getHorizontalSashTop() {
    return (this.domNode.style.height === null ? 0 : parseInt(this.domNode.style.height)) - this._decoratingElementsHeight() / 2;
  }
  getHorizontalSashWidth() {
    const layoutInfo = this.editor.getLayoutInfo();
    return layoutInfo.width - layoutInfo.minimap.minimapWidth;
  }
}
const dropdown = "";
class BaseDropdown extends ActionRunner {
  constructor(container2, options) {
    super();
    this._onDidChangeVisibility = this._register(new Emitter$1());
    this.onDidChangeVisibility = this._onDidChangeVisibility.event;
    this._element = append$1(container2, $$d(".monaco-dropdown"));
    this._label = append$1(this._element, $$d(".dropdown-label"));
    let labelRenderer = options.labelRenderer;
    if (!labelRenderer) {
      labelRenderer = (container3) => {
        container3.textContent = options.label || "";
        return null;
      };
    }
    for (const event of [EventType$1.CLICK, EventType$1.MOUSE_DOWN, EventType.Tap]) {
      this._register(addDisposableListener(this.element, event, (e) => EventHelper.stop(e, true)));
    }
    for (const event of [EventType$1.MOUSE_DOWN, EventType.Tap]) {
      this._register(addDisposableListener(this._label, event, (e) => {
        if (e instanceof MouseEvent && (e.detail > 1 || e.button !== 0)) {
          return;
        }
        if (this.visible) {
          this.hide();
        } else {
          this.show();
        }
      }));
    }
    this._register(addDisposableListener(this._label, EventType$1.KEY_UP, (e) => {
      const event = new StandardKeyboardEvent(e);
      if (event.equals(
        3
        /* KeyCode.Enter */
      ) || event.equals(
        10
        /* KeyCode.Space */
      )) {
        EventHelper.stop(e, true);
        if (this.visible) {
          this.hide();
        } else {
          this.show();
        }
      }
    }));
    const cleanupFn = labelRenderer(this._label);
    if (cleanupFn) {
      this._register(cleanupFn);
    }
    this._register(Gesture.addTarget(this._label));
  }
  get element() {
    return this._element;
  }
  show() {
    if (!this.visible) {
      this.visible = true;
      this._onDidChangeVisibility.fire(true);
    }
  }
  hide() {
    if (this.visible) {
      this.visible = false;
      this._onDidChangeVisibility.fire(false);
    }
  }
  dispose() {
    super.dispose();
    this.hide();
    if (this.boxContainer) {
      this.boxContainer.remove();
      this.boxContainer = void 0;
    }
    if (this.contents) {
      this.contents.remove();
      this.contents = void 0;
    }
    if (this._label) {
      this._label.remove();
      this._label = void 0;
    }
  }
}
class DropdownMenu extends BaseDropdown {
  constructor(container2, _options) {
    super(container2, _options);
    this._options = _options;
    this._actions = [];
    this.actions = _options.actions || [];
  }
  set menuOptions(options) {
    this._menuOptions = options;
  }
  get menuOptions() {
    return this._menuOptions;
  }
  get actions() {
    if (this._options.actionProvider) {
      return this._options.actionProvider.getActions();
    }
    return this._actions;
  }
  set actions(actions) {
    this._actions = actions;
  }
  show() {
    super.show();
    this.element.classList.add("active");
    this._options.contextMenuProvider.showContextMenu({
      getAnchor: () => this.element,
      getActions: () => this.actions,
      getActionsContext: () => this.menuOptions ? this.menuOptions.context : null,
      getActionViewItem: (action, options) => this.menuOptions && this.menuOptions.actionViewItemProvider ? this.menuOptions.actionViewItemProvider(action, options) : void 0,
      getKeyBinding: (action) => this.menuOptions && this.menuOptions.getKeyBinding ? this.menuOptions.getKeyBinding(action) : void 0,
      getMenuClassName: () => this._options.menuClassName || "",
      onHide: () => this.onHide(),
      actionRunner: this.menuOptions ? this.menuOptions.actionRunner : void 0,
      anchorAlignment: this.menuOptions ? this.menuOptions.anchorAlignment : 0,
      domForShadowRoot: this._options.menuAsChild ? this.element : void 0,
      skipTelemetry: this._options.skipTelemetry
    });
  }
  hide() {
    super.hide();
  }
  onHide() {
    this.hide();
    this.element.classList.remove("active");
  }
}
class DropdownMenuActionViewItem extends BaseActionViewItem {
  constructor(action, menuActionsOrProvider, contextMenuProvider, options = /* @__PURE__ */ Object.create(null)) {
    super(null, action, options);
    this.actionItem = null;
    this._onDidChangeVisibility = this._register(new Emitter$1());
    this.onDidChangeVisibility = this._onDidChangeVisibility.event;
    this.menuActionsOrProvider = menuActionsOrProvider;
    this.contextMenuProvider = contextMenuProvider;
    this.options = options;
    if (this.options.actionRunner) {
      this.actionRunner = this.options.actionRunner;
    }
  }
  render(container2) {
    this.actionItem = container2;
    const labelRenderer = (el) => {
      this.element = append$1(el, $$d("a.action-label"));
      let classNames = [];
      if (typeof this.options.classNames === "string") {
        classNames = this.options.classNames.split(/\s+/g).filter((s) => !!s);
      } else if (this.options.classNames) {
        classNames = this.options.classNames;
      }
      if (!classNames.find((c) => c === "icon")) {
        classNames.push("codicon");
      }
      this.element.classList.add(...classNames);
      this.element.setAttribute("role", "button");
      this.element.setAttribute("aria-haspopup", "true");
      this.element.setAttribute("aria-expanded", "false");
      this.element.title = this._action.label || "";
      this.element.ariaLabel = this._action.label || "";
      return null;
    };
    const isActionsArray = Array.isArray(this.menuActionsOrProvider);
    const options = {
      contextMenuProvider: this.contextMenuProvider,
      labelRenderer,
      menuAsChild: this.options.menuAsChild,
      actions: isActionsArray ? this.menuActionsOrProvider : void 0,
      actionProvider: isActionsArray ? void 0 : this.menuActionsOrProvider,
      skipTelemetry: this.options.skipTelemetry
    };
    this.dropdownMenu = this._register(new DropdownMenu(container2, options));
    this._register(this.dropdownMenu.onDidChangeVisibility((visible) => {
      var _a2;
      (_a2 = this.element) === null || _a2 === void 0 ? void 0 : _a2.setAttribute("aria-expanded", `${visible}`);
      this._onDidChangeVisibility.fire(visible);
    }));
    this.dropdownMenu.menuOptions = {
      actionViewItemProvider: this.options.actionViewItemProvider,
      actionRunner: this.actionRunner,
      getKeyBinding: this.options.keybindingProvider,
      context: this._context
    };
    if (this.options.anchorAlignmentProvider) {
      const that = this;
      this.dropdownMenu.menuOptions = Object.assign(Object.assign({}, this.dropdownMenu.menuOptions), { get anchorAlignment() {
        return that.options.anchorAlignmentProvider();
      } });
    }
    this.updateTooltip();
    this.updateEnabled();
  }
  getTooltip() {
    let title2 = null;
    if (this.action.tooltip) {
      title2 = this.action.tooltip;
    } else if (this.action.label) {
      title2 = this.action.label;
    }
    return title2 !== null && title2 !== void 0 ? title2 : void 0;
  }
  setActionContext(newContext) {
    super.setActionContext(newContext);
    if (this.dropdownMenu) {
      if (this.dropdownMenu.menuOptions) {
        this.dropdownMenu.menuOptions.context = newContext;
      } else {
        this.dropdownMenu.menuOptions = { context: newContext };
      }
    }
  }
  show() {
    var _a2;
    (_a2 = this.dropdownMenu) === null || _a2 === void 0 ? void 0 : _a2.show();
  }
  updateEnabled() {
    var _a2, _b2;
    const disabled = !this.action.enabled;
    (_a2 = this.actionItem) === null || _a2 === void 0 ? void 0 : _a2.classList.toggle("disabled", disabled);
    (_b2 = this.element) === null || _b2 === void 0 ? void 0 : _b2.classList.toggle("disabled", disabled);
  }
}
const menuEntryActionViewItem = "";
function isICommandActionToggleInfo(thing) {
  return thing ? thing.condition !== void 0 : false;
}
var __decorate$1G = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1D = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$19 = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
function createAndFillInContextMenuActions(menu, options, target, primaryGroup) {
  const groups = menu.getActions(options);
  const modifierKeyEmitter = ModifierKeyEmitter.getInstance();
  const useAlternativeActions = modifierKeyEmitter.keyStatus.altKey || (isWindows || isLinux) && modifierKeyEmitter.keyStatus.shiftKey;
  fillInActions(groups, target, useAlternativeActions, primaryGroup ? (actionGroup) => actionGroup === primaryGroup : (actionGroup) => actionGroup === "navigation");
}
function createAndFillInActionBarActions(menu, options, target, primaryGroup, shouldInlineSubmenu, useSeparatorsInPrimaryActions) {
  const groups = menu.getActions(options);
  const isPrimaryAction = typeof primaryGroup === "string" ? (actionGroup) => actionGroup === primaryGroup : primaryGroup;
  fillInActions(groups, target, false, isPrimaryAction, shouldInlineSubmenu, useSeparatorsInPrimaryActions);
}
function fillInActions(groups, target, useAlternativeActions, isPrimaryAction = (actionGroup) => actionGroup === "navigation", shouldInlineSubmenu = () => false, useSeparatorsInPrimaryActions = false) {
  let primaryBucket;
  let secondaryBucket;
  if (Array.isArray(target)) {
    primaryBucket = target;
    secondaryBucket = target;
  } else {
    primaryBucket = target.primary;
    secondaryBucket = target.secondary;
  }
  const submenuInfo = /* @__PURE__ */ new Set();
  for (const [group2, actions] of groups) {
    let target2;
    if (isPrimaryAction(group2)) {
      target2 = primaryBucket;
      if (target2.length > 0 && useSeparatorsInPrimaryActions) {
        target2.push(new Separator());
      }
    } else {
      target2 = secondaryBucket;
      if (target2.length > 0) {
        target2.push(new Separator());
      }
    }
    for (let action of actions) {
      if (useAlternativeActions) {
        action = action instanceof MenuItemAction && action.alt ? action.alt : action;
      }
      const newLen = target2.push(action);
      if (action instanceof SubmenuAction) {
        submenuInfo.add({ group: group2, action, index: newLen - 1 });
      }
    }
  }
  for (const { group: group2, action, index } of submenuInfo) {
    const target2 = isPrimaryAction(group2) ? primaryBucket : secondaryBucket;
    const submenuActions = action.actions;
    if (submenuActions.length <= 1 && shouldInlineSubmenu(action, group2, target2.length)) {
      target2.splice(index, 1, ...submenuActions);
    }
  }
}
let MenuEntryActionViewItem = class MenuEntryActionViewItem2 extends ActionViewItem {
  constructor(action, options, _keybindingService, _notificationService, _contextKeyService, _themeService, _contextMenuService, _accessibilityService) {
    super(void 0, action, { icon: !!(action.class || action.item.icon), label: !action.class && !action.item.icon, draggable: options === null || options === void 0 ? void 0 : options.draggable, keybinding: options === null || options === void 0 ? void 0 : options.keybinding, hoverDelegate: options === null || options === void 0 ? void 0 : options.hoverDelegate });
    this._keybindingService = _keybindingService;
    this._notificationService = _notificationService;
    this._contextKeyService = _contextKeyService;
    this._themeService = _themeService;
    this._contextMenuService = _contextMenuService;
    this._accessibilityService = _accessibilityService;
    this._wantsAltCommand = false;
    this._itemClassDispose = this._register(new MutableDisposable());
    this._altKey = ModifierKeyEmitter.getInstance();
  }
  get _menuItemAction() {
    return this._action;
  }
  get _commandAction() {
    return this._wantsAltCommand && this._menuItemAction.alt || this._menuItemAction;
  }
  onClick(event) {
    return __awaiter$19(this, void 0, void 0, function* () {
      event.preventDefault();
      event.stopPropagation();
      try {
        yield this.actionRunner.run(this._commandAction, this._context);
      } catch (err) {
        this._notificationService.error(err);
      }
    });
  }
  render(container2) {
    super.render(container2);
    container2.classList.add("menu-entry");
    if (this.options.icon) {
      this._updateItemClass(this._menuItemAction.item);
    }
    if (this._menuItemAction.alt) {
      let isMouseOver = false;
      const updateAltState = () => {
        var _a2;
        const wantsAltCommand = !!((_a2 = this._menuItemAction.alt) === null || _a2 === void 0 ? void 0 : _a2.enabled) && (!this._accessibilityService.isMotionReduced() || isMouseOver) && (this._altKey.keyStatus.altKey || this._altKey.keyStatus.shiftKey && isMouseOver);
        if (wantsAltCommand !== this._wantsAltCommand) {
          this._wantsAltCommand = wantsAltCommand;
          this.updateLabel();
          this.updateTooltip();
          this.updateClass();
        }
      };
      this._register(this._altKey.event(updateAltState));
      this._register(addDisposableListener(container2, "mouseleave", (_) => {
        isMouseOver = false;
        updateAltState();
      }));
      this._register(addDisposableListener(container2, "mouseenter", (_) => {
        isMouseOver = true;
        updateAltState();
      }));
      updateAltState();
    }
  }
  updateLabel() {
    if (this.options.label && this.label) {
      this.label.textContent = this._commandAction.label;
    }
  }
  getTooltip() {
    var _a2;
    const keybinding = this._keybindingService.lookupKeybinding(this._commandAction.id, this._contextKeyService);
    const keybindingLabel2 = keybinding && keybinding.getLabel();
    const tooltip = this._commandAction.tooltip || this._commandAction.label;
    let title2 = keybindingLabel2 ? localize("titleAndKb", "{0} ({1})", tooltip, keybindingLabel2) : tooltip;
    if (!this._wantsAltCommand && ((_a2 = this._menuItemAction.alt) === null || _a2 === void 0 ? void 0 : _a2.enabled)) {
      const altTooltip = this._menuItemAction.alt.tooltip || this._menuItemAction.alt.label;
      const altKeybinding = this._keybindingService.lookupKeybinding(this._menuItemAction.alt.id, this._contextKeyService);
      const altKeybindingLabel = altKeybinding && altKeybinding.getLabel();
      const altTitleSection = altKeybindingLabel ? localize("titleAndKb", "{0} ({1})", altTooltip, altKeybindingLabel) : altTooltip;
      title2 = localize("titleAndKbAndAlt", "{0}\n[{1}] {2}", title2, UILabelProvider.modifierLabels[OS].altKey, altTitleSection);
    }
    return title2;
  }
  updateClass() {
    if (this.options.icon) {
      if (this._commandAction !== this._menuItemAction) {
        if (this._menuItemAction.alt) {
          this._updateItemClass(this._menuItemAction.alt.item);
        }
      } else {
        this._updateItemClass(this._menuItemAction.item);
      }
    }
  }
  _updateItemClass(item) {
    this._itemClassDispose.value = void 0;
    const { element, label } = this;
    if (!element || !label) {
      return;
    }
    const icon = this._commandAction.checked && isICommandActionToggleInfo(item.toggled) && item.toggled.icon ? item.toggled.icon : item.icon;
    if (!icon) {
      return;
    }
    if (ThemeIcon.isThemeIcon(icon)) {
      const iconClasses = ThemeIcon.asClassNameArray(icon);
      label.classList.add(...iconClasses);
      this._itemClassDispose.value = toDisposable(() => {
        label.classList.remove(...iconClasses);
      });
    } else {
      label.style.backgroundImage = isDark(this._themeService.getColorTheme().type) ? asCSSUrl(icon.dark) : asCSSUrl(icon.light);
      label.classList.add("icon");
      this._itemClassDispose.value = combinedDisposable(toDisposable(() => {
        label.style.backgroundImage = "";
        label.classList.remove("icon");
      }), this._themeService.onDidColorThemeChange(() => {
        this.updateClass();
      }));
    }
  }
};
MenuEntryActionViewItem = __decorate$1G([
  __param$1D(2, IKeybindingService),
  __param$1D(3, INotificationService),
  __param$1D(4, IContextKeyService),
  __param$1D(5, IThemeService),
  __param$1D(6, IContextMenuService),
  __param$1D(7, IAccessibilityService)
], MenuEntryActionViewItem);
let SubmenuEntryActionViewItem = class SubmenuEntryActionViewItem2 extends DropdownMenuActionViewItem {
  constructor(action, options, _keybindingService, _contextMenuService, _themeService) {
    var _a2, _b2, _c2;
    const dropdownOptions = Object.assign(Object.assign({}, options), { menuAsChild: (_a2 = options === null || options === void 0 ? void 0 : options.menuAsChild) !== null && _a2 !== void 0 ? _a2 : false, classNames: (_b2 = options === null || options === void 0 ? void 0 : options.classNames) !== null && _b2 !== void 0 ? _b2 : ThemeIcon.isThemeIcon(action.item.icon) ? ThemeIcon.asClassName(action.item.icon) : void 0, keybindingProvider: (_c2 = options === null || options === void 0 ? void 0 : options.keybindingProvider) !== null && _c2 !== void 0 ? _c2 : (action2) => _keybindingService.lookupKeybinding(action2.id) });
    super(action, { getActions: () => action.actions }, _contextMenuService, dropdownOptions);
    this._keybindingService = _keybindingService;
    this._contextMenuService = _contextMenuService;
    this._themeService = _themeService;
  }
  render(container2) {
    super.render(container2);
    assertType(this.element);
    container2.classList.add("menu-entry");
    const action = this._action;
    const { icon } = action.item;
    if (icon && !ThemeIcon.isThemeIcon(icon)) {
      this.element.classList.add("icon");
      const setBackgroundImage = () => {
        if (this.element) {
          this.element.style.backgroundImage = isDark(this._themeService.getColorTheme().type) ? asCSSUrl(icon.dark) : asCSSUrl(icon.light);
        }
      };
      setBackgroundImage();
      this._register(this._themeService.onDidColorThemeChange(() => {
        setBackgroundImage();
      }));
    }
  }
};
SubmenuEntryActionViewItem = __decorate$1G([
  __param$1D(2, IKeybindingService),
  __param$1D(3, IContextMenuService),
  __param$1D(4, IThemeService)
], SubmenuEntryActionViewItem);
let DropdownWithDefaultActionViewItem = class DropdownWithDefaultActionViewItem2 extends BaseActionViewItem {
  constructor(submenuAction, options, _keybindingService, _notificationService, _contextMenuService, _menuService, _instaService, _storageService) {
    var _a2, _b2, _c2;
    super(null, submenuAction);
    this._keybindingService = _keybindingService;
    this._notificationService = _notificationService;
    this._contextMenuService = _contextMenuService;
    this._menuService = _menuService;
    this._instaService = _instaService;
    this._storageService = _storageService;
    this._container = null;
    this._options = options;
    this._storageKey = `${submenuAction.item.submenu.id}_lastActionId`;
    let defaultAction;
    const defaultActionId = (options === null || options === void 0 ? void 0 : options.persistLastActionId) ? _storageService.get(
      this._storageKey,
      1
      /* StorageScope.WORKSPACE */
    ) : void 0;
    if (defaultActionId) {
      defaultAction = submenuAction.actions.find((a) => defaultActionId === a.id);
    }
    if (!defaultAction) {
      defaultAction = submenuAction.actions[0];
    }
    this._defaultAction = this._instaService.createInstance(MenuEntryActionViewItem, defaultAction, { keybinding: this._getDefaultActionKeybindingLabel(defaultAction) });
    const dropdownOptions = Object.assign(Object.assign({ keybindingProvider: (action) => this._keybindingService.lookupKeybinding(action.id) }, options), { menuAsChild: (_a2 = options === null || options === void 0 ? void 0 : options.menuAsChild) !== null && _a2 !== void 0 ? _a2 : true, classNames: (_b2 = options === null || options === void 0 ? void 0 : options.classNames) !== null && _b2 !== void 0 ? _b2 : ["codicon", "codicon-chevron-down"], actionRunner: (_c2 = options === null || options === void 0 ? void 0 : options.actionRunner) !== null && _c2 !== void 0 ? _c2 : new ActionRunner() });
    this._dropdown = new DropdownMenuActionViewItem(submenuAction, submenuAction.actions, this._contextMenuService, dropdownOptions);
    this._dropdown.actionRunner.onDidRun((e) => {
      if (e.action instanceof MenuItemAction) {
        this.update(e.action);
      }
    });
  }
  update(lastAction) {
    var _a2;
    if ((_a2 = this._options) === null || _a2 === void 0 ? void 0 : _a2.persistLastActionId) {
      this._storageService.store(
        this._storageKey,
        lastAction.id,
        1,
        1
        /* StorageTarget.MACHINE */
      );
    }
    this._defaultAction.dispose();
    this._defaultAction = this._instaService.createInstance(MenuEntryActionViewItem, lastAction, { keybinding: this._getDefaultActionKeybindingLabel(lastAction) });
    this._defaultAction.actionRunner = new class extends ActionRunner {
      runAction(action, context) {
        return __awaiter$19(this, void 0, void 0, function* () {
          yield action.run(void 0);
        });
      }
    }();
    if (this._container) {
      this._defaultAction.render(prepend$1(this._container, $$d(".action-container")));
    }
  }
  _getDefaultActionKeybindingLabel(defaultAction) {
    var _a2;
    let defaultActionKeybinding;
    if ((_a2 = this._options) === null || _a2 === void 0 ? void 0 : _a2.renderKeybindingWithDefaultActionLabel) {
      const kb = this._keybindingService.lookupKeybinding(defaultAction.id);
      if (kb) {
        defaultActionKeybinding = `(${kb.getLabel()})`;
      }
    }
    return defaultActionKeybinding;
  }
  setActionContext(newContext) {
    super.setActionContext(newContext);
    this._defaultAction.setActionContext(newContext);
    this._dropdown.setActionContext(newContext);
  }
  render(container2) {
    this._container = container2;
    super.render(this._container);
    this._container.classList.add("monaco-dropdown-with-default");
    const primaryContainer = $$d(".action-container");
    this._defaultAction.render(append$1(this._container, primaryContainer));
    this._register(addDisposableListener(primaryContainer, EventType$1.KEY_DOWN, (e) => {
      const event = new StandardKeyboardEvent(e);
      if (event.equals(
        17
        /* KeyCode.RightArrow */
      )) {
        this._defaultAction.element.tabIndex = -1;
        this._dropdown.focus();
        event.stopPropagation();
      }
    }));
    const dropdownContainer = $$d(".dropdown-action-container");
    this._dropdown.render(append$1(this._container, dropdownContainer));
    this._register(addDisposableListener(dropdownContainer, EventType$1.KEY_DOWN, (e) => {
      var _a2;
      const event = new StandardKeyboardEvent(e);
      if (event.equals(
        15
        /* KeyCode.LeftArrow */
      )) {
        this._defaultAction.element.tabIndex = 0;
        this._dropdown.setFocusable(false);
        (_a2 = this._defaultAction.element) === null || _a2 === void 0 ? void 0 : _a2.focus();
        event.stopPropagation();
      }
    }));
  }
  focus(fromRight) {
    if (fromRight) {
      this._dropdown.focus();
    } else {
      this._defaultAction.element.tabIndex = 0;
      this._defaultAction.element.focus();
    }
  }
  blur() {
    this._defaultAction.element.tabIndex = -1;
    this._dropdown.blur();
    this._container.blur();
  }
  setFocusable(focusable) {
    if (focusable) {
      this._defaultAction.element.tabIndex = 0;
    } else {
      this._defaultAction.element.tabIndex = -1;
      this._dropdown.setFocusable(false);
    }
  }
  dispose() {
    this._defaultAction.dispose();
    this._dropdown.dispose();
    super.dispose();
  }
};
DropdownWithDefaultActionViewItem = __decorate$1G([
  __param$1D(2, IKeybindingService),
  __param$1D(3, INotificationService),
  __param$1D(4, IContextMenuService),
  __param$1D(5, IMenuService),
  __param$1D(6, IInstantiationService),
  __param$1D(7, IStorageService)
], DropdownWithDefaultActionViewItem);
let SubmenuEntrySelectActionViewItem = class SubmenuEntrySelectActionViewItem2 extends SelectActionViewItem {
  constructor(action, contextViewService) {
    super(null, action, action.actions.map((a) => ({
      text: a.id === Separator.ID ? "─────────" : a.label,
      isDisabled: !a.enabled
    })), 0, contextViewService, defaultSelectBoxStyles, { ariaLabel: action.tooltip, optionsAsChildren: true });
    this.select(Math.max(0, action.actions.findIndex((a) => a.checked)));
  }
  render(container2) {
    super.render(container2);
    container2.style.borderColor = asCssVariable(selectBorder);
  }
  runAction(option, index) {
    const action = this.action.actions[index];
    if (action) {
      this.actionRunner.run(action);
    }
  }
};
SubmenuEntrySelectActionViewItem = __decorate$1G([
  __param$1D(1, IContextViewService)
], SubmenuEntrySelectActionViewItem);
function createActionViewItem(instaService, action, options) {
  if (action instanceof MenuItemAction) {
    return instaService.createInstance(MenuEntryActionViewItem, action, options);
  } else if (action instanceof SubmenuItemAction) {
    if (action.item.isSelection) {
      return instaService.createInstance(SubmenuEntrySelectActionViewItem, action);
    } else {
      if (action.item.rememberDefaultAction) {
        return instaService.createInstance(DropdownWithDefaultActionViewItem, action, Object.assign(Object.assign({}, options), { persistLastActionId: true }));
      } else {
        return instaService.createInstance(SubmenuEntryActionViewItem, action, options);
      }
    }
  } else {
    return void 0;
  }
}
var __decorate$1F = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1C = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
const IPeekViewService = createDecorator("IPeekViewService");
registerSingleton(
  IPeekViewService,
  class {
    constructor() {
      this._widgets = /* @__PURE__ */ new Map();
    }
    addExclusiveWidget(editor2, widget) {
      const existing = this._widgets.get(editor2);
      if (existing) {
        existing.listener.dispose();
        existing.widget.dispose();
      }
      const remove2 = () => {
        const data = this._widgets.get(editor2);
        if (data && data.widget === widget) {
          data.listener.dispose();
          this._widgets.delete(editor2);
        }
      };
      this._widgets.set(editor2, { widget, listener: widget.onDidClose(remove2) });
    }
  },
  1
  /* InstantiationType.Delayed */
);
var PeekContext;
(function(PeekContext2) {
  PeekContext2.inPeekEditor = new RawContextKey("inReferenceSearchEditor", true, localize("inReferenceSearchEditor", "Whether the current code editor is embedded inside peek"));
  PeekContext2.notInPeekEditor = PeekContext2.inPeekEditor.toNegated();
})(PeekContext || (PeekContext = {}));
let PeekContextController = class PeekContextController2 {
  constructor(editor2, contextKeyService) {
    if (editor2 instanceof EmbeddedCodeEditorWidget) {
      PeekContext.inPeekEditor.bindTo(contextKeyService);
    }
  }
  dispose() {
  }
};
PeekContextController.ID = "editor.contrib.referenceController";
PeekContextController = __decorate$1F([
  __param$1C(1, IContextKeyService)
], PeekContextController);
registerEditorContribution(
  PeekContextController.ID,
  PeekContextController,
  0
  /* EditorContributionInstantiation.Eager */
);
function getOuterEditor(accessor) {
  const editor2 = accessor.get(ICodeEditorService).getFocusedCodeEditor();
  if (editor2 instanceof EmbeddedCodeEditorWidget) {
    return editor2.getParentEditor();
  }
  return editor2;
}
const defaultOptions$1 = {
  headerBackgroundColor: Color.white,
  primaryHeadingColor: Color.fromHex("#333333"),
  secondaryHeadingColor: Color.fromHex("#6c6c6cb3")
};
let PeekViewWidget = class PeekViewWidget2 extends ZoneWidget {
  constructor(editor2, options, instantiationService) {
    super(editor2, options);
    this.instantiationService = instantiationService;
    this._onDidClose = new Emitter$1();
    this.onDidClose = this._onDidClose.event;
    mixin(this.options, defaultOptions$1, false);
  }
  dispose() {
    if (!this.disposed) {
      this.disposed = true;
      super.dispose();
      this._onDidClose.fire(this);
    }
  }
  style(styles) {
    const options = this.options;
    if (styles.headerBackgroundColor) {
      options.headerBackgroundColor = styles.headerBackgroundColor;
    }
    if (styles.primaryHeadingColor) {
      options.primaryHeadingColor = styles.primaryHeadingColor;
    }
    if (styles.secondaryHeadingColor) {
      options.secondaryHeadingColor = styles.secondaryHeadingColor;
    }
    super.style(styles);
  }
  _applyStyles() {
    super._applyStyles();
    const options = this.options;
    if (this._headElement && options.headerBackgroundColor) {
      this._headElement.style.backgroundColor = options.headerBackgroundColor.toString();
    }
    if (this._primaryHeading && options.primaryHeadingColor) {
      this._primaryHeading.style.color = options.primaryHeadingColor.toString();
    }
    if (this._secondaryHeading && options.secondaryHeadingColor) {
      this._secondaryHeading.style.color = options.secondaryHeadingColor.toString();
    }
    if (this._bodyElement && options.frameColor) {
      this._bodyElement.style.borderColor = options.frameColor.toString();
    }
  }
  _fillContainer(container2) {
    this.setCssClass("peekview-widget");
    this._headElement = $$d(".head");
    this._bodyElement = $$d(".body");
    this._fillHead(this._headElement);
    this._fillBody(this._bodyElement);
    container2.appendChild(this._headElement);
    container2.appendChild(this._bodyElement);
  }
  _fillHead(container2, noCloseAction) {
    this._titleElement = $$d(".peekview-title");
    if (this.options.supportOnTitleClick) {
      this._titleElement.classList.add("clickable");
      addStandardDisposableListener(this._titleElement, "click", (event) => this._onTitleClick(event));
    }
    append$1(this._headElement, this._titleElement);
    this._fillTitleIcon(this._titleElement);
    this._primaryHeading = $$d("span.filename");
    this._secondaryHeading = $$d("span.dirname");
    this._metaHeading = $$d("span.meta");
    append$1(this._titleElement, this._primaryHeading, this._secondaryHeading, this._metaHeading);
    const actionsContainer = $$d(".peekview-actions");
    append$1(this._headElement, actionsContainer);
    const actionBarOptions = this._getActionBarOptions();
    this._actionbarWidget = new ActionBar(actionsContainer, actionBarOptions);
    this._disposables.add(this._actionbarWidget);
    if (!noCloseAction) {
      this._actionbarWidget.push(new Action("peekview.close", localize("label.close", "Close"), ThemeIcon.asClassName(Codicon.close), true, () => {
        this.dispose();
        return Promise.resolve();
      }), { label: false, icon: true });
    }
  }
  _fillTitleIcon(container2) {
  }
  _getActionBarOptions() {
    return {
      actionViewItemProvider: createActionViewItem.bind(void 0, this.instantiationService),
      orientation: 0
      /* ActionsOrientation.HORIZONTAL */
    };
  }
  _onTitleClick(event) {
  }
  setTitle(primaryHeading, secondaryHeading) {
    if (this._primaryHeading && this._secondaryHeading) {
      this._primaryHeading.innerText = primaryHeading;
      this._primaryHeading.setAttribute("title", primaryHeading);
      if (secondaryHeading) {
        this._secondaryHeading.innerText = secondaryHeading;
      } else {
        clearNode(this._secondaryHeading);
      }
    }
  }
  setMetaTitle(value) {
    if (this._metaHeading) {
      if (value) {
        this._metaHeading.innerText = value;
        show(this._metaHeading);
      } else {
        hide(this._metaHeading);
      }
    }
  }
  _doLayout(heightInPixel, widthInPixel) {
    if (!this._isShowing && heightInPixel < 0) {
      this.dispose();
      return;
    }
    const headHeight = Math.ceil(this.editor.getOption(
      65
      /* EditorOption.lineHeight */
    ) * 1.2);
    const bodyHeight = Math.round(heightInPixel - (headHeight + 2));
    this._doLayoutHead(headHeight, widthInPixel);
    this._doLayoutBody(bodyHeight, widthInPixel);
  }
  _doLayoutHead(heightInPixel, widthInPixel) {
    if (this._headElement) {
      this._headElement.style.height = `${heightInPixel}px`;
      this._headElement.style.lineHeight = this._headElement.style.height;
    }
  }
  _doLayoutBody(heightInPixel, widthInPixel) {
    if (this._bodyElement) {
      this._bodyElement.style.height = `${heightInPixel}px`;
    }
  }
};
PeekViewWidget = __decorate$1F([
  __param$1C(2, IInstantiationService)
], PeekViewWidget);
const peekViewTitleBackground = registerColor("peekViewTitle.background", { dark: "#252526", light: "#F3F3F3", hcDark: Color.black, hcLight: Color.white }, localize("peekViewTitleBackground", "Background color of the peek view title area."));
const peekViewTitleForeground = registerColor("peekViewTitleLabel.foreground", { dark: Color.white, light: Color.black, hcDark: Color.white, hcLight: editorForeground }, localize("peekViewTitleForeground", "Color of the peek view title."));
const peekViewTitleInfoForeground = registerColor("peekViewTitleDescription.foreground", { dark: "#ccccccb3", light: "#616161", hcDark: "#FFFFFF99", hcLight: "#292929" }, localize("peekViewTitleInfoForeground", "Color of the peek view title info."));
const peekViewBorder = registerColor("peekView.border", { dark: editorInfoForeground, light: editorInfoForeground, hcDark: contrastBorder, hcLight: contrastBorder }, localize("peekViewBorder", "Color of the peek view borders and arrow."));
const peekViewResultsBackground = registerColor("peekViewResult.background", { dark: "#252526", light: "#F3F3F3", hcDark: Color.black, hcLight: Color.white }, localize("peekViewResultsBackground", "Background color of the peek view result list."));
registerColor("peekViewResult.lineForeground", { dark: "#bbbbbb", light: "#646465", hcDark: Color.white, hcLight: editorForeground }, localize("peekViewResultsMatchForeground", "Foreground color for line nodes in the peek view result list."));
registerColor("peekViewResult.fileForeground", { dark: Color.white, light: "#1E1E1E", hcDark: Color.white, hcLight: editorForeground }, localize("peekViewResultsFileForeground", "Foreground color for file nodes in the peek view result list."));
registerColor("peekViewResult.selectionBackground", { dark: "#3399ff33", light: "#3399ff33", hcDark: null, hcLight: null }, localize("peekViewResultsSelectionBackground", "Background color of the selected entry in the peek view result list."));
registerColor("peekViewResult.selectionForeground", { dark: Color.white, light: "#6C6C6C", hcDark: Color.white, hcLight: editorForeground }, localize("peekViewResultsSelectionForeground", "Foreground color of the selected entry in the peek view result list."));
const peekViewEditorBackground = registerColor("peekViewEditor.background", { dark: "#001F33", light: "#F2F8FC", hcDark: Color.black, hcLight: Color.white }, localize("peekViewEditorBackground", "Background color of the peek view editor."));
registerColor("peekViewEditorGutter.background", { dark: peekViewEditorBackground, light: peekViewEditorBackground, hcDark: peekViewEditorBackground, hcLight: peekViewEditorBackground }, localize("peekViewEditorGutterBackground", "Background color of the gutter in the peek view editor."));
registerColor("peekViewEditorStickyScroll.background", { dark: peekViewEditorBackground, light: peekViewEditorBackground, hcDark: peekViewEditorBackground, hcLight: peekViewEditorBackground }, localize("peekViewEditorStickScrollBackground", "Background color of sticky scroll in the peek view editor."));
registerColor("peekViewResult.matchHighlightBackground", { dark: "#ea5c004d", light: "#ea5c004d", hcDark: null, hcLight: null }, localize("peekViewResultsMatchHighlight", "Match highlight color in the peek view result list."));
registerColor("peekViewEditor.matchHighlightBackground", { dark: "#ff8f0099", light: "#f5d802de", hcDark: null, hcLight: null }, localize("peekViewEditorMatchHighlight", "Match highlight color in the peek view editor."));
registerColor("peekViewEditor.matchHighlightBorder", { dark: null, light: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize("peekViewEditorMatchHighlightBorder", "Match highlight border in the peek view editor."));
function isCodeEditor(thing) {
  if (thing && typeof thing.getEditorType === "function") {
    return thing.getEditorType() === EditorType.ICodeEditor;
  } else {
    return false;
  }
}
function isDiffEditor(thing) {
  if (thing && typeof thing.getEditorType === "function") {
    return thing.getEditorType() === EditorType.IDiffEditor;
  } else {
    return false;
  }
}
function isCompositeEditor(thing) {
  return !!thing && typeof thing === "object" && typeof thing.onDidChangeActiveEditor === "function";
}
function getCodeEditor(thing) {
  if (isCodeEditor(thing)) {
    return thing;
  }
  if (isDiffEditor(thing)) {
    return thing.getModifiedEditor();
  }
  if (isCompositeEditor(thing) && isCodeEditor(thing.activeCodeEditor)) {
    return thing.activeCodeEditor;
  }
  return null;
}
class PagedRenderer {
  get templateId() {
    return this.renderer.templateId;
  }
  constructor(renderer2, modelProvider) {
    this.renderer = renderer2;
    this.modelProvider = modelProvider;
  }
  renderTemplate(container2) {
    const data = this.renderer.renderTemplate(container2);
    return { data, disposable: Disposable.None };
  }
  renderElement(index, _, data, height) {
    var _a2;
    (_a2 = data.disposable) === null || _a2 === void 0 ? void 0 : _a2.dispose();
    if (!data.data) {
      return;
    }
    const model = this.modelProvider();
    if (model.isResolved(index)) {
      return this.renderer.renderElement(model.get(index), index, data.data, height);
    }
    const cts = new CancellationTokenSource$1();
    const promise = model.resolve(index, cts.token);
    data.disposable = { dispose: () => cts.cancel() };
    this.renderer.renderPlaceholder(index, data.data);
    promise.then((entry) => this.renderer.renderElement(entry, index, data.data, height));
  }
  disposeTemplate(data) {
    if (data.disposable) {
      data.disposable.dispose();
      data.disposable = void 0;
    }
    if (data.data) {
      this.renderer.disposeTemplate(data.data);
      data.data = void 0;
    }
  }
}
class PagedAccessibilityProvider {
  constructor(modelProvider, accessibilityProvider) {
    this.modelProvider = modelProvider;
    this.accessibilityProvider = accessibilityProvider;
  }
  getWidgetAriaLabel() {
    return this.accessibilityProvider.getWidgetAriaLabel();
  }
  getAriaLabel(index) {
    const model = this.modelProvider();
    if (!model.isResolved(index)) {
      return null;
    }
    return this.accessibilityProvider.getAriaLabel(model.get(index));
  }
}
function fromPagedListOptions(modelProvider, options) {
  return Object.assign(Object.assign({}, options), { accessibilityProvider: options.accessibilityProvider && new PagedAccessibilityProvider(modelProvider, options.accessibilityProvider) });
}
class PagedList {
  constructor(user, container2, virtualDelegate, renderers, options = {}) {
    const modelProvider = () => this.model;
    const pagedRenderers = renderers.map((r) => new PagedRenderer(r, modelProvider));
    this.list = new List(user, container2, virtualDelegate, pagedRenderers, fromPagedListOptions(modelProvider, options));
  }
  updateOptions(options) {
    this.list.updateOptions(options);
  }
  getHTMLElement() {
    return this.list.getHTMLElement();
  }
  get onDidFocus() {
    return this.list.onDidFocus;
  }
  get widget() {
    return this.list;
  }
  get onDidDispose() {
    return this.list.onDidDispose;
  }
  get onMouseDblClick() {
    return Event$1.map(this.list.onMouseDblClick, ({ element, index, browserEvent }) => ({ element: element === void 0 ? void 0 : this._model.get(element), index, browserEvent }));
  }
  get onPointer() {
    return Event$1.map(this.list.onPointer, ({ element, index, browserEvent }) => ({ element: element === void 0 ? void 0 : this._model.get(element), index, browserEvent }));
  }
  get onDidChangeSelection() {
    return Event$1.map(this.list.onDidChangeSelection, ({ elements, indexes, browserEvent }) => ({ elements: elements.map((e) => this._model.get(e)), indexes, browserEvent }));
  }
  get model() {
    return this._model;
  }
  set model(model) {
    this._model = model;
    this.list.splice(0, this.list.length, range$1(model.length));
  }
  getFocus() {
    return this.list.getFocus();
  }
  getSelection() {
    return this.list.getSelection();
  }
  getSelectedElements() {
    return this.getSelection().map((i) => this.model.get(i));
  }
  style(styles) {
    this.list.style(styles);
  }
  dispose() {
    this.list.dispose();
  }
}
const splitview = "";
const defaultStyles = {
  separatorBorder: Color.transparent
};
class ViewItem {
  set size(size2) {
    this._size = size2;
  }
  get size() {
    return this._size;
  }
  get visible() {
    return typeof this._cachedVisibleSize === "undefined";
  }
  setVisible(visible, size2) {
    var _a2, _b2;
    if (visible === this.visible) {
      return;
    }
    if (visible) {
      this.size = clamp(this._cachedVisibleSize, this.viewMinimumSize, this.viewMaximumSize);
      this._cachedVisibleSize = void 0;
    } else {
      this._cachedVisibleSize = typeof size2 === "number" ? size2 : this.size;
      this.size = 0;
    }
    this.container.classList.toggle("visible", visible);
    (_b2 = (_a2 = this.view).setVisible) === null || _b2 === void 0 ? void 0 : _b2.call(_a2, visible);
  }
  get minimumSize() {
    return this.visible ? this.view.minimumSize : 0;
  }
  get viewMinimumSize() {
    return this.view.minimumSize;
  }
  get maximumSize() {
    return this.visible ? this.view.maximumSize : 0;
  }
  get viewMaximumSize() {
    return this.view.maximumSize;
  }
  get priority() {
    return this.view.priority;
  }
  get proportionalLayout() {
    var _a2;
    return (_a2 = this.view.proportionalLayout) !== null && _a2 !== void 0 ? _a2 : true;
  }
  get snap() {
    return !!this.view.snap;
  }
  set enabled(enabled) {
    this.container.style.pointerEvents = enabled ? "" : "none";
  }
  constructor(container2, view, size2, disposable) {
    this.container = container2;
    this.view = view;
    this.disposable = disposable;
    this._cachedVisibleSize = void 0;
    if (typeof size2 === "number") {
      this._size = size2;
      this._cachedVisibleSize = void 0;
      container2.classList.add("visible");
    } else {
      this._size = 0;
      this._cachedVisibleSize = size2.cachedVisibleSize;
    }
  }
  layout(offset, layoutContext) {
    this.layoutContainer(offset);
    this.view.layout(this.size, offset, layoutContext);
  }
  dispose() {
    this.disposable.dispose();
  }
}
class VerticalViewItem extends ViewItem {
  layoutContainer(offset) {
    this.container.style.top = `${offset}px`;
    this.container.style.height = `${this.size}px`;
  }
}
class HorizontalViewItem extends ViewItem {
  layoutContainer(offset) {
    this.container.style.left = `${offset}px`;
    this.container.style.width = `${this.size}px`;
  }
}
var State$1;
(function(State2) {
  State2[State2["Idle"] = 0] = "Idle";
  State2[State2["Busy"] = 1] = "Busy";
})(State$1 || (State$1 = {}));
var Sizing;
(function(Sizing2) {
  Sizing2.Distribute = { type: "distribute" };
  function Split(index) {
    return { type: "split", index };
  }
  Sizing2.Split = Split;
  function Auto(index) {
    return { type: "auto", index };
  }
  Sizing2.Auto = Auto;
  function Invisible(cachedVisibleSize) {
    return { type: "invisible", cachedVisibleSize };
  }
  Sizing2.Invisible = Invisible;
})(Sizing || (Sizing = {}));
class SplitView extends Disposable {
  get orthogonalStartSash() {
    return this._orthogonalStartSash;
  }
  get orthogonalEndSash() {
    return this._orthogonalEndSash;
  }
  get startSnappingEnabled() {
    return this._startSnappingEnabled;
  }
  get endSnappingEnabled() {
    return this._endSnappingEnabled;
  }
  /**
   * A reference to a sash, perpendicular to all sashes in this {@link SplitView},
   * located at the left- or top-most side of the SplitView.
   * Corner sashes will be created automatically at the intersections.
   */
  set orthogonalStartSash(sash2) {
    for (const sashItem of this.sashItems) {
      sashItem.sash.orthogonalStartSash = sash2;
    }
    this._orthogonalStartSash = sash2;
  }
  /**
   * A reference to a sash, perpendicular to all sashes in this {@link SplitView},
   * located at the right- or bottom-most side of the SplitView.
   * Corner sashes will be created automatically at the intersections.
   */
  set orthogonalEndSash(sash2) {
    for (const sashItem of this.sashItems) {
      sashItem.sash.orthogonalEndSash = sash2;
    }
    this._orthogonalEndSash = sash2;
  }
  /**
   * Enable/disable snapping at the beginning of this {@link SplitView}.
   */
  set startSnappingEnabled(startSnappingEnabled) {
    if (this._startSnappingEnabled === startSnappingEnabled) {
      return;
    }
    this._startSnappingEnabled = startSnappingEnabled;
    this.updateSashEnablement();
  }
  /**
   * Enable/disable snapping at the end of this {@link SplitView}.
   */
  set endSnappingEnabled(endSnappingEnabled) {
    if (this._endSnappingEnabled === endSnappingEnabled) {
      return;
    }
    this._endSnappingEnabled = endSnappingEnabled;
    this.updateSashEnablement();
  }
  /**
   * Create a new {@link SplitView} instance.
   */
  constructor(container2, options = {}) {
    var _a2, _b2, _c2, _d2, _e2;
    super();
    this.size = 0;
    this.contentSize = 0;
    this.proportions = void 0;
    this.viewItems = [];
    this.sashItems = [];
    this.state = State$1.Idle;
    this._onDidSashChange = this._register(new Emitter$1());
    this._onDidSashReset = this._register(new Emitter$1());
    this._startSnappingEnabled = true;
    this._endSnappingEnabled = true;
    this.onDidSashChange = this._onDidSashChange.event;
    this.onDidSashReset = this._onDidSashReset.event;
    this.orientation = (_a2 = options.orientation) !== null && _a2 !== void 0 ? _a2 : 0;
    this.inverseAltBehavior = (_b2 = options.inverseAltBehavior) !== null && _b2 !== void 0 ? _b2 : false;
    this.proportionalLayout = (_c2 = options.proportionalLayout) !== null && _c2 !== void 0 ? _c2 : true;
    this.getSashOrthogonalSize = options.getSashOrthogonalSize;
    this.el = document.createElement("div");
    this.el.classList.add("monaco-split-view2");
    this.el.classList.add(this.orientation === 0 ? "vertical" : "horizontal");
    container2.appendChild(this.el);
    this.sashContainer = append$1(this.el, $$d(".sash-container"));
    this.viewContainer = $$d(".split-view-container");
    this.scrollable = new Scrollable({
      forceIntegerValues: true,
      smoothScrollDuration: 125,
      scheduleAtNextAnimationFrame
    });
    this.scrollableElement = this._register(new SmoothScrollableElement(this.viewContainer, {
      vertical: this.orientation === 0 ? (_d2 = options.scrollbarVisibility) !== null && _d2 !== void 0 ? _d2 : 1 : 2,
      horizontal: this.orientation === 1 ? (_e2 = options.scrollbarVisibility) !== null && _e2 !== void 0 ? _e2 : 1 : 2
      /* ScrollbarVisibility.Hidden */
    }, this.scrollable));
    const onDidScrollViewContainer = this._register(new DomEmitter(this.viewContainer, "scroll")).event;
    this._register(onDidScrollViewContainer((_) => {
      const position = this.scrollableElement.getScrollPosition();
      const scrollLeft = Math.abs(this.viewContainer.scrollLeft - position.scrollLeft) <= 1 ? void 0 : this.viewContainer.scrollLeft;
      const scrollTop = Math.abs(this.viewContainer.scrollTop - position.scrollTop) <= 1 ? void 0 : this.viewContainer.scrollTop;
      if (scrollLeft !== void 0 || scrollTop !== void 0) {
        this.scrollableElement.setScrollPosition({ scrollLeft, scrollTop });
      }
    }));
    this.onDidScroll = this.scrollableElement.onScroll;
    this._register(this.onDidScroll((e) => {
      if (e.scrollTopChanged) {
        this.viewContainer.scrollTop = e.scrollTop;
      }
      if (e.scrollLeftChanged) {
        this.viewContainer.scrollLeft = e.scrollLeft;
      }
    }));
    append$1(this.el, this.scrollableElement.getDomNode());
    this.style(options.styles || defaultStyles);
    if (options.descriptor) {
      this.size = options.descriptor.size;
      options.descriptor.views.forEach((viewDescriptor, index) => {
        const sizing = isUndefined$1(viewDescriptor.visible) || viewDescriptor.visible ? viewDescriptor.size : { type: "invisible", cachedVisibleSize: viewDescriptor.size };
        const view = viewDescriptor.view;
        this.doAddView(view, sizing, index, true);
      });
      this.contentSize = this.viewItems.reduce((r, i) => r + i.size, 0);
      this.saveProportions();
    }
  }
  style(styles) {
    if (styles.separatorBorder.isTransparent()) {
      this.el.classList.remove("separator-border");
      this.el.style.removeProperty("--separator-border");
    } else {
      this.el.classList.add("separator-border");
      this.el.style.setProperty("--separator-border", styles.separatorBorder.toString());
    }
  }
  /**
   * Add a {@link IView view} to this {@link SplitView}.
   *
   * @param view The view to add.
   * @param size Either a fixed size, or a dynamic {@link Sizing} strategy.
   * @param index The index to insert the view on.
   * @param skipLayout Whether layout should be skipped.
   */
  addView(view, size2, index = this.viewItems.length, skipLayout) {
    this.doAddView(view, size2, index, skipLayout);
  }
  /**
   * Layout the {@link SplitView}.
   *
   * @param size The entire size of the {@link SplitView}.
   * @param layoutContext An optional layout context to pass along to {@link IView views}.
   */
  layout(size2, layoutContext) {
    const previousSize = Math.max(this.size, this.contentSize);
    this.size = size2;
    this.layoutContext = layoutContext;
    if (!this.proportions) {
      const indexes = range$1(this.viewItems.length);
      const lowPriorityIndexes = indexes.filter(
        (i) => this.viewItems[i].priority === 1
        /* LayoutPriority.Low */
      );
      const highPriorityIndexes = indexes.filter(
        (i) => this.viewItems[i].priority === 2
        /* LayoutPriority.High */
      );
      this.resize(this.viewItems.length - 1, size2 - previousSize, void 0, lowPriorityIndexes, highPriorityIndexes);
    } else {
      let total = 0;
      for (let i = 0; i < this.viewItems.length; i++) {
        const item = this.viewItems[i];
        const proportion = this.proportions[i];
        if (typeof proportion === "number") {
          total += proportion;
        } else {
          size2 -= item.size;
        }
      }
      for (let i = 0; i < this.viewItems.length; i++) {
        const item = this.viewItems[i];
        const proportion = this.proportions[i];
        if (typeof proportion === "number") {
          item.size = clamp(Math.round(proportion * size2 / total), item.minimumSize, item.maximumSize);
        }
      }
    }
    this.distributeEmptySpace();
    this.layoutViews();
  }
  saveProportions() {
    if (this.proportionalLayout && this.contentSize > 0) {
      this.proportions = this.viewItems.map((i) => i.proportionalLayout ? i.size / this.contentSize : void 0);
    }
  }
  onSashStart({ sash: sash2, start, alt }) {
    for (const item of this.viewItems) {
      item.enabled = false;
    }
    const index = this.sashItems.findIndex((item) => item.sash === sash2);
    const disposable = combinedDisposable(addDisposableListener(document.body, "keydown", (e) => resetSashDragState(this.sashDragState.current, e.altKey)), addDisposableListener(document.body, "keyup", () => resetSashDragState(this.sashDragState.current, false)));
    const resetSashDragState = (start2, alt2) => {
      const sizes = this.viewItems.map((i) => i.size);
      let minDelta = Number.NEGATIVE_INFINITY;
      let maxDelta = Number.POSITIVE_INFINITY;
      if (this.inverseAltBehavior) {
        alt2 = !alt2;
      }
      if (alt2) {
        const isLastSash = index === this.sashItems.length - 1;
        if (isLastSash) {
          const viewItem = this.viewItems[index];
          minDelta = (viewItem.minimumSize - viewItem.size) / 2;
          maxDelta = (viewItem.maximumSize - viewItem.size) / 2;
        } else {
          const viewItem = this.viewItems[index + 1];
          minDelta = (viewItem.size - viewItem.maximumSize) / 2;
          maxDelta = (viewItem.size - viewItem.minimumSize) / 2;
        }
      }
      let snapBefore;
      let snapAfter;
      if (!alt2) {
        const upIndexes = range$1(index, -1);
        const downIndexes = range$1(index + 1, this.viewItems.length);
        const minDeltaUp = upIndexes.reduce((r, i) => r + (this.viewItems[i].minimumSize - sizes[i]), 0);
        const maxDeltaUp = upIndexes.reduce((r, i) => r + (this.viewItems[i].viewMaximumSize - sizes[i]), 0);
        const maxDeltaDown = downIndexes.length === 0 ? Number.POSITIVE_INFINITY : downIndexes.reduce((r, i) => r + (sizes[i] - this.viewItems[i].minimumSize), 0);
        const minDeltaDown = downIndexes.length === 0 ? Number.NEGATIVE_INFINITY : downIndexes.reduce((r, i) => r + (sizes[i] - this.viewItems[i].viewMaximumSize), 0);
        const minDelta2 = Math.max(minDeltaUp, minDeltaDown);
        const maxDelta2 = Math.min(maxDeltaDown, maxDeltaUp);
        const snapBeforeIndex = this.findFirstSnapIndex(upIndexes);
        const snapAfterIndex = this.findFirstSnapIndex(downIndexes);
        if (typeof snapBeforeIndex === "number") {
          const viewItem = this.viewItems[snapBeforeIndex];
          const halfSize = Math.floor(viewItem.viewMinimumSize / 2);
          snapBefore = {
            index: snapBeforeIndex,
            limitDelta: viewItem.visible ? minDelta2 - halfSize : minDelta2 + halfSize,
            size: viewItem.size
          };
        }
        if (typeof snapAfterIndex === "number") {
          const viewItem = this.viewItems[snapAfterIndex];
          const halfSize = Math.floor(viewItem.viewMinimumSize / 2);
          snapAfter = {
            index: snapAfterIndex,
            limitDelta: viewItem.visible ? maxDelta2 + halfSize : maxDelta2 - halfSize,
            size: viewItem.size
          };
        }
      }
      this.sashDragState = { start: start2, current: start2, index, sizes, minDelta, maxDelta, alt: alt2, snapBefore, snapAfter, disposable };
    };
    resetSashDragState(start, alt);
  }
  onSashChange({ current }) {
    const { index, start, sizes, alt, minDelta, maxDelta, snapBefore, snapAfter } = this.sashDragState;
    this.sashDragState.current = current;
    const delta = current - start;
    const newDelta = this.resize(index, delta, sizes, void 0, void 0, minDelta, maxDelta, snapBefore, snapAfter);
    if (alt) {
      const isLastSash = index === this.sashItems.length - 1;
      const newSizes = this.viewItems.map((i) => i.size);
      const viewItemIndex = isLastSash ? index : index + 1;
      const viewItem = this.viewItems[viewItemIndex];
      const newMinDelta = viewItem.size - viewItem.maximumSize;
      const newMaxDelta = viewItem.size - viewItem.minimumSize;
      const resizeIndex = isLastSash ? index - 1 : index + 1;
      this.resize(resizeIndex, -newDelta, newSizes, void 0, void 0, newMinDelta, newMaxDelta);
    }
    this.distributeEmptySpace();
    this.layoutViews();
  }
  onSashEnd(index) {
    this._onDidSashChange.fire(index);
    this.sashDragState.disposable.dispose();
    this.saveProportions();
    for (const item of this.viewItems) {
      item.enabled = true;
    }
  }
  onViewChange(item, size2) {
    const index = this.viewItems.indexOf(item);
    if (index < 0 || index >= this.viewItems.length) {
      return;
    }
    size2 = typeof size2 === "number" ? size2 : item.size;
    size2 = clamp(size2, item.minimumSize, item.maximumSize);
    if (this.inverseAltBehavior && index > 0) {
      this.resize(index - 1, Math.floor((item.size - size2) / 2));
      this.distributeEmptySpace();
      this.layoutViews();
    } else {
      item.size = size2;
      this.relayout([index], void 0);
    }
  }
  /**
   * Resize a {@link IView view} within the {@link SplitView}.
   *
   * @param index The {@link IView view} index.
   * @param size The {@link IView view} size.
   */
  resizeView(index, size2) {
    if (this.state !== State$1.Idle) {
      throw new Error("Cant modify splitview");
    }
    this.state = State$1.Busy;
    if (index < 0 || index >= this.viewItems.length) {
      return;
    }
    const indexes = range$1(this.viewItems.length).filter((i) => i !== index);
    const lowPriorityIndexes = [...indexes.filter(
      (i) => this.viewItems[i].priority === 1
      /* LayoutPriority.Low */
    ), index];
    const highPriorityIndexes = indexes.filter(
      (i) => this.viewItems[i].priority === 2
      /* LayoutPriority.High */
    );
    const item = this.viewItems[index];
    size2 = Math.round(size2);
    size2 = clamp(size2, item.minimumSize, Math.min(item.maximumSize, this.size));
    item.size = size2;
    this.relayout(lowPriorityIndexes, highPriorityIndexes);
    this.state = State$1.Idle;
  }
  /**
   * Distribute the entire {@link SplitView} size among all {@link IView views}.
   */
  distributeViewSizes() {
    const flexibleViewItems = [];
    let flexibleSize = 0;
    for (const item of this.viewItems) {
      if (item.maximumSize - item.minimumSize > 0) {
        flexibleViewItems.push(item);
        flexibleSize += item.size;
      }
    }
    const size2 = Math.floor(flexibleSize / flexibleViewItems.length);
    for (const item of flexibleViewItems) {
      item.size = clamp(size2, item.minimumSize, item.maximumSize);
    }
    const indexes = range$1(this.viewItems.length);
    const lowPriorityIndexes = indexes.filter(
      (i) => this.viewItems[i].priority === 1
      /* LayoutPriority.Low */
    );
    const highPriorityIndexes = indexes.filter(
      (i) => this.viewItems[i].priority === 2
      /* LayoutPriority.High */
    );
    this.relayout(lowPriorityIndexes, highPriorityIndexes);
  }
  /**
   * Returns the size of a {@link IView view}.
   */
  getViewSize(index) {
    if (index < 0 || index >= this.viewItems.length) {
      return -1;
    }
    return this.viewItems[index].size;
  }
  doAddView(view, size2, index = this.viewItems.length, skipLayout) {
    if (this.state !== State$1.Idle) {
      throw new Error("Cant modify splitview");
    }
    this.state = State$1.Busy;
    const container2 = $$d(".split-view-view");
    if (index === this.viewItems.length) {
      this.viewContainer.appendChild(container2);
    } else {
      this.viewContainer.insertBefore(container2, this.viewContainer.children.item(index));
    }
    const onChangeDisposable = view.onDidChange((size3) => this.onViewChange(item, size3));
    const containerDisposable = toDisposable(() => this.viewContainer.removeChild(container2));
    const disposable = combinedDisposable(onChangeDisposable, containerDisposable);
    let viewSize;
    if (typeof size2 === "number") {
      viewSize = size2;
    } else {
      if (size2.type === "auto") {
        if (this.areViewsDistributed()) {
          size2 = { type: "distribute" };
        } else {
          size2 = { type: "split", index: size2.index };
        }
      }
      if (size2.type === "split") {
        viewSize = this.getViewSize(size2.index) / 2;
      } else if (size2.type === "invisible") {
        viewSize = { cachedVisibleSize: size2.cachedVisibleSize };
      } else {
        viewSize = view.minimumSize;
      }
    }
    const item = this.orientation === 0 ? new VerticalViewItem(container2, view, viewSize, disposable) : new HorizontalViewItem(container2, view, viewSize, disposable);
    this.viewItems.splice(index, 0, item);
    if (this.viewItems.length > 1) {
      const opts = { orthogonalStartSash: this.orthogonalStartSash, orthogonalEndSash: this.orthogonalEndSash };
      const sash2 = this.orientation === 0 ? new Sash(this.sashContainer, { getHorizontalSashTop: (s) => this.getSashPosition(s), getHorizontalSashWidth: this.getSashOrthogonalSize }, Object.assign(Object.assign({}, opts), {
        orientation: 1
        /* Orientation.HORIZONTAL */
      })) : new Sash(this.sashContainer, { getVerticalSashLeft: (s) => this.getSashPosition(s), getVerticalSashHeight: this.getSashOrthogonalSize }, Object.assign(Object.assign({}, opts), {
        orientation: 0
        /* Orientation.VERTICAL */
      }));
      const sashEventMapper = this.orientation === 0 ? (e) => ({ sash: sash2, start: e.startY, current: e.currentY, alt: e.altKey }) : (e) => ({ sash: sash2, start: e.startX, current: e.currentX, alt: e.altKey });
      const onStart = Event$1.map(sash2.onDidStart, sashEventMapper);
      const onStartDisposable = onStart(this.onSashStart, this);
      const onChange = Event$1.map(sash2.onDidChange, sashEventMapper);
      const onChangeDisposable2 = onChange(this.onSashChange, this);
      const onEnd = Event$1.map(sash2.onDidEnd, () => this.sashItems.findIndex((item2) => item2.sash === sash2));
      const onEndDisposable = onEnd(this.onSashEnd, this);
      const onDidResetDisposable = sash2.onDidReset(() => {
        const index2 = this.sashItems.findIndex((item2) => item2.sash === sash2);
        const upIndexes = range$1(index2, -1);
        const downIndexes = range$1(index2 + 1, this.viewItems.length);
        const snapBeforeIndex = this.findFirstSnapIndex(upIndexes);
        const snapAfterIndex = this.findFirstSnapIndex(downIndexes);
        if (typeof snapBeforeIndex === "number" && !this.viewItems[snapBeforeIndex].visible) {
          return;
        }
        if (typeof snapAfterIndex === "number" && !this.viewItems[snapAfterIndex].visible) {
          return;
        }
        this._onDidSashReset.fire(index2);
      });
      const disposable2 = combinedDisposable(onStartDisposable, onChangeDisposable2, onEndDisposable, onDidResetDisposable, sash2);
      const sashItem = { sash: sash2, disposable: disposable2 };
      this.sashItems.splice(index - 1, 0, sashItem);
    }
    container2.appendChild(view.element);
    let highPriorityIndexes;
    if (typeof size2 !== "number" && size2.type === "split") {
      highPriorityIndexes = [size2.index];
    }
    if (!skipLayout) {
      this.relayout([index], highPriorityIndexes);
    }
    this.state = State$1.Idle;
    if (!skipLayout && typeof size2 !== "number" && size2.type === "distribute") {
      this.distributeViewSizes();
    }
  }
  relayout(lowPriorityIndexes, highPriorityIndexes) {
    const contentSize = this.viewItems.reduce((r, i) => r + i.size, 0);
    this.resize(this.viewItems.length - 1, this.size - contentSize, void 0, lowPriorityIndexes, highPriorityIndexes);
    this.distributeEmptySpace();
    this.layoutViews();
    this.saveProportions();
  }
  resize(index, delta, sizes = this.viewItems.map((i) => i.size), lowPriorityIndexes, highPriorityIndexes, overloadMinDelta = Number.NEGATIVE_INFINITY, overloadMaxDelta = Number.POSITIVE_INFINITY, snapBefore, snapAfter) {
    if (index < 0 || index >= this.viewItems.length) {
      return 0;
    }
    const upIndexes = range$1(index, -1);
    const downIndexes = range$1(index + 1, this.viewItems.length);
    if (highPriorityIndexes) {
      for (const index2 of highPriorityIndexes) {
        pushToStart(upIndexes, index2);
        pushToStart(downIndexes, index2);
      }
    }
    if (lowPriorityIndexes) {
      for (const index2 of lowPriorityIndexes) {
        pushToEnd(upIndexes, index2);
        pushToEnd(downIndexes, index2);
      }
    }
    const upItems = upIndexes.map((i) => this.viewItems[i]);
    const upSizes = upIndexes.map((i) => sizes[i]);
    const downItems = downIndexes.map((i) => this.viewItems[i]);
    const downSizes = downIndexes.map((i) => sizes[i]);
    const minDeltaUp = upIndexes.reduce((r, i) => r + (this.viewItems[i].minimumSize - sizes[i]), 0);
    const maxDeltaUp = upIndexes.reduce((r, i) => r + (this.viewItems[i].maximumSize - sizes[i]), 0);
    const maxDeltaDown = downIndexes.length === 0 ? Number.POSITIVE_INFINITY : downIndexes.reduce((r, i) => r + (sizes[i] - this.viewItems[i].minimumSize), 0);
    const minDeltaDown = downIndexes.length === 0 ? Number.NEGATIVE_INFINITY : downIndexes.reduce((r, i) => r + (sizes[i] - this.viewItems[i].maximumSize), 0);
    const minDelta = Math.max(minDeltaUp, minDeltaDown, overloadMinDelta);
    const maxDelta = Math.min(maxDeltaDown, maxDeltaUp, overloadMaxDelta);
    let snapped = false;
    if (snapBefore) {
      const snapView = this.viewItems[snapBefore.index];
      const visible = delta >= snapBefore.limitDelta;
      snapped = visible !== snapView.visible;
      snapView.setVisible(visible, snapBefore.size);
    }
    if (!snapped && snapAfter) {
      const snapView = this.viewItems[snapAfter.index];
      const visible = delta < snapAfter.limitDelta;
      snapped = visible !== snapView.visible;
      snapView.setVisible(visible, snapAfter.size);
    }
    if (snapped) {
      return this.resize(index, delta, sizes, lowPriorityIndexes, highPriorityIndexes, overloadMinDelta, overloadMaxDelta);
    }
    delta = clamp(delta, minDelta, maxDelta);
    for (let i = 0, deltaUp = delta; i < upItems.length; i++) {
      const item = upItems[i];
      const size2 = clamp(upSizes[i] + deltaUp, item.minimumSize, item.maximumSize);
      const viewDelta = size2 - upSizes[i];
      deltaUp -= viewDelta;
      item.size = size2;
    }
    for (let i = 0, deltaDown = delta; i < downItems.length; i++) {
      const item = downItems[i];
      const size2 = clamp(downSizes[i] - deltaDown, item.minimumSize, item.maximumSize);
      const viewDelta = size2 - downSizes[i];
      deltaDown += viewDelta;
      item.size = size2;
    }
    return delta;
  }
  distributeEmptySpace(lowPriorityIndex) {
    const contentSize = this.viewItems.reduce((r, i) => r + i.size, 0);
    let emptyDelta = this.size - contentSize;
    const indexes = range$1(this.viewItems.length - 1, -1);
    const lowPriorityIndexes = indexes.filter(
      (i) => this.viewItems[i].priority === 1
      /* LayoutPriority.Low */
    );
    const highPriorityIndexes = indexes.filter(
      (i) => this.viewItems[i].priority === 2
      /* LayoutPriority.High */
    );
    for (const index of highPriorityIndexes) {
      pushToStart(indexes, index);
    }
    for (const index of lowPriorityIndexes) {
      pushToEnd(indexes, index);
    }
    if (typeof lowPriorityIndex === "number") {
      pushToEnd(indexes, lowPriorityIndex);
    }
    for (let i = 0; emptyDelta !== 0 && i < indexes.length; i++) {
      const item = this.viewItems[indexes[i]];
      const size2 = clamp(item.size + emptyDelta, item.minimumSize, item.maximumSize);
      const viewDelta = size2 - item.size;
      emptyDelta -= viewDelta;
      item.size = size2;
    }
  }
  layoutViews() {
    this.contentSize = this.viewItems.reduce((r, i) => r + i.size, 0);
    let offset = 0;
    for (const viewItem of this.viewItems) {
      viewItem.layout(offset, this.layoutContext);
      offset += viewItem.size;
    }
    this.sashItems.forEach((item) => item.sash.layout());
    this.updateSashEnablement();
    this.updateScrollableElement();
  }
  updateScrollableElement() {
    if (this.orientation === 0) {
      this.scrollableElement.setScrollDimensions({
        height: this.size,
        scrollHeight: this.contentSize
      });
    } else {
      this.scrollableElement.setScrollDimensions({
        width: this.size,
        scrollWidth: this.contentSize
      });
    }
  }
  updateSashEnablement() {
    let previous = false;
    const collapsesDown = this.viewItems.map((i) => previous = i.size - i.minimumSize > 0 || previous);
    previous = false;
    const expandsDown = this.viewItems.map((i) => previous = i.maximumSize - i.size > 0 || previous);
    const reverseViews = [...this.viewItems].reverse();
    previous = false;
    const collapsesUp = reverseViews.map((i) => previous = i.size - i.minimumSize > 0 || previous).reverse();
    previous = false;
    const expandsUp = reverseViews.map((i) => previous = i.maximumSize - i.size > 0 || previous).reverse();
    let position = 0;
    for (let index = 0; index < this.sashItems.length; index++) {
      const { sash: sash2 } = this.sashItems[index];
      const viewItem = this.viewItems[index];
      position += viewItem.size;
      const min = !(collapsesDown[index] && expandsUp[index + 1]);
      const max = !(expandsDown[index] && collapsesUp[index + 1]);
      if (min && max) {
        const upIndexes = range$1(index, -1);
        const downIndexes = range$1(index + 1, this.viewItems.length);
        const snapBeforeIndex = this.findFirstSnapIndex(upIndexes);
        const snapAfterIndex = this.findFirstSnapIndex(downIndexes);
        const snappedBefore = typeof snapBeforeIndex === "number" && !this.viewItems[snapBeforeIndex].visible;
        const snappedAfter = typeof snapAfterIndex === "number" && !this.viewItems[snapAfterIndex].visible;
        if (snappedBefore && collapsesUp[index] && (position > 0 || this.startSnappingEnabled)) {
          sash2.state = 1;
        } else if (snappedAfter && collapsesDown[index] && (position < this.contentSize || this.endSnappingEnabled)) {
          sash2.state = 2;
        } else {
          sash2.state = 0;
        }
      } else if (min && !max) {
        sash2.state = 1;
      } else if (!min && max) {
        sash2.state = 2;
      } else {
        sash2.state = 3;
      }
    }
  }
  getSashPosition(sash2) {
    let position = 0;
    for (let i = 0; i < this.sashItems.length; i++) {
      position += this.viewItems[i].size;
      if (this.sashItems[i].sash === sash2) {
        return position;
      }
    }
    return 0;
  }
  findFirstSnapIndex(indexes) {
    for (const index of indexes) {
      const viewItem = this.viewItems[index];
      if (!viewItem.visible) {
        continue;
      }
      if (viewItem.snap) {
        return index;
      }
    }
    for (const index of indexes) {
      const viewItem = this.viewItems[index];
      if (viewItem.visible && viewItem.maximumSize - viewItem.minimumSize > 0) {
        return void 0;
      }
      if (!viewItem.visible && viewItem.snap) {
        return index;
      }
    }
    return void 0;
  }
  areViewsDistributed() {
    let min = void 0, max = void 0;
    for (const view of this.viewItems) {
      min = min === void 0 ? view.size : Math.min(min, view.size);
      max = max === void 0 ? view.size : Math.max(max, view.size);
      if (max - min > 2) {
        return false;
      }
    }
    return true;
  }
  dispose() {
    var _a2;
    (_a2 = this.sashDragState) === null || _a2 === void 0 ? void 0 : _a2.disposable.dispose();
    dispose(this.viewItems);
    this.viewItems = [];
    this.sashItems.forEach((i) => i.disposable.dispose());
    this.sashItems = [];
    super.dispose();
  }
}
const table = "";
class TableListRenderer {
  constructor(columns, renderers, getColumnSize) {
    this.columns = columns;
    this.getColumnSize = getColumnSize;
    this.templateId = TableListRenderer.TemplateId;
    this.renderedTemplates = /* @__PURE__ */ new Set();
    const rendererMap = new Map(renderers.map((r) => [r.templateId, r]));
    this.renderers = [];
    for (const column of columns) {
      const renderer2 = rendererMap.get(column.templateId);
      if (!renderer2) {
        throw new Error(`Table cell renderer for template id ${column.templateId} not found.`);
      }
      this.renderers.push(renderer2);
    }
  }
  renderTemplate(container2) {
    const rowContainer = append$1(container2, $$d(".monaco-table-tr"));
    const cellContainers = [];
    const cellTemplateData = [];
    for (let i = 0; i < this.columns.length; i++) {
      const renderer2 = this.renderers[i];
      const cellContainer = append$1(rowContainer, $$d(".monaco-table-td", { "data-col-index": i }));
      cellContainer.style.width = `${this.getColumnSize(i)}px`;
      cellContainers.push(cellContainer);
      cellTemplateData.push(renderer2.renderTemplate(cellContainer));
    }
    const result2 = { container: container2, cellContainers, cellTemplateData };
    this.renderedTemplates.add(result2);
    return result2;
  }
  renderElement(element, index, templateData, height) {
    for (let i = 0; i < this.columns.length; i++) {
      const column = this.columns[i];
      const cell = column.project(element);
      const renderer2 = this.renderers[i];
      renderer2.renderElement(cell, index, templateData.cellTemplateData[i], height);
    }
  }
  disposeElement(element, index, templateData, height) {
    for (let i = 0; i < this.columns.length; i++) {
      const renderer2 = this.renderers[i];
      if (renderer2.disposeElement) {
        const column = this.columns[i];
        const cell = column.project(element);
        renderer2.disposeElement(cell, index, templateData.cellTemplateData[i], height);
      }
    }
  }
  disposeTemplate(templateData) {
    for (let i = 0; i < this.columns.length; i++) {
      const renderer2 = this.renderers[i];
      renderer2.disposeTemplate(templateData.cellTemplateData[i]);
    }
    clearNode(templateData.container);
    this.renderedTemplates.delete(templateData);
  }
  layoutColumn(index, size2) {
    for (const { cellContainers } of this.renderedTemplates) {
      cellContainers[index].style.width = `${size2}px`;
    }
  }
}
TableListRenderer.TemplateId = "row";
function asListVirtualDelegate(delegate) {
  return {
    getHeight(row) {
      return delegate.getHeight(row);
    },
    getTemplateId() {
      return TableListRenderer.TemplateId;
    }
  };
}
class ColumnHeader {
  get minimumSize() {
    var _a2;
    return (_a2 = this.column.minimumWidth) !== null && _a2 !== void 0 ? _a2 : 120;
  }
  get maximumSize() {
    var _a2;
    return (_a2 = this.column.maximumWidth) !== null && _a2 !== void 0 ? _a2 : Number.POSITIVE_INFINITY;
  }
  get onDidChange() {
    var _a2;
    return (_a2 = this.column.onDidChangeWidthConstraints) !== null && _a2 !== void 0 ? _a2 : Event$1.None;
  }
  constructor(column, index) {
    this.column = column;
    this.index = index;
    this._onDidLayout = new Emitter$1();
    this.onDidLayout = this._onDidLayout.event;
    this.element = $$d(".monaco-table-th", { "data-col-index": index, title: column.tooltip }, column.label);
  }
  layout(size2) {
    this._onDidLayout.fire([this.index, size2]);
  }
}
class Table {
  get onDidChangeFocus() {
    return this.list.onDidChangeFocus;
  }
  get onDidChangeSelection() {
    return this.list.onDidChangeSelection;
  }
  get onDidScroll() {
    return this.list.onDidScroll;
  }
  get onMouseDblClick() {
    return this.list.onMouseDblClick;
  }
  get onPointer() {
    return this.list.onPointer;
  }
  get onDidFocus() {
    return this.list.onDidFocus;
  }
  get scrollTop() {
    return this.list.scrollTop;
  }
  set scrollTop(scrollTop) {
    this.list.scrollTop = scrollTop;
  }
  get scrollHeight() {
    return this.list.scrollHeight;
  }
  get renderHeight() {
    return this.list.renderHeight;
  }
  get onDidDispose() {
    return this.list.onDidDispose;
  }
  constructor(user, container2, virtualDelegate, columns, renderers, _options) {
    this.virtualDelegate = virtualDelegate;
    this.domId = `table_id_${++Table.InstanceCount}`;
    this.disposables = new DisposableStore();
    this.cachedWidth = 0;
    this.cachedHeight = 0;
    this.domNode = append$1(container2, $$d(`.monaco-table.${this.domId}`));
    const headers = columns.map((c, i) => new ColumnHeader(c, i));
    const descriptor = {
      size: headers.reduce((a, b) => a + b.column.weight, 0),
      views: headers.map((view) => ({ size: view.column.weight, view }))
    };
    this.splitview = this.disposables.add(new SplitView(this.domNode, {
      orientation: 1,
      scrollbarVisibility: 2,
      getSashOrthogonalSize: () => this.cachedHeight,
      descriptor
    }));
    this.splitview.el.style.height = `${virtualDelegate.headerRowHeight}px`;
    this.splitview.el.style.lineHeight = `${virtualDelegate.headerRowHeight}px`;
    const renderer2 = new TableListRenderer(columns, renderers, (i) => this.splitview.getViewSize(i));
    this.list = this.disposables.add(new List(user, this.domNode, asListVirtualDelegate(virtualDelegate), [renderer2], _options));
    Event$1.any(...headers.map((h2) => h2.onDidLayout))(([index, size2]) => renderer2.layoutColumn(index, size2), null, this.disposables);
    this.splitview.onDidSashReset((index) => {
      const totalWeight = columns.reduce((r, c) => r + c.weight, 0);
      const size2 = columns[index].weight / totalWeight * this.cachedWidth;
      this.splitview.resizeView(index, size2);
    }, null, this.disposables);
    this.styleElement = createStyleSheet(this.domNode);
    this.style(unthemedListStyles);
  }
  updateOptions(options) {
    this.list.updateOptions(options);
  }
  splice(start, deleteCount, elements = []) {
    this.list.splice(start, deleteCount, elements);
  }
  getHTMLElement() {
    return this.domNode;
  }
  style(styles) {
    const content = [];
    content.push(`.monaco-table.${this.domId} > .monaco-split-view2 .monaco-sash.vertical::before {
			top: ${this.virtualDelegate.headerRowHeight + 1}px;
			height: calc(100% - ${this.virtualDelegate.headerRowHeight}px);
		}`);
    this.styleElement.textContent = content.join("\n");
    this.list.style(styles);
  }
  getSelectedElements() {
    return this.list.getSelectedElements();
  }
  getSelection() {
    return this.list.getSelection();
  }
  getFocus() {
    return this.list.getFocus();
  }
  dispose() {
    this.disposables.dispose();
  }
}
Table.InstanceCount = 0;
const toggle = "";
class Toggle extends Widget$1 {
  constructor(opts) {
    super();
    this._onChange = this._register(new Emitter$1());
    this.onChange = this._onChange.event;
    this._onKeyDown = this._register(new Emitter$1());
    this.onKeyDown = this._onKeyDown.event;
    this._opts = opts;
    this._checked = this._opts.isChecked;
    const classes = ["monaco-custom-toggle"];
    if (this._opts.icon) {
      this._icon = this._opts.icon;
      classes.push(...ThemeIcon.asClassNameArray(this._icon));
    }
    if (this._opts.actionClassName) {
      classes.push(...this._opts.actionClassName.split(" "));
    }
    if (this._checked) {
      classes.push("checked");
    }
    this.domNode = document.createElement("div");
    this.domNode.title = this._opts.title;
    this.domNode.classList.add(...classes);
    if (!this._opts.notFocusable) {
      this.domNode.tabIndex = 0;
    }
    this.domNode.setAttribute("role", "checkbox");
    this.domNode.setAttribute("aria-checked", String(this._checked));
    this.domNode.setAttribute("aria-label", this._opts.title);
    this.applyStyles();
    this.onclick(this.domNode, (ev) => {
      if (this.enabled) {
        this.checked = !this._checked;
        this._onChange.fire(false);
        ev.preventDefault();
      }
    });
    this._register(this.ignoreGesture(this.domNode));
    this.onkeydown(this.domNode, (keyboardEvent) => {
      if (keyboardEvent.keyCode === 10 || keyboardEvent.keyCode === 3) {
        this.checked = !this._checked;
        this._onChange.fire(true);
        keyboardEvent.preventDefault();
        keyboardEvent.stopPropagation();
        return;
      }
      this._onKeyDown.fire(keyboardEvent);
    });
  }
  get enabled() {
    return this.domNode.getAttribute("aria-disabled") !== "true";
  }
  focus() {
    this.domNode.focus();
  }
  get checked() {
    return this._checked;
  }
  set checked(newIsChecked) {
    this._checked = newIsChecked;
    this.domNode.setAttribute("aria-checked", String(this._checked));
    this.domNode.classList.toggle("checked", this._checked);
    this.applyStyles();
  }
  width() {
    return 2 + 2 + 2 + 16;
  }
  applyStyles() {
    if (this.domNode) {
      this.domNode.style.borderColor = this._checked && this._opts.inputActiveOptionBorder || "";
      this.domNode.style.color = this._checked && this._opts.inputActiveOptionForeground || "inherit";
      this.domNode.style.backgroundColor = this._checked && this._opts.inputActiveOptionBackground || "";
    }
  }
  enable() {
    this.domNode.setAttribute("aria-disabled", String(false));
  }
  disable() {
    this.domNode.setAttribute("aria-disabled", String(true));
  }
}
const NLS_CASE_SENSITIVE_TOGGLE_LABEL = localize("caseDescription", "Match Case");
const NLS_WHOLE_WORD_TOGGLE_LABEL = localize("wordsDescription", "Match Whole Word");
const NLS_REGEX_TOGGLE_LABEL = localize("regexDescription", "Use Regular Expression");
class CaseSensitiveToggle extends Toggle {
  constructor(opts) {
    super({
      icon: Codicon.caseSensitive,
      title: NLS_CASE_SENSITIVE_TOGGLE_LABEL + opts.appendTitle,
      isChecked: opts.isChecked,
      inputActiveOptionBorder: opts.inputActiveOptionBorder,
      inputActiveOptionForeground: opts.inputActiveOptionForeground,
      inputActiveOptionBackground: opts.inputActiveOptionBackground
    });
  }
}
class WholeWordsToggle extends Toggle {
  constructor(opts) {
    super({
      icon: Codicon.wholeWord,
      title: NLS_WHOLE_WORD_TOGGLE_LABEL + opts.appendTitle,
      isChecked: opts.isChecked,
      inputActiveOptionBorder: opts.inputActiveOptionBorder,
      inputActiveOptionForeground: opts.inputActiveOptionForeground,
      inputActiveOptionBackground: opts.inputActiveOptionBackground
    });
  }
}
class RegexToggle extends Toggle {
  constructor(opts) {
    super({
      icon: Codicon.regex,
      title: NLS_REGEX_TOGGLE_LABEL + opts.appendTitle,
      isChecked: opts.isChecked,
      inputActiveOptionBorder: opts.inputActiveOptionBorder,
      inputActiveOptionForeground: opts.inputActiveOptionForeground,
      inputActiveOptionBackground: opts.inputActiveOptionBackground
    });
  }
}
class ArrayNavigator {
  constructor(items, start = 0, end = items.length, index = start - 1) {
    this.items = items;
    this.start = start;
    this.end = end;
    this.index = index;
  }
  current() {
    if (this.index === this.start - 1 || this.index === this.end) {
      return null;
    }
    return this.items[this.index];
  }
  next() {
    this.index = Math.min(this.index + 1, this.end);
    return this.current();
  }
  previous() {
    this.index = Math.max(this.index - 1, this.start - 1);
    return this.current();
  }
  first() {
    this.index = this.start;
    return this.current();
  }
  last() {
    this.index = this.end - 1;
    return this.current();
  }
}
class HistoryNavigator {
  constructor(history = [], limit = 10) {
    this._initialize(history);
    this._limit = limit;
    this._onChange();
  }
  getHistory() {
    return this._elements;
  }
  add(t) {
    this._history.delete(t);
    this._history.add(t);
    this._onChange();
  }
  next() {
    return this._navigator.next();
  }
  previous() {
    if (this._currentPosition() !== 0) {
      return this._navigator.previous();
    }
    return null;
  }
  current() {
    return this._navigator.current();
  }
  first() {
    return this._navigator.first();
  }
  last() {
    return this._navigator.last();
  }
  isLast() {
    return this._currentPosition() >= this._elements.length - 1;
  }
  isNowhere() {
    return this._navigator.current() === null;
  }
  has(t) {
    return this._history.has(t);
  }
  _onChange() {
    this._reduceToLimit();
    const elements = this._elements;
    this._navigator = new ArrayNavigator(elements, 0, elements.length, elements.length);
  }
  _reduceToLimit() {
    const data = this._elements;
    if (data.length > this._limit) {
      this._initialize(data.slice(data.length - this._limit));
    }
  }
  _currentPosition() {
    const currentElement = this._navigator.current();
    if (!currentElement) {
      return -1;
    }
    return this._elements.indexOf(currentElement);
  }
  _initialize(history) {
    this._history = /* @__PURE__ */ new Set();
    for (const entry of history) {
      this._history.add(entry);
    }
  }
  get _elements() {
    const elements = [];
    this._history.forEach((e) => elements.push(e));
    return elements;
  }
}
const inputBox = "";
const $$9 = $$d;
let InputBox$1 = class InputBox extends Widget$1 {
  constructor(container2, contextViewProvider, options) {
    var _a2;
    super();
    this.state = "idle";
    this.maxHeight = Number.POSITIVE_INFINITY;
    this._onDidChange = this._register(new Emitter$1());
    this.onDidChange = this._onDidChange.event;
    this._onDidHeightChange = this._register(new Emitter$1());
    this.onDidHeightChange = this._onDidHeightChange.event;
    this.contextViewProvider = contextViewProvider;
    this.options = options;
    this.message = null;
    this.placeholder = this.options.placeholder || "";
    this.tooltip = (_a2 = this.options.tooltip) !== null && _a2 !== void 0 ? _a2 : this.placeholder || "";
    this.ariaLabel = this.options.ariaLabel || "";
    if (this.options.validationOptions) {
      this.validation = this.options.validationOptions.validation;
    }
    this.element = append$1(container2, $$9(".monaco-inputbox.idle"));
    const tagName = this.options.flexibleHeight ? "textarea" : "input";
    const wrapper = append$1(this.element, $$9(".ibwrapper"));
    this.input = append$1(wrapper, $$9(tagName + ".input.empty"));
    this.input.setAttribute("autocorrect", "off");
    this.input.setAttribute("autocapitalize", "off");
    this.input.setAttribute("spellcheck", "false");
    this.onfocus(this.input, () => this.element.classList.add("synthetic-focus"));
    this.onblur(this.input, () => this.element.classList.remove("synthetic-focus"));
    if (this.options.flexibleHeight) {
      this.maxHeight = typeof this.options.flexibleMaxHeight === "number" ? this.options.flexibleMaxHeight : Number.POSITIVE_INFINITY;
      this.mirror = append$1(wrapper, $$9("div.mirror"));
      this.mirror.innerText = " ";
      this.scrollableElement = new ScrollableElement(this.element, {
        vertical: 1
        /* ScrollbarVisibility.Auto */
      });
      if (this.options.flexibleWidth) {
        this.input.setAttribute("wrap", "off");
        this.mirror.style.whiteSpace = "pre";
        this.mirror.style.wordWrap = "initial";
      }
      append$1(container2, this.scrollableElement.getDomNode());
      this._register(this.scrollableElement);
      this._register(this.scrollableElement.onScroll((e) => this.input.scrollTop = e.scrollTop));
      const onSelectionChange = this._register(new DomEmitter(document, "selectionchange"));
      const onAnchoredSelectionChange = Event$1.filter(onSelectionChange.event, () => {
        const selection = document.getSelection();
        return (selection === null || selection === void 0 ? void 0 : selection.anchorNode) === wrapper;
      });
      this._register(onAnchoredSelectionChange(this.updateScrollDimensions, this));
      this._register(this.onDidHeightChange(this.updateScrollDimensions, this));
    } else {
      this.input.type = this.options.type || "text";
      this.input.setAttribute("wrap", "off");
    }
    if (this.ariaLabel) {
      this.input.setAttribute("aria-label", this.ariaLabel);
    }
    if (this.placeholder && !this.options.showPlaceholderOnFocus) {
      this.setPlaceHolder(this.placeholder);
    }
    if (this.tooltip) {
      this.setTooltip(this.tooltip);
    }
    this.oninput(this.input, () => this.onValueChange());
    this.onblur(this.input, () => this.onBlur());
    this.onfocus(this.input, () => this.onFocus());
    this._register(this.ignoreGesture(this.input));
    setTimeout(() => this.updateMirror(), 0);
    if (this.options.actions) {
      this.actionbar = this._register(new ActionBar(this.element));
      this.actionbar.push(this.options.actions, { icon: true, label: false });
    }
    this.applyStyles();
  }
  onBlur() {
    this._hideMessage();
    if (this.options.showPlaceholderOnFocus) {
      this.input.setAttribute("placeholder", "");
    }
  }
  onFocus() {
    this._showMessage();
    if (this.options.showPlaceholderOnFocus) {
      this.input.setAttribute("placeholder", this.placeholder || "");
    }
  }
  setPlaceHolder(placeHolder) {
    this.placeholder = placeHolder;
    this.input.setAttribute("placeholder", placeHolder);
  }
  setTooltip(tooltip) {
    this.tooltip = tooltip;
    this.input.title = tooltip;
  }
  get inputElement() {
    return this.input;
  }
  get value() {
    return this.input.value;
  }
  set value(newValue) {
    if (this.input.value !== newValue) {
      this.input.value = newValue;
      this.onValueChange();
    }
  }
  get height() {
    return typeof this.cachedHeight === "number" ? this.cachedHeight : getTotalHeight(this.element);
  }
  focus() {
    this.input.focus();
  }
  blur() {
    this.input.blur();
  }
  hasFocus() {
    return document.activeElement === this.input;
  }
  select(range2 = null) {
    this.input.select();
    if (range2) {
      this.input.setSelectionRange(range2.start, range2.end);
      if (range2.end === this.input.value.length) {
        this.input.scrollLeft = this.input.scrollWidth;
      }
    }
  }
  isSelectionAtEnd() {
    return this.input.selectionEnd === this.input.value.length && this.input.selectionStart === this.input.selectionEnd;
  }
  enable() {
    this.input.removeAttribute("disabled");
  }
  disable() {
    this.blur();
    this.input.disabled = true;
    this._hideMessage();
  }
  set paddingRight(paddingRight) {
    this.input.style.width = `calc(100% - ${paddingRight}px)`;
    if (this.mirror) {
      this.mirror.style.paddingRight = paddingRight + "px";
    }
  }
  updateScrollDimensions() {
    if (typeof this.cachedContentHeight !== "number" || typeof this.cachedHeight !== "number" || !this.scrollableElement) {
      return;
    }
    const scrollHeight = this.cachedContentHeight;
    const height = this.cachedHeight;
    const scrollTop = this.input.scrollTop;
    this.scrollableElement.setScrollDimensions({ scrollHeight, height });
    this.scrollableElement.setScrollPosition({ scrollTop });
  }
  showMessage(message, force) {
    if (this.state === "open" && equals$2(this.message, message)) {
      return;
    }
    this.message = message;
    this.element.classList.remove("idle");
    this.element.classList.remove("info");
    this.element.classList.remove("warning");
    this.element.classList.remove("error");
    this.element.classList.add(this.classForType(message.type));
    const styles = this.stylesForType(this.message.type);
    this.element.style.border = `1px solid ${asCssValueWithDefault(styles.border, "transparent")}`;
    if (this.message.content && (this.hasFocus() || force)) {
      this._showMessage();
    }
  }
  hideMessage() {
    this.message = null;
    this.element.classList.remove("info");
    this.element.classList.remove("warning");
    this.element.classList.remove("error");
    this.element.classList.add("idle");
    this._hideMessage();
    this.applyStyles();
  }
  validate() {
    let errorMsg = null;
    if (this.validation) {
      errorMsg = this.validation(this.value);
      if (errorMsg) {
        this.inputElement.setAttribute("aria-invalid", "true");
        this.showMessage(errorMsg);
      } else if (this.inputElement.hasAttribute("aria-invalid")) {
        this.inputElement.removeAttribute("aria-invalid");
        this.hideMessage();
      }
    }
    return errorMsg === null || errorMsg === void 0 ? void 0 : errorMsg.type;
  }
  stylesForType(type) {
    const styles = this.options.inputBoxStyles;
    switch (type) {
      case 1:
        return { border: styles.inputValidationInfoBorder, background: styles.inputValidationInfoBackground, foreground: styles.inputValidationInfoForeground };
      case 2:
        return { border: styles.inputValidationWarningBorder, background: styles.inputValidationWarningBackground, foreground: styles.inputValidationWarningForeground };
      default:
        return { border: styles.inputValidationErrorBorder, background: styles.inputValidationErrorBackground, foreground: styles.inputValidationErrorForeground };
    }
  }
  classForType(type) {
    switch (type) {
      case 1:
        return "info";
      case 2:
        return "warning";
      default:
        return "error";
    }
  }
  _showMessage() {
    if (!this.contextViewProvider || !this.message) {
      return;
    }
    let div;
    const layout2 = () => div.style.width = getTotalWidth(this.element) + "px";
    this.contextViewProvider.showContextView({
      getAnchor: () => this.element,
      anchorAlignment: 1,
      render: (container2) => {
        var _a2, _b2;
        if (!this.message) {
          return null;
        }
        div = append$1(container2, $$9(".monaco-inputbox-container"));
        layout2();
        const renderOptions = {
          inline: true,
          className: "monaco-inputbox-message"
        };
        const spanElement = this.message.formatContent ? renderFormattedText(this.message.content, renderOptions) : renderText(this.message.content, renderOptions);
        spanElement.classList.add(this.classForType(this.message.type));
        const styles = this.stylesForType(this.message.type);
        spanElement.style.backgroundColor = (_a2 = styles.background) !== null && _a2 !== void 0 ? _a2 : "";
        spanElement.style.color = (_b2 = styles.foreground) !== null && _b2 !== void 0 ? _b2 : "";
        spanElement.style.border = styles.border ? `1px solid ${styles.border}` : "";
        append$1(div, spanElement);
        return null;
      },
      onHide: () => {
        this.state = "closed";
      },
      layout: layout2
    });
    let alertText;
    if (this.message.type === 3) {
      alertText = localize("alertErrorMessage", "Error: {0}", this.message.content);
    } else if (this.message.type === 2) {
      alertText = localize("alertWarningMessage", "Warning: {0}", this.message.content);
    } else {
      alertText = localize("alertInfoMessage", "Info: {0}", this.message.content);
    }
    alert(alertText);
    this.state = "open";
  }
  _hideMessage() {
    if (!this.contextViewProvider) {
      return;
    }
    if (this.state === "open") {
      this.contextViewProvider.hideContextView();
    }
    this.state = "idle";
  }
  onValueChange() {
    this._onDidChange.fire(this.value);
    this.validate();
    this.updateMirror();
    this.input.classList.toggle("empty", !this.value);
    if (this.state === "open" && this.contextViewProvider) {
      this.contextViewProvider.layout();
    }
  }
  updateMirror() {
    if (!this.mirror) {
      return;
    }
    const value = this.value;
    const lastCharCode = value.charCodeAt(value.length - 1);
    const suffix = lastCharCode === 10 ? " " : "";
    const mirrorTextContent = (value + suffix).replace(/\u000c/g, "");
    if (mirrorTextContent) {
      this.mirror.textContent = value + suffix;
    } else {
      this.mirror.innerText = " ";
    }
    this.layout();
  }
  applyStyles() {
    var _a2, _b2, _c2;
    const styles = this.options.inputBoxStyles;
    const background = (_a2 = styles.inputBackground) !== null && _a2 !== void 0 ? _a2 : "";
    const foreground2 = (_b2 = styles.inputForeground) !== null && _b2 !== void 0 ? _b2 : "";
    const border = (_c2 = styles.inputBorder) !== null && _c2 !== void 0 ? _c2 : "";
    this.element.style.backgroundColor = background;
    this.element.style.color = foreground2;
    this.input.style.backgroundColor = "inherit";
    this.input.style.color = foreground2;
    this.element.style.border = `1px solid ${asCssValueWithDefault(border, "transparent")}`;
  }
  layout() {
    if (!this.mirror) {
      return;
    }
    const previousHeight = this.cachedContentHeight;
    this.cachedContentHeight = getTotalHeight(this.mirror);
    if (previousHeight !== this.cachedContentHeight) {
      this.cachedHeight = Math.min(this.cachedContentHeight, this.maxHeight);
      this.input.style.height = this.cachedHeight + "px";
      this._onDidHeightChange.fire(this.cachedContentHeight);
    }
  }
  insertAtCursor(text2) {
    const inputElement = this.inputElement;
    const start = inputElement.selectionStart;
    const end = inputElement.selectionEnd;
    const content = inputElement.value;
    if (start !== null && end !== null) {
      this.value = content.substr(0, start) + text2 + content.substr(end);
      inputElement.setSelectionRange(start + 1, start + 1);
      this.layout();
    }
  }
  dispose() {
    var _a2;
    this._hideMessage();
    this.message = null;
    (_a2 = this.actionbar) === null || _a2 === void 0 ? void 0 : _a2.dispose();
    super.dispose();
  }
};
class HistoryInputBox extends InputBox$1 {
  constructor(container2, contextViewProvider, options) {
    const NLS_PLACEHOLDER_HISTORY_HINT = localize({ key: "history.inputbox.hint", comment: ["Text will be prefixed with ⇅ plus a single space, then used as a hint where input field keeps history"] }, "for history");
    const NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX = ` or ⇅ ${NLS_PLACEHOLDER_HISTORY_HINT}`;
    const NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_IN_PARENS = ` (⇅ ${NLS_PLACEHOLDER_HISTORY_HINT})`;
    super(container2, contextViewProvider, options);
    this._onDidFocus = this._register(new Emitter$1());
    this.onDidFocus = this._onDidFocus.event;
    this._onDidBlur = this._register(new Emitter$1());
    this.onDidBlur = this._onDidBlur.event;
    this.history = new HistoryNavigator(options.history, 100);
    const addSuffix = () => {
      if (options.showHistoryHint && options.showHistoryHint() && !this.placeholder.endsWith(NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX) && !this.placeholder.endsWith(NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_IN_PARENS) && this.history.getHistory().length) {
        const suffix = this.placeholder.endsWith(")") ? NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX : NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_IN_PARENS;
        const suffixedPlaceholder = this.placeholder + suffix;
        if (options.showPlaceholderOnFocus && document.activeElement !== this.input) {
          this.placeholder = suffixedPlaceholder;
        } else {
          this.setPlaceHolder(suffixedPlaceholder);
        }
      }
    };
    this.observer = new MutationObserver((mutationList, observer) => {
      mutationList.forEach((mutation) => {
        if (!mutation.target.textContent) {
          addSuffix();
        }
      });
    });
    this.observer.observe(this.input, { attributeFilter: ["class"] });
    this.onfocus(this.input, () => addSuffix());
    this.onblur(this.input, () => {
      const resetPlaceholder = (historyHint) => {
        if (!this.placeholder.endsWith(historyHint)) {
          return false;
        } else {
          const revertedPlaceholder = this.placeholder.slice(0, this.placeholder.length - historyHint.length);
          if (options.showPlaceholderOnFocus) {
            this.placeholder = revertedPlaceholder;
          } else {
            this.setPlaceHolder(revertedPlaceholder);
          }
          return true;
        }
      };
      if (!resetPlaceholder(NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX_IN_PARENS)) {
        resetPlaceholder(NLS_PLACEHOLDER_HISTORY_HINT_SUFFIX);
      }
    });
  }
  dispose() {
    super.dispose();
    if (this.observer) {
      this.observer.disconnect();
      this.observer = void 0;
    }
  }
  addToHistory(always) {
    if (this.value && (always || this.value !== this.getCurrentValue())) {
      this.history.add(this.value);
    }
  }
  isAtLastInHistory() {
    return this.history.isLast();
  }
  isNowhereInHistory() {
    return this.history.isNowhere();
  }
  showNextValue() {
    if (!this.history.has(this.value)) {
      this.addToHistory();
    }
    let next = this.getNextValue();
    if (next) {
      next = next === this.value ? this.getNextValue() : next;
    }
    this.value = next !== null && next !== void 0 ? next : "";
    status(this.value ? this.value : localize("clearedInput", "Cleared Input"));
  }
  showPreviousValue() {
    if (!this.history.has(this.value)) {
      this.addToHistory();
    }
    let previous = this.getPreviousValue();
    if (previous) {
      previous = previous === this.value ? this.getPreviousValue() : previous;
    }
    if (previous) {
      this.value = previous;
      status(this.value);
    }
  }
  onBlur() {
    super.onBlur();
    this._onDidBlur.fire();
  }
  onFocus() {
    super.onFocus();
    this._onDidFocus.fire();
  }
  getCurrentValue() {
    let currentValue = this.history.current();
    if (!currentValue) {
      currentValue = this.history.last();
      this.history.next();
    }
    return currentValue;
  }
  getPreviousValue() {
    return this.history.previous() || this.history.first();
  }
  getNextValue() {
    return this.history.next();
  }
}
const findInput = "";
const NLS_DEFAULT_LABEL$1 = localize("defaultLabel", "input");
class FindInput extends Widget$1 {
  constructor(parent, contextViewProvider, options) {
    super();
    this.fixFocusOnOptionClickEnabled = true;
    this.imeSessionInProgress = false;
    this.additionalTogglesDisposables = new DisposableStore();
    this.additionalToggles = [];
    this._onDidOptionChange = this._register(new Emitter$1());
    this.onDidOptionChange = this._onDidOptionChange.event;
    this._onKeyDown = this._register(new Emitter$1());
    this.onKeyDown = this._onKeyDown.event;
    this._onMouseDown = this._register(new Emitter$1());
    this.onMouseDown = this._onMouseDown.event;
    this._onInput = this._register(new Emitter$1());
    this._onKeyUp = this._register(new Emitter$1());
    this._onCaseSensitiveKeyDown = this._register(new Emitter$1());
    this.onCaseSensitiveKeyDown = this._onCaseSensitiveKeyDown.event;
    this._onRegexKeyDown = this._register(new Emitter$1());
    this.onRegexKeyDown = this._onRegexKeyDown.event;
    this._lastHighlightFindOptions = 0;
    this.placeholder = options.placeholder || "";
    this.validation = options.validation;
    this.label = options.label || NLS_DEFAULT_LABEL$1;
    this.showCommonFindToggles = !!options.showCommonFindToggles;
    const appendCaseSensitiveLabel = options.appendCaseSensitiveLabel || "";
    const appendWholeWordsLabel = options.appendWholeWordsLabel || "";
    const appendRegexLabel = options.appendRegexLabel || "";
    const history = options.history || [];
    const flexibleHeight = !!options.flexibleHeight;
    const flexibleWidth = !!options.flexibleWidth;
    const flexibleMaxHeight = options.flexibleMaxHeight;
    this.domNode = document.createElement("div");
    this.domNode.classList.add("monaco-findInput");
    this.inputBox = this._register(new HistoryInputBox(this.domNode, contextViewProvider, {
      placeholder: this.placeholder || "",
      ariaLabel: this.label || "",
      validationOptions: {
        validation: this.validation
      },
      history,
      showHistoryHint: options.showHistoryHint,
      flexibleHeight,
      flexibleWidth,
      flexibleMaxHeight,
      inputBoxStyles: options.inputBoxStyles
    }));
    if (this.showCommonFindToggles) {
      this.regex = this._register(new RegexToggle(Object.assign({ appendTitle: appendRegexLabel, isChecked: false }, options.toggleStyles)));
      this._register(this.regex.onChange((viaKeyboard) => {
        this._onDidOptionChange.fire(viaKeyboard);
        if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
          this.inputBox.focus();
        }
        this.validate();
      }));
      this._register(this.regex.onKeyDown((e) => {
        this._onRegexKeyDown.fire(e);
      }));
      this.wholeWords = this._register(new WholeWordsToggle(Object.assign({ appendTitle: appendWholeWordsLabel, isChecked: false }, options.toggleStyles)));
      this._register(this.wholeWords.onChange((viaKeyboard) => {
        this._onDidOptionChange.fire(viaKeyboard);
        if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
          this.inputBox.focus();
        }
        this.validate();
      }));
      this.caseSensitive = this._register(new CaseSensitiveToggle(Object.assign({ appendTitle: appendCaseSensitiveLabel, isChecked: false }, options.toggleStyles)));
      this._register(this.caseSensitive.onChange((viaKeyboard) => {
        this._onDidOptionChange.fire(viaKeyboard);
        if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
          this.inputBox.focus();
        }
        this.validate();
      }));
      this._register(this.caseSensitive.onKeyDown((e) => {
        this._onCaseSensitiveKeyDown.fire(e);
      }));
      const indexes = [this.caseSensitive.domNode, this.wholeWords.domNode, this.regex.domNode];
      this.onkeydown(this.domNode, (event) => {
        if (event.equals(
          15
          /* KeyCode.LeftArrow */
        ) || event.equals(
          17
          /* KeyCode.RightArrow */
        ) || event.equals(
          9
          /* KeyCode.Escape */
        )) {
          const index = indexes.indexOf(document.activeElement);
          if (index >= 0) {
            let newIndex = -1;
            if (event.equals(
              17
              /* KeyCode.RightArrow */
            )) {
              newIndex = (index + 1) % indexes.length;
            } else if (event.equals(
              15
              /* KeyCode.LeftArrow */
            )) {
              if (index === 0) {
                newIndex = indexes.length - 1;
              } else {
                newIndex = index - 1;
              }
            }
            if (event.equals(
              9
              /* KeyCode.Escape */
            )) {
              indexes[index].blur();
              this.inputBox.focus();
            } else if (newIndex >= 0) {
              indexes[newIndex].focus();
            }
            EventHelper.stop(event, true);
          }
        }
      });
    }
    this.controls = document.createElement("div");
    this.controls.className = "controls";
    this.controls.style.display = this.showCommonFindToggles ? "" : "none";
    if (this.caseSensitive) {
      this.controls.append(this.caseSensitive.domNode);
    }
    if (this.wholeWords) {
      this.controls.appendChild(this.wholeWords.domNode);
    }
    if (this.regex) {
      this.controls.appendChild(this.regex.domNode);
    }
    this.setAdditionalToggles(options === null || options === void 0 ? void 0 : options.additionalToggles);
    if (this.controls) {
      this.domNode.appendChild(this.controls);
    }
    parent === null || parent === void 0 ? void 0 : parent.appendChild(this.domNode);
    this._register(addDisposableListener(this.inputBox.inputElement, "compositionstart", (e) => {
      this.imeSessionInProgress = true;
    }));
    this._register(addDisposableListener(this.inputBox.inputElement, "compositionend", (e) => {
      this.imeSessionInProgress = false;
      this._onInput.fire();
    }));
    this.onkeydown(this.inputBox.inputElement, (e) => this._onKeyDown.fire(e));
    this.onkeyup(this.inputBox.inputElement, (e) => this._onKeyUp.fire(e));
    this.oninput(this.inputBox.inputElement, (e) => this._onInput.fire());
    this.onmousedown(this.inputBox.inputElement, (e) => this._onMouseDown.fire(e));
  }
  get onDidChange() {
    return this.inputBox.onDidChange;
  }
  layout(style2) {
    this.inputBox.layout();
    this.updateInputBoxPadding(style2.collapsedFindWidget);
  }
  enable() {
    var _a2, _b2, _c2;
    this.domNode.classList.remove("disabled");
    this.inputBox.enable();
    (_a2 = this.regex) === null || _a2 === void 0 ? void 0 : _a2.enable();
    (_b2 = this.wholeWords) === null || _b2 === void 0 ? void 0 : _b2.enable();
    (_c2 = this.caseSensitive) === null || _c2 === void 0 ? void 0 : _c2.enable();
    for (const toggle2 of this.additionalToggles) {
      toggle2.enable();
    }
  }
  disable() {
    var _a2, _b2, _c2;
    this.domNode.classList.add("disabled");
    this.inputBox.disable();
    (_a2 = this.regex) === null || _a2 === void 0 ? void 0 : _a2.disable();
    (_b2 = this.wholeWords) === null || _b2 === void 0 ? void 0 : _b2.disable();
    (_c2 = this.caseSensitive) === null || _c2 === void 0 ? void 0 : _c2.disable();
    for (const toggle2 of this.additionalToggles) {
      toggle2.disable();
    }
  }
  setFocusInputOnOptionClick(value) {
    this.fixFocusOnOptionClickEnabled = value;
  }
  setEnabled(enabled) {
    if (enabled) {
      this.enable();
    } else {
      this.disable();
    }
  }
  setAdditionalToggles(toggles) {
    for (const currentToggle of this.additionalToggles) {
      currentToggle.domNode.remove();
    }
    this.additionalToggles = [];
    this.additionalTogglesDisposables.dispose();
    this.additionalTogglesDisposables = new DisposableStore();
    for (const toggle2 of toggles !== null && toggles !== void 0 ? toggles : []) {
      this.additionalTogglesDisposables.add(toggle2);
      this.controls.appendChild(toggle2.domNode);
      this.additionalTogglesDisposables.add(toggle2.onChange((viaKeyboard) => {
        this._onDidOptionChange.fire(viaKeyboard);
        if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
          this.inputBox.focus();
        }
      }));
      this.additionalToggles.push(toggle2);
    }
    if (this.additionalToggles.length > 0) {
      this.controls.style.display = "";
    }
    this.updateInputBoxPadding();
  }
  updateInputBoxPadding(controlsHidden = false) {
    var _a2, _b2, _c2, _d2, _e2, _f2;
    if (controlsHidden) {
      this.inputBox.paddingRight = 0;
    } else {
      this.inputBox.paddingRight = ((_b2 = (_a2 = this.caseSensitive) === null || _a2 === void 0 ? void 0 : _a2.width()) !== null && _b2 !== void 0 ? _b2 : 0) + ((_d2 = (_c2 = this.wholeWords) === null || _c2 === void 0 ? void 0 : _c2.width()) !== null && _d2 !== void 0 ? _d2 : 0) + ((_f2 = (_e2 = this.regex) === null || _e2 === void 0 ? void 0 : _e2.width()) !== null && _f2 !== void 0 ? _f2 : 0) + this.additionalToggles.reduce((r, t) => r + t.width(), 0);
    }
  }
  getValue() {
    return this.inputBox.value;
  }
  setValue(value) {
    if (this.inputBox.value !== value) {
      this.inputBox.value = value;
    }
  }
  select() {
    this.inputBox.select();
  }
  focus() {
    this.inputBox.focus();
  }
  getCaseSensitive() {
    var _a2, _b2;
    return (_b2 = (_a2 = this.caseSensitive) === null || _a2 === void 0 ? void 0 : _a2.checked) !== null && _b2 !== void 0 ? _b2 : false;
  }
  setCaseSensitive(value) {
    if (this.caseSensitive) {
      this.caseSensitive.checked = value;
    }
  }
  getWholeWords() {
    var _a2, _b2;
    return (_b2 = (_a2 = this.wholeWords) === null || _a2 === void 0 ? void 0 : _a2.checked) !== null && _b2 !== void 0 ? _b2 : false;
  }
  setWholeWords(value) {
    if (this.wholeWords) {
      this.wholeWords.checked = value;
    }
  }
  getRegex() {
    var _a2, _b2;
    return (_b2 = (_a2 = this.regex) === null || _a2 === void 0 ? void 0 : _a2.checked) !== null && _b2 !== void 0 ? _b2 : false;
  }
  setRegex(value) {
    if (this.regex) {
      this.regex.checked = value;
      this.validate();
    }
  }
  focusOnCaseSensitive() {
    var _a2;
    (_a2 = this.caseSensitive) === null || _a2 === void 0 ? void 0 : _a2.focus();
  }
  highlightFindOptions() {
    this.domNode.classList.remove("highlight-" + this._lastHighlightFindOptions);
    this._lastHighlightFindOptions = 1 - this._lastHighlightFindOptions;
    this.domNode.classList.add("highlight-" + this._lastHighlightFindOptions);
  }
  validate() {
    this.inputBox.validate();
  }
  showMessage(message) {
    this.inputBox.showMessage(message);
  }
  clearMessage() {
    this.inputBox.hideMessage();
  }
}
var ObjectTreeElementCollapseState;
(function(ObjectTreeElementCollapseState2) {
  ObjectTreeElementCollapseState2[ObjectTreeElementCollapseState2["Expanded"] = 0] = "Expanded";
  ObjectTreeElementCollapseState2[ObjectTreeElementCollapseState2["Collapsed"] = 1] = "Collapsed";
  ObjectTreeElementCollapseState2[ObjectTreeElementCollapseState2["PreserveOrExpanded"] = 2] = "PreserveOrExpanded";
  ObjectTreeElementCollapseState2[ObjectTreeElementCollapseState2["PreserveOrCollapsed"] = 3] = "PreserveOrCollapsed";
})(ObjectTreeElementCollapseState || (ObjectTreeElementCollapseState = {}));
var TreeMouseEventTarget;
(function(TreeMouseEventTarget2) {
  TreeMouseEventTarget2[TreeMouseEventTarget2["Unknown"] = 0] = "Unknown";
  TreeMouseEventTarget2[TreeMouseEventTarget2["Twistie"] = 1] = "Twistie";
  TreeMouseEventTarget2[TreeMouseEventTarget2["Element"] = 2] = "Element";
  TreeMouseEventTarget2[TreeMouseEventTarget2["Filter"] = 3] = "Filter";
})(TreeMouseEventTarget || (TreeMouseEventTarget = {}));
class TreeError extends Error {
  constructor(user, message) {
    super(`TreeError [${user}] ${message}`);
  }
}
class WeakMapper {
  constructor(fn) {
    this.fn = fn;
    this._map = /* @__PURE__ */ new WeakMap();
  }
  map(key) {
    let result2 = this._map.get(key);
    if (!result2) {
      result2 = this.fn(key);
      this._map.set(key, result2);
    }
    return result2;
  }
}
function isFilterResult(obj) {
  return typeof obj === "object" && "visibility" in obj && "data" in obj;
}
function getVisibleState(visibility) {
  switch (visibility) {
    case true:
      return 1;
    case false:
      return 0;
    default:
      return visibility;
  }
}
function isCollapsibleStateUpdate(update) {
  return typeof update.collapsible === "boolean";
}
class IndexTreeModel {
  constructor(user, list2, rootElement, options = {}) {
    this.user = user;
    this.list = list2;
    this.rootRef = [];
    this.eventBufferer = new EventBufferer();
    this._onDidChangeCollapseState = new Emitter$1();
    this.onDidChangeCollapseState = this.eventBufferer.wrapEvent(this._onDidChangeCollapseState.event);
    this._onDidChangeRenderNodeCount = new Emitter$1();
    this.onDidChangeRenderNodeCount = this.eventBufferer.wrapEvent(this._onDidChangeRenderNodeCount.event);
    this._onDidSplice = new Emitter$1();
    this.onDidSplice = this._onDidSplice.event;
    this.refilterDelayer = new Delayer(MicrotaskDelay);
    this.collapseByDefault = typeof options.collapseByDefault === "undefined" ? false : options.collapseByDefault;
    this.filter = options.filter;
    this.autoExpandSingleChildren = typeof options.autoExpandSingleChildren === "undefined" ? false : options.autoExpandSingleChildren;
    this.root = {
      parent: void 0,
      element: rootElement,
      children: [],
      depth: 0,
      visibleChildrenCount: 0,
      visibleChildIndex: -1,
      collapsible: false,
      collapsed: false,
      renderNodeCount: 0,
      visibility: 1,
      visible: true,
      filterData: void 0
    };
  }
  splice(location, deleteCount, toInsert = Iterable.empty(), options = {}) {
    if (location.length === 0) {
      throw new TreeError(this.user, "Invalid tree location");
    }
    if (options.diffIdentityProvider) {
      this.spliceSmart(options.diffIdentityProvider, location, deleteCount, toInsert, options);
    } else {
      this.spliceSimple(location, deleteCount, toInsert, options);
    }
  }
  spliceSmart(identity, location, deleteCount, toInsertIterable, options, recurseLevels) {
    var _a2;
    if (toInsertIterable === void 0) {
      toInsertIterable = Iterable.empty();
    }
    if (recurseLevels === void 0) {
      recurseLevels = (_a2 = options.diffDepth) !== null && _a2 !== void 0 ? _a2 : 0;
    }
    const { parentNode } = this.getParentNodeWithListIndex(location);
    if (!parentNode.lastDiffIds) {
      return this.spliceSimple(location, deleteCount, toInsertIterable, options);
    }
    const toInsert = [...toInsertIterable];
    const index = location[location.length - 1];
    const diff = new LcsDiff({ getElements: () => parentNode.lastDiffIds }, {
      getElements: () => [
        ...parentNode.children.slice(0, index),
        ...toInsert,
        ...parentNode.children.slice(index + deleteCount)
      ].map((e) => identity.getId(e.element).toString())
    }).ComputeDiff(false);
    if (diff.quitEarly) {
      parentNode.lastDiffIds = void 0;
      return this.spliceSimple(location, deleteCount, toInsert, options);
    }
    const locationPrefix = location.slice(0, -1);
    const recurseSplice = (fromOriginal, fromModified, count) => {
      if (recurseLevels > 0) {
        for (let i = 0; i < count; i++) {
          fromOriginal--;
          fromModified--;
          this.spliceSmart(identity, [...locationPrefix, fromOriginal, 0], Number.MAX_SAFE_INTEGER, toInsert[fromModified].children, options, recurseLevels - 1);
        }
      }
    };
    let lastStartO = Math.min(parentNode.children.length, index + deleteCount);
    let lastStartM = toInsert.length;
    for (const change of diff.changes.sort((a, b) => b.originalStart - a.originalStart)) {
      recurseSplice(lastStartO, lastStartM, lastStartO - (change.originalStart + change.originalLength));
      lastStartO = change.originalStart;
      lastStartM = change.modifiedStart - index;
      this.spliceSimple([...locationPrefix, lastStartO], change.originalLength, Iterable.slice(toInsert, lastStartM, lastStartM + change.modifiedLength), options);
    }
    recurseSplice(lastStartO, lastStartM, lastStartO);
  }
  spliceSimple(location, deleteCount, toInsert = Iterable.empty(), { onDidCreateNode, onDidDeleteNode, diffIdentityProvider }) {
    const { parentNode, listIndex, revealed, visible } = this.getParentNodeWithListIndex(location);
    const treeListElementsToInsert = [];
    const nodesToInsertIterator = Iterable.map(toInsert, (el) => this.createTreeNode(el, parentNode, parentNode.visible ? 1 : 0, revealed, treeListElementsToInsert, onDidCreateNode));
    const lastIndex2 = location[location.length - 1];
    const lastHadChildren = parentNode.children.length > 0;
    let visibleChildStartIndex = 0;
    for (let i = lastIndex2; i >= 0 && i < parentNode.children.length; i--) {
      const child = parentNode.children[i];
      if (child.visible) {
        visibleChildStartIndex = child.visibleChildIndex;
        break;
      }
    }
    const nodesToInsert = [];
    let insertedVisibleChildrenCount = 0;
    let renderNodeCount = 0;
    for (const child of nodesToInsertIterator) {
      nodesToInsert.push(child);
      renderNodeCount += child.renderNodeCount;
      if (child.visible) {
        child.visibleChildIndex = visibleChildStartIndex + insertedVisibleChildrenCount++;
      }
    }
    const deletedNodes = splice$1(parentNode.children, lastIndex2, deleteCount, nodesToInsert);
    if (!diffIdentityProvider) {
      parentNode.lastDiffIds = void 0;
    } else if (parentNode.lastDiffIds) {
      splice$1(parentNode.lastDiffIds, lastIndex2, deleteCount, nodesToInsert.map((n2) => diffIdentityProvider.getId(n2.element).toString()));
    } else {
      parentNode.lastDiffIds = parentNode.children.map((n2) => diffIdentityProvider.getId(n2.element).toString());
    }
    let deletedVisibleChildrenCount = 0;
    for (const child of deletedNodes) {
      if (child.visible) {
        deletedVisibleChildrenCount++;
      }
    }
    if (deletedVisibleChildrenCount !== 0) {
      for (let i = lastIndex2 + nodesToInsert.length; i < parentNode.children.length; i++) {
        const child = parentNode.children[i];
        if (child.visible) {
          child.visibleChildIndex -= deletedVisibleChildrenCount;
        }
      }
    }
    parentNode.visibleChildrenCount += insertedVisibleChildrenCount - deletedVisibleChildrenCount;
    if (revealed && visible) {
      const visibleDeleteCount = deletedNodes.reduce((r, node3) => r + (node3.visible ? node3.renderNodeCount : 0), 0);
      this._updateAncestorsRenderNodeCount(parentNode, renderNodeCount - visibleDeleteCount);
      this.list.splice(listIndex, visibleDeleteCount, treeListElementsToInsert);
    }
    if (deletedNodes.length > 0 && onDidDeleteNode) {
      const visit = (node3) => {
        onDidDeleteNode(node3);
        node3.children.forEach(visit);
      };
      deletedNodes.forEach(visit);
    }
    this._onDidSplice.fire({ insertedNodes: nodesToInsert, deletedNodes });
    const currentlyHasChildren = parentNode.children.length > 0;
    if (lastHadChildren !== currentlyHasChildren) {
      this.setCollapsible(location.slice(0, -1), currentlyHasChildren);
    }
    let node2 = parentNode;
    while (node2) {
      if (node2.visibility === 2) {
        this.refilterDelayer.trigger(() => this.refilter());
        break;
      }
      node2 = node2.parent;
    }
  }
  rerender(location) {
    if (location.length === 0) {
      throw new TreeError(this.user, "Invalid tree location");
    }
    const { node: node2, listIndex, revealed } = this.getTreeNodeWithListIndex(location);
    if (node2.visible && revealed) {
      this.list.splice(listIndex, 1, [node2]);
    }
  }
  has(location) {
    return this.hasTreeNode(location);
  }
  getListIndex(location) {
    const { listIndex, visible, revealed } = this.getTreeNodeWithListIndex(location);
    return visible && revealed ? listIndex : -1;
  }
  getListRenderCount(location) {
    return this.getTreeNode(location).renderNodeCount;
  }
  isCollapsible(location) {
    return this.getTreeNode(location).collapsible;
  }
  setCollapsible(location, collapsible) {
    const node2 = this.getTreeNode(location);
    if (typeof collapsible === "undefined") {
      collapsible = !node2.collapsible;
    }
    const update = { collapsible };
    return this.eventBufferer.bufferEvents(() => this._setCollapseState(location, update));
  }
  isCollapsed(location) {
    return this.getTreeNode(location).collapsed;
  }
  setCollapsed(location, collapsed, recursive) {
    const node2 = this.getTreeNode(location);
    if (typeof collapsed === "undefined") {
      collapsed = !node2.collapsed;
    }
    const update = { collapsed, recursive: recursive || false };
    return this.eventBufferer.bufferEvents(() => this._setCollapseState(location, update));
  }
  _setCollapseState(location, update) {
    const { node: node2, listIndex, revealed } = this.getTreeNodeWithListIndex(location);
    const result2 = this._setListNodeCollapseState(node2, listIndex, revealed, update);
    if (node2 !== this.root && this.autoExpandSingleChildren && result2 && !isCollapsibleStateUpdate(update) && node2.collapsible && !node2.collapsed && !update.recursive) {
      let onlyVisibleChildIndex = -1;
      for (let i = 0; i < node2.children.length; i++) {
        const child = node2.children[i];
        if (child.visible) {
          if (onlyVisibleChildIndex > -1) {
            onlyVisibleChildIndex = -1;
            break;
          } else {
            onlyVisibleChildIndex = i;
          }
        }
      }
      if (onlyVisibleChildIndex > -1) {
        this._setCollapseState([...location, onlyVisibleChildIndex], update);
      }
    }
    return result2;
  }
  _setListNodeCollapseState(node2, listIndex, revealed, update) {
    const result2 = this._setNodeCollapseState(node2, update, false);
    if (!revealed || !node2.visible || !result2) {
      return result2;
    }
    const previousRenderNodeCount = node2.renderNodeCount;
    const toInsert = this.updateNodeAfterCollapseChange(node2);
    const deleteCount = previousRenderNodeCount - (listIndex === -1 ? 0 : 1);
    this.list.splice(listIndex + 1, deleteCount, toInsert.slice(1));
    return result2;
  }
  _setNodeCollapseState(node2, update, deep) {
    let result2;
    if (node2 === this.root) {
      result2 = false;
    } else {
      if (isCollapsibleStateUpdate(update)) {
        result2 = node2.collapsible !== update.collapsible;
        node2.collapsible = update.collapsible;
      } else if (!node2.collapsible) {
        result2 = false;
      } else {
        result2 = node2.collapsed !== update.collapsed;
        node2.collapsed = update.collapsed;
      }
      if (result2) {
        this._onDidChangeCollapseState.fire({ node: node2, deep });
      }
    }
    if (!isCollapsibleStateUpdate(update) && update.recursive) {
      for (const child of node2.children) {
        result2 = this._setNodeCollapseState(child, update, true) || result2;
      }
    }
    return result2;
  }
  expandTo(location) {
    this.eventBufferer.bufferEvents(() => {
      let node2 = this.getTreeNode(location);
      while (node2.parent) {
        node2 = node2.parent;
        location = location.slice(0, location.length - 1);
        if (node2.collapsed) {
          this._setCollapseState(location, { collapsed: false, recursive: false });
        }
      }
    });
  }
  refilter() {
    const previousRenderNodeCount = this.root.renderNodeCount;
    const toInsert = this.updateNodeAfterFilterChange(this.root);
    this.list.splice(0, previousRenderNodeCount, toInsert);
    this.refilterDelayer.cancel();
  }
  createTreeNode(treeElement, parent, parentVisibility, revealed, treeListElements, onDidCreateNode) {
    const node2 = {
      parent,
      element: treeElement.element,
      children: [],
      depth: parent.depth + 1,
      visibleChildrenCount: 0,
      visibleChildIndex: -1,
      collapsible: typeof treeElement.collapsible === "boolean" ? treeElement.collapsible : typeof treeElement.collapsed !== "undefined",
      collapsed: typeof treeElement.collapsed === "undefined" ? this.collapseByDefault : treeElement.collapsed,
      renderNodeCount: 1,
      visibility: 1,
      visible: true,
      filterData: void 0
    };
    const visibility = this._filterNode(node2, parentVisibility);
    node2.visibility = visibility;
    if (revealed) {
      treeListElements.push(node2);
    }
    const childElements = treeElement.children || Iterable.empty();
    const childRevealed = revealed && visibility !== 0 && !node2.collapsed;
    let visibleChildrenCount = 0;
    let renderNodeCount = 1;
    for (const el of childElements) {
      const child = this.createTreeNode(el, node2, visibility, childRevealed, treeListElements, onDidCreateNode);
      node2.children.push(child);
      renderNodeCount += child.renderNodeCount;
      if (child.visible) {
        child.visibleChildIndex = visibleChildrenCount++;
      }
    }
    node2.collapsible = node2.collapsible || node2.children.length > 0;
    node2.visibleChildrenCount = visibleChildrenCount;
    node2.visible = visibility === 2 ? visibleChildrenCount > 0 : visibility === 1;
    if (!node2.visible) {
      node2.renderNodeCount = 0;
      if (revealed) {
        treeListElements.pop();
      }
    } else if (!node2.collapsed) {
      node2.renderNodeCount = renderNodeCount;
    }
    onDidCreateNode === null || onDidCreateNode === void 0 ? void 0 : onDidCreateNode(node2);
    return node2;
  }
  updateNodeAfterCollapseChange(node2) {
    const previousRenderNodeCount = node2.renderNodeCount;
    const result2 = [];
    this._updateNodeAfterCollapseChange(node2, result2);
    this._updateAncestorsRenderNodeCount(node2.parent, result2.length - previousRenderNodeCount);
    return result2;
  }
  _updateNodeAfterCollapseChange(node2, result2) {
    if (node2.visible === false) {
      return 0;
    }
    result2.push(node2);
    node2.renderNodeCount = 1;
    if (!node2.collapsed) {
      for (const child of node2.children) {
        node2.renderNodeCount += this._updateNodeAfterCollapseChange(child, result2);
      }
    }
    this._onDidChangeRenderNodeCount.fire(node2);
    return node2.renderNodeCount;
  }
  updateNodeAfterFilterChange(node2) {
    const previousRenderNodeCount = node2.renderNodeCount;
    const result2 = [];
    this._updateNodeAfterFilterChange(node2, node2.visible ? 1 : 0, result2);
    this._updateAncestorsRenderNodeCount(node2.parent, result2.length - previousRenderNodeCount);
    return result2;
  }
  _updateNodeAfterFilterChange(node2, parentVisibility, result2, revealed = true) {
    let visibility;
    if (node2 !== this.root) {
      visibility = this._filterNode(node2, parentVisibility);
      if (visibility === 0) {
        node2.visible = false;
        node2.renderNodeCount = 0;
        return false;
      }
      if (revealed) {
        result2.push(node2);
      }
    }
    const resultStartLength = result2.length;
    node2.renderNodeCount = node2 === this.root ? 0 : 1;
    let hasVisibleDescendants = false;
    if (!node2.collapsed || visibility !== 0) {
      let visibleChildIndex = 0;
      for (const child of node2.children) {
        hasVisibleDescendants = this._updateNodeAfterFilterChange(child, visibility, result2, revealed && !node2.collapsed) || hasVisibleDescendants;
        if (child.visible) {
          child.visibleChildIndex = visibleChildIndex++;
        }
      }
      node2.visibleChildrenCount = visibleChildIndex;
    } else {
      node2.visibleChildrenCount = 0;
    }
    if (node2 !== this.root) {
      node2.visible = visibility === 2 ? hasVisibleDescendants : visibility === 1;
      node2.visibility = visibility;
    }
    if (!node2.visible) {
      node2.renderNodeCount = 0;
      if (revealed) {
        result2.pop();
      }
    } else if (!node2.collapsed) {
      node2.renderNodeCount += result2.length - resultStartLength;
    }
    this._onDidChangeRenderNodeCount.fire(node2);
    return node2.visible;
  }
  _updateAncestorsRenderNodeCount(node2, diff) {
    if (diff === 0) {
      return;
    }
    while (node2) {
      node2.renderNodeCount += diff;
      this._onDidChangeRenderNodeCount.fire(node2);
      node2 = node2.parent;
    }
  }
  _filterNode(node2, parentVisibility) {
    const result2 = this.filter ? this.filter.filter(node2.element, parentVisibility) : 1;
    if (typeof result2 === "boolean") {
      node2.filterData = void 0;
      return result2 ? 1 : 0;
    } else if (isFilterResult(result2)) {
      node2.filterData = result2.data;
      return getVisibleState(result2.visibility);
    } else {
      node2.filterData = void 0;
      return getVisibleState(result2);
    }
  }
  // cheap
  hasTreeNode(location, node2 = this.root) {
    if (!location || location.length === 0) {
      return true;
    }
    const [index, ...rest] = location;
    if (index < 0 || index > node2.children.length) {
      return false;
    }
    return this.hasTreeNode(rest, node2.children[index]);
  }
  // cheap
  getTreeNode(location, node2 = this.root) {
    if (!location || location.length === 0) {
      return node2;
    }
    const [index, ...rest] = location;
    if (index < 0 || index > node2.children.length) {
      throw new TreeError(this.user, "Invalid tree location");
    }
    return this.getTreeNode(rest, node2.children[index]);
  }
  // expensive
  getTreeNodeWithListIndex(location) {
    if (location.length === 0) {
      return { node: this.root, listIndex: -1, revealed: true, visible: false };
    }
    const { parentNode, listIndex, revealed, visible } = this.getParentNodeWithListIndex(location);
    const index = location[location.length - 1];
    if (index < 0 || index > parentNode.children.length) {
      throw new TreeError(this.user, "Invalid tree location");
    }
    const node2 = parentNode.children[index];
    return { node: node2, listIndex, revealed, visible: visible && node2.visible };
  }
  getParentNodeWithListIndex(location, node2 = this.root, listIndex = 0, revealed = true, visible = true) {
    const [index, ...rest] = location;
    if (index < 0 || index > node2.children.length) {
      throw new TreeError(this.user, "Invalid tree location");
    }
    for (let i = 0; i < index; i++) {
      listIndex += node2.children[i].renderNodeCount;
    }
    revealed = revealed && !node2.collapsed;
    visible = visible && node2.visible;
    if (rest.length === 0) {
      return { parentNode: node2, listIndex, revealed, visible };
    }
    return this.getParentNodeWithListIndex(rest, node2.children[index], listIndex + 1, revealed, visible);
  }
  getNode(location = []) {
    return this.getTreeNode(location);
  }
  // TODO@joao perf!
  getNodeLocation(node2) {
    const location = [];
    let indexTreeNode = node2;
    while (indexTreeNode.parent) {
      location.push(indexTreeNode.parent.children.indexOf(indexTreeNode));
      indexTreeNode = indexTreeNode.parent;
    }
    return location.reverse();
  }
  getParentNodeLocation(location) {
    if (location.length === 0) {
      return void 0;
    } else if (location.length === 1) {
      return [];
    } else {
      return tail2(location)[0];
    }
  }
  getFirstElementChild(location) {
    const node2 = this.getTreeNode(location);
    if (node2.children.length === 0) {
      return void 0;
    }
    return node2.children[0].element;
  }
}
class SetMap {
  constructor() {
    this.map = /* @__PURE__ */ new Map();
  }
  add(key, value) {
    let values = this.map.get(key);
    if (!values) {
      values = /* @__PURE__ */ new Set();
      this.map.set(key, values);
    }
    values.add(value);
  }
  delete(key, value) {
    const values = this.map.get(key);
    if (!values) {
      return;
    }
    values.delete(value);
    if (values.size === 0) {
      this.map.delete(key);
    }
  }
  forEach(key, fn) {
    const values = this.map.get(key);
    if (!values) {
      return;
    }
    values.forEach(fn);
  }
  get(key) {
    const values = this.map.get(key);
    if (!values) {
      return /* @__PURE__ */ new Set();
    }
    return new Set(values);
  }
}
const tree = "";
globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class TreeElementsDragAndDropData extends ElementsDragAndDropData {
  constructor(data) {
    super(data.elements.map((node2) => node2.element));
    this.data = data;
  }
}
function asTreeDragAndDropData(data) {
  if (data instanceof ElementsDragAndDropData) {
    return new TreeElementsDragAndDropData(data);
  }
  return data;
}
class TreeNodeListDragAndDrop {
  constructor(modelProvider, dnd2) {
    this.modelProvider = modelProvider;
    this.dnd = dnd2;
    this.autoExpandDisposable = Disposable.None;
  }
  getDragURI(node2) {
    return this.dnd.getDragURI(node2.element);
  }
  getDragLabel(nodes, originalEvent) {
    if (this.dnd.getDragLabel) {
      return this.dnd.getDragLabel(nodes.map((node2) => node2.element), originalEvent);
    }
    return void 0;
  }
  onDragStart(data, originalEvent) {
    var _a2, _b2;
    (_b2 = (_a2 = this.dnd).onDragStart) === null || _b2 === void 0 ? void 0 : _b2.call(_a2, asTreeDragAndDropData(data), originalEvent);
  }
  onDragOver(data, targetNode, targetIndex, originalEvent, raw = true) {
    const result2 = this.dnd.onDragOver(asTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, originalEvent);
    const didChangeAutoExpandNode = this.autoExpandNode !== targetNode;
    if (didChangeAutoExpandNode) {
      this.autoExpandDisposable.dispose();
      this.autoExpandNode = targetNode;
    }
    if (typeof targetNode === "undefined") {
      return result2;
    }
    if (didChangeAutoExpandNode && typeof result2 !== "boolean" && result2.autoExpand) {
      this.autoExpandDisposable = disposableTimeout(() => {
        const model2 = this.modelProvider();
        const ref3 = model2.getNodeLocation(targetNode);
        if (model2.isCollapsed(ref3)) {
          model2.setCollapsed(ref3, false);
        }
        this.autoExpandNode = void 0;
      }, 500);
    }
    if (typeof result2 === "boolean" || !result2.accept || typeof result2.bubble === "undefined" || result2.feedback) {
      if (!raw) {
        const accept = typeof result2 === "boolean" ? result2 : result2.accept;
        const effect = typeof result2 === "boolean" ? void 0 : result2.effect;
        return { accept, effect, feedback: [targetIndex] };
      }
      return result2;
    }
    if (result2.bubble === 1) {
      const model2 = this.modelProvider();
      const ref3 = model2.getNodeLocation(targetNode);
      const parentRef = model2.getParentNodeLocation(ref3);
      const parentNode = model2.getNode(parentRef);
      const parentIndex = parentRef && model2.getListIndex(parentRef);
      return this.onDragOver(data, parentNode, parentIndex, originalEvent, false);
    }
    const model = this.modelProvider();
    const ref2 = model.getNodeLocation(targetNode);
    const start = model.getListIndex(ref2);
    const length2 = model.getListRenderCount(ref2);
    return Object.assign(Object.assign({}, result2), { feedback: range$1(start, start + length2) });
  }
  drop(data, targetNode, targetIndex, originalEvent) {
    this.autoExpandDisposable.dispose();
    this.autoExpandNode = void 0;
    this.dnd.drop(asTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, originalEvent);
  }
  onDragEnd(originalEvent) {
    var _a2, _b2;
    (_b2 = (_a2 = this.dnd).onDragEnd) === null || _b2 === void 0 ? void 0 : _b2.call(_a2, originalEvent);
  }
}
function asListOptions(modelProvider, options) {
  return options && Object.assign(Object.assign({}, options), { identityProvider: options.identityProvider && {
    getId(el) {
      return options.identityProvider.getId(el.element);
    }
  }, dnd: options.dnd && new TreeNodeListDragAndDrop(modelProvider, options.dnd), multipleSelectionController: options.multipleSelectionController && {
    isSelectionSingleChangeEvent(e) {
      return options.multipleSelectionController.isSelectionSingleChangeEvent(Object.assign(Object.assign({}, e), { element: e.element }));
    },
    isSelectionRangeChangeEvent(e) {
      return options.multipleSelectionController.isSelectionRangeChangeEvent(Object.assign(Object.assign({}, e), { element: e.element }));
    }
  }, accessibilityProvider: options.accessibilityProvider && Object.assign(Object.assign({}, options.accessibilityProvider), {
    getSetSize(node2) {
      const model = modelProvider();
      const ref2 = model.getNodeLocation(node2);
      const parentRef = model.getParentNodeLocation(ref2);
      const parentNode = model.getNode(parentRef);
      return parentNode.visibleChildrenCount;
    },
    getPosInSet(node2) {
      return node2.visibleChildIndex + 1;
    },
    isChecked: options.accessibilityProvider && options.accessibilityProvider.isChecked ? (node2) => {
      return options.accessibilityProvider.isChecked(node2.element);
    } : void 0,
    getRole: options.accessibilityProvider && options.accessibilityProvider.getRole ? (node2) => {
      return options.accessibilityProvider.getRole(node2.element);
    } : () => "treeitem",
    getAriaLabel(e) {
      return options.accessibilityProvider.getAriaLabel(e.element);
    },
    getWidgetAriaLabel() {
      return options.accessibilityProvider.getWidgetAriaLabel();
    },
    getWidgetRole: options.accessibilityProvider && options.accessibilityProvider.getWidgetRole ? () => options.accessibilityProvider.getWidgetRole() : () => "tree",
    getAriaLevel: options.accessibilityProvider && options.accessibilityProvider.getAriaLevel ? (node2) => options.accessibilityProvider.getAriaLevel(node2.element) : (node2) => {
      return node2.depth;
    },
    getActiveDescendantId: options.accessibilityProvider.getActiveDescendantId && ((node2) => {
      return options.accessibilityProvider.getActiveDescendantId(node2.element);
    })
  }), keyboardNavigationLabelProvider: options.keyboardNavigationLabelProvider && Object.assign(Object.assign({}, options.keyboardNavigationLabelProvider), { getKeyboardNavigationLabel(node2) {
    return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(node2.element);
  } }) });
}
class ComposedTreeDelegate {
  constructor(delegate) {
    this.delegate = delegate;
  }
  getHeight(element) {
    return this.delegate.getHeight(element.element);
  }
  getTemplateId(element) {
    return this.delegate.getTemplateId(element.element);
  }
  hasDynamicHeight(element) {
    return !!this.delegate.hasDynamicHeight && this.delegate.hasDynamicHeight(element.element);
  }
  setDynamicHeight(element, height) {
    var _a2, _b2;
    (_b2 = (_a2 = this.delegate).setDynamicHeight) === null || _b2 === void 0 ? void 0 : _b2.call(_a2, element.element, height);
  }
}
var RenderIndentGuides;
(function(RenderIndentGuides2) {
  RenderIndentGuides2["None"] = "none";
  RenderIndentGuides2["OnHover"] = "onHover";
  RenderIndentGuides2["Always"] = "always";
})(RenderIndentGuides || (RenderIndentGuides = {}));
class EventCollection {
  get elements() {
    return this._elements;
  }
  constructor(onDidChange, _elements = []) {
    this._elements = _elements;
    this.disposables = new DisposableStore();
    this.onDidChange = Event$1.forEach(onDidChange, (elements) => this._elements = elements, this.disposables);
  }
  dispose() {
    this.disposables.dispose();
  }
}
class TreeRenderer {
  constructor(renderer2, modelProvider, onDidChangeCollapseState, activeNodes, renderedIndentGuides, options = {}) {
    var _a2;
    this.renderer = renderer2;
    this.modelProvider = modelProvider;
    this.activeNodes = activeNodes;
    this.renderedIndentGuides = renderedIndentGuides;
    this.renderedElements = /* @__PURE__ */ new Map();
    this.renderedNodes = /* @__PURE__ */ new Map();
    this.indent = TreeRenderer.DefaultIndent;
    this.hideTwistiesOfChildlessElements = false;
    this.shouldRenderIndentGuides = false;
    this.activeIndentNodes = /* @__PURE__ */ new Set();
    this.indentGuidesDisposable = Disposable.None;
    this.disposables = new DisposableStore();
    this.templateId = renderer2.templateId;
    this.updateOptions(options);
    Event$1.map(onDidChangeCollapseState, (e) => e.node)(this.onDidChangeNodeTwistieState, this, this.disposables);
    (_a2 = renderer2.onDidChangeTwistieState) === null || _a2 === void 0 ? void 0 : _a2.call(renderer2, this.onDidChangeTwistieState, this, this.disposables);
  }
  updateOptions(options = {}) {
    if (typeof options.indent !== "undefined") {
      const indent = clamp(options.indent, 0, 40);
      if (indent !== this.indent) {
        this.indent = indent;
        for (const [node2, templateData] of this.renderedNodes) {
          this.renderTreeElement(node2, templateData);
        }
      }
    }
    if (typeof options.renderIndentGuides !== "undefined") {
      const shouldRenderIndentGuides = options.renderIndentGuides !== RenderIndentGuides.None;
      if (shouldRenderIndentGuides !== this.shouldRenderIndentGuides) {
        this.shouldRenderIndentGuides = shouldRenderIndentGuides;
        for (const [node2, templateData] of this.renderedNodes) {
          this._renderIndentGuides(node2, templateData);
        }
        this.indentGuidesDisposable.dispose();
        if (shouldRenderIndentGuides) {
          const disposables = new DisposableStore();
          this.activeNodes.onDidChange(this._onDidChangeActiveNodes, this, disposables);
          this.indentGuidesDisposable = disposables;
          this._onDidChangeActiveNodes(this.activeNodes.elements);
        }
      }
    }
    if (typeof options.hideTwistiesOfChildlessElements !== "undefined") {
      this.hideTwistiesOfChildlessElements = options.hideTwistiesOfChildlessElements;
    }
  }
  renderTemplate(container2) {
    const el = append$1(container2, $$d(".monaco-tl-row"));
    const indent = append$1(el, $$d(".monaco-tl-indent"));
    const twistie = append$1(el, $$d(".monaco-tl-twistie"));
    const contents = append$1(el, $$d(".monaco-tl-contents"));
    const templateData = this.renderer.renderTemplate(contents);
    return { container: container2, indent, twistie, indentGuidesDisposable: Disposable.None, templateData };
  }
  renderElement(node2, index, templateData, height) {
    this.renderedNodes.set(node2, templateData);
    this.renderedElements.set(node2.element, node2);
    this.renderTreeElement(node2, templateData);
    this.renderer.renderElement(node2, index, templateData.templateData, height);
  }
  disposeElement(node2, index, templateData, height) {
    var _a2, _b2;
    templateData.indentGuidesDisposable.dispose();
    (_b2 = (_a2 = this.renderer).disposeElement) === null || _b2 === void 0 ? void 0 : _b2.call(_a2, node2, index, templateData.templateData, height);
    if (typeof height === "number") {
      this.renderedNodes.delete(node2);
      this.renderedElements.delete(node2.element);
    }
  }
  disposeTemplate(templateData) {
    this.renderer.disposeTemplate(templateData.templateData);
  }
  onDidChangeTwistieState(element) {
    const node2 = this.renderedElements.get(element);
    if (!node2) {
      return;
    }
    this.onDidChangeNodeTwistieState(node2);
  }
  onDidChangeNodeTwistieState(node2) {
    const templateData = this.renderedNodes.get(node2);
    if (!templateData) {
      return;
    }
    this._onDidChangeActiveNodes(this.activeNodes.elements);
    this.renderTreeElement(node2, templateData);
  }
  renderTreeElement(node2, templateData) {
    const indent = TreeRenderer.DefaultIndent + (node2.depth - 1) * this.indent;
    templateData.twistie.style.paddingLeft = `${indent}px`;
    templateData.indent.style.width = `${indent + this.indent - 16}px`;
    if (node2.collapsible) {
      templateData.container.setAttribute("aria-expanded", String(!node2.collapsed));
    } else {
      templateData.container.removeAttribute("aria-expanded");
    }
    templateData.twistie.classList.remove(...ThemeIcon.asClassNameArray(Codicon.treeItemExpanded));
    let twistieRendered = false;
    if (this.renderer.renderTwistie) {
      twistieRendered = this.renderer.renderTwistie(node2.element, templateData.twistie);
    }
    if (node2.collapsible && (!this.hideTwistiesOfChildlessElements || node2.visibleChildrenCount > 0)) {
      if (!twistieRendered) {
        templateData.twistie.classList.add(...ThemeIcon.asClassNameArray(Codicon.treeItemExpanded));
      }
      templateData.twistie.classList.add("collapsible");
      templateData.twistie.classList.toggle("collapsed", node2.collapsed);
    } else {
      templateData.twistie.classList.remove("collapsible", "collapsed");
    }
    this._renderIndentGuides(node2, templateData);
  }
  _renderIndentGuides(node2, templateData) {
    clearNode(templateData.indent);
    templateData.indentGuidesDisposable.dispose();
    if (!this.shouldRenderIndentGuides) {
      return;
    }
    const disposableStore = new DisposableStore();
    const model = this.modelProvider();
    while (true) {
      const ref2 = model.getNodeLocation(node2);
      const parentRef = model.getParentNodeLocation(ref2);
      if (!parentRef) {
        break;
      }
      const parent = model.getNode(parentRef);
      const guide = $$d(".indent-guide", { style: `width: ${this.indent}px` });
      if (this.activeIndentNodes.has(parent)) {
        guide.classList.add("active");
      }
      if (templateData.indent.childElementCount === 0) {
        templateData.indent.appendChild(guide);
      } else {
        templateData.indent.insertBefore(guide, templateData.indent.firstElementChild);
      }
      this.renderedIndentGuides.add(parent, guide);
      disposableStore.add(toDisposable(() => this.renderedIndentGuides.delete(parent, guide)));
      node2 = parent;
    }
    templateData.indentGuidesDisposable = disposableStore;
  }
  _onDidChangeActiveNodes(nodes) {
    if (!this.shouldRenderIndentGuides) {
      return;
    }
    const set2 = /* @__PURE__ */ new Set();
    const model = this.modelProvider();
    nodes.forEach((node2) => {
      const ref2 = model.getNodeLocation(node2);
      try {
        const parentRef = model.getParentNodeLocation(ref2);
        if (node2.collapsible && node2.children.length > 0 && !node2.collapsed) {
          set2.add(node2);
        } else if (parentRef) {
          set2.add(model.getNode(parentRef));
        }
      } catch (_a2) {
      }
    });
    this.activeIndentNodes.forEach((node2) => {
      if (!set2.has(node2)) {
        this.renderedIndentGuides.forEach(node2, (line) => line.classList.remove("active"));
      }
    });
    set2.forEach((node2) => {
      if (!this.activeIndentNodes.has(node2)) {
        this.renderedIndentGuides.forEach(node2, (line) => line.classList.add("active"));
      }
    });
    this.activeIndentNodes = set2;
  }
  dispose() {
    this.renderedNodes.clear();
    this.renderedElements.clear();
    this.indentGuidesDisposable.dispose();
    dispose(this.disposables);
  }
}
TreeRenderer.DefaultIndent = 8;
class FindFilter {
  get totalCount() {
    return this._totalCount;
  }
  get matchCount() {
    return this._matchCount;
  }
  constructor(tree2, keyboardNavigationLabelProvider, _filter) {
    this.tree = tree2;
    this.keyboardNavigationLabelProvider = keyboardNavigationLabelProvider;
    this._filter = _filter;
    this._totalCount = 0;
    this._matchCount = 0;
    this._pattern = "";
    this._lowercasePattern = "";
    this.disposables = new DisposableStore();
    tree2.onWillRefilter(this.reset, this, this.disposables);
  }
  filter(element, parentVisibility) {
    let visibility = 1;
    if (this._filter) {
      const result2 = this._filter.filter(element, parentVisibility);
      if (typeof result2 === "boolean") {
        visibility = result2 ? 1 : 0;
      } else if (isFilterResult(result2)) {
        visibility = getVisibleState(result2.visibility);
      } else {
        visibility = result2;
      }
      if (visibility === 0) {
        return false;
      }
    }
    this._totalCount++;
    if (!this._pattern) {
      this._matchCount++;
      return { data: FuzzyScore.Default, visibility };
    }
    const label = this.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(element);
    const labels = Array.isArray(label) ? label : [label];
    for (const l of labels) {
      const labelStr = l && l.toString();
      if (typeof labelStr === "undefined") {
        return { data: FuzzyScore.Default, visibility };
      }
      let score2;
      if (this.tree.findMatchType === TreeFindMatchType.Contiguous) {
        const index = labelStr.toLowerCase().indexOf(this._lowercasePattern);
        if (index > -1) {
          score2 = [Number.MAX_SAFE_INTEGER, 0];
          for (let i = this._lowercasePattern.length; i > 0; i--) {
            score2.push(index + i - 1);
          }
        }
      } else {
        score2 = fuzzyScore(this._pattern, this._lowercasePattern, 0, labelStr, labelStr.toLowerCase(), 0, { firstMatchCanBeWeak: true, boostFullMatch: true });
      }
      if (score2) {
        this._matchCount++;
        return labels.length === 1 ? { data: score2, visibility } : { data: { label: labelStr, score: score2 }, visibility };
      }
    }
    if (this.tree.findMode === TreeFindMode.Filter) {
      if (typeof this.tree.options.defaultFindVisibility === "number") {
        return this.tree.options.defaultFindVisibility;
      } else if (this.tree.options.defaultFindVisibility) {
        return this.tree.options.defaultFindVisibility(element);
      } else {
        return 2;
      }
    } else {
      return { data: FuzzyScore.Default, visibility };
    }
  }
  reset() {
    this._totalCount = 0;
    this._matchCount = 0;
  }
  dispose() {
    dispose(this.disposables);
  }
}
var TreeFindMode;
(function(TreeFindMode2) {
  TreeFindMode2[TreeFindMode2["Highlight"] = 0] = "Highlight";
  TreeFindMode2[TreeFindMode2["Filter"] = 1] = "Filter";
})(TreeFindMode || (TreeFindMode = {}));
var TreeFindMatchType;
(function(TreeFindMatchType2) {
  TreeFindMatchType2[TreeFindMatchType2["Fuzzy"] = 0] = "Fuzzy";
  TreeFindMatchType2[TreeFindMatchType2["Contiguous"] = 1] = "Contiguous";
})(TreeFindMatchType || (TreeFindMatchType = {}));
let FindController$1 = class FindController {
  get pattern() {
    return this._pattern;
  }
  get mode() {
    return this._mode;
  }
  set mode(mode) {
    if (mode === this._mode) {
      return;
    }
    this._mode = mode;
    if (this.widget) {
      this.widget.mode = this._mode;
    }
    this.tree.refilter();
    this.render();
    this._onDidChangeMode.fire(mode);
  }
  get matchType() {
    return this._matchType;
  }
  set matchType(matchType) {
    if (matchType === this._matchType) {
      return;
    }
    this._matchType = matchType;
    if (this.widget) {
      this.widget.matchType = this._matchType;
    }
    this.tree.refilter();
    this.render();
    this._onDidChangeMatchType.fire(matchType);
  }
  constructor(tree2, model, view, filter2, contextViewProvider, options = {}) {
    var _a2, _b2;
    this.tree = tree2;
    this.view = view;
    this.filter = filter2;
    this.contextViewProvider = contextViewProvider;
    this.options = options;
    this._pattern = "";
    this.width = 0;
    this._onDidChangeMode = new Emitter$1();
    this.onDidChangeMode = this._onDidChangeMode.event;
    this._onDidChangeMatchType = new Emitter$1();
    this.onDidChangeMatchType = this._onDidChangeMatchType.event;
    this._onDidChangePattern = new Emitter$1();
    this._onDidChangeOpenState = new Emitter$1();
    this.onDidChangeOpenState = this._onDidChangeOpenState.event;
    this.enabledDisposables = new DisposableStore();
    this.disposables = new DisposableStore();
    this._mode = (_a2 = tree2.options.defaultFindMode) !== null && _a2 !== void 0 ? _a2 : TreeFindMode.Highlight;
    this._matchType = (_b2 = tree2.options.defaultFindMatchType) !== null && _b2 !== void 0 ? _b2 : TreeFindMatchType.Fuzzy;
    model.onDidSplice(this.onDidSpliceModel, this, this.disposables);
  }
  updateOptions(optionsUpdate = {}) {
    if (optionsUpdate.defaultFindMode !== void 0) {
      this.mode = optionsUpdate.defaultFindMode;
    }
    if (optionsUpdate.defaultFindMatchType !== void 0) {
      this.matchType = optionsUpdate.defaultFindMatchType;
    }
  }
  onDidSpliceModel() {
    if (!this.widget || this.pattern.length === 0) {
      return;
    }
    this.tree.refilter();
    this.render();
  }
  render() {
    var _a2, _b2, _c2, _d2;
    const noMatches = this.filter.totalCount > 0 && this.filter.matchCount === 0;
    if (this.pattern && noMatches) {
      if ((_a2 = this.tree.options.showNotFoundMessage) !== null && _a2 !== void 0 ? _a2 : true) {
        (_b2 = this.widget) === null || _b2 === void 0 ? void 0 : _b2.showMessage({ type: 2, content: localize("not found", "No elements found.") });
      } else {
        (_c2 = this.widget) === null || _c2 === void 0 ? void 0 : _c2.showMessage({
          type: 2
          /* MessageType.WARNING */
        });
      }
    } else {
      (_d2 = this.widget) === null || _d2 === void 0 ? void 0 : _d2.clearMessage();
    }
  }
  shouldAllowFocus(node2) {
    if (!this.widget || !this.pattern || this._mode === TreeFindMode.Filter) {
      return true;
    }
    if (this.filter.totalCount > 0 && this.filter.matchCount <= 1) {
      return true;
    }
    return !FuzzyScore.isDefault(node2.filterData);
  }
  layout(width) {
    var _a2;
    this.width = width;
    (_a2 = this.widget) === null || _a2 === void 0 ? void 0 : _a2.layout(width);
  }
  dispose() {
    this._history = void 0;
    this._onDidChangePattern.dispose();
    this.enabledDisposables.dispose();
    this.disposables.dispose();
  }
};
function asTreeMouseEvent$1(event) {
  let target = TreeMouseEventTarget.Unknown;
  if (hasParentWithClass(event.browserEvent.target, "monaco-tl-twistie", "monaco-tl-row")) {
    target = TreeMouseEventTarget.Twistie;
  } else if (hasParentWithClass(event.browserEvent.target, "monaco-tl-contents", "monaco-tl-row")) {
    target = TreeMouseEventTarget.Element;
  } else if (hasParentWithClass(event.browserEvent.target, "monaco-tree-type-filter", "monaco-list")) {
    target = TreeMouseEventTarget.Filter;
  }
  return {
    browserEvent: event.browserEvent,
    element: event.element ? event.element.element : null,
    target
  };
}
function dfs$1(node2, fn) {
  fn(node2);
  node2.children.forEach((child) => dfs$1(child, fn));
}
class Trait2 {
  get nodeSet() {
    if (!this._nodeSet) {
      this._nodeSet = this.createNodeSet();
    }
    return this._nodeSet;
  }
  constructor(getFirstViewElementWithTrait, identityProvider) {
    this.getFirstViewElementWithTrait = getFirstViewElementWithTrait;
    this.identityProvider = identityProvider;
    this.nodes = [];
    this._onDidChange = new Emitter$1();
    this.onDidChange = this._onDidChange.event;
  }
  set(nodes, browserEvent) {
    if (!(browserEvent === null || browserEvent === void 0 ? void 0 : browserEvent.__forceEvent) && equals$3(this.nodes, nodes)) {
      return;
    }
    this._set(nodes, false, browserEvent);
  }
  _set(nodes, silent, browserEvent) {
    this.nodes = [...nodes];
    this.elements = void 0;
    this._nodeSet = void 0;
    if (!silent) {
      const that = this;
      this._onDidChange.fire({ get elements() {
        return that.get();
      }, browserEvent });
    }
  }
  get() {
    if (!this.elements) {
      this.elements = this.nodes.map((node2) => node2.element);
    }
    return [...this.elements];
  }
  getNodes() {
    return this.nodes;
  }
  has(node2) {
    return this.nodeSet.has(node2);
  }
  onDidModelSplice({ insertedNodes, deletedNodes }) {
    if (!this.identityProvider) {
      const set2 = this.createNodeSet();
      const visit = (node2) => set2.delete(node2);
      deletedNodes.forEach((node2) => dfs$1(node2, visit));
      this.set([...set2.values()]);
      return;
    }
    const deletedNodesIdSet = /* @__PURE__ */ new Set();
    const deletedNodesVisitor = (node2) => deletedNodesIdSet.add(this.identityProvider.getId(node2.element).toString());
    deletedNodes.forEach((node2) => dfs$1(node2, deletedNodesVisitor));
    const insertedNodesMap = /* @__PURE__ */ new Map();
    const insertedNodesVisitor = (node2) => insertedNodesMap.set(this.identityProvider.getId(node2.element).toString(), node2);
    insertedNodes.forEach((node2) => dfs$1(node2, insertedNodesVisitor));
    const nodes = [];
    for (const node2 of this.nodes) {
      const id3 = this.identityProvider.getId(node2.element).toString();
      const wasDeleted = deletedNodesIdSet.has(id3);
      if (!wasDeleted) {
        nodes.push(node2);
      } else {
        const insertedNode = insertedNodesMap.get(id3);
        if (insertedNode && insertedNode.visible) {
          nodes.push(insertedNode);
        }
      }
    }
    if (this.nodes.length > 0 && nodes.length === 0) {
      const node2 = this.getFirstViewElementWithTrait();
      if (node2) {
        nodes.push(node2);
      }
    }
    this._set(nodes, true);
  }
  createNodeSet() {
    const set2 = /* @__PURE__ */ new Set();
    for (const node2 of this.nodes) {
      set2.add(node2);
    }
    return set2;
  }
}
class TreeNodeListMouseController extends MouseController {
  constructor(list2, tree2) {
    super(list2);
    this.tree = tree2;
  }
  onViewPointer(e) {
    if (isButton(e.browserEvent.target) || isInputElement(e.browserEvent.target) || isMonacoEditor(e.browserEvent.target)) {
      return;
    }
    if (e.browserEvent.isHandledByList) {
      return;
    }
    const node2 = e.element;
    if (!node2) {
      return super.onViewPointer(e);
    }
    if (this.isSelectionRangeChangeEvent(e) || this.isSelectionSingleChangeEvent(e)) {
      return super.onViewPointer(e);
    }
    const target = e.browserEvent.target;
    const onTwistie = target.classList.contains("monaco-tl-twistie") || target.classList.contains("monaco-icon-label") && target.classList.contains("folder-icon") && e.browserEvent.offsetX < 16;
    let expandOnlyOnTwistieClick = false;
    if (typeof this.tree.expandOnlyOnTwistieClick === "function") {
      expandOnlyOnTwistieClick = this.tree.expandOnlyOnTwistieClick(node2.element);
    } else {
      expandOnlyOnTwistieClick = !!this.tree.expandOnlyOnTwistieClick;
    }
    if (expandOnlyOnTwistieClick && !onTwistie && e.browserEvent.detail !== 2) {
      return super.onViewPointer(e);
    }
    if (!this.tree.expandOnDoubleClick && e.browserEvent.detail === 2) {
      return super.onViewPointer(e);
    }
    if (node2.collapsible) {
      const location = this.tree.getNodeLocation(node2);
      const recursive = e.browserEvent.altKey;
      this.tree.setFocus([location]);
      this.tree.toggleCollapsed(location, recursive);
      if (expandOnlyOnTwistieClick && onTwistie) {
        e.browserEvent.isHandledByList = true;
        return;
      }
    }
    super.onViewPointer(e);
  }
  onDoubleClick(e) {
    const onTwistie = e.browserEvent.target.classList.contains("monaco-tl-twistie");
    if (onTwistie || !this.tree.expandOnDoubleClick) {
      return;
    }
    if (e.browserEvent.isHandledByList) {
      return;
    }
    super.onDoubleClick(e);
  }
}
class TreeNodeList extends List {
  constructor(user, container2, virtualDelegate, renderers, focusTrait, selectionTrait, anchorTrait, options) {
    super(user, container2, virtualDelegate, renderers, options);
    this.focusTrait = focusTrait;
    this.selectionTrait = selectionTrait;
    this.anchorTrait = anchorTrait;
  }
  createMouseController(options) {
    return new TreeNodeListMouseController(this, options.tree);
  }
  splice(start, deleteCount, elements = []) {
    super.splice(start, deleteCount, elements);
    if (elements.length === 0) {
      return;
    }
    const additionalFocus = [];
    const additionalSelection = [];
    let anchor;
    elements.forEach((node2, index) => {
      if (this.focusTrait.has(node2)) {
        additionalFocus.push(start + index);
      }
      if (this.selectionTrait.has(node2)) {
        additionalSelection.push(start + index);
      }
      if (this.anchorTrait.has(node2)) {
        anchor = start + index;
      }
    });
    if (additionalFocus.length > 0) {
      super.setFocus(distinct([...super.getFocus(), ...additionalFocus]));
    }
    if (additionalSelection.length > 0) {
      super.setSelection(distinct([...super.getSelection(), ...additionalSelection]));
    }
    if (typeof anchor === "number") {
      super.setAnchor(anchor);
    }
  }
  setFocus(indexes, browserEvent, fromAPI = false) {
    super.setFocus(indexes, browserEvent);
    if (!fromAPI) {
      this.focusTrait.set(indexes.map((i) => this.element(i)), browserEvent);
    }
  }
  setSelection(indexes, browserEvent, fromAPI = false) {
    super.setSelection(indexes, browserEvent);
    if (!fromAPI) {
      this.selectionTrait.set(indexes.map((i) => this.element(i)), browserEvent);
    }
  }
  setAnchor(index, fromAPI = false) {
    super.setAnchor(index);
    if (!fromAPI) {
      if (typeof index === "undefined") {
        this.anchorTrait.set([]);
      } else {
        this.anchorTrait.set([this.element(index)]);
      }
    }
  }
}
class AbstractTree {
  get onDidScroll() {
    return this.view.onDidScroll;
  }
  get onDidChangeFocus() {
    return this.eventBufferer.wrapEvent(this.focus.onDidChange);
  }
  get onDidChangeSelection() {
    return this.eventBufferer.wrapEvent(this.selection.onDidChange);
  }
  get onMouseDblClick() {
    return Event$1.filter(Event$1.map(this.view.onMouseDblClick, asTreeMouseEvent$1), (e) => e.target !== TreeMouseEventTarget.Filter);
  }
  get onPointer() {
    return Event$1.map(this.view.onPointer, asTreeMouseEvent$1);
  }
  get onDidFocus() {
    return this.view.onDidFocus;
  }
  get onDidChangeModel() {
    return Event$1.signal(this.model.onDidSplice);
  }
  get onDidChangeCollapseState() {
    return this.model.onDidChangeCollapseState;
  }
  get findMode() {
    var _a2, _b2;
    return (_b2 = (_a2 = this.findController) === null || _a2 === void 0 ? void 0 : _a2.mode) !== null && _b2 !== void 0 ? _b2 : TreeFindMode.Highlight;
  }
  set findMode(findMode) {
    if (this.findController) {
      this.findController.mode = findMode;
    }
  }
  get findMatchType() {
    var _a2, _b2;
    return (_b2 = (_a2 = this.findController) === null || _a2 === void 0 ? void 0 : _a2.matchType) !== null && _b2 !== void 0 ? _b2 : TreeFindMatchType.Fuzzy;
  }
  set findMatchType(findFuzzy) {
    if (this.findController) {
      this.findController.matchType = findFuzzy;
    }
  }
  get expandOnDoubleClick() {
    return typeof this._options.expandOnDoubleClick === "undefined" ? true : this._options.expandOnDoubleClick;
  }
  get expandOnlyOnTwistieClick() {
    return typeof this._options.expandOnlyOnTwistieClick === "undefined" ? true : this._options.expandOnlyOnTwistieClick;
  }
  get onDidDispose() {
    return this.view.onDidDispose;
  }
  constructor(_user, container2, delegate, renderers, _options = {}) {
    var _a2;
    this._user = _user;
    this._options = _options;
    this.eventBufferer = new EventBufferer();
    this.onDidChangeFindOpenState = Event$1.None;
    this.disposables = new DisposableStore();
    this._onWillRefilter = new Emitter$1();
    this.onWillRefilter = this._onWillRefilter.event;
    this._onDidUpdateOptions = new Emitter$1();
    const treeDelegate = new ComposedTreeDelegate(delegate);
    const onDidChangeCollapseStateRelay = new Relay();
    const onDidChangeActiveNodes = new Relay();
    const activeNodes = this.disposables.add(new EventCollection(onDidChangeActiveNodes.event));
    const renderedIndentGuides = new SetMap();
    this.renderers = renderers.map((r) => new TreeRenderer(r, () => this.model, onDidChangeCollapseStateRelay.event, activeNodes, renderedIndentGuides, _options));
    for (const r of this.renderers) {
      this.disposables.add(r);
    }
    let filter2;
    if (_options.keyboardNavigationLabelProvider) {
      filter2 = new FindFilter(this, _options.keyboardNavigationLabelProvider, _options.filter);
      _options = Object.assign(Object.assign({}, _options), { filter: filter2 });
      this.disposables.add(filter2);
    }
    this.focus = new Trait2(() => this.view.getFocusedElements()[0], _options.identityProvider);
    this.selection = new Trait2(() => this.view.getSelectedElements()[0], _options.identityProvider);
    this.anchor = new Trait2(() => this.view.getAnchorElement(), _options.identityProvider);
    this.view = new TreeNodeList(_user, container2, treeDelegate, this.renderers, this.focus, this.selection, this.anchor, Object.assign(Object.assign({}, asListOptions(() => this.model, _options)), { tree: this }));
    this.model = this.createModel(_user, this.view, _options);
    onDidChangeCollapseStateRelay.input = this.model.onDidChangeCollapseState;
    const onDidModelSplice = Event$1.forEach(this.model.onDidSplice, (e) => {
      this.eventBufferer.bufferEvents(() => {
        this.focus.onDidModelSplice(e);
        this.selection.onDidModelSplice(e);
      });
    }, this.disposables);
    onDidModelSplice(() => null, null, this.disposables);
    onDidChangeActiveNodes.input = Event$1.chain(Event$1.any(onDidModelSplice, this.focus.onDidChange, this.selection.onDidChange)).debounce(() => null, 0).map(() => {
      const set2 = /* @__PURE__ */ new Set();
      for (const node2 of this.focus.getNodes()) {
        set2.add(node2);
      }
      for (const node2 of this.selection.getNodes()) {
        set2.add(node2);
      }
      return [...set2.values()];
    }).event;
    if (_options.keyboardSupport !== false) {
      const onKeyDown = Event$1.chain(this.view.onKeyDown).filter((e) => !isInputElement(e.target)).map((e) => new StandardKeyboardEvent(e));
      onKeyDown.filter(
        (e) => e.keyCode === 15
        /* KeyCode.LeftArrow */
      ).on(this.onLeftArrow, this, this.disposables);
      onKeyDown.filter(
        (e) => e.keyCode === 17
        /* KeyCode.RightArrow */
      ).on(this.onRightArrow, this, this.disposables);
      onKeyDown.filter(
        (e) => e.keyCode === 10
        /* KeyCode.Space */
      ).on(this.onSpace, this, this.disposables);
    }
    if (((_a2 = _options.findWidgetEnabled) !== null && _a2 !== void 0 ? _a2 : true) && _options.keyboardNavigationLabelProvider && _options.contextViewProvider) {
      const opts = this.options.findWidgetStyles ? { styles: this.options.findWidgetStyles } : void 0;
      this.findController = new FindController$1(this, this.model, this.view, filter2, _options.contextViewProvider, opts);
      this.focusNavigationFilter = (node2) => this.findController.shouldAllowFocus(node2);
      this.onDidChangeFindOpenState = this.findController.onDidChangeOpenState;
      this.disposables.add(this.findController);
      this.onDidChangeFindMode = this.findController.onDidChangeMode;
      this.onDidChangeFindMatchType = this.findController.onDidChangeMatchType;
    } else {
      this.onDidChangeFindMode = Event$1.None;
      this.onDidChangeFindMatchType = Event$1.None;
    }
    this.styleElement = createStyleSheet(this.view.getHTMLElement());
    this.getHTMLElement().classList.toggle("always", this._options.renderIndentGuides === RenderIndentGuides.Always);
  }
  updateOptions(optionsUpdate = {}) {
    var _a2;
    this._options = Object.assign(Object.assign({}, this._options), optionsUpdate);
    for (const renderer2 of this.renderers) {
      renderer2.updateOptions(optionsUpdate);
    }
    this.view.updateOptions(this._options);
    (_a2 = this.findController) === null || _a2 === void 0 ? void 0 : _a2.updateOptions(optionsUpdate);
    this._onDidUpdateOptions.fire(this._options);
    this.getHTMLElement().classList.toggle("always", this._options.renderIndentGuides === RenderIndentGuides.Always);
  }
  get options() {
    return this._options;
  }
  // Widget
  getHTMLElement() {
    return this.view.getHTMLElement();
  }
  get scrollTop() {
    return this.view.scrollTop;
  }
  set scrollTop(scrollTop) {
    this.view.scrollTop = scrollTop;
  }
  get scrollHeight() {
    return this.view.scrollHeight;
  }
  get renderHeight() {
    return this.view.renderHeight;
  }
  domFocus() {
    this.view.domFocus();
  }
  layout(height, width) {
    var _a2;
    this.view.layout(height, width);
    if (isNumber$3(width)) {
      (_a2 = this.findController) === null || _a2 === void 0 ? void 0 : _a2.layout(width);
    }
  }
  style(styles) {
    const suffix = `.${this.view.domId}`;
    const content = [];
    if (styles.treeIndentGuidesStroke) {
      content.push(`.monaco-list${suffix}:hover .monaco-tl-indent > .indent-guide, .monaco-list${suffix}.always .monaco-tl-indent > .indent-guide  { border-color: ${styles.treeInactiveIndentGuidesStroke}; }`);
      content.push(`.monaco-list${suffix} .monaco-tl-indent > .indent-guide.active { border-color: ${styles.treeIndentGuidesStroke}; }`);
    }
    this.styleElement.textContent = content.join("\n");
    this.view.style(styles);
  }
  // Tree navigation
  getParentElement(location) {
    const parentRef = this.model.getParentNodeLocation(location);
    const parentNode = this.model.getNode(parentRef);
    return parentNode.element;
  }
  getFirstElementChild(location) {
    return this.model.getFirstElementChild(location);
  }
  // Tree
  getNode(location) {
    return this.model.getNode(location);
  }
  getNodeLocation(node2) {
    return this.model.getNodeLocation(node2);
  }
  collapse(location, recursive = false) {
    return this.model.setCollapsed(location, true, recursive);
  }
  expand(location, recursive = false) {
    return this.model.setCollapsed(location, false, recursive);
  }
  toggleCollapsed(location, recursive = false) {
    return this.model.setCollapsed(location, void 0, recursive);
  }
  isCollapsible(location) {
    return this.model.isCollapsible(location);
  }
  setCollapsible(location, collapsible) {
    return this.model.setCollapsible(location, collapsible);
  }
  isCollapsed(location) {
    return this.model.isCollapsed(location);
  }
  refilter() {
    this._onWillRefilter.fire(void 0);
    this.model.refilter();
  }
  setSelection(elements, browserEvent) {
    const nodes = elements.map((e) => this.model.getNode(e));
    this.selection.set(nodes, browserEvent);
    const indexes = elements.map((e) => this.model.getListIndex(e)).filter((i) => i > -1);
    this.view.setSelection(indexes, browserEvent, true);
  }
  getSelection() {
    return this.selection.get();
  }
  setFocus(elements, browserEvent) {
    const nodes = elements.map((e) => this.model.getNode(e));
    this.focus.set(nodes, browserEvent);
    const indexes = elements.map((e) => this.model.getListIndex(e)).filter((i) => i > -1);
    this.view.setFocus(indexes, browserEvent, true);
  }
  getFocus() {
    return this.focus.get();
  }
  reveal(location, relativeTop) {
    this.model.expandTo(location);
    const index = this.model.getListIndex(location);
    if (index === -1) {
      return;
    }
    this.view.reveal(index, relativeTop);
  }
  // List
  onLeftArrow(e) {
    e.preventDefault();
    e.stopPropagation();
    const nodes = this.view.getFocusedElements();
    if (nodes.length === 0) {
      return;
    }
    const node2 = nodes[0];
    const location = this.model.getNodeLocation(node2);
    const didChange = this.model.setCollapsed(location, true);
    if (!didChange) {
      const parentLocation = this.model.getParentNodeLocation(location);
      if (!parentLocation) {
        return;
      }
      const parentListIndex = this.model.getListIndex(parentLocation);
      this.view.reveal(parentListIndex);
      this.view.setFocus([parentListIndex]);
    }
  }
  onRightArrow(e) {
    e.preventDefault();
    e.stopPropagation();
    const nodes = this.view.getFocusedElements();
    if (nodes.length === 0) {
      return;
    }
    const node2 = nodes[0];
    const location = this.model.getNodeLocation(node2);
    const didChange = this.model.setCollapsed(location, false);
    if (!didChange) {
      if (!node2.children.some((child) => child.visible)) {
        return;
      }
      const [focusedIndex] = this.view.getFocus();
      const firstChildIndex = focusedIndex + 1;
      this.view.reveal(firstChildIndex);
      this.view.setFocus([firstChildIndex]);
    }
  }
  onSpace(e) {
    e.preventDefault();
    e.stopPropagation();
    const nodes = this.view.getFocusedElements();
    if (nodes.length === 0) {
      return;
    }
    const node2 = nodes[0];
    const location = this.model.getNodeLocation(node2);
    const recursive = e.browserEvent.altKey;
    this.model.setCollapsed(location, void 0, recursive);
  }
  dispose() {
    dispose(this.disposables);
    this.view.dispose();
  }
}
class ObjectTreeModel {
  constructor(user, list2, options = {}) {
    this.user = user;
    this.rootRef = null;
    this.nodes = /* @__PURE__ */ new Map();
    this.nodesByIdentity = /* @__PURE__ */ new Map();
    this.model = new IndexTreeModel(user, list2, null, options);
    this.onDidSplice = this.model.onDidSplice;
    this.onDidChangeCollapseState = this.model.onDidChangeCollapseState;
    this.onDidChangeRenderNodeCount = this.model.onDidChangeRenderNodeCount;
    if (options.sorter) {
      this.sorter = {
        compare(a, b) {
          return options.sorter.compare(a.element, b.element);
        }
      };
    }
    this.identityProvider = options.identityProvider;
  }
  setChildren(element, children = Iterable.empty(), options = {}) {
    const location = this.getElementLocation(element);
    this._setChildren(location, this.preserveCollapseState(children), options);
  }
  _setChildren(location, children = Iterable.empty(), options) {
    const insertedElements = /* @__PURE__ */ new Set();
    const insertedElementIds = /* @__PURE__ */ new Set();
    const onDidCreateNode = (node2) => {
      var _a2;
      if (node2.element === null) {
        return;
      }
      const tnode = node2;
      insertedElements.add(tnode.element);
      this.nodes.set(tnode.element, tnode);
      if (this.identityProvider) {
        const id3 = this.identityProvider.getId(tnode.element).toString();
        insertedElementIds.add(id3);
        this.nodesByIdentity.set(id3, tnode);
      }
      (_a2 = options.onDidCreateNode) === null || _a2 === void 0 ? void 0 : _a2.call(options, tnode);
    };
    const onDidDeleteNode = (node2) => {
      var _a2;
      if (node2.element === null) {
        return;
      }
      const tnode = node2;
      if (!insertedElements.has(tnode.element)) {
        this.nodes.delete(tnode.element);
      }
      if (this.identityProvider) {
        const id3 = this.identityProvider.getId(tnode.element).toString();
        if (!insertedElementIds.has(id3)) {
          this.nodesByIdentity.delete(id3);
        }
      }
      (_a2 = options.onDidDeleteNode) === null || _a2 === void 0 ? void 0 : _a2.call(options, tnode);
    };
    this.model.splice([...location, 0], Number.MAX_VALUE, children, Object.assign(Object.assign({}, options), { onDidCreateNode, onDidDeleteNode }));
  }
  preserveCollapseState(elements = Iterable.empty()) {
    if (this.sorter) {
      elements = [...elements].sort(this.sorter.compare.bind(this.sorter));
    }
    return Iterable.map(elements, (treeElement) => {
      let node2 = this.nodes.get(treeElement.element);
      if (!node2 && this.identityProvider) {
        const id3 = this.identityProvider.getId(treeElement.element).toString();
        node2 = this.nodesByIdentity.get(id3);
      }
      if (!node2) {
        let collapsed2;
        if (typeof treeElement.collapsed === "undefined") {
          collapsed2 = void 0;
        } else if (treeElement.collapsed === ObjectTreeElementCollapseState.Collapsed || treeElement.collapsed === ObjectTreeElementCollapseState.PreserveOrCollapsed) {
          collapsed2 = true;
        } else if (treeElement.collapsed === ObjectTreeElementCollapseState.Expanded || treeElement.collapsed === ObjectTreeElementCollapseState.PreserveOrExpanded) {
          collapsed2 = false;
        } else {
          collapsed2 = Boolean(treeElement.collapsed);
        }
        return Object.assign(Object.assign({}, treeElement), { children: this.preserveCollapseState(treeElement.children), collapsed: collapsed2 });
      }
      const collapsible = typeof treeElement.collapsible === "boolean" ? treeElement.collapsible : node2.collapsible;
      let collapsed;
      if (typeof treeElement.collapsed === "undefined" || treeElement.collapsed === ObjectTreeElementCollapseState.PreserveOrCollapsed || treeElement.collapsed === ObjectTreeElementCollapseState.PreserveOrExpanded) {
        collapsed = node2.collapsed;
      } else if (treeElement.collapsed === ObjectTreeElementCollapseState.Collapsed) {
        collapsed = true;
      } else if (treeElement.collapsed === ObjectTreeElementCollapseState.Expanded) {
        collapsed = false;
      } else {
        collapsed = Boolean(treeElement.collapsed);
      }
      return Object.assign(Object.assign({}, treeElement), {
        collapsible,
        collapsed,
        children: this.preserveCollapseState(treeElement.children)
      });
    });
  }
  rerender(element) {
    const location = this.getElementLocation(element);
    this.model.rerender(location);
  }
  getFirstElementChild(ref2 = null) {
    const location = this.getElementLocation(ref2);
    return this.model.getFirstElementChild(location);
  }
  has(element) {
    return this.nodes.has(element);
  }
  getListIndex(element) {
    const location = this.getElementLocation(element);
    return this.model.getListIndex(location);
  }
  getListRenderCount(element) {
    const location = this.getElementLocation(element);
    return this.model.getListRenderCount(location);
  }
  isCollapsible(element) {
    const location = this.getElementLocation(element);
    return this.model.isCollapsible(location);
  }
  setCollapsible(element, collapsible) {
    const location = this.getElementLocation(element);
    return this.model.setCollapsible(location, collapsible);
  }
  isCollapsed(element) {
    const location = this.getElementLocation(element);
    return this.model.isCollapsed(location);
  }
  setCollapsed(element, collapsed, recursive) {
    const location = this.getElementLocation(element);
    return this.model.setCollapsed(location, collapsed, recursive);
  }
  expandTo(element) {
    const location = this.getElementLocation(element);
    this.model.expandTo(location);
  }
  refilter() {
    this.model.refilter();
  }
  getNode(element = null) {
    if (element === null) {
      return this.model.getNode(this.model.rootRef);
    }
    const node2 = this.nodes.get(element);
    if (!node2) {
      throw new TreeError(this.user, `Tree element not found: ${element}`);
    }
    return node2;
  }
  getNodeLocation(node2) {
    return node2.element;
  }
  getParentNodeLocation(element) {
    if (element === null) {
      throw new TreeError(this.user, `Invalid getParentNodeLocation call`);
    }
    const node2 = this.nodes.get(element);
    if (!node2) {
      throw new TreeError(this.user, `Tree element not found: ${element}`);
    }
    const location = this.model.getNodeLocation(node2);
    const parentLocation = this.model.getParentNodeLocation(location);
    const parent = this.model.getNode(parentLocation);
    return parent.element;
  }
  getElementLocation(element) {
    if (element === null) {
      return [];
    }
    const node2 = this.nodes.get(element);
    if (!node2) {
      throw new TreeError(this.user, `Tree element not found: ${element}`);
    }
    return this.model.getNodeLocation(node2);
  }
}
function noCompress(element) {
  const elements = [element.element];
  const incompressible = element.incompressible || false;
  return {
    element: { elements, incompressible },
    children: Iterable.map(Iterable.from(element.children), noCompress),
    collapsible: element.collapsible,
    collapsed: element.collapsed
  };
}
function compress(element) {
  const elements = [element.element];
  const incompressible = element.incompressible || false;
  let childrenIterator;
  let children;
  while (true) {
    [children, childrenIterator] = Iterable.consume(Iterable.from(element.children), 2);
    if (children.length !== 1) {
      break;
    }
    if (children[0].incompressible) {
      break;
    }
    element = children[0];
    elements.push(element.element);
  }
  return {
    element: { elements, incompressible },
    children: Iterable.map(Iterable.concat(children, childrenIterator), compress),
    collapsible: element.collapsible,
    collapsed: element.collapsed
  };
}
function _decompress(element, index = 0) {
  let children;
  if (index < element.element.elements.length - 1) {
    children = [_decompress(element, index + 1)];
  } else {
    children = Iterable.map(Iterable.from(element.children), (el) => _decompress(el, 0));
  }
  if (index === 0 && element.element.incompressible) {
    return {
      element: element.element.elements[index],
      children,
      incompressible: true,
      collapsible: element.collapsible,
      collapsed: element.collapsed
    };
  }
  return {
    element: element.element.elements[index],
    children,
    collapsible: element.collapsible,
    collapsed: element.collapsed
  };
}
function decompress(element) {
  return _decompress(element, 0);
}
function splice(treeElement, element, children) {
  if (treeElement.element === element) {
    return Object.assign(Object.assign({}, treeElement), { children });
  }
  return Object.assign(Object.assign({}, treeElement), { children: Iterable.map(Iterable.from(treeElement.children), (e) => splice(e, element, children)) });
}
const wrapIdentityProvider = (base2) => ({
  getId(node2) {
    return node2.elements.map((e) => base2.getId(e).toString()).join("\0");
  }
});
class CompressedObjectTreeModel {
  get onDidSplice() {
    return this.model.onDidSplice;
  }
  get onDidChangeCollapseState() {
    return this.model.onDidChangeCollapseState;
  }
  get onDidChangeRenderNodeCount() {
    return this.model.onDidChangeRenderNodeCount;
  }
  constructor(user, list2, options = {}) {
    this.user = user;
    this.rootRef = null;
    this.nodes = /* @__PURE__ */ new Map();
    this.model = new ObjectTreeModel(user, list2, options);
    this.enabled = typeof options.compressionEnabled === "undefined" ? true : options.compressionEnabled;
    this.identityProvider = options.identityProvider;
  }
  setChildren(element, children = Iterable.empty(), options) {
    const diffIdentityProvider = options.diffIdentityProvider && wrapIdentityProvider(options.diffIdentityProvider);
    if (element === null) {
      const compressedChildren = Iterable.map(children, this.enabled ? compress : noCompress);
      this._setChildren(null, compressedChildren, { diffIdentityProvider, diffDepth: Infinity });
      return;
    }
    const compressedNode = this.nodes.get(element);
    if (!compressedNode) {
      throw new TreeError(this.user, "Unknown compressed tree node");
    }
    const node2 = this.model.getNode(compressedNode);
    const compressedParentNode = this.model.getParentNodeLocation(compressedNode);
    const parent = this.model.getNode(compressedParentNode);
    const decompressedElement = decompress(node2);
    const splicedElement = splice(decompressedElement, element, children);
    const recompressedElement = (this.enabled ? compress : noCompress)(splicedElement);
    const elementComparator = options.diffIdentityProvider ? (a, b) => options.diffIdentityProvider.getId(a) === options.diffIdentityProvider.getId(b) : void 0;
    if (equals$3(recompressedElement.element.elements, node2.element.elements, elementComparator)) {
      this._setChildren(compressedNode, recompressedElement.children || Iterable.empty(), { diffIdentityProvider, diffDepth: 1 });
      return;
    }
    const parentChildren = parent.children.map((child) => child === node2 ? recompressedElement : child);
    this._setChildren(parent.element, parentChildren, {
      diffIdentityProvider,
      diffDepth: node2.depth - parent.depth
    });
  }
  setCompressionEnabled(enabled) {
    if (enabled === this.enabled) {
      return;
    }
    this.enabled = enabled;
    const root3 = this.model.getNode();
    const rootChildren = root3.children;
    const decompressedRootChildren = Iterable.map(rootChildren, decompress);
    const recompressedRootChildren = Iterable.map(decompressedRootChildren, enabled ? compress : noCompress);
    this._setChildren(null, recompressedRootChildren, {
      diffIdentityProvider: this.identityProvider,
      diffDepth: Infinity
    });
  }
  _setChildren(node2, children, options) {
    const insertedElements = /* @__PURE__ */ new Set();
    const onDidCreateNode = (node3) => {
      for (const element of node3.element.elements) {
        insertedElements.add(element);
        this.nodes.set(element, node3.element);
      }
    };
    const onDidDeleteNode = (node3) => {
      for (const element of node3.element.elements) {
        if (!insertedElements.has(element)) {
          this.nodes.delete(element);
        }
      }
    };
    this.model.setChildren(node2, children, Object.assign(Object.assign({}, options), { onDidCreateNode, onDidDeleteNode }));
  }
  has(element) {
    return this.nodes.has(element);
  }
  getListIndex(location) {
    const node2 = this.getCompressedNode(location);
    return this.model.getListIndex(node2);
  }
  getListRenderCount(location) {
    const node2 = this.getCompressedNode(location);
    return this.model.getListRenderCount(node2);
  }
  getNode(location) {
    if (typeof location === "undefined") {
      return this.model.getNode();
    }
    const node2 = this.getCompressedNode(location);
    return this.model.getNode(node2);
  }
  // TODO: review this
  getNodeLocation(node2) {
    const compressedNode = this.model.getNodeLocation(node2);
    if (compressedNode === null) {
      return null;
    }
    return compressedNode.elements[compressedNode.elements.length - 1];
  }
  // TODO: review this
  getParentNodeLocation(location) {
    const compressedNode = this.getCompressedNode(location);
    const parentNode = this.model.getParentNodeLocation(compressedNode);
    if (parentNode === null) {
      return null;
    }
    return parentNode.elements[parentNode.elements.length - 1];
  }
  getFirstElementChild(location) {
    const compressedNode = this.getCompressedNode(location);
    return this.model.getFirstElementChild(compressedNode);
  }
  isCollapsible(location) {
    const compressedNode = this.getCompressedNode(location);
    return this.model.isCollapsible(compressedNode);
  }
  setCollapsible(location, collapsible) {
    const compressedNode = this.getCompressedNode(location);
    return this.model.setCollapsible(compressedNode, collapsible);
  }
  isCollapsed(location) {
    const compressedNode = this.getCompressedNode(location);
    return this.model.isCollapsed(compressedNode);
  }
  setCollapsed(location, collapsed, recursive) {
    const compressedNode = this.getCompressedNode(location);
    return this.model.setCollapsed(compressedNode, collapsed, recursive);
  }
  expandTo(location) {
    const compressedNode = this.getCompressedNode(location);
    this.model.expandTo(compressedNode);
  }
  rerender(location) {
    const compressedNode = this.getCompressedNode(location);
    this.model.rerender(compressedNode);
  }
  refilter() {
    this.model.refilter();
  }
  getCompressedNode(element) {
    if (element === null) {
      return null;
    }
    const node2 = this.nodes.get(element);
    if (!node2) {
      throw new TreeError(this.user, `Tree element not found: ${element}`);
    }
    return node2;
  }
}
const DefaultElementMapper = (elements) => elements[elements.length - 1];
class CompressedTreeNodeWrapper {
  get element() {
    return this.node.element === null ? null : this.unwrapper(this.node.element);
  }
  get children() {
    return this.node.children.map((node2) => new CompressedTreeNodeWrapper(this.unwrapper, node2));
  }
  get depth() {
    return this.node.depth;
  }
  get visibleChildrenCount() {
    return this.node.visibleChildrenCount;
  }
  get visibleChildIndex() {
    return this.node.visibleChildIndex;
  }
  get collapsible() {
    return this.node.collapsible;
  }
  get collapsed() {
    return this.node.collapsed;
  }
  get visible() {
    return this.node.visible;
  }
  get filterData() {
    return this.node.filterData;
  }
  constructor(unwrapper, node2) {
    this.unwrapper = unwrapper;
    this.node = node2;
  }
}
function mapList(nodeMapper, list2) {
  return {
    splice(start, deleteCount, toInsert) {
      list2.splice(start, deleteCount, toInsert.map((node2) => nodeMapper.map(node2)));
    },
    updateElementHeight(index, height) {
      list2.updateElementHeight(index, height);
    }
  };
}
function mapOptions(compressedNodeUnwrapper, options) {
  return Object.assign(Object.assign({}, options), { identityProvider: options.identityProvider && {
    getId(node2) {
      return options.identityProvider.getId(compressedNodeUnwrapper(node2));
    }
  }, sorter: options.sorter && {
    compare(node2, otherNode) {
      return options.sorter.compare(node2.elements[0], otherNode.elements[0]);
    }
  }, filter: options.filter && {
    filter(node2, parentVisibility) {
      return options.filter.filter(compressedNodeUnwrapper(node2), parentVisibility);
    }
  } });
}
class CompressibleObjectTreeModel {
  get onDidSplice() {
    return Event$1.map(this.model.onDidSplice, ({ insertedNodes, deletedNodes }) => ({
      insertedNodes: insertedNodes.map((node2) => this.nodeMapper.map(node2)),
      deletedNodes: deletedNodes.map((node2) => this.nodeMapper.map(node2))
    }));
  }
  get onDidChangeCollapseState() {
    return Event$1.map(this.model.onDidChangeCollapseState, ({ node: node2, deep }) => ({
      node: this.nodeMapper.map(node2),
      deep
    }));
  }
  get onDidChangeRenderNodeCount() {
    return Event$1.map(this.model.onDidChangeRenderNodeCount, (node2) => this.nodeMapper.map(node2));
  }
  constructor(user, list2, options = {}) {
    this.rootRef = null;
    this.elementMapper = options.elementMapper || DefaultElementMapper;
    const compressedNodeUnwrapper = (node2) => this.elementMapper(node2.elements);
    this.nodeMapper = new WeakMapper((node2) => new CompressedTreeNodeWrapper(compressedNodeUnwrapper, node2));
    this.model = new CompressedObjectTreeModel(user, mapList(this.nodeMapper, list2), mapOptions(compressedNodeUnwrapper, options));
  }
  setChildren(element, children = Iterable.empty(), options = {}) {
    this.model.setChildren(element, children, options);
  }
  setCompressionEnabled(enabled) {
    this.model.setCompressionEnabled(enabled);
  }
  has(location) {
    return this.model.has(location);
  }
  getListIndex(location) {
    return this.model.getListIndex(location);
  }
  getListRenderCount(location) {
    return this.model.getListRenderCount(location);
  }
  getNode(location) {
    return this.nodeMapper.map(this.model.getNode(location));
  }
  getNodeLocation(node2) {
    return node2.element;
  }
  getParentNodeLocation(location) {
    return this.model.getParentNodeLocation(location);
  }
  getFirstElementChild(location) {
    const result2 = this.model.getFirstElementChild(location);
    if (result2 === null || typeof result2 === "undefined") {
      return result2;
    }
    return this.elementMapper(result2.elements);
  }
  isCollapsible(location) {
    return this.model.isCollapsible(location);
  }
  setCollapsible(location, collapsed) {
    return this.model.setCollapsible(location, collapsed);
  }
  isCollapsed(location) {
    return this.model.isCollapsed(location);
  }
  setCollapsed(location, collapsed, recursive) {
    return this.model.setCollapsed(location, collapsed, recursive);
  }
  expandTo(location) {
    return this.model.expandTo(location);
  }
  rerender(location) {
    return this.model.rerender(location);
  }
  refilter() {
    return this.model.refilter();
  }
  getCompressedTreeNode(location = null) {
    return this.model.getNode(location);
  }
}
var __decorate$1E = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
class ObjectTree extends AbstractTree {
  get onDidChangeCollapseState() {
    return this.model.onDidChangeCollapseState;
  }
  constructor(user, container2, delegate, renderers, options = {}) {
    super(user, container2, delegate, renderers, options);
    this.user = user;
  }
  setChildren(element, children = Iterable.empty(), options) {
    this.model.setChildren(element, children, options);
  }
  rerender(element) {
    if (element === void 0) {
      this.view.rerender();
      return;
    }
    this.model.rerender(element);
  }
  hasElement(element) {
    return this.model.has(element);
  }
  createModel(user, view, options) {
    return new ObjectTreeModel(user, view, options);
  }
}
class CompressibleRenderer {
  get compressedTreeNodeProvider() {
    return this._compressedTreeNodeProvider();
  }
  constructor(_compressedTreeNodeProvider, renderer2) {
    this._compressedTreeNodeProvider = _compressedTreeNodeProvider;
    this.renderer = renderer2;
    this.templateId = renderer2.templateId;
    if (renderer2.onDidChangeTwistieState) {
      this.onDidChangeTwistieState = renderer2.onDidChangeTwistieState;
    }
  }
  renderTemplate(container2) {
    const data = this.renderer.renderTemplate(container2);
    return { compressedTreeNode: void 0, data };
  }
  renderElement(node2, index, templateData, height) {
    const compressedTreeNode = this.compressedTreeNodeProvider.getCompressedTreeNode(node2.element);
    if (compressedTreeNode.element.elements.length === 1) {
      templateData.compressedTreeNode = void 0;
      this.renderer.renderElement(node2, index, templateData.data, height);
    } else {
      templateData.compressedTreeNode = compressedTreeNode;
      this.renderer.renderCompressedElements(compressedTreeNode, index, templateData.data, height);
    }
  }
  disposeElement(node2, index, templateData, height) {
    var _a2, _b2, _c2, _d2;
    if (templateData.compressedTreeNode) {
      (_b2 = (_a2 = this.renderer).disposeCompressedElements) === null || _b2 === void 0 ? void 0 : _b2.call(_a2, templateData.compressedTreeNode, index, templateData.data, height);
    } else {
      (_d2 = (_c2 = this.renderer).disposeElement) === null || _d2 === void 0 ? void 0 : _d2.call(_c2, node2, index, templateData.data, height);
    }
  }
  disposeTemplate(templateData) {
    this.renderer.disposeTemplate(templateData.data);
  }
  renderTwistie(element, twistieElement) {
    if (this.renderer.renderTwistie) {
      return this.renderer.renderTwistie(element, twistieElement);
    }
    return false;
  }
}
__decorate$1E([
  memoize
], CompressibleRenderer.prototype, "compressedTreeNodeProvider", null);
function asObjectTreeOptions$1(compressedTreeNodeProvider, options) {
  return options && Object.assign(Object.assign({}, options), { keyboardNavigationLabelProvider: options.keyboardNavigationLabelProvider && {
    getKeyboardNavigationLabel(e) {
      let compressedTreeNode;
      try {
        compressedTreeNode = compressedTreeNodeProvider().getCompressedTreeNode(e);
      } catch (_a2) {
        return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(e);
      }
      if (compressedTreeNode.element.elements.length === 1) {
        return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(e);
      } else {
        return options.keyboardNavigationLabelProvider.getCompressedNodeKeyboardNavigationLabel(compressedTreeNode.element.elements);
      }
    }
  } });
}
class CompressibleObjectTree extends ObjectTree {
  constructor(user, container2, delegate, renderers, options = {}) {
    const compressedTreeNodeProvider = () => this;
    const compressibleRenderers = renderers.map((r) => new CompressibleRenderer(compressedTreeNodeProvider, r));
    super(user, container2, delegate, compressibleRenderers, asObjectTreeOptions$1(compressedTreeNodeProvider, options));
  }
  setChildren(element, children = Iterable.empty(), options) {
    this.model.setChildren(element, children, options);
  }
  createModel(user, view, options) {
    return new CompressibleObjectTreeModel(user, view, options);
  }
  updateOptions(optionsUpdate = {}) {
    super.updateOptions(optionsUpdate);
    if (typeof optionsUpdate.compressionEnabled !== "undefined") {
      this.model.setCompressionEnabled(optionsUpdate.compressionEnabled);
    }
  }
  getCompressedTreeNode(element = null) {
    return this.model.getCompressedTreeNode(element);
  }
}
var __awaiter$18 = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
function createAsyncDataTreeNode(props) {
  return Object.assign(Object.assign({}, props), { children: [], refreshPromise: void 0, stale: true, slow: false, collapsedByDefault: void 0 });
}
function isAncestor(ancestor, descendant) {
  if (!descendant.parent) {
    return false;
  } else if (descendant.parent === ancestor) {
    return true;
  } else {
    return isAncestor(ancestor, descendant.parent);
  }
}
function intersects(node2, other) {
  return node2 === other || isAncestor(node2, other) || isAncestor(other, node2);
}
class AsyncDataTreeNodeWrapper {
  get element() {
    return this.node.element.element;
  }
  get children() {
    return this.node.children.map((node2) => new AsyncDataTreeNodeWrapper(node2));
  }
  get depth() {
    return this.node.depth;
  }
  get visibleChildrenCount() {
    return this.node.visibleChildrenCount;
  }
  get visibleChildIndex() {
    return this.node.visibleChildIndex;
  }
  get collapsible() {
    return this.node.collapsible;
  }
  get collapsed() {
    return this.node.collapsed;
  }
  get visible() {
    return this.node.visible;
  }
  get filterData() {
    return this.node.filterData;
  }
  constructor(node2) {
    this.node = node2;
  }
}
class AsyncDataTreeRenderer {
  constructor(renderer2, nodeMapper, onDidChangeTwistieState) {
    this.renderer = renderer2;
    this.nodeMapper = nodeMapper;
    this.onDidChangeTwistieState = onDidChangeTwistieState;
    this.renderedNodes = /* @__PURE__ */ new Map();
    this.templateId = renderer2.templateId;
  }
  renderTemplate(container2) {
    const templateData = this.renderer.renderTemplate(container2);
    return { templateData };
  }
  renderElement(node2, index, templateData, height) {
    this.renderer.renderElement(this.nodeMapper.map(node2), index, templateData.templateData, height);
  }
  renderTwistie(element, twistieElement) {
    if (element.slow) {
      twistieElement.classList.add(...ThemeIcon.asClassNameArray(Codicon.treeItemLoading));
      return true;
    } else {
      twistieElement.classList.remove(...ThemeIcon.asClassNameArray(Codicon.treeItemLoading));
      return false;
    }
  }
  disposeElement(node2, index, templateData, height) {
    var _a2, _b2;
    (_b2 = (_a2 = this.renderer).disposeElement) === null || _b2 === void 0 ? void 0 : _b2.call(_a2, this.nodeMapper.map(node2), index, templateData.templateData, height);
  }
  disposeTemplate(templateData) {
    this.renderer.disposeTemplate(templateData.templateData);
  }
  dispose() {
    this.renderedNodes.clear();
  }
}
function asTreeEvent(e) {
  return {
    browserEvent: e.browserEvent,
    elements: e.elements.map((e2) => e2.element)
  };
}
function asTreeMouseEvent(e) {
  return {
    browserEvent: e.browserEvent,
    element: e.element && e.element.element,
    target: e.target
  };
}
class AsyncDataTreeElementsDragAndDropData extends ElementsDragAndDropData {
  constructor(data) {
    super(data.elements.map((node2) => node2.element));
    this.data = data;
  }
}
function asAsyncDataTreeDragAndDropData(data) {
  if (data instanceof ElementsDragAndDropData) {
    return new AsyncDataTreeElementsDragAndDropData(data);
  }
  return data;
}
class AsyncDataTreeNodeListDragAndDrop {
  constructor(dnd2) {
    this.dnd = dnd2;
  }
  getDragURI(node2) {
    return this.dnd.getDragURI(node2.element);
  }
  getDragLabel(nodes, originalEvent) {
    if (this.dnd.getDragLabel) {
      return this.dnd.getDragLabel(nodes.map((node2) => node2.element), originalEvent);
    }
    return void 0;
  }
  onDragStart(data, originalEvent) {
    var _a2, _b2;
    (_b2 = (_a2 = this.dnd).onDragStart) === null || _b2 === void 0 ? void 0 : _b2.call(_a2, asAsyncDataTreeDragAndDropData(data), originalEvent);
  }
  onDragOver(data, targetNode, targetIndex, originalEvent, raw = true) {
    return this.dnd.onDragOver(asAsyncDataTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, originalEvent);
  }
  drop(data, targetNode, targetIndex, originalEvent) {
    this.dnd.drop(asAsyncDataTreeDragAndDropData(data), targetNode && targetNode.element, targetIndex, originalEvent);
  }
  onDragEnd(originalEvent) {
    var _a2, _b2;
    (_b2 = (_a2 = this.dnd).onDragEnd) === null || _b2 === void 0 ? void 0 : _b2.call(_a2, originalEvent);
  }
}
function asObjectTreeOptions(options) {
  return options && Object.assign(Object.assign({}, options), { collapseByDefault: true, identityProvider: options.identityProvider && {
    getId(el) {
      return options.identityProvider.getId(el.element);
    }
  }, dnd: options.dnd && new AsyncDataTreeNodeListDragAndDrop(options.dnd), multipleSelectionController: options.multipleSelectionController && {
    isSelectionSingleChangeEvent(e) {
      return options.multipleSelectionController.isSelectionSingleChangeEvent(Object.assign(Object.assign({}, e), { element: e.element }));
    },
    isSelectionRangeChangeEvent(e) {
      return options.multipleSelectionController.isSelectionRangeChangeEvent(Object.assign(Object.assign({}, e), { element: e.element }));
    }
  }, accessibilityProvider: options.accessibilityProvider && Object.assign(Object.assign({}, options.accessibilityProvider), {
    getPosInSet: void 0,
    getSetSize: void 0,
    getRole: options.accessibilityProvider.getRole ? (el) => {
      return options.accessibilityProvider.getRole(el.element);
    } : () => "treeitem",
    isChecked: options.accessibilityProvider.isChecked ? (e) => {
      var _a2;
      return !!((_a2 = options.accessibilityProvider) === null || _a2 === void 0 ? void 0 : _a2.isChecked(e.element));
    } : void 0,
    getAriaLabel(e) {
      return options.accessibilityProvider.getAriaLabel(e.element);
    },
    getWidgetAriaLabel() {
      return options.accessibilityProvider.getWidgetAriaLabel();
    },
    getWidgetRole: options.accessibilityProvider.getWidgetRole ? () => options.accessibilityProvider.getWidgetRole() : () => "tree",
    getAriaLevel: options.accessibilityProvider.getAriaLevel && ((node2) => {
      return options.accessibilityProvider.getAriaLevel(node2.element);
    }),
    getActiveDescendantId: options.accessibilityProvider.getActiveDescendantId && ((node2) => {
      return options.accessibilityProvider.getActiveDescendantId(node2.element);
    })
  }), filter: options.filter && {
    filter(e, parentVisibility) {
      return options.filter.filter(e.element, parentVisibility);
    }
  }, keyboardNavigationLabelProvider: options.keyboardNavigationLabelProvider && Object.assign(Object.assign({}, options.keyboardNavigationLabelProvider), { getKeyboardNavigationLabel(e) {
    return options.keyboardNavigationLabelProvider.getKeyboardNavigationLabel(e.element);
  } }), sorter: void 0, expandOnlyOnTwistieClick: typeof options.expandOnlyOnTwistieClick === "undefined" ? void 0 : typeof options.expandOnlyOnTwistieClick !== "function" ? options.expandOnlyOnTwistieClick : (e) => options.expandOnlyOnTwistieClick(e.element), defaultFindVisibility: (e) => {
    if (e.hasChildren && e.stale) {
      return 1;
    } else if (typeof options.defaultFindVisibility === "number") {
      return options.defaultFindVisibility;
    } else if (typeof options.defaultFindVisibility === "undefined") {
      return 2;
    } else {
      return options.defaultFindVisibility(e.element);
    }
  } });
}
function dfs(node2, fn) {
  fn(node2);
  node2.children.forEach((child) => dfs(child, fn));
}
class AsyncDataTree {
  get onDidScroll() {
    return this.tree.onDidScroll;
  }
  get onDidChangeFocus() {
    return Event$1.map(this.tree.onDidChangeFocus, asTreeEvent);
  }
  get onDidChangeSelection() {
    return Event$1.map(this.tree.onDidChangeSelection, asTreeEvent);
  }
  get onMouseDblClick() {
    return Event$1.map(this.tree.onMouseDblClick, asTreeMouseEvent);
  }
  get onPointer() {
    return Event$1.map(this.tree.onPointer, asTreeMouseEvent);
  }
  get onDidFocus() {
    return this.tree.onDidFocus;
  }
  /**
   * To be used internally only!
   * @deprecated
   */
  get onDidChangeModel() {
    return this.tree.onDidChangeModel;
  }
  get onDidChangeCollapseState() {
    return this.tree.onDidChangeCollapseState;
  }
  get onDidChangeFindOpenState() {
    return this.tree.onDidChangeFindOpenState;
  }
  get onDidDispose() {
    return this.tree.onDidDispose;
  }
  constructor(user, container2, delegate, renderers, dataSource, options = {}) {
    this.user = user;
    this.dataSource = dataSource;
    this.nodes = /* @__PURE__ */ new Map();
    this.subTreeRefreshPromises = /* @__PURE__ */ new Map();
    this.refreshPromises = /* @__PURE__ */ new Map();
    this._onDidRender = new Emitter$1();
    this._onDidChangeNodeSlowState = new Emitter$1();
    this.nodeMapper = new WeakMapper((node2) => new AsyncDataTreeNodeWrapper(node2));
    this.disposables = new DisposableStore();
    this.identityProvider = options.identityProvider;
    this.autoExpandSingleChildren = typeof options.autoExpandSingleChildren === "undefined" ? false : options.autoExpandSingleChildren;
    this.sorter = options.sorter;
    this.collapseByDefault = options.collapseByDefault;
    this.tree = this.createTree(user, container2, delegate, renderers, options);
    this.onDidChangeFindMode = this.tree.onDidChangeFindMode;
    this.root = createAsyncDataTreeNode({
      element: void 0,
      parent: null,
      hasChildren: true
    });
    if (this.identityProvider) {
      this.root = Object.assign(Object.assign({}, this.root), { id: null });
    }
    this.nodes.set(null, this.root);
    this.tree.onDidChangeCollapseState(this._onDidChangeCollapseState, this, this.disposables);
  }
  createTree(user, container2, delegate, renderers, options) {
    const objectTreeDelegate = new ComposedTreeDelegate(delegate);
    const objectTreeRenderers = renderers.map((r) => new AsyncDataTreeRenderer(r, this.nodeMapper, this._onDidChangeNodeSlowState.event));
    const objectTreeOptions = asObjectTreeOptions(options) || {};
    return new ObjectTree(user, container2, objectTreeDelegate, objectTreeRenderers, objectTreeOptions);
  }
  updateOptions(options = {}) {
    this.tree.updateOptions(options);
  }
  // Widget
  getHTMLElement() {
    return this.tree.getHTMLElement();
  }
  get scrollTop() {
    return this.tree.scrollTop;
  }
  set scrollTop(scrollTop) {
    this.tree.scrollTop = scrollTop;
  }
  get scrollHeight() {
    return this.tree.scrollHeight;
  }
  get renderHeight() {
    return this.tree.renderHeight;
  }
  domFocus() {
    this.tree.domFocus();
  }
  layout(height, width) {
    this.tree.layout(height, width);
  }
  style(styles) {
    this.tree.style(styles);
  }
  // Model
  getInput() {
    return this.root.element;
  }
  setInput(input2, viewState) {
    return __awaiter$18(this, void 0, void 0, function* () {
      this.refreshPromises.forEach((promise) => promise.cancel());
      this.refreshPromises.clear();
      this.root.element = input2;
      const viewStateContext = viewState && { viewState, focus: [], selection: [] };
      yield this._updateChildren(input2, true, false, viewStateContext);
      if (viewStateContext) {
        this.tree.setFocus(viewStateContext.focus);
        this.tree.setSelection(viewStateContext.selection);
      }
      if (viewState && typeof viewState.scrollTop === "number") {
        this.scrollTop = viewState.scrollTop;
      }
    });
  }
  _updateChildren(element = this.root.element, recursive = true, rerender = false, viewStateContext, options) {
    return __awaiter$18(this, void 0, void 0, function* () {
      if (typeof this.root.element === "undefined") {
        throw new TreeError(this.user, "Tree input not set");
      }
      if (this.root.refreshPromise) {
        yield this.root.refreshPromise;
        yield Event$1.toPromise(this._onDidRender.event);
      }
      const node2 = this.getDataNode(element);
      yield this.refreshAndRenderNode(node2, recursive, viewStateContext, options);
      if (rerender) {
        try {
          this.tree.rerender(node2);
        } catch (_a2) {
        }
      }
    });
  }
  // View
  rerender(element) {
    if (element === void 0 || element === this.root.element) {
      this.tree.rerender();
      return;
    }
    const node2 = this.getDataNode(element);
    this.tree.rerender(node2);
  }
  // Tree
  getNode(element = this.root.element) {
    const dataNode = this.getDataNode(element);
    const node2 = this.tree.getNode(dataNode === this.root ? null : dataNode);
    return this.nodeMapper.map(node2);
  }
  collapse(element, recursive = false) {
    const node2 = this.getDataNode(element);
    return this.tree.collapse(node2 === this.root ? null : node2, recursive);
  }
  expand(element, recursive = false) {
    return __awaiter$18(this, void 0, void 0, function* () {
      if (typeof this.root.element === "undefined") {
        throw new TreeError(this.user, "Tree input not set");
      }
      if (this.root.refreshPromise) {
        yield this.root.refreshPromise;
        yield Event$1.toPromise(this._onDidRender.event);
      }
      const node2 = this.getDataNode(element);
      if (this.tree.hasElement(node2) && !this.tree.isCollapsible(node2)) {
        return false;
      }
      if (node2.refreshPromise) {
        yield this.root.refreshPromise;
        yield Event$1.toPromise(this._onDidRender.event);
      }
      if (node2 !== this.root && !node2.refreshPromise && !this.tree.isCollapsed(node2)) {
        return false;
      }
      const result2 = this.tree.expand(node2 === this.root ? null : node2, recursive);
      if (node2.refreshPromise) {
        yield this.root.refreshPromise;
        yield Event$1.toPromise(this._onDidRender.event);
      }
      return result2;
    });
  }
  setSelection(elements, browserEvent) {
    const nodes = elements.map((e) => this.getDataNode(e));
    this.tree.setSelection(nodes, browserEvent);
  }
  getSelection() {
    const nodes = this.tree.getSelection();
    return nodes.map((n2) => n2.element);
  }
  setFocus(elements, browserEvent) {
    const nodes = elements.map((e) => this.getDataNode(e));
    this.tree.setFocus(nodes, browserEvent);
  }
  getFocus() {
    const nodes = this.tree.getFocus();
    return nodes.map((n2) => n2.element);
  }
  reveal(element, relativeTop) {
    this.tree.reveal(this.getDataNode(element), relativeTop);
  }
  // Tree navigation
  getParentElement(element) {
    const node2 = this.tree.getParentElement(this.getDataNode(element));
    return node2 && node2.element;
  }
  getFirstElementChild(element = this.root.element) {
    const dataNode = this.getDataNode(element);
    const node2 = this.tree.getFirstElementChild(dataNode === this.root ? null : dataNode);
    return node2 && node2.element;
  }
  // Implementation
  getDataNode(element) {
    const node2 = this.nodes.get(element === this.root.element ? null : element);
    if (!node2) {
      throw new TreeError(this.user, `Data tree node not found: ${element}`);
    }
    return node2;
  }
  refreshAndRenderNode(node2, recursive, viewStateContext, options) {
    return __awaiter$18(this, void 0, void 0, function* () {
      yield this.refreshNode(node2, recursive, viewStateContext);
      this.render(node2, viewStateContext, options);
    });
  }
  refreshNode(node2, recursive, viewStateContext) {
    return __awaiter$18(this, void 0, void 0, function* () {
      let result2;
      this.subTreeRefreshPromises.forEach((refreshPromise, refreshNode) => {
        if (!result2 && intersects(refreshNode, node2)) {
          result2 = refreshPromise.then(() => this.refreshNode(node2, recursive, viewStateContext));
        }
      });
      if (result2) {
        return result2;
      }
      if (node2 !== this.root) {
        const treeNode = this.tree.getNode(node2);
        if (treeNode.collapsed) {
          node2.hasChildren = !!this.dataSource.hasChildren(node2.element);
          node2.stale = true;
          return;
        }
      }
      return this.doRefreshSubTree(node2, recursive, viewStateContext);
    });
  }
  doRefreshSubTree(node2, recursive, viewStateContext) {
    return __awaiter$18(this, void 0, void 0, function* () {
      let done;
      node2.refreshPromise = new Promise((c) => done = c);
      this.subTreeRefreshPromises.set(node2, node2.refreshPromise);
      node2.refreshPromise.finally(() => {
        node2.refreshPromise = void 0;
        this.subTreeRefreshPromises.delete(node2);
      });
      try {
        const childrenToRefresh = yield this.doRefreshNode(node2, recursive, viewStateContext);
        node2.stale = false;
        yield Promises.settled(childrenToRefresh.map((child) => this.doRefreshSubTree(child, recursive, viewStateContext)));
      } finally {
        done();
      }
    });
  }
  doRefreshNode(node2, recursive, viewStateContext) {
    return __awaiter$18(this, void 0, void 0, function* () {
      node2.hasChildren = !!this.dataSource.hasChildren(node2.element);
      let childrenPromise;
      if (!node2.hasChildren) {
        childrenPromise = Promise.resolve(Iterable.empty());
      } else {
        const children = this.doGetChildren(node2);
        if (isIterable(children)) {
          childrenPromise = Promise.resolve(children);
        } else {
          const slowTimeout = timeout(800);
          slowTimeout.then(() => {
            node2.slow = true;
            this._onDidChangeNodeSlowState.fire(node2);
          }, (_) => null);
          childrenPromise = children.finally(() => slowTimeout.cancel());
        }
      }
      try {
        const children = yield childrenPromise;
        return this.setChildren(node2, children, recursive, viewStateContext);
      } catch (err) {
        if (node2 !== this.root && this.tree.hasElement(node2)) {
          this.tree.collapse(node2);
        }
        if (isCancellationError(err)) {
          return [];
        }
        throw err;
      } finally {
        if (node2.slow) {
          node2.slow = false;
          this._onDidChangeNodeSlowState.fire(node2);
        }
      }
    });
  }
  doGetChildren(node2) {
    let result2 = this.refreshPromises.get(node2);
    if (result2) {
      return result2;
    }
    const children = this.dataSource.getChildren(node2.element);
    if (isIterable(children)) {
      return this.processChildren(children);
    } else {
      result2 = createCancelablePromise(() => __awaiter$18(this, void 0, void 0, function* () {
        return this.processChildren(yield children);
      }));
      this.refreshPromises.set(node2, result2);
      return result2.finally(() => {
        this.refreshPromises.delete(node2);
      });
    }
  }
  _onDidChangeCollapseState({ node: node2, deep }) {
    if (node2.element === null) {
      return;
    }
    if (!node2.collapsed && node2.element.stale) {
      if (deep) {
        this.collapse(node2.element.element);
      } else {
        this.refreshAndRenderNode(node2.element, false).catch(onUnexpectedError);
      }
    }
  }
  setChildren(node2, childrenElementsIterable, recursive, viewStateContext) {
    const childrenElements = [...childrenElementsIterable];
    if (node2.children.length === 0 && childrenElements.length === 0) {
      return [];
    }
    const nodesToForget = /* @__PURE__ */ new Map();
    const childrenTreeNodesById = /* @__PURE__ */ new Map();
    for (const child of node2.children) {
      nodesToForget.set(child.element, child);
      if (this.identityProvider) {
        const collapsed = this.tree.isCollapsed(child);
        childrenTreeNodesById.set(child.id, { node: child, collapsed });
      }
    }
    const childrenToRefresh = [];
    const children = childrenElements.map((element) => {
      const hasChildren = !!this.dataSource.hasChildren(element);
      if (!this.identityProvider) {
        const asyncDataTreeNode = createAsyncDataTreeNode({ element, parent: node2, hasChildren });
        if (hasChildren && this.collapseByDefault && !this.collapseByDefault(element)) {
          asyncDataTreeNode.collapsedByDefault = false;
          childrenToRefresh.push(asyncDataTreeNode);
        }
        return asyncDataTreeNode;
      }
      const id3 = this.identityProvider.getId(element).toString();
      const result2 = childrenTreeNodesById.get(id3);
      if (result2) {
        const asyncDataTreeNode = result2.node;
        nodesToForget.delete(asyncDataTreeNode.element);
        this.nodes.delete(asyncDataTreeNode.element);
        this.nodes.set(element, asyncDataTreeNode);
        asyncDataTreeNode.element = element;
        asyncDataTreeNode.hasChildren = hasChildren;
        if (recursive) {
          if (result2.collapsed) {
            asyncDataTreeNode.children.forEach((node3) => dfs(node3, (node4) => this.nodes.delete(node4.element)));
            asyncDataTreeNode.children.splice(0, asyncDataTreeNode.children.length);
            asyncDataTreeNode.stale = true;
          } else {
            childrenToRefresh.push(asyncDataTreeNode);
          }
        } else if (hasChildren && this.collapseByDefault && !this.collapseByDefault(element)) {
          asyncDataTreeNode.collapsedByDefault = false;
          childrenToRefresh.push(asyncDataTreeNode);
        }
        return asyncDataTreeNode;
      }
      const childAsyncDataTreeNode = createAsyncDataTreeNode({ element, parent: node2, id: id3, hasChildren });
      if (viewStateContext && viewStateContext.viewState.focus && viewStateContext.viewState.focus.indexOf(id3) > -1) {
        viewStateContext.focus.push(childAsyncDataTreeNode);
      }
      if (viewStateContext && viewStateContext.viewState.selection && viewStateContext.viewState.selection.indexOf(id3) > -1) {
        viewStateContext.selection.push(childAsyncDataTreeNode);
      }
      if (viewStateContext && viewStateContext.viewState.expanded && viewStateContext.viewState.expanded.indexOf(id3) > -1) {
        childrenToRefresh.push(childAsyncDataTreeNode);
      } else if (hasChildren && this.collapseByDefault && !this.collapseByDefault(element)) {
        childAsyncDataTreeNode.collapsedByDefault = false;
        childrenToRefresh.push(childAsyncDataTreeNode);
      }
      return childAsyncDataTreeNode;
    });
    for (const node3 of nodesToForget.values()) {
      dfs(node3, (node4) => this.nodes.delete(node4.element));
    }
    for (const child of children) {
      this.nodes.set(child.element, child);
    }
    node2.children.splice(0, node2.children.length, ...children);
    if (node2 !== this.root && this.autoExpandSingleChildren && children.length === 1 && childrenToRefresh.length === 0) {
      children[0].collapsedByDefault = false;
      childrenToRefresh.push(children[0]);
    }
    return childrenToRefresh;
  }
  render(node2, viewStateContext, options) {
    const children = node2.children.map((node3) => this.asTreeElement(node3, viewStateContext));
    const objectTreeOptions = options && Object.assign(Object.assign({}, options), { diffIdentityProvider: options.diffIdentityProvider && {
      getId(node3) {
        return options.diffIdentityProvider.getId(node3.element);
      }
    } });
    this.tree.setChildren(node2 === this.root ? null : node2, children, objectTreeOptions);
    if (node2 !== this.root) {
      this.tree.setCollapsible(node2, node2.hasChildren);
    }
    this._onDidRender.fire();
  }
  asTreeElement(node2, viewStateContext) {
    if (node2.stale) {
      return {
        element: node2,
        collapsible: node2.hasChildren,
        collapsed: true
      };
    }
    let collapsed;
    if (viewStateContext && viewStateContext.viewState.expanded && node2.id && viewStateContext.viewState.expanded.indexOf(node2.id) > -1) {
      collapsed = false;
    } else {
      collapsed = node2.collapsedByDefault;
    }
    node2.collapsedByDefault = void 0;
    return {
      element: node2,
      children: node2.hasChildren ? Iterable.map(node2.children, (child) => this.asTreeElement(child, viewStateContext)) : [],
      collapsible: node2.hasChildren,
      collapsed
    };
  }
  processChildren(children) {
    if (this.sorter) {
      children = [...children].sort(this.sorter.compare.bind(this.sorter));
    }
    return children;
  }
  dispose() {
    this.disposables.dispose();
  }
}
class CompressibleAsyncDataTreeNodeWrapper {
  get element() {
    return {
      elements: this.node.element.elements.map((e) => e.element),
      incompressible: this.node.element.incompressible
    };
  }
  get children() {
    return this.node.children.map((node2) => new CompressibleAsyncDataTreeNodeWrapper(node2));
  }
  get depth() {
    return this.node.depth;
  }
  get visibleChildrenCount() {
    return this.node.visibleChildrenCount;
  }
  get visibleChildIndex() {
    return this.node.visibleChildIndex;
  }
  get collapsible() {
    return this.node.collapsible;
  }
  get collapsed() {
    return this.node.collapsed;
  }
  get visible() {
    return this.node.visible;
  }
  get filterData() {
    return this.node.filterData;
  }
  constructor(node2) {
    this.node = node2;
  }
}
class CompressibleAsyncDataTreeRenderer {
  constructor(renderer2, nodeMapper, compressibleNodeMapperProvider, onDidChangeTwistieState) {
    this.renderer = renderer2;
    this.nodeMapper = nodeMapper;
    this.compressibleNodeMapperProvider = compressibleNodeMapperProvider;
    this.onDidChangeTwistieState = onDidChangeTwistieState;
    this.renderedNodes = /* @__PURE__ */ new Map();
    this.disposables = [];
    this.templateId = renderer2.templateId;
  }
  renderTemplate(container2) {
    const templateData = this.renderer.renderTemplate(container2);
    return { templateData };
  }
  renderElement(node2, index, templateData, height) {
    this.renderer.renderElement(this.nodeMapper.map(node2), index, templateData.templateData, height);
  }
  renderCompressedElements(node2, index, templateData, height) {
    this.renderer.renderCompressedElements(this.compressibleNodeMapperProvider().map(node2), index, templateData.templateData, height);
  }
  renderTwistie(element, twistieElement) {
    if (element.slow) {
      twistieElement.classList.add(...ThemeIcon.asClassNameArray(Codicon.treeItemLoading));
      return true;
    } else {
      twistieElement.classList.remove(...ThemeIcon.asClassNameArray(Codicon.treeItemLoading));
      return false;
    }
  }
  disposeElement(node2, index, templateData, height) {
    var _a2, _b2;
    (_b2 = (_a2 = this.renderer).disposeElement) === null || _b2 === void 0 ? void 0 : _b2.call(_a2, this.nodeMapper.map(node2), index, templateData.templateData, height);
  }
  disposeCompressedElements(node2, index, templateData, height) {
    var _a2, _b2;
    (_b2 = (_a2 = this.renderer).disposeCompressedElements) === null || _b2 === void 0 ? void 0 : _b2.call(_a2, this.compressibleNodeMapperProvider().map(node2), index, templateData.templateData, height);
  }
  disposeTemplate(templateData) {
    this.renderer.disposeTemplate(templateData.templateData);
  }
  dispose() {
    this.renderedNodes.clear();
    this.disposables = dispose(this.disposables);
  }
}
function asCompressibleObjectTreeOptions(options) {
  const objectTreeOptions = options && asObjectTreeOptions(options);
  return objectTreeOptions && Object.assign(Object.assign({}, objectTreeOptions), { keyboardNavigationLabelProvider: objectTreeOptions.keyboardNavigationLabelProvider && Object.assign(Object.assign({}, objectTreeOptions.keyboardNavigationLabelProvider), { getCompressedNodeKeyboardNavigationLabel(els) {
    return options.keyboardNavigationLabelProvider.getCompressedNodeKeyboardNavigationLabel(els.map((e) => e.element));
  } }) });
}
class CompressibleAsyncDataTree extends AsyncDataTree {
  constructor(user, container2, virtualDelegate, compressionDelegate, renderers, dataSource, options = {}) {
    super(user, container2, virtualDelegate, renderers, dataSource, options);
    this.compressionDelegate = compressionDelegate;
    this.compressibleNodeMapper = new WeakMapper((node2) => new CompressibleAsyncDataTreeNodeWrapper(node2));
    this.filter = options.filter;
  }
  createTree(user, container2, delegate, renderers, options) {
    const objectTreeDelegate = new ComposedTreeDelegate(delegate);
    const objectTreeRenderers = renderers.map((r) => new CompressibleAsyncDataTreeRenderer(r, this.nodeMapper, () => this.compressibleNodeMapper, this._onDidChangeNodeSlowState.event));
    const objectTreeOptions = asCompressibleObjectTreeOptions(options) || {};
    return new CompressibleObjectTree(user, container2, objectTreeDelegate, objectTreeRenderers, objectTreeOptions);
  }
  asTreeElement(node2, viewStateContext) {
    return Object.assign({ incompressible: this.compressionDelegate.isIncompressible(node2.element) }, super.asTreeElement(node2, viewStateContext));
  }
  updateOptions(options = {}) {
    this.tree.updateOptions(options);
  }
  render(node2, viewStateContext) {
    if (!this.identityProvider) {
      return super.render(node2, viewStateContext);
    }
    const getId2 = (element) => this.identityProvider.getId(element).toString();
    const getUncompressedIds = (nodes) => {
      const result2 = /* @__PURE__ */ new Set();
      for (const node3 of nodes) {
        const compressedNode = this.tree.getCompressedTreeNode(node3 === this.root ? null : node3);
        if (!compressedNode.element) {
          continue;
        }
        for (const node4 of compressedNode.element.elements) {
          result2.add(getId2(node4.element));
        }
      }
      return result2;
    };
    const oldSelection = getUncompressedIds(this.tree.getSelection());
    const oldFocus = getUncompressedIds(this.tree.getFocus());
    super.render(node2, viewStateContext);
    const selection = this.getSelection();
    let didChangeSelection = false;
    const focus = this.getFocus();
    let didChangeFocus = false;
    const visit = (node3) => {
      const compressedNode = node3.element;
      if (compressedNode) {
        for (let i = 0; i < compressedNode.elements.length; i++) {
          const id3 = getId2(compressedNode.elements[i].element);
          const element = compressedNode.elements[compressedNode.elements.length - 1].element;
          if (oldSelection.has(id3) && selection.indexOf(element) === -1) {
            selection.push(element);
            didChangeSelection = true;
          }
          if (oldFocus.has(id3) && focus.indexOf(element) === -1) {
            focus.push(element);
            didChangeFocus = true;
          }
        }
      }
      node3.children.forEach(visit);
    };
    visit(this.tree.getCompressedTreeNode(node2 === this.root ? null : node2));
    if (didChangeSelection) {
      this.setSelection(selection);
    }
    if (didChangeFocus) {
      this.setFocus(focus);
    }
  }
  // For compressed async data trees, `TreeVisibility.Recurse` doesn't currently work
  // and we have to filter everything beforehand
  // Related to #85193 and #85835
  processChildren(children) {
    if (this.filter) {
      children = Iterable.filter(children, (e) => {
        const result2 = this.filter.filter(
          e,
          1
          /* TreeVisibility.Visible */
        );
        const visibility = getVisibility(result2);
        if (visibility === 2) {
          throw new Error("Recursive tree visibility not supported in async data compressed trees");
        }
        return visibility === 1;
      });
    }
    return super.processChildren(children);
  }
}
function getVisibility(filterResult) {
  if (typeof filterResult === "boolean") {
    return filterResult ? 1 : 0;
  } else if (isFilterResult(filterResult)) {
    return getVisibleState(filterResult.visibility);
  } else {
    return getVisibleState(filterResult);
  }
}
class DataTree extends AbstractTree {
  constructor(user, container2, delegate, renderers, dataSource, options = {}) {
    super(user, container2, delegate, renderers, options);
    this.user = user;
    this.dataSource = dataSource;
    this.identityProvider = options.identityProvider;
  }
  createModel(user, view, options) {
    return new ObjectTreeModel(user, view, options);
  }
}
new RawContextKey("isMac", isMacintosh, localize("isMac", "Whether the operating system is macOS"));
new RawContextKey("isLinux", isLinux, localize("isLinux", "Whether the operating system is Linux"));
const IsWindowsContext = new RawContextKey("isWindows", isWindows, localize("isWindows", "Whether the operating system is Windows"));
const IsWebContext = new RawContextKey("isWeb", isWeb, localize("isWeb", "Whether the platform is a web browser"));
new RawContextKey("isMacNative", isMacintosh && !isWeb, localize("isMacNative", "Whether the operating system is macOS on a non-browser platform"));
new RawContextKey("isIOS", isIOS, localize("isIOS", "Whether the operating system is iOS"));
new RawContextKey("isMobile", isMobile, localize("isMobile", "Whether the platform is a mobile web browser"));
new RawContextKey("isDevelopment", false, true);
new RawContextKey("productQualityType", "", localize("productQualityType", "Quality type of VS Code"));
const InputFocusedContextKey = "inputFocus";
new RawContextKey(InputFocusedContextKey, false, localize("inputFocus", "Whether keyboard focus is inside an input box"));
var __decorate$1D = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1B = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
const IListService = createDecorator("listService");
class ListService {
  get lastFocusedList() {
    return this._lastFocusedWidget;
  }
  constructor() {
    this.disposables = new DisposableStore();
    this.lists = [];
    this._lastFocusedWidget = void 0;
    this._hasCreatedStyleController = false;
  }
  setLastFocusedList(widget) {
    var _a2, _b2;
    if (widget === this._lastFocusedWidget) {
      return;
    }
    (_a2 = this._lastFocusedWidget) === null || _a2 === void 0 ? void 0 : _a2.getHTMLElement().classList.remove("last-focused");
    this._lastFocusedWidget = widget;
    (_b2 = this._lastFocusedWidget) === null || _b2 === void 0 ? void 0 : _b2.getHTMLElement().classList.add("last-focused");
  }
  register(widget, extraContextKeys) {
    if (!this._hasCreatedStyleController) {
      this._hasCreatedStyleController = true;
      const styleController = new DefaultStyleController(createStyleSheet(), "");
      styleController.style(defaultListStyles);
    }
    if (this.lists.some((l) => l.widget === widget)) {
      throw new Error("Cannot register the same widget multiple times");
    }
    const registeredList = { widget, extraContextKeys };
    this.lists.push(registeredList);
    if (widget.getHTMLElement() === document.activeElement) {
      this.setLastFocusedList(widget);
    }
    return combinedDisposable(widget.onDidFocus(() => this.setLastFocusedList(widget)), toDisposable(() => this.lists.splice(this.lists.indexOf(registeredList), 1)), widget.onDidDispose(() => {
      this.lists = this.lists.filter((l) => l !== registeredList);
      if (this._lastFocusedWidget === widget) {
        this.setLastFocusedList(void 0);
      }
    }));
  }
  dispose() {
    this.disposables.dispose();
  }
}
const RawWorkbenchListScrollAtBoundaryContextKey = new RawContextKey("listScrollAtBoundary", "none");
ContextKeyExpr.or(RawWorkbenchListScrollAtBoundaryContextKey.isEqualTo("top"), RawWorkbenchListScrollAtBoundaryContextKey.isEqualTo("both"));
ContextKeyExpr.or(RawWorkbenchListScrollAtBoundaryContextKey.isEqualTo("bottom"), RawWorkbenchListScrollAtBoundaryContextKey.isEqualTo("both"));
const RawWorkbenchListFocusContextKey = new RawContextKey("listFocus", true);
const WorkbenchListSupportsMultiSelectContextKey = new RawContextKey("listSupportsMultiselect", true);
const WorkbenchListFocusContextKey = ContextKeyExpr.and(RawWorkbenchListFocusContextKey, ContextKeyExpr.not(InputFocusedContextKey));
const WorkbenchListHasSelectionOrFocus = new RawContextKey("listHasSelectionOrFocus", false);
const WorkbenchListDoubleSelection = new RawContextKey("listDoubleSelection", false);
const WorkbenchListMultiSelection = new RawContextKey("listMultiSelection", false);
const WorkbenchListSelectionNavigation = new RawContextKey("listSelectionNavigation", false);
const WorkbenchListSupportsFind = new RawContextKey("listSupportsFind", true);
const WorkbenchTreeElementCanCollapse = new RawContextKey("treeElementCanCollapse", false);
const WorkbenchTreeElementHasParent = new RawContextKey("treeElementHasParent", false);
const WorkbenchTreeElementCanExpand = new RawContextKey("treeElementCanExpand", false);
const WorkbenchTreeElementHasChild = new RawContextKey("treeElementHasChild", false);
const WorkbenchTreeFindOpen = new RawContextKey("treeFindOpen", false);
const WorkbenchListTypeNavigationModeKey = "listTypeNavigationMode";
const WorkbenchListAutomaticKeyboardNavigationLegacyKey = "listAutomaticKeyboardNavigation";
function createScopedContextKeyService(contextKeyService, widget) {
  const result2 = contextKeyService.createScoped(widget.getHTMLElement());
  RawWorkbenchListFocusContextKey.bindTo(result2);
  return result2;
}
function createScrollObserver(contextKeyService, widget) {
  const listScrollAt = RawWorkbenchListScrollAtBoundaryContextKey.bindTo(contextKeyService);
  const update = () => {
    const atTop = widget.scrollTop === 0;
    const atBottom = widget.scrollHeight - widget.renderHeight - widget.scrollTop < 1;
    if (atTop && atBottom) {
      listScrollAt.set("both");
    } else if (atTop) {
      listScrollAt.set("top");
    } else if (atBottom) {
      listScrollAt.set("bottom");
    } else {
      listScrollAt.set("none");
    }
  };
  update();
  return widget.onDidScroll(update);
}
const multiSelectModifierSettingKey = "workbench.list.multiSelectModifier";
const openModeSettingKey = "workbench.list.openMode";
const horizontalScrollingKey = "workbench.list.horizontalScrolling";
const defaultFindModeSettingKey = "workbench.list.defaultFindMode";
const typeNavigationModeSettingKey = "workbench.list.typeNavigationMode";
const keyboardNavigationSettingKey = "workbench.list.keyboardNavigation";
const scrollByPageKey = "workbench.list.scrollByPage";
const defaultFindMatchTypeSettingKey = "workbench.list.defaultFindMatchType";
const treeIndentKey = "workbench.tree.indent";
const treeRenderIndentGuidesKey = "workbench.tree.renderIndentGuides";
const listSmoothScrolling = "workbench.list.smoothScrolling";
const mouseWheelScrollSensitivityKey = "workbench.list.mouseWheelScrollSensitivity";
const fastScrollSensitivityKey = "workbench.list.fastScrollSensitivity";
const treeExpandMode = "workbench.tree.expandMode";
function useAltAsMultipleSelectionModifier(configurationService) {
  return configurationService.getValue(multiSelectModifierSettingKey) === "alt";
}
class MultipleSelectionController extends Disposable {
  constructor(configurationService) {
    super();
    this.configurationService = configurationService;
    this.useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
    this.registerListeners();
  }
  registerListeners() {
    this._register(this.configurationService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
        this.useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(this.configurationService);
      }
    }));
  }
  isSelectionSingleChangeEvent(event) {
    if (this.useAltAsMultipleSelectionModifier) {
      return event.browserEvent.altKey;
    }
    return isSelectionSingleChangeEvent(event);
  }
  isSelectionRangeChangeEvent(event) {
    return isSelectionRangeChangeEvent(event);
  }
}
function toWorkbenchListOptions(accessor, options) {
  var _a2;
  const configurationService = accessor.get(IConfigurationService);
  const keybindingService = accessor.get(IKeybindingService);
  const disposables = new DisposableStore();
  const result2 = Object.assign(Object.assign({}, options), { keyboardNavigationDelegate: { mightProducePrintableCharacter(e) {
    return keybindingService.mightProducePrintableCharacter(e);
  } }, smoothScrolling: Boolean(configurationService.getValue(listSmoothScrolling)), mouseWheelScrollSensitivity: configurationService.getValue(mouseWheelScrollSensitivityKey), fastScrollSensitivity: configurationService.getValue(fastScrollSensitivityKey), multipleSelectionController: (_a2 = options.multipleSelectionController) !== null && _a2 !== void 0 ? _a2 : disposables.add(new MultipleSelectionController(configurationService)), keyboardNavigationEventFilter: createKeyboardNavigationEventFilter(keybindingService), scrollByPage: Boolean(configurationService.getValue(scrollByPageKey)) });
  return [result2, disposables];
}
let WorkbenchList = class WorkbenchList2 extends List {
  constructor(user, container2, delegate, renderers, options, contextKeyService, listService, configurationService, instantiationService) {
    const horizontalScrolling = typeof options.horizontalScrolling !== "undefined" ? options.horizontalScrolling : Boolean(configurationService.getValue(horizontalScrollingKey));
    const [workbenchListOptions, workbenchListOptionsDisposable] = instantiationService.invokeFunction(toWorkbenchListOptions, options);
    super(user, container2, delegate, renderers, Object.assign(Object.assign({ keyboardSupport: false }, workbenchListOptions), { horizontalScrolling }));
    this.disposables.add(workbenchListOptionsDisposable);
    this.contextKeyService = createScopedContextKeyService(contextKeyService, this);
    this.disposables.add(createScrollObserver(this.contextKeyService, this));
    this.listSupportsMultiSelect = WorkbenchListSupportsMultiSelectContextKey.bindTo(this.contextKeyService);
    this.listSupportsMultiSelect.set(options.multipleSelectionSupport !== false);
    const listSelectionNavigation = WorkbenchListSelectionNavigation.bindTo(this.contextKeyService);
    listSelectionNavigation.set(Boolean(options.selectionNavigation));
    this.listHasSelectionOrFocus = WorkbenchListHasSelectionOrFocus.bindTo(this.contextKeyService);
    this.listDoubleSelection = WorkbenchListDoubleSelection.bindTo(this.contextKeyService);
    this.listMultiSelection = WorkbenchListMultiSelection.bindTo(this.contextKeyService);
    this.horizontalScrolling = options.horizontalScrolling;
    this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
    this.disposables.add(this.contextKeyService);
    this.disposables.add(listService.register(this));
    this.updateStyles(options.overrideStyles);
    this.disposables.add(this.onDidChangeSelection(() => {
      const selection = this.getSelection();
      const focus = this.getFocus();
      this.contextKeyService.bufferChangeEvents(() => {
        this.listHasSelectionOrFocus.set(selection.length > 0 || focus.length > 0);
        this.listMultiSelection.set(selection.length > 1);
        this.listDoubleSelection.set(selection.length === 2);
      });
    }));
    this.disposables.add(this.onDidChangeFocus(() => {
      const selection = this.getSelection();
      const focus = this.getFocus();
      this.listHasSelectionOrFocus.set(selection.length > 0 || focus.length > 0);
    }));
    this.disposables.add(configurationService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
        this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
      }
      let options2 = {};
      if (e.affectsConfiguration(horizontalScrollingKey) && this.horizontalScrolling === void 0) {
        const horizontalScrolling2 = Boolean(configurationService.getValue(horizontalScrollingKey));
        options2 = Object.assign(Object.assign({}, options2), { horizontalScrolling: horizontalScrolling2 });
      }
      if (e.affectsConfiguration(scrollByPageKey)) {
        const scrollByPage = Boolean(configurationService.getValue(scrollByPageKey));
        options2 = Object.assign(Object.assign({}, options2), { scrollByPage });
      }
      if (e.affectsConfiguration(listSmoothScrolling)) {
        const smoothScrolling = Boolean(configurationService.getValue(listSmoothScrolling));
        options2 = Object.assign(Object.assign({}, options2), { smoothScrolling });
      }
      if (e.affectsConfiguration(mouseWheelScrollSensitivityKey)) {
        const mouseWheelScrollSensitivity = configurationService.getValue(mouseWheelScrollSensitivityKey);
        options2 = Object.assign(Object.assign({}, options2), { mouseWheelScrollSensitivity });
      }
      if (e.affectsConfiguration(fastScrollSensitivityKey)) {
        const fastScrollSensitivity = configurationService.getValue(fastScrollSensitivityKey);
        options2 = Object.assign(Object.assign({}, options2), { fastScrollSensitivity });
      }
      if (Object.keys(options2).length > 0) {
        this.updateOptions(options2);
      }
    }));
    this.navigator = new ListResourceNavigator(this, Object.assign({ configurationService }, options));
    this.disposables.add(this.navigator);
  }
  updateOptions(options) {
    super.updateOptions(options);
    if (options.overrideStyles !== void 0) {
      this.updateStyles(options.overrideStyles);
    }
    if (options.multipleSelectionSupport !== void 0) {
      this.listSupportsMultiSelect.set(!!options.multipleSelectionSupport);
    }
  }
  updateStyles(styles) {
    this.style(styles ? getListStyles(styles) : defaultListStyles);
  }
};
WorkbenchList = __decorate$1D([
  __param$1B(5, IContextKeyService),
  __param$1B(6, IListService),
  __param$1B(7, IConfigurationService),
  __param$1B(8, IInstantiationService)
], WorkbenchList);
let WorkbenchPagedList = class WorkbenchPagedList2 extends PagedList {
  constructor(user, container2, delegate, renderers, options, contextKeyService, listService, configurationService, instantiationService) {
    const horizontalScrolling = typeof options.horizontalScrolling !== "undefined" ? options.horizontalScrolling : Boolean(configurationService.getValue(horizontalScrollingKey));
    const [workbenchListOptions, workbenchListOptionsDisposable] = instantiationService.invokeFunction(toWorkbenchListOptions, options);
    super(user, container2, delegate, renderers, Object.assign(Object.assign({ keyboardSupport: false }, workbenchListOptions), { horizontalScrolling }));
    this.disposables = new DisposableStore();
    this.disposables.add(workbenchListOptionsDisposable);
    this.contextKeyService = createScopedContextKeyService(contextKeyService, this);
    this.disposables.add(createScrollObserver(this.contextKeyService, this.widget));
    this.horizontalScrolling = options.horizontalScrolling;
    this.listSupportsMultiSelect = WorkbenchListSupportsMultiSelectContextKey.bindTo(this.contextKeyService);
    this.listSupportsMultiSelect.set(options.multipleSelectionSupport !== false);
    const listSelectionNavigation = WorkbenchListSelectionNavigation.bindTo(this.contextKeyService);
    listSelectionNavigation.set(Boolean(options.selectionNavigation));
    this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
    this.disposables.add(this.contextKeyService);
    this.disposables.add(listService.register(this));
    this.updateStyles(options.overrideStyles);
    this.disposables.add(configurationService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
        this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
      }
      let options2 = {};
      if (e.affectsConfiguration(horizontalScrollingKey) && this.horizontalScrolling === void 0) {
        const horizontalScrolling2 = Boolean(configurationService.getValue(horizontalScrollingKey));
        options2 = Object.assign(Object.assign({}, options2), { horizontalScrolling: horizontalScrolling2 });
      }
      if (e.affectsConfiguration(scrollByPageKey)) {
        const scrollByPage = Boolean(configurationService.getValue(scrollByPageKey));
        options2 = Object.assign(Object.assign({}, options2), { scrollByPage });
      }
      if (e.affectsConfiguration(listSmoothScrolling)) {
        const smoothScrolling = Boolean(configurationService.getValue(listSmoothScrolling));
        options2 = Object.assign(Object.assign({}, options2), { smoothScrolling });
      }
      if (e.affectsConfiguration(mouseWheelScrollSensitivityKey)) {
        const mouseWheelScrollSensitivity = configurationService.getValue(mouseWheelScrollSensitivityKey);
        options2 = Object.assign(Object.assign({}, options2), { mouseWheelScrollSensitivity });
      }
      if (e.affectsConfiguration(fastScrollSensitivityKey)) {
        const fastScrollSensitivity = configurationService.getValue(fastScrollSensitivityKey);
        options2 = Object.assign(Object.assign({}, options2), { fastScrollSensitivity });
      }
      if (Object.keys(options2).length > 0) {
        this.updateOptions(options2);
      }
    }));
    this.navigator = new ListResourceNavigator(this, Object.assign({ configurationService }, options));
    this.disposables.add(this.navigator);
  }
  updateOptions(options) {
    super.updateOptions(options);
    if (options.overrideStyles !== void 0) {
      this.updateStyles(options.overrideStyles);
    }
    if (options.multipleSelectionSupport !== void 0) {
      this.listSupportsMultiSelect.set(!!options.multipleSelectionSupport);
    }
  }
  updateStyles(styles) {
    this.style(styles ? getListStyles(styles) : defaultListStyles);
  }
  dispose() {
    this.disposables.dispose();
    super.dispose();
  }
};
WorkbenchPagedList = __decorate$1D([
  __param$1B(5, IContextKeyService),
  __param$1B(6, IListService),
  __param$1B(7, IConfigurationService),
  __param$1B(8, IInstantiationService)
], WorkbenchPagedList);
let WorkbenchTable = class WorkbenchTable2 extends Table {
  constructor(user, container2, delegate, columns, renderers, options, contextKeyService, listService, configurationService, instantiationService) {
    const horizontalScrolling = typeof options.horizontalScrolling !== "undefined" ? options.horizontalScrolling : Boolean(configurationService.getValue(horizontalScrollingKey));
    const [workbenchListOptions, workbenchListOptionsDisposable] = instantiationService.invokeFunction(toWorkbenchListOptions, options);
    super(user, container2, delegate, columns, renderers, Object.assign(Object.assign({ keyboardSupport: false }, workbenchListOptions), { horizontalScrolling }));
    this.disposables.add(workbenchListOptionsDisposable);
    this.contextKeyService = createScopedContextKeyService(contextKeyService, this);
    this.disposables.add(createScrollObserver(this.contextKeyService, this));
    this.listSupportsMultiSelect = WorkbenchListSupportsMultiSelectContextKey.bindTo(this.contextKeyService);
    this.listSupportsMultiSelect.set(options.multipleSelectionSupport !== false);
    const listSelectionNavigation = WorkbenchListSelectionNavigation.bindTo(this.contextKeyService);
    listSelectionNavigation.set(Boolean(options.selectionNavigation));
    this.listHasSelectionOrFocus = WorkbenchListHasSelectionOrFocus.bindTo(this.contextKeyService);
    this.listDoubleSelection = WorkbenchListDoubleSelection.bindTo(this.contextKeyService);
    this.listMultiSelection = WorkbenchListMultiSelection.bindTo(this.contextKeyService);
    this.horizontalScrolling = options.horizontalScrolling;
    this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
    this.disposables.add(this.contextKeyService);
    this.disposables.add(listService.register(this));
    this.updateStyles(options.overrideStyles);
    this.disposables.add(this.onDidChangeSelection(() => {
      const selection = this.getSelection();
      const focus = this.getFocus();
      this.contextKeyService.bufferChangeEvents(() => {
        this.listHasSelectionOrFocus.set(selection.length > 0 || focus.length > 0);
        this.listMultiSelection.set(selection.length > 1);
        this.listDoubleSelection.set(selection.length === 2);
      });
    }));
    this.disposables.add(this.onDidChangeFocus(() => {
      const selection = this.getSelection();
      const focus = this.getFocus();
      this.listHasSelectionOrFocus.set(selection.length > 0 || focus.length > 0);
    }));
    this.disposables.add(configurationService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
        this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
      }
      let options2 = {};
      if (e.affectsConfiguration(horizontalScrollingKey) && this.horizontalScrolling === void 0) {
        const horizontalScrolling2 = Boolean(configurationService.getValue(horizontalScrollingKey));
        options2 = Object.assign(Object.assign({}, options2), { horizontalScrolling: horizontalScrolling2 });
      }
      if (e.affectsConfiguration(scrollByPageKey)) {
        const scrollByPage = Boolean(configurationService.getValue(scrollByPageKey));
        options2 = Object.assign(Object.assign({}, options2), { scrollByPage });
      }
      if (e.affectsConfiguration(listSmoothScrolling)) {
        const smoothScrolling = Boolean(configurationService.getValue(listSmoothScrolling));
        options2 = Object.assign(Object.assign({}, options2), { smoothScrolling });
      }
      if (e.affectsConfiguration(mouseWheelScrollSensitivityKey)) {
        const mouseWheelScrollSensitivity = configurationService.getValue(mouseWheelScrollSensitivityKey);
        options2 = Object.assign(Object.assign({}, options2), { mouseWheelScrollSensitivity });
      }
      if (e.affectsConfiguration(fastScrollSensitivityKey)) {
        const fastScrollSensitivity = configurationService.getValue(fastScrollSensitivityKey);
        options2 = Object.assign(Object.assign({}, options2), { fastScrollSensitivity });
      }
      if (Object.keys(options2).length > 0) {
        this.updateOptions(options2);
      }
    }));
    this.navigator = new TableResourceNavigator(this, Object.assign({ configurationService }, options));
    this.disposables.add(this.navigator);
  }
  updateOptions(options) {
    super.updateOptions(options);
    if (options.overrideStyles !== void 0) {
      this.updateStyles(options.overrideStyles);
    }
    if (options.multipleSelectionSupport !== void 0) {
      this.listSupportsMultiSelect.set(!!options.multipleSelectionSupport);
    }
  }
  updateStyles(styles) {
    this.style(styles ? getListStyles(styles) : defaultListStyles);
  }
  dispose() {
    this.disposables.dispose();
    super.dispose();
  }
};
WorkbenchTable = __decorate$1D([
  __param$1B(6, IContextKeyService),
  __param$1B(7, IListService),
  __param$1B(8, IConfigurationService),
  __param$1B(9, IInstantiationService)
], WorkbenchTable);
class ResourceNavigator extends Disposable {
  constructor(widget, options) {
    var _a2;
    super();
    this.widget = widget;
    this._onDidOpen = this._register(new Emitter$1());
    this.onDidOpen = this._onDidOpen.event;
    this._register(Event$1.filter(this.widget.onDidChangeSelection, (e) => e.browserEvent instanceof KeyboardEvent)((e) => this.onSelectionFromKeyboard(e)));
    this._register(this.widget.onPointer((e) => this.onPointer(e.element, e.browserEvent)));
    this._register(this.widget.onMouseDblClick((e) => this.onMouseDblClick(e.element, e.browserEvent)));
    if (typeof (options === null || options === void 0 ? void 0 : options.openOnSingleClick) !== "boolean" && (options === null || options === void 0 ? void 0 : options.configurationService)) {
      this.openOnSingleClick = (options === null || options === void 0 ? void 0 : options.configurationService.getValue(openModeSettingKey)) !== "doubleClick";
      this._register(options === null || options === void 0 ? void 0 : options.configurationService.onDidChangeConfiguration((e) => {
        if (e.affectsConfiguration(openModeSettingKey)) {
          this.openOnSingleClick = (options === null || options === void 0 ? void 0 : options.configurationService.getValue(openModeSettingKey)) !== "doubleClick";
        }
      }));
    } else {
      this.openOnSingleClick = (_a2 = options === null || options === void 0 ? void 0 : options.openOnSingleClick) !== null && _a2 !== void 0 ? _a2 : true;
    }
  }
  onSelectionFromKeyboard(event) {
    if (event.elements.length !== 1) {
      return;
    }
    const selectionKeyboardEvent = event.browserEvent;
    const preserveFocus = typeof selectionKeyboardEvent.preserveFocus === "boolean" ? selectionKeyboardEvent.preserveFocus : true;
    const pinned = typeof selectionKeyboardEvent.pinned === "boolean" ? selectionKeyboardEvent.pinned : !preserveFocus;
    const sideBySide = false;
    this._open(this.getSelectedElement(), preserveFocus, pinned, sideBySide, event.browserEvent);
  }
  onPointer(element, browserEvent) {
    if (!this.openOnSingleClick) {
      return;
    }
    const isDoubleClick = browserEvent.detail === 2;
    if (isDoubleClick) {
      return;
    }
    const isMiddleClick = browserEvent.button === 1;
    const preserveFocus = true;
    const pinned = isMiddleClick;
    const sideBySide = browserEvent.ctrlKey || browserEvent.metaKey || browserEvent.altKey;
    this._open(element, preserveFocus, pinned, sideBySide, browserEvent);
  }
  onMouseDblClick(element, browserEvent) {
    if (!browserEvent) {
      return;
    }
    const target = browserEvent.target;
    const onTwistie = target.classList.contains("monaco-tl-twistie") || target.classList.contains("monaco-icon-label") && target.classList.contains("folder-icon") && browserEvent.offsetX < 16;
    if (onTwistie) {
      return;
    }
    const preserveFocus = false;
    const pinned = true;
    const sideBySide = browserEvent.ctrlKey || browserEvent.metaKey || browserEvent.altKey;
    this._open(element, preserveFocus, pinned, sideBySide, browserEvent);
  }
  _open(element, preserveFocus, pinned, sideBySide, browserEvent) {
    if (!element) {
      return;
    }
    this._onDidOpen.fire({
      editorOptions: {
        preserveFocus,
        pinned,
        revealIfVisible: true
      },
      sideBySide,
      element,
      browserEvent
    });
  }
}
class ListResourceNavigator extends ResourceNavigator {
  constructor(widget, options) {
    super(widget, options);
    this.widget = widget;
  }
  getSelectedElement() {
    return this.widget.getSelectedElements()[0];
  }
}
class TableResourceNavigator extends ResourceNavigator {
  constructor(widget, options) {
    super(widget, options);
  }
  getSelectedElement() {
    return this.widget.getSelectedElements()[0];
  }
}
class TreeResourceNavigator extends ResourceNavigator {
  constructor(widget, options) {
    super(widget, options);
  }
  getSelectedElement() {
    var _a2;
    return (_a2 = this.widget.getSelection()[0]) !== null && _a2 !== void 0 ? _a2 : void 0;
  }
}
function createKeyboardNavigationEventFilter(keybindingService) {
  let inMultiChord = false;
  return (event) => {
    if (event.toKeyCodeChord().isModifierKey()) {
      return false;
    }
    if (inMultiChord) {
      inMultiChord = false;
      return false;
    }
    const result2 = keybindingService.softDispatch(event, event.target);
    if (result2.kind === 1) {
      inMultiChord = true;
      return false;
    }
    inMultiChord = false;
    return result2.kind === 0;
  };
}
let WorkbenchObjectTree = class WorkbenchObjectTree2 extends ObjectTree {
  constructor(user, container2, delegate, renderers, options, instantiationService, contextKeyService, listService, configurationService) {
    const { options: treeOptions, getTypeNavigationMode, disposable } = instantiationService.invokeFunction(workbenchTreeDataPreamble, options);
    super(user, container2, delegate, renderers, treeOptions);
    this.disposables.add(disposable);
    this.internals = new WorkbenchTreeInternals(this, options, getTypeNavigationMode, options.overrideStyles, contextKeyService, listService, configurationService);
    this.disposables.add(this.internals);
  }
  updateOptions(options) {
    super.updateOptions(options);
    this.internals.updateOptions(options);
  }
};
WorkbenchObjectTree = __decorate$1D([
  __param$1B(5, IInstantiationService),
  __param$1B(6, IContextKeyService),
  __param$1B(7, IListService),
  __param$1B(8, IConfigurationService)
], WorkbenchObjectTree);
let WorkbenchCompressibleObjectTree = class WorkbenchCompressibleObjectTree2 extends CompressibleObjectTree {
  constructor(user, container2, delegate, renderers, options, instantiationService, contextKeyService, listService, configurationService) {
    const { options: treeOptions, getTypeNavigationMode, disposable } = instantiationService.invokeFunction(workbenchTreeDataPreamble, options);
    super(user, container2, delegate, renderers, treeOptions);
    this.disposables.add(disposable);
    this.internals = new WorkbenchTreeInternals(this, options, getTypeNavigationMode, options.overrideStyles, contextKeyService, listService, configurationService);
    this.disposables.add(this.internals);
  }
  updateOptions(options = {}) {
    super.updateOptions(options);
    if (options.overrideStyles) {
      this.internals.updateStyleOverrides(options.overrideStyles);
    }
    this.internals.updateOptions(options);
  }
};
WorkbenchCompressibleObjectTree = __decorate$1D([
  __param$1B(5, IInstantiationService),
  __param$1B(6, IContextKeyService),
  __param$1B(7, IListService),
  __param$1B(8, IConfigurationService)
], WorkbenchCompressibleObjectTree);
let WorkbenchDataTree = class WorkbenchDataTree2 extends DataTree {
  constructor(user, container2, delegate, renderers, dataSource, options, instantiationService, contextKeyService, listService, configurationService) {
    const { options: treeOptions, getTypeNavigationMode, disposable } = instantiationService.invokeFunction(workbenchTreeDataPreamble, options);
    super(user, container2, delegate, renderers, dataSource, treeOptions);
    this.disposables.add(disposable);
    this.internals = new WorkbenchTreeInternals(this, options, getTypeNavigationMode, options.overrideStyles, contextKeyService, listService, configurationService);
    this.disposables.add(this.internals);
  }
  updateOptions(options = {}) {
    super.updateOptions(options);
    if (options.overrideStyles !== void 0) {
      this.internals.updateStyleOverrides(options.overrideStyles);
    }
    this.internals.updateOptions(options);
  }
};
WorkbenchDataTree = __decorate$1D([
  __param$1B(6, IInstantiationService),
  __param$1B(7, IContextKeyService),
  __param$1B(8, IListService),
  __param$1B(9, IConfigurationService)
], WorkbenchDataTree);
let WorkbenchAsyncDataTree = class WorkbenchAsyncDataTree2 extends AsyncDataTree {
  get onDidOpen() {
    return this.internals.onDidOpen;
  }
  constructor(user, container2, delegate, renderers, dataSource, options, instantiationService, contextKeyService, listService, configurationService) {
    const { options: treeOptions, getTypeNavigationMode, disposable } = instantiationService.invokeFunction(workbenchTreeDataPreamble, options);
    super(user, container2, delegate, renderers, dataSource, treeOptions);
    this.disposables.add(disposable);
    this.internals = new WorkbenchTreeInternals(this, options, getTypeNavigationMode, options.overrideStyles, contextKeyService, listService, configurationService);
    this.disposables.add(this.internals);
  }
  updateOptions(options = {}) {
    super.updateOptions(options);
    if (options.overrideStyles) {
      this.internals.updateStyleOverrides(options.overrideStyles);
    }
    this.internals.updateOptions(options);
  }
};
WorkbenchAsyncDataTree = __decorate$1D([
  __param$1B(6, IInstantiationService),
  __param$1B(7, IContextKeyService),
  __param$1B(8, IListService),
  __param$1B(9, IConfigurationService)
], WorkbenchAsyncDataTree);
let WorkbenchCompressibleAsyncDataTree = class WorkbenchCompressibleAsyncDataTree2 extends CompressibleAsyncDataTree {
  constructor(user, container2, virtualDelegate, compressionDelegate, renderers, dataSource, options, instantiationService, contextKeyService, listService, configurationService) {
    const { options: treeOptions, getTypeNavigationMode, disposable } = instantiationService.invokeFunction(workbenchTreeDataPreamble, options);
    super(user, container2, virtualDelegate, compressionDelegate, renderers, dataSource, treeOptions);
    this.disposables.add(disposable);
    this.internals = new WorkbenchTreeInternals(this, options, getTypeNavigationMode, options.overrideStyles, contextKeyService, listService, configurationService);
    this.disposables.add(this.internals);
  }
  updateOptions(options) {
    super.updateOptions(options);
    this.internals.updateOptions(options);
  }
};
WorkbenchCompressibleAsyncDataTree = __decorate$1D([
  __param$1B(7, IInstantiationService),
  __param$1B(8, IContextKeyService),
  __param$1B(9, IListService),
  __param$1B(10, IConfigurationService)
], WorkbenchCompressibleAsyncDataTree);
function getDefaultTreeFindMode(configurationService) {
  const value = configurationService.getValue(defaultFindModeSettingKey);
  if (value === "highlight") {
    return TreeFindMode.Highlight;
  } else if (value === "filter") {
    return TreeFindMode.Filter;
  }
  const deprecatedValue = configurationService.getValue(keyboardNavigationSettingKey);
  if (deprecatedValue === "simple" || deprecatedValue === "highlight") {
    return TreeFindMode.Highlight;
  } else if (deprecatedValue === "filter") {
    return TreeFindMode.Filter;
  }
  return void 0;
}
function getDefaultTreeFindMatchType(configurationService) {
  const value = configurationService.getValue(defaultFindMatchTypeSettingKey);
  if (value === "fuzzy") {
    return TreeFindMatchType.Fuzzy;
  } else if (value === "contiguous") {
    return TreeFindMatchType.Contiguous;
  }
  return void 0;
}
function workbenchTreeDataPreamble(accessor, options) {
  var _a2;
  const configurationService = accessor.get(IConfigurationService);
  const contextViewService = accessor.get(IContextViewService);
  const contextKeyService = accessor.get(IContextKeyService);
  const instantiationService = accessor.get(IInstantiationService);
  const getTypeNavigationMode = () => {
    const modeString = contextKeyService.getContextKeyValue(WorkbenchListTypeNavigationModeKey);
    if (modeString === "automatic") {
      return TypeNavigationMode.Automatic;
    } else if (modeString === "trigger") {
      return TypeNavigationMode.Trigger;
    }
    const modeBoolean = contextKeyService.getContextKeyValue(WorkbenchListAutomaticKeyboardNavigationLegacyKey);
    if (modeBoolean === false) {
      return TypeNavigationMode.Trigger;
    }
    const configString = configurationService.getValue(typeNavigationModeSettingKey);
    if (configString === "automatic") {
      return TypeNavigationMode.Automatic;
    } else if (configString === "trigger") {
      return TypeNavigationMode.Trigger;
    }
    return void 0;
  };
  const horizontalScrolling = options.horizontalScrolling !== void 0 ? options.horizontalScrolling : Boolean(configurationService.getValue(horizontalScrollingKey));
  const [workbenchListOptions, disposable] = instantiationService.invokeFunction(toWorkbenchListOptions, options);
  const additionalScrollHeight = options.additionalScrollHeight;
  const renderIndentGuides = options.renderIndentGuides !== void 0 ? options.renderIndentGuides : configurationService.getValue(treeRenderIndentGuidesKey);
  return {
    getTypeNavigationMode,
    disposable,
    options: Object.assign(Object.assign({
      // ...options, // TODO@Joao why is this not splatted here?
      keyboardSupport: false
    }, workbenchListOptions), { indent: typeof configurationService.getValue(treeIndentKey) === "number" ? configurationService.getValue(treeIndentKey) : void 0, renderIndentGuides, smoothScrolling: Boolean(configurationService.getValue(listSmoothScrolling)), defaultFindMode: getDefaultTreeFindMode(configurationService), defaultFindMatchType: getDefaultTreeFindMatchType(configurationService), horizontalScrolling, scrollByPage: Boolean(configurationService.getValue(scrollByPageKey)), additionalScrollHeight, hideTwistiesOfChildlessElements: options.hideTwistiesOfChildlessElements, expandOnlyOnTwistieClick: (_a2 = options.expandOnlyOnTwistieClick) !== null && _a2 !== void 0 ? _a2 : configurationService.getValue(treeExpandMode) === "doubleClick", contextViewProvider: contextViewService, findWidgetStyles: defaultFindWidgetStyles })
  };
}
let WorkbenchTreeInternals = class WorkbenchTreeInternals2 {
  get onDidOpen() {
    return this.navigator.onDidOpen;
  }
  constructor(tree2, options, getTypeNavigationMode, overrideStyles2, contextKeyService, listService, configurationService) {
    var _a2;
    this.tree = tree2;
    this.disposables = [];
    this.contextKeyService = createScopedContextKeyService(contextKeyService, tree2);
    this.disposables.push(createScrollObserver(this.contextKeyService, tree2));
    this.listSupportsMultiSelect = WorkbenchListSupportsMultiSelectContextKey.bindTo(this.contextKeyService);
    this.listSupportsMultiSelect.set(options.multipleSelectionSupport !== false);
    const listSelectionNavigation = WorkbenchListSelectionNavigation.bindTo(this.contextKeyService);
    listSelectionNavigation.set(Boolean(options.selectionNavigation));
    this.listSupportFindWidget = WorkbenchListSupportsFind.bindTo(this.contextKeyService);
    this.listSupportFindWidget.set((_a2 = options.findWidgetEnabled) !== null && _a2 !== void 0 ? _a2 : true);
    this.hasSelectionOrFocus = WorkbenchListHasSelectionOrFocus.bindTo(this.contextKeyService);
    this.hasDoubleSelection = WorkbenchListDoubleSelection.bindTo(this.contextKeyService);
    this.hasMultiSelection = WorkbenchListMultiSelection.bindTo(this.contextKeyService);
    this.treeElementCanCollapse = WorkbenchTreeElementCanCollapse.bindTo(this.contextKeyService);
    this.treeElementHasParent = WorkbenchTreeElementHasParent.bindTo(this.contextKeyService);
    this.treeElementCanExpand = WorkbenchTreeElementCanExpand.bindTo(this.contextKeyService);
    this.treeElementHasChild = WorkbenchTreeElementHasChild.bindTo(this.contextKeyService);
    this.treeFindOpen = WorkbenchTreeFindOpen.bindTo(this.contextKeyService);
    this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
    this.updateStyleOverrides(overrideStyles2);
    const updateCollapseContextKeys = () => {
      const focus = tree2.getFocus()[0];
      if (!focus) {
        return;
      }
      const node2 = tree2.getNode(focus);
      this.treeElementCanCollapse.set(node2.collapsible && !node2.collapsed);
      this.treeElementHasParent.set(!!tree2.getParentElement(focus));
      this.treeElementCanExpand.set(node2.collapsible && node2.collapsed);
      this.treeElementHasChild.set(!!tree2.getFirstElementChild(focus));
    };
    const interestingContextKeys = /* @__PURE__ */ new Set();
    interestingContextKeys.add(WorkbenchListTypeNavigationModeKey);
    interestingContextKeys.add(WorkbenchListAutomaticKeyboardNavigationLegacyKey);
    this.disposables.push(this.contextKeyService, listService.register(tree2), tree2.onDidChangeSelection(() => {
      const selection = tree2.getSelection();
      const focus = tree2.getFocus();
      this.contextKeyService.bufferChangeEvents(() => {
        this.hasSelectionOrFocus.set(selection.length > 0 || focus.length > 0);
        this.hasMultiSelection.set(selection.length > 1);
        this.hasDoubleSelection.set(selection.length === 2);
      });
    }), tree2.onDidChangeFocus(() => {
      const selection = tree2.getSelection();
      const focus = tree2.getFocus();
      this.hasSelectionOrFocus.set(selection.length > 0 || focus.length > 0);
      updateCollapseContextKeys();
    }), tree2.onDidChangeCollapseState(updateCollapseContextKeys), tree2.onDidChangeModel(updateCollapseContextKeys), tree2.onDidChangeFindOpenState((enabled) => this.treeFindOpen.set(enabled)), configurationService.onDidChangeConfiguration((e) => {
      let newOptions = {};
      if (e.affectsConfiguration(multiSelectModifierSettingKey)) {
        this._useAltAsMultipleSelectionModifier = useAltAsMultipleSelectionModifier(configurationService);
      }
      if (e.affectsConfiguration(treeIndentKey)) {
        const indent = configurationService.getValue(treeIndentKey);
        newOptions = Object.assign(Object.assign({}, newOptions), { indent });
      }
      if (e.affectsConfiguration(treeRenderIndentGuidesKey) && options.renderIndentGuides === void 0) {
        const renderIndentGuides = configurationService.getValue(treeRenderIndentGuidesKey);
        newOptions = Object.assign(Object.assign({}, newOptions), { renderIndentGuides });
      }
      if (e.affectsConfiguration(listSmoothScrolling)) {
        const smoothScrolling = Boolean(configurationService.getValue(listSmoothScrolling));
        newOptions = Object.assign(Object.assign({}, newOptions), { smoothScrolling });
      }
      if (e.affectsConfiguration(defaultFindModeSettingKey) || e.affectsConfiguration(keyboardNavigationSettingKey)) {
        const defaultFindMode = getDefaultTreeFindMode(configurationService);
        newOptions = Object.assign(Object.assign({}, newOptions), { defaultFindMode });
      }
      if (e.affectsConfiguration(typeNavigationModeSettingKey) || e.affectsConfiguration(keyboardNavigationSettingKey)) {
        const typeNavigationMode = getTypeNavigationMode();
        newOptions = Object.assign(Object.assign({}, newOptions), { typeNavigationMode });
      }
      if (e.affectsConfiguration(defaultFindMatchTypeSettingKey)) {
        const defaultFindMatchType = getDefaultTreeFindMatchType(configurationService);
        newOptions = Object.assign(Object.assign({}, newOptions), { defaultFindMatchType });
      }
      if (e.affectsConfiguration(horizontalScrollingKey) && options.horizontalScrolling === void 0) {
        const horizontalScrolling = Boolean(configurationService.getValue(horizontalScrollingKey));
        newOptions = Object.assign(Object.assign({}, newOptions), { horizontalScrolling });
      }
      if (e.affectsConfiguration(scrollByPageKey)) {
        const scrollByPage = Boolean(configurationService.getValue(scrollByPageKey));
        newOptions = Object.assign(Object.assign({}, newOptions), { scrollByPage });
      }
      if (e.affectsConfiguration(treeExpandMode) && options.expandOnlyOnTwistieClick === void 0) {
        newOptions = Object.assign(Object.assign({}, newOptions), { expandOnlyOnTwistieClick: configurationService.getValue(treeExpandMode) === "doubleClick" });
      }
      if (e.affectsConfiguration(mouseWheelScrollSensitivityKey)) {
        const mouseWheelScrollSensitivity = configurationService.getValue(mouseWheelScrollSensitivityKey);
        newOptions = Object.assign(Object.assign({}, newOptions), { mouseWheelScrollSensitivity });
      }
      if (e.affectsConfiguration(fastScrollSensitivityKey)) {
        const fastScrollSensitivity = configurationService.getValue(fastScrollSensitivityKey);
        newOptions = Object.assign(Object.assign({}, newOptions), { fastScrollSensitivity });
      }
      if (Object.keys(newOptions).length > 0) {
        tree2.updateOptions(newOptions);
      }
    }), this.contextKeyService.onDidChangeContext((e) => {
      if (e.affectsSome(interestingContextKeys)) {
        tree2.updateOptions({ typeNavigationMode: getTypeNavigationMode() });
      }
    }));
    this.navigator = new TreeResourceNavigator(tree2, Object.assign({ configurationService }, options));
    this.disposables.push(this.navigator);
  }
  updateOptions(options) {
    if (options.multipleSelectionSupport !== void 0) {
      this.listSupportsMultiSelect.set(!!options.multipleSelectionSupport);
    }
  }
  updateStyleOverrides(overrideStyles2) {
    this.tree.style(overrideStyles2 ? getListStyles(overrideStyles2) : defaultListStyles);
  }
  dispose() {
    this.disposables = dispose(this.disposables);
  }
};
WorkbenchTreeInternals = __decorate$1D([
  __param$1B(4, IContextKeyService),
  __param$1B(5, IListService),
  __param$1B(6, IConfigurationService)
], WorkbenchTreeInternals);
const configurationRegistry = Registry.as(Extensions$6.Configuration);
configurationRegistry.registerConfiguration({
  id: "workbench",
  order: 7,
  title: localize("workbenchConfigurationTitle", "Workbench"),
  type: "object",
  properties: {
    [multiSelectModifierSettingKey]: {
      type: "string",
      enum: ["ctrlCmd", "alt"],
      markdownEnumDescriptions: [
        localize("multiSelectModifier.ctrlCmd", "Maps to `Control` on Windows and Linux and to `Command` on macOS."),
        localize("multiSelectModifier.alt", "Maps to `Alt` on Windows and Linux and to `Option` on macOS.")
      ],
      default: "ctrlCmd",
      description: localize({
        key: "multiSelectModifier",
        comment: [
          "- `ctrlCmd` refers to a value the setting can take and should not be localized.",
          "- `Control` and `Command` refer to the modifier keys Ctrl or Cmd on the keyboard and can be localized."
        ]
      }, "The modifier to be used to add an item in trees and lists to a multi-selection with the mouse (for example in the explorer, open editors and scm view). The 'Open to Side' mouse gestures - if supported - will adapt such that they do not conflict with the multiselect modifier.")
    },
    [openModeSettingKey]: {
      type: "string",
      enum: ["singleClick", "doubleClick"],
      default: "singleClick",
      description: localize({
        key: "openModeModifier",
        comment: ["`singleClick` and `doubleClick` refers to a value the setting can take and should not be localized."]
      }, "Controls how to open items in trees and lists using the mouse (if supported). Note that some trees and lists might choose to ignore this setting if it is not applicable.")
    },
    [horizontalScrollingKey]: {
      type: "boolean",
      default: false,
      description: localize("horizontalScrolling setting", "Controls whether lists and trees support horizontal scrolling in the workbench. Warning: turning on this setting has a performance implication.")
    },
    [scrollByPageKey]: {
      type: "boolean",
      default: false,
      description: localize("list.scrollByPage", "Controls whether clicks in the scrollbar scroll page by page.")
    },
    [treeIndentKey]: {
      type: "number",
      default: 8,
      minimum: 4,
      maximum: 40,
      description: localize("tree indent setting", "Controls tree indentation in pixels.")
    },
    [treeRenderIndentGuidesKey]: {
      type: "string",
      enum: ["none", "onHover", "always"],
      default: "onHover",
      description: localize("render tree indent guides", "Controls whether the tree should render indent guides.")
    },
    [listSmoothScrolling]: {
      type: "boolean",
      default: false,
      description: localize("list smoothScrolling setting", "Controls whether lists and trees have smooth scrolling.")
    },
    [mouseWheelScrollSensitivityKey]: {
      type: "number",
      default: 1,
      markdownDescription: localize("Mouse Wheel Scroll Sensitivity", "A multiplier to be used on the `deltaX` and `deltaY` of mouse wheel scroll events.")
    },
    [fastScrollSensitivityKey]: {
      type: "number",
      default: 5,
      markdownDescription: localize("Fast Scroll Sensitivity", "Scrolling speed multiplier when pressing `Alt`.")
    },
    [defaultFindModeSettingKey]: {
      type: "string",
      enum: ["highlight", "filter"],
      enumDescriptions: [
        localize("defaultFindModeSettingKey.highlight", "Highlight elements when searching. Further up and down navigation will traverse only the highlighted elements."),
        localize("defaultFindModeSettingKey.filter", "Filter elements when searching.")
      ],
      default: "highlight",
      description: localize("defaultFindModeSettingKey", "Controls the default find mode for lists and trees in the workbench.")
    },
    [keyboardNavigationSettingKey]: {
      type: "string",
      enum: ["simple", "highlight", "filter"],
      enumDescriptions: [
        localize("keyboardNavigationSettingKey.simple", "Simple keyboard navigation focuses elements which match the keyboard input. Matching is done only on prefixes."),
        localize("keyboardNavigationSettingKey.highlight", "Highlight keyboard navigation highlights elements which match the keyboard input. Further up and down navigation will traverse only the highlighted elements."),
        localize("keyboardNavigationSettingKey.filter", "Filter keyboard navigation will filter out and hide all the elements which do not match the keyboard input.")
      ],
      default: "highlight",
      description: localize("keyboardNavigationSettingKey", "Controls the keyboard navigation style for lists and trees in the workbench. Can be simple, highlight and filter."),
      deprecated: true,
      deprecationMessage: localize("keyboardNavigationSettingKeyDeprecated", "Please use 'workbench.list.defaultFindMode' and	'workbench.list.typeNavigationMode' instead.")
    },
    [defaultFindMatchTypeSettingKey]: {
      type: "string",
      enum: ["fuzzy", "contiguous"],
      enumDescriptions: [
        localize("defaultFindMatchTypeSettingKey.fuzzy", "Use fuzzy matching when searching."),
        localize("defaultFindMatchTypeSettingKey.contiguous", "Use contiguous matching when searching.")
      ],
      default: "fuzzy",
      description: localize("defaultFindMatchTypeSettingKey", "Controls the type of matching used when searching lists and trees in the workbench.")
    },
    [treeExpandMode]: {
      type: "string",
      enum: ["singleClick", "doubleClick"],
      default: "singleClick",
      description: localize("expand mode", "Controls how tree folders are expanded when clicking the folder names. Note that some trees and lists might choose to ignore this setting if it is not applicable.")
    },
    [typeNavigationModeSettingKey]: {
      type: "string",
      enum: ["automatic", "trigger"],
      default: "automatic",
      description: localize("typeNavigationMode", "Controls the how type navigation works in lists and trees in the workbench. When set to 'trigger', type navigation begins once the 'list.triggerTypeNavigation' command is run.")
    }
  }
});
var __awaiter$17 = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class OneReference {
  constructor(isProviderFirst, parent, link2, _rangeCallback) {
    this.isProviderFirst = isProviderFirst;
    this.parent = parent;
    this.link = link2;
    this._rangeCallback = _rangeCallback;
    this.id = defaultGenerator.nextId();
  }
  get uri() {
    return this.link.uri;
  }
  get range() {
    var _a2, _b2;
    return (_b2 = (_a2 = this._range) !== null && _a2 !== void 0 ? _a2 : this.link.targetSelectionRange) !== null && _b2 !== void 0 ? _b2 : this.link.range;
  }
  set range(value) {
    this._range = value;
    this._rangeCallback(this);
  }
  get ariaMessage() {
    var _a2;
    const preview = (_a2 = this.parent.getPreview(this)) === null || _a2 === void 0 ? void 0 : _a2.preview(this.range);
    if (!preview) {
      return localize("aria.oneReference", "in {0} on line {1} at column {2}", basename$1(this.uri), this.range.startLineNumber, this.range.startColumn);
    } else {
      return localize({ key: "aria.oneReference.preview", comment: ["Placeholders are: 0: filename, 1:line number, 2: column number, 3: preview snippet of source code"] }, "{0} in {1} on line {2} at column {3}", preview.value, basename$1(this.uri), this.range.startLineNumber, this.range.startColumn);
    }
  }
}
class FilePreview {
  constructor(_modelReference) {
    this._modelReference = _modelReference;
  }
  dispose() {
    this._modelReference.dispose();
  }
  preview(range2, n2 = 8) {
    const model = this._modelReference.object.textEditorModel;
    if (!model) {
      return void 0;
    }
    const { startLineNumber, startColumn, endLineNumber, endColumn } = range2;
    const word2 = model.getWordUntilPosition({ lineNumber: startLineNumber, column: startColumn - n2 });
    const beforeRange = new Range$2(startLineNumber, word2.startColumn, startLineNumber, startColumn);
    const afterRange = new Range$2(
      endLineNumber,
      endColumn,
      endLineNumber,
      1073741824
      /* Constants.MAX_SAFE_SMALL_INTEGER */
    );
    const before = model.getValueInRange(beforeRange).replace(/^\s+/, "");
    const inside = model.getValueInRange(range2);
    const after = model.getValueInRange(afterRange).replace(/\s+$/, "");
    return {
      value: before + inside + after,
      highlight: { start: before.length, end: before.length + inside.length }
    };
  }
}
class FileReferences {
  constructor(parent, uri) {
    this.parent = parent;
    this.uri = uri;
    this.children = [];
    this._previews = new ResourceMap();
  }
  dispose() {
    dispose(this._previews.values());
    this._previews.clear();
  }
  getPreview(child) {
    return this._previews.get(child.uri);
  }
  get ariaMessage() {
    const len = this.children.length;
    if (len === 1) {
      return localize("aria.fileReferences.1", "1 symbol in {0}, full path {1}", basename$1(this.uri), this.uri.fsPath);
    } else {
      return localize("aria.fileReferences.N", "{0} symbols in {1}, full path {2}", len, basename$1(this.uri), this.uri.fsPath);
    }
  }
  resolve(textModelResolverService) {
    return __awaiter$17(this, void 0, void 0, function* () {
      if (this._previews.size !== 0) {
        return this;
      }
      for (const child of this.children) {
        if (this._previews.has(child.uri)) {
          continue;
        }
        try {
          const ref2 = yield textModelResolverService.createModelReference(child.uri);
          this._previews.set(child.uri, new FilePreview(ref2));
        } catch (err) {
          onUnexpectedError(err);
        }
      }
      return this;
    });
  }
}
class ReferencesModel {
  constructor(links2, title2) {
    this.groups = [];
    this.references = [];
    this._onDidChangeReferenceRange = new Emitter$1();
    this.onDidChangeReferenceRange = this._onDidChangeReferenceRange.event;
    this._links = links2;
    this._title = title2;
    const [providersFirst] = links2;
    links2.sort(ReferencesModel._compareReferences);
    let current;
    for (const link2 of links2) {
      if (!current || !extUri.isEqual(current.uri, link2.uri, true)) {
        current = new FileReferences(this, link2.uri);
        this.groups.push(current);
      }
      if (current.children.length === 0 || ReferencesModel._compareReferences(link2, current.children[current.children.length - 1]) !== 0) {
        const oneRef = new OneReference(providersFirst === link2, current, link2, (ref2) => this._onDidChangeReferenceRange.fire(ref2));
        this.references.push(oneRef);
        current.children.push(oneRef);
      }
    }
  }
  dispose() {
    dispose(this.groups);
    this._onDidChangeReferenceRange.dispose();
    this.groups.length = 0;
  }
  clone() {
    return new ReferencesModel(this._links, this._title);
  }
  get title() {
    return this._title;
  }
  get isEmpty() {
    return this.groups.length === 0;
  }
  get ariaMessage() {
    if (this.isEmpty) {
      return localize("aria.result.0", "No results found");
    } else if (this.references.length === 1) {
      return localize("aria.result.1", "Found 1 symbol in {0}", this.references[0].uri.fsPath);
    } else if (this.groups.length === 1) {
      return localize("aria.result.n1", "Found {0} symbols in {1}", this.references.length, this.groups[0].uri.fsPath);
    } else {
      return localize("aria.result.nm", "Found {0} symbols in {1} files", this.references.length, this.groups.length);
    }
  }
  nextOrPreviousReference(reference, next) {
    const { parent } = reference;
    let idx = parent.children.indexOf(reference);
    const childCount = parent.children.length;
    const groupCount = parent.parent.groups.length;
    if (groupCount === 1 || next && idx + 1 < childCount || !next && idx > 0) {
      if (next) {
        idx = (idx + 1) % childCount;
      } else {
        idx = (idx + childCount - 1) % childCount;
      }
      return parent.children[idx];
    }
    idx = parent.parent.groups.indexOf(parent);
    if (next) {
      idx = (idx + 1) % groupCount;
      return parent.parent.groups[idx].children[0];
    } else {
      idx = (idx + groupCount - 1) % groupCount;
      return parent.parent.groups[idx].children[parent.parent.groups[idx].children.length - 1];
    }
  }
  nearestReference(resource, position) {
    const nearest = this.references.map((ref2, idx) => {
      return {
        idx,
        prefixLen: commonPrefixLength(ref2.uri.toString(), resource.toString()),
        offsetDist: Math.abs(ref2.range.startLineNumber - position.lineNumber) * 100 + Math.abs(ref2.range.startColumn - position.column)
      };
    }).sort((a, b) => {
      if (a.prefixLen > b.prefixLen) {
        return -1;
      } else if (a.prefixLen < b.prefixLen) {
        return 1;
      } else if (a.offsetDist < b.offsetDist) {
        return -1;
      } else if (a.offsetDist > b.offsetDist) {
        return 1;
      } else {
        return 0;
      }
    })[0];
    if (nearest) {
      return this.references[nearest.idx];
    }
    return void 0;
  }
  referenceAt(resource, position) {
    for (const ref2 of this.references) {
      if (ref2.uri.toString() === resource.toString()) {
        if (Range$2.containsPosition(ref2.range, position)) {
          return ref2;
        }
      }
    }
    return void 0;
  }
  firstReference() {
    for (const ref2 of this.references) {
      if (ref2.isProviderFirst) {
        return ref2;
      }
    }
    return this.references[0];
  }
  static _compareReferences(a, b) {
    return extUri.compare(a.uri, b.uri) || Range$2.compareRangesUsingStarts(a.range, b.range);
  }
}
const referencesWidget = "";
const countBadge = "";
class CountBadge {
  constructor(container2, options, styles) {
    this.options = options;
    this.styles = styles;
    this.count = 0;
    this.element = append$1(container2, $$d(".monaco-count-badge"));
    this.countFormat = this.options.countFormat || "{0}";
    this.titleFormat = this.options.titleFormat || "";
    this.setCount(this.options.count || 0);
  }
  setCount(count) {
    this.count = count;
    this.render();
  }
  setTitleFormat(titleFormat) {
    this.titleFormat = titleFormat;
    this.render();
  }
  render() {
    var _a2, _b2;
    this.element.textContent = format$2(this.countFormat, this.count);
    this.element.title = format$2(this.titleFormat, this.count);
    this.element.style.backgroundColor = (_a2 = this.styles.badgeBackground) !== null && _a2 !== void 0 ? _a2 : "";
    this.element.style.color = (_b2 = this.styles.badgeForeground) !== null && _b2 !== void 0 ? _b2 : "";
    if (this.styles.badgeBorder) {
      this.element.style.border = `1px solid ${this.styles.badgeBorder}`;
    }
  }
}
class HighlightedLabel {
  /**
   * Create a new {@link HighlightedLabel}.
   *
   * @param container The parent container to append to.
   */
  constructor(container2, options) {
    var _a2;
    this.text = "";
    this.title = "";
    this.highlights = [];
    this.didEverRender = false;
    this.supportIcons = (_a2 = options === null || options === void 0 ? void 0 : options.supportIcons) !== null && _a2 !== void 0 ? _a2 : false;
    this.domNode = append$1(container2, $$d("span.monaco-highlighted-label"));
  }
  /**
   * The label's DOM node.
   */
  get element() {
    return this.domNode;
  }
  /**
   * Set the label and highlights.
   *
   * @param text The label to display.
   * @param highlights The ranges to highlight.
   * @param title An optional title for the hover tooltip.
   * @param escapeNewLines Whether to escape new lines.
   * @returns
   */
  set(text2, highlights = [], title2 = "", escapeNewLines) {
    if (!text2) {
      text2 = "";
    }
    if (escapeNewLines) {
      text2 = HighlightedLabel.escapeNewLines(text2, highlights);
    }
    if (this.didEverRender && this.text === text2 && this.title === title2 && equals$2(this.highlights, highlights)) {
      return;
    }
    this.text = text2;
    this.title = title2;
    this.highlights = highlights;
    this.render();
  }
  render() {
    const children = [];
    let pos = 0;
    for (const highlight of this.highlights) {
      if (highlight.end === highlight.start) {
        continue;
      }
      if (pos < highlight.start) {
        const substring2 = this.text.substring(pos, highlight.start);
        if (this.supportIcons) {
          children.push(...renderLabelWithIcons(substring2));
        } else {
          children.push(substring2);
        }
        pos = highlight.start;
      }
      const substring = this.text.substring(pos, highlight.end);
      const element = $$d("span.highlight", void 0, ...this.supportIcons ? renderLabelWithIcons(substring) : [substring]);
      if (highlight.extraClasses) {
        element.classList.add(...highlight.extraClasses);
      }
      children.push(element);
      pos = highlight.end;
    }
    if (pos < this.text.length) {
      const substring = this.text.substring(pos);
      if (this.supportIcons) {
        children.push(...renderLabelWithIcons(substring));
      } else {
        children.push(substring);
      }
    }
    reset(this.domNode, ...children);
    if (this.title) {
      this.domNode.title = this.title;
    } else {
      this.domNode.removeAttribute("title");
    }
    this.didEverRender = true;
  }
  static escapeNewLines(text2, highlights) {
    let total = 0;
    let extra = 0;
    return text2.replace(/\r\n|\r|\n/g, (match2, offset) => {
      extra = match2 === "\r\n" ? -1 : 0;
      offset += total;
      for (const highlight of highlights) {
        if (highlight.end <= offset) {
          continue;
        }
        if (highlight.start >= offset) {
          highlight.start += extra;
        }
        if (highlight.end >= offset) {
          highlight.end += extra;
        }
      }
      total += extra;
      return "⏎";
    });
  }
}
const iconlabel = "";
class FastLabelNode {
  constructor(_element) {
    this._element = _element;
  }
  get element() {
    return this._element;
  }
  set textContent(content) {
    if (this.disposed || content === this._textContent) {
      return;
    }
    this._textContent = content;
    this._element.textContent = content;
  }
  set className(className3) {
    if (this.disposed || className3 === this._className) {
      return;
    }
    this._className = className3;
    this._element.className = className3;
  }
  set empty(empty2) {
    if (this.disposed || empty2 === this._empty) {
      return;
    }
    this._empty = empty2;
    this._element.style.marginLeft = empty2 ? "0" : "";
  }
  dispose() {
    this.disposed = true;
  }
}
class IconLabel extends Disposable {
  constructor(container2, options) {
    super();
    this.customHovers = /* @__PURE__ */ new Map();
    this.creationOptions = options;
    this.domNode = this._register(new FastLabelNode(append$1(container2, $$d(".monaco-icon-label"))));
    this.labelContainer = append$1(this.domNode.element, $$d(".monaco-icon-label-container"));
    const nameContainer = append$1(this.labelContainer, $$d("span.monaco-icon-name-container"));
    if ((options === null || options === void 0 ? void 0 : options.supportHighlights) || (options === null || options === void 0 ? void 0 : options.supportIcons)) {
      this.nameNode = new LabelWithHighlights(nameContainer, !!options.supportIcons);
    } else {
      this.nameNode = new Label(nameContainer);
    }
    this.hoverDelegate = options === null || options === void 0 ? void 0 : options.hoverDelegate;
  }
  get element() {
    return this.domNode.element;
  }
  setLabel(label, description, options) {
    const labelClasses = ["monaco-icon-label"];
    const containerClasses = ["monaco-icon-label-container"];
    if (options) {
      if (options.extraClasses) {
        labelClasses.push(...options.extraClasses);
      }
      if (options.italic) {
        labelClasses.push("italic");
      }
      if (options.strikethrough) {
        labelClasses.push("strikethrough");
      }
      if (options.disabledCommand) {
        containerClasses.push("disabled");
      }
    }
    this.domNode.className = labelClasses.join(" ");
    this.labelContainer.className = containerClasses.join(" ");
    this.setupHover((options === null || options === void 0 ? void 0 : options.descriptionTitle) ? this.labelContainer : this.element, options === null || options === void 0 ? void 0 : options.title);
    this.nameNode.setLabel(label, options);
    if (description || this.descriptionNode) {
      const descriptionNode = this.getOrCreateDescriptionNode();
      if (descriptionNode instanceof HighlightedLabel) {
        descriptionNode.set(description || "", options ? options.descriptionMatches : void 0, void 0, options === null || options === void 0 ? void 0 : options.labelEscapeNewLines);
        this.setupHover(descriptionNode.element, options === null || options === void 0 ? void 0 : options.descriptionTitle);
      } else {
        descriptionNode.textContent = description && (options === null || options === void 0 ? void 0 : options.labelEscapeNewLines) ? HighlightedLabel.escapeNewLines(description, []) : description || "";
        this.setupHover(descriptionNode.element, (options === null || options === void 0 ? void 0 : options.descriptionTitle) || "");
        descriptionNode.empty = !description;
      }
    }
  }
  setupHover(htmlElement, tooltip) {
    const previousCustomHover = this.customHovers.get(htmlElement);
    if (previousCustomHover) {
      previousCustomHover.dispose();
      this.customHovers.delete(htmlElement);
    }
    if (!tooltip) {
      htmlElement.removeAttribute("title");
      return;
    }
    if (!this.hoverDelegate) {
      setupNativeHover(htmlElement, tooltip);
    } else {
      const hoverDisposable = setupCustomHover(this.hoverDelegate, htmlElement, tooltip);
      if (hoverDisposable) {
        this.customHovers.set(htmlElement, hoverDisposable);
      }
    }
  }
  dispose() {
    super.dispose();
    for (const disposable of this.customHovers.values()) {
      disposable.dispose();
    }
    this.customHovers.clear();
  }
  getOrCreateDescriptionNode() {
    var _a2;
    if (!this.descriptionNode) {
      const descriptionContainer = this._register(new FastLabelNode(append$1(this.labelContainer, $$d("span.monaco-icon-description-container"))));
      if ((_a2 = this.creationOptions) === null || _a2 === void 0 ? void 0 : _a2.supportDescriptionHighlights) {
        this.descriptionNode = new HighlightedLabel(append$1(descriptionContainer.element, $$d("span.label-description")), { supportIcons: !!this.creationOptions.supportIcons });
      } else {
        this.descriptionNode = this._register(new FastLabelNode(append$1(descriptionContainer.element, $$d("span.label-description"))));
      }
    }
    return this.descriptionNode;
  }
}
class Label {
  constructor(container2) {
    this.container = container2;
    this.label = void 0;
    this.singleLabel = void 0;
  }
  setLabel(label, options) {
    if (this.label === label && equals$2(this.options, options)) {
      return;
    }
    this.label = label;
    this.options = options;
    if (typeof label === "string") {
      if (!this.singleLabel) {
        this.container.innerText = "";
        this.container.classList.remove("multiple");
        this.singleLabel = append$1(this.container, $$d("a.label-name", { id: options === null || options === void 0 ? void 0 : options.domId }));
      }
      this.singleLabel.textContent = label;
    } else {
      this.container.innerText = "";
      this.container.classList.add("multiple");
      this.singleLabel = void 0;
      for (let i = 0; i < label.length; i++) {
        const l = label[i];
        const id3 = (options === null || options === void 0 ? void 0 : options.domId) && `${options === null || options === void 0 ? void 0 : options.domId}_${i}`;
        append$1(this.container, $$d("a.label-name", { id: id3, "data-icon-label-count": label.length, "data-icon-label-index": i, "role": "treeitem" }, l));
        if (i < label.length - 1) {
          append$1(this.container, $$d("span.label-separator", void 0, (options === null || options === void 0 ? void 0 : options.separator) || "/"));
        }
      }
    }
  }
}
function splitMatches(labels, separator, matches) {
  if (!matches) {
    return void 0;
  }
  let labelStart = 0;
  return labels.map((label) => {
    const labelRange = { start: labelStart, end: labelStart + label.length };
    const result2 = matches.map((match2) => Range$1.intersect(labelRange, match2)).filter((range2) => !Range$1.isEmpty(range2)).map(({ start, end }) => ({ start: start - labelStart, end: end - labelStart }));
    labelStart = labelRange.end + separator.length;
    return result2;
  });
}
class LabelWithHighlights {
  constructor(container2, supportIcons) {
    this.container = container2;
    this.supportIcons = supportIcons;
    this.label = void 0;
    this.singleLabel = void 0;
  }
  setLabel(label, options) {
    if (this.label === label && equals$2(this.options, options)) {
      return;
    }
    this.label = label;
    this.options = options;
    if (typeof label === "string") {
      if (!this.singleLabel) {
        this.container.innerText = "";
        this.container.classList.remove("multiple");
        this.singleLabel = new HighlightedLabel(append$1(this.container, $$d("a.label-name", { id: options === null || options === void 0 ? void 0 : options.domId })), { supportIcons: this.supportIcons });
      }
      this.singleLabel.set(label, options === null || options === void 0 ? void 0 : options.matches, void 0, options === null || options === void 0 ? void 0 : options.labelEscapeNewLines);
    } else {
      this.container.innerText = "";
      this.container.classList.add("multiple");
      this.singleLabel = void 0;
      const separator = (options === null || options === void 0 ? void 0 : options.separator) || "/";
      const matches = splitMatches(label, separator, options === null || options === void 0 ? void 0 : options.matches);
      for (let i = 0; i < label.length; i++) {
        const l = label[i];
        const m = matches ? matches[i] : void 0;
        const id3 = (options === null || options === void 0 ? void 0 : options.domId) && `${options === null || options === void 0 ? void 0 : options.domId}_${i}`;
        const name = $$d("a.label-name", { id: id3, "data-icon-label-count": label.length, "data-icon-label-index": i, "role": "treeitem" });
        const highlightedLabel = new HighlightedLabel(append$1(this.container, name), { supportIcons: this.supportIcons });
        highlightedLabel.set(l, m, void 0, options === null || options === void 0 ? void 0 : options.labelEscapeNewLines);
        if (i < label.length - 1) {
          append$1(name, $$d("span.label-separator", void 0, separator));
        }
      }
    }
  }
}
const ILabelService = createDecorator("labelService");
var __decorate$1C = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1A = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let DataSource = class DataSource2 {
  constructor(_resolverService) {
    this._resolverService = _resolverService;
  }
  hasChildren(element) {
    if (element instanceof ReferencesModel) {
      return true;
    }
    if (element instanceof FileReferences) {
      return true;
    }
    return false;
  }
  getChildren(element) {
    if (element instanceof ReferencesModel) {
      return element.groups;
    }
    if (element instanceof FileReferences) {
      return element.resolve(this._resolverService).then((val) => {
        return val.children;
      });
    }
    throw new Error("bad tree");
  }
};
DataSource = __decorate$1C([
  __param$1A(0, ITextModelService)
], DataSource);
class Delegate {
  getHeight() {
    return 23;
  }
  getTemplateId(element) {
    if (element instanceof FileReferences) {
      return FileReferencesRenderer.id;
    } else {
      return OneReferenceRenderer.id;
    }
  }
}
let StringRepresentationProvider = class StringRepresentationProvider2 {
  constructor(_keybindingService) {
    this._keybindingService = _keybindingService;
  }
  getKeyboardNavigationLabel(element) {
    var _a2;
    if (element instanceof OneReference) {
      const parts = (_a2 = element.parent.getPreview(element)) === null || _a2 === void 0 ? void 0 : _a2.preview(element.range);
      if (parts) {
        return parts.value;
      }
    }
    return basename$1(element.uri);
  }
};
StringRepresentationProvider = __decorate$1C([
  __param$1A(0, IKeybindingService)
], StringRepresentationProvider);
class IdentityProvider {
  getId(element) {
    return element instanceof OneReference ? element.id : element.uri;
  }
}
let FileReferencesTemplate = class FileReferencesTemplate2 extends Disposable {
  constructor(container2, _labelService) {
    super();
    this._labelService = _labelService;
    const parent = document.createElement("div");
    parent.classList.add("reference-file");
    this.file = this._register(new IconLabel(parent, { supportHighlights: true }));
    this.badge = new CountBadge(append$1(parent, $$d(".count")), {}, defaultCountBadgeStyles);
    container2.appendChild(parent);
  }
  set(element, matches) {
    const parent = dirname$3(element.uri);
    this.file.setLabel(this._labelService.getUriBasenameLabel(element.uri), this._labelService.getUriLabel(parent, { relative: true }), { title: this._labelService.getUriLabel(element.uri), matches });
    const len = element.children.length;
    this.badge.setCount(len);
    if (len > 1) {
      this.badge.setTitleFormat(localize("referencesCount", "{0} references", len));
    } else {
      this.badge.setTitleFormat(localize("referenceCount", "{0} reference", len));
    }
  }
};
FileReferencesTemplate = __decorate$1C([
  __param$1A(1, ILabelService)
], FileReferencesTemplate);
let FileReferencesRenderer = class FileReferencesRenderer2 {
  constructor(_instantiationService) {
    this._instantiationService = _instantiationService;
    this.templateId = FileReferencesRenderer2.id;
  }
  renderTemplate(container2) {
    return this._instantiationService.createInstance(FileReferencesTemplate, container2);
  }
  renderElement(node2, index, template) {
    template.set(node2.element, createMatches(node2.filterData));
  }
  disposeTemplate(templateData) {
    templateData.dispose();
  }
};
FileReferencesRenderer.id = "FileReferencesRenderer";
FileReferencesRenderer = __decorate$1C([
  __param$1A(0, IInstantiationService)
], FileReferencesRenderer);
class OneReferenceTemplate {
  constructor(container2) {
    this.label = new HighlightedLabel(container2);
  }
  set(element, score2) {
    var _a2;
    const preview = (_a2 = element.parent.getPreview(element)) === null || _a2 === void 0 ? void 0 : _a2.preview(element.range);
    if (!preview || !preview.value) {
      this.label.set(`${basename$1(element.uri)}:${element.range.startLineNumber + 1}:${element.range.startColumn + 1}`);
    } else {
      const { value, highlight } = preview;
      if (score2 && !FuzzyScore.isDefault(score2)) {
        this.label.element.classList.toggle("referenceMatch", false);
        this.label.set(value, createMatches(score2));
      } else {
        this.label.element.classList.toggle("referenceMatch", true);
        this.label.set(value, [highlight]);
      }
    }
  }
}
class OneReferenceRenderer {
  constructor() {
    this.templateId = OneReferenceRenderer.id;
  }
  renderTemplate(container2) {
    return new OneReferenceTemplate(container2);
  }
  renderElement(node2, index, templateData) {
    templateData.set(node2.element, node2.filterData);
  }
  disposeTemplate() {
  }
}
OneReferenceRenderer.id = "OneReferenceRenderer";
class AccessibilityProvider {
  getWidgetAriaLabel() {
    return localize("treeAriaLabel", "References");
  }
  getAriaLabel(element) {
    return element.ariaMessage;
  }
}
var __decorate$1B = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1z = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$16 = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class DecorationsManager {
  constructor(_editor, _model) {
    this._editor = _editor;
    this._model = _model;
    this._decorations = /* @__PURE__ */ new Map();
    this._decorationIgnoreSet = /* @__PURE__ */ new Set();
    this._callOnDispose = new DisposableStore();
    this._callOnModelChange = new DisposableStore();
    this._callOnDispose.add(this._editor.onDidChangeModel(() => this._onModelChanged()));
    this._onModelChanged();
  }
  dispose() {
    this._callOnModelChange.dispose();
    this._callOnDispose.dispose();
    this.removeDecorations();
  }
  _onModelChanged() {
    this._callOnModelChange.clear();
    const model = this._editor.getModel();
    if (!model) {
      return;
    }
    for (const ref2 of this._model.references) {
      if (ref2.uri.toString() === model.uri.toString()) {
        this._addDecorations(ref2.parent);
        return;
      }
    }
  }
  _addDecorations(reference) {
    if (!this._editor.hasModel()) {
      return;
    }
    this._callOnModelChange.add(this._editor.getModel().onDidChangeDecorations(() => this._onDecorationChanged()));
    const newDecorations = [];
    const newDecorationsActualIndex = [];
    for (let i = 0, len = reference.children.length; i < len; i++) {
      const oneReference = reference.children[i];
      if (this._decorationIgnoreSet.has(oneReference.id)) {
        continue;
      }
      if (oneReference.uri.toString() !== this._editor.getModel().uri.toString()) {
        continue;
      }
      newDecorations.push({
        range: oneReference.range,
        options: DecorationsManager.DecorationOptions
      });
      newDecorationsActualIndex.push(i);
    }
    this._editor.changeDecorations((changeAccessor) => {
      const decorations2 = changeAccessor.deltaDecorations([], newDecorations);
      for (let i = 0; i < decorations2.length; i++) {
        this._decorations.set(decorations2[i], reference.children[newDecorationsActualIndex[i]]);
      }
    });
  }
  _onDecorationChanged() {
    const toRemove = [];
    const model = this._editor.getModel();
    if (!model) {
      return;
    }
    for (const [decorationId, reference] of this._decorations) {
      const newRange = model.getDecorationRange(decorationId);
      if (!newRange) {
        continue;
      }
      let ignore = false;
      if (Range$2.equalsRange(newRange, reference.range)) {
        continue;
      }
      if (Range$2.spansMultipleLines(newRange)) {
        ignore = true;
      } else {
        const lineLength = reference.range.endColumn - reference.range.startColumn;
        const newLineLength = newRange.endColumn - newRange.startColumn;
        if (lineLength !== newLineLength) {
          ignore = true;
        }
      }
      if (ignore) {
        this._decorationIgnoreSet.add(reference.id);
        toRemove.push(decorationId);
      } else {
        reference.range = newRange;
      }
    }
    for (let i = 0, len = toRemove.length; i < len; i++) {
      this._decorations.delete(toRemove[i]);
    }
    this._editor.removeDecorations(toRemove);
  }
  removeDecorations() {
    this._editor.removeDecorations([...this._decorations.keys()]);
    this._decorations.clear();
  }
}
DecorationsManager.DecorationOptions = ModelDecorationOptions.register({
  description: "reference-decoration",
  stickiness: 1,
  className: "reference-decoration"
});
class LayoutData {
  constructor() {
    this.ratio = 0.7;
    this.heightInLines = 18;
  }
  static fromJSON(raw) {
    let ratio;
    let heightInLines;
    try {
      const data = JSON.parse(raw);
      ratio = data.ratio;
      heightInLines = data.heightInLines;
    } catch (_a2) {
    }
    return {
      ratio: ratio || 0.7,
      heightInLines: heightInLines || 18
    };
  }
}
class ReferencesTree extends WorkbenchAsyncDataTree {
}
let ReferenceWidget = class ReferenceWidget2 extends PeekViewWidget {
  constructor(editor2, _defaultTreeKeyboardSupport, layoutData, themeService, _textModelResolverService, _instantiationService, _peekViewService, _uriLabel, _undoRedoService, _keybindingService, _languageService, _languageConfigurationService) {
    super(editor2, { showFrame: false, showArrow: true, isResizeable: true, isAccessible: true, supportOnTitleClick: true }, _instantiationService);
    this._defaultTreeKeyboardSupport = _defaultTreeKeyboardSupport;
    this.layoutData = layoutData;
    this._textModelResolverService = _textModelResolverService;
    this._instantiationService = _instantiationService;
    this._peekViewService = _peekViewService;
    this._uriLabel = _uriLabel;
    this._undoRedoService = _undoRedoService;
    this._keybindingService = _keybindingService;
    this._languageService = _languageService;
    this._languageConfigurationService = _languageConfigurationService;
    this._disposeOnNewModel = new DisposableStore();
    this._callOnDispose = new DisposableStore();
    this._onDidSelectReference = new Emitter$1();
    this.onDidSelectReference = this._onDidSelectReference.event;
    this._dim = new Dimension(0, 0);
    this._applyTheme(themeService.getColorTheme());
    this._callOnDispose.add(themeService.onDidColorThemeChange(this._applyTheme.bind(this)));
    this._peekViewService.addExclusiveWidget(editor2, this);
    this.create();
  }
  dispose() {
    this.setModel(void 0);
    this._callOnDispose.dispose();
    this._disposeOnNewModel.dispose();
    dispose(this._preview);
    dispose(this._previewNotAvailableMessage);
    dispose(this._tree);
    dispose(this._previewModelReference);
    this._splitView.dispose();
    super.dispose();
  }
  _applyTheme(theme) {
    const borderColor = theme.getColor(peekViewBorder) || Color.transparent;
    this.style({
      arrowColor: borderColor,
      frameColor: borderColor,
      headerBackgroundColor: theme.getColor(peekViewTitleBackground) || Color.transparent,
      primaryHeadingColor: theme.getColor(peekViewTitleForeground),
      secondaryHeadingColor: theme.getColor(peekViewTitleInfoForeground)
    });
  }
  show(where) {
    super.show(where, this.layoutData.heightInLines || 18);
  }
  focusOnReferenceTree() {
    this._tree.domFocus();
  }
  focusOnPreviewEditor() {
    this._preview.focus();
  }
  isPreviewEditorFocused() {
    return this._preview.hasTextFocus();
  }
  _onTitleClick(e) {
    if (this._preview && this._preview.getModel()) {
      this._onDidSelectReference.fire({
        element: this._getFocusedReference(),
        kind: e.ctrlKey || e.metaKey || e.altKey ? "side" : "open",
        source: "title"
      });
    }
  }
  _fillBody(containerElement) {
    this.setCssClass("reference-zone-widget");
    this._messageContainer = append$1(containerElement, $$d("div.messages"));
    hide(this._messageContainer);
    this._splitView = new SplitView(containerElement, {
      orientation: 1
      /* Orientation.HORIZONTAL */
    });
    this._previewContainer = append$1(containerElement, $$d("div.preview.inline"));
    const options = {
      scrollBeyondLastLine: false,
      scrollbar: {
        verticalScrollbarSize: 14,
        horizontal: "auto",
        useShadows: true,
        verticalHasArrows: false,
        horizontalHasArrows: false,
        alwaysConsumeMouseWheel: false
      },
      overviewRulerLanes: 2,
      fixedOverflowWidgets: true,
      minimap: {
        enabled: false
      }
    };
    this._preview = this._instantiationService.createInstance(EmbeddedCodeEditorWidget, this._previewContainer, options, {}, this.editor);
    hide(this._previewContainer);
    this._previewNotAvailableMessage = new TextModel(localize("missingPreviewMessage", "no preview available"), PLAINTEXT_LANGUAGE_ID, TextModel.DEFAULT_CREATION_OPTIONS, null, this._undoRedoService, this._languageService, this._languageConfigurationService);
    this._treeContainer = append$1(containerElement, $$d("div.ref-tree.inline"));
    const treeOptions = {
      keyboardSupport: this._defaultTreeKeyboardSupport,
      accessibilityProvider: new AccessibilityProvider(),
      keyboardNavigationLabelProvider: this._instantiationService.createInstance(StringRepresentationProvider),
      identityProvider: new IdentityProvider(),
      openOnSingleClick: true,
      selectionNavigation: true,
      overrideStyles: {
        listBackground: peekViewResultsBackground
      }
    };
    if (this._defaultTreeKeyboardSupport) {
      this._callOnDispose.add(addStandardDisposableListener(this._treeContainer, "keydown", (e) => {
        if (e.equals(
          9
          /* KeyCode.Escape */
        )) {
          this._keybindingService.dispatchEvent(e, e.target);
          e.stopPropagation();
        }
      }, true));
    }
    this._tree = this._instantiationService.createInstance(ReferencesTree, "ReferencesWidget", this._treeContainer, new Delegate(), [
      this._instantiationService.createInstance(FileReferencesRenderer),
      this._instantiationService.createInstance(OneReferenceRenderer)
    ], this._instantiationService.createInstance(DataSource), treeOptions);
    this._splitView.addView({
      onDidChange: Event$1.None,
      element: this._previewContainer,
      minimumSize: 200,
      maximumSize: Number.MAX_VALUE,
      layout: (width) => {
        this._preview.layout({ height: this._dim.height, width });
      }
    }, Sizing.Distribute);
    this._splitView.addView({
      onDidChange: Event$1.None,
      element: this._treeContainer,
      minimumSize: 100,
      maximumSize: Number.MAX_VALUE,
      layout: (width) => {
        this._treeContainer.style.height = `${this._dim.height}px`;
        this._treeContainer.style.width = `${width}px`;
        this._tree.layout(this._dim.height, width);
      }
    }, Sizing.Distribute);
    this._disposables.add(this._splitView.onDidSashChange(() => {
      if (this._dim.width) {
        this.layoutData.ratio = this._splitView.getViewSize(0) / this._dim.width;
      }
    }, void 0));
    const onEvent = (element, kind) => {
      if (element instanceof OneReference) {
        if (kind === "show") {
          this._revealReference(element, false);
        }
        this._onDidSelectReference.fire({ element, kind, source: "tree" });
      }
    };
    this._tree.onDidOpen((e) => {
      if (e.sideBySide) {
        onEvent(e.element, "side");
      } else if (e.editorOptions.pinned) {
        onEvent(e.element, "goto");
      } else {
        onEvent(e.element, "show");
      }
    });
    hide(this._treeContainer);
  }
  _onWidth(width) {
    if (this._dim) {
      this._doLayoutBody(this._dim.height, width);
    }
  }
  _doLayoutBody(heightInPixel, widthInPixel) {
    super._doLayoutBody(heightInPixel, widthInPixel);
    this._dim = new Dimension(widthInPixel, heightInPixel);
    this.layoutData.heightInLines = this._viewZone ? this._viewZone.heightInLines : this.layoutData.heightInLines;
    this._splitView.layout(widthInPixel);
    this._splitView.resizeView(0, widthInPixel * this.layoutData.ratio);
  }
  setSelection(selection) {
    return this._revealReference(selection, true).then(() => {
      if (!this._model) {
        return;
      }
      this._tree.setSelection([selection]);
      this._tree.setFocus([selection]);
    });
  }
  setModel(newModel) {
    this._disposeOnNewModel.clear();
    this._model = newModel;
    if (this._model) {
      return this._onNewModel();
    }
    return Promise.resolve();
  }
  _onNewModel() {
    if (!this._model) {
      return Promise.resolve(void 0);
    }
    if (this._model.isEmpty) {
      this.setTitle("");
      this._messageContainer.innerText = localize("noResults", "No results");
      show(this._messageContainer);
      return Promise.resolve(void 0);
    }
    hide(this._messageContainer);
    this._decorationsManager = new DecorationsManager(this._preview, this._model);
    this._disposeOnNewModel.add(this._decorationsManager);
    this._disposeOnNewModel.add(this._model.onDidChangeReferenceRange((reference) => this._tree.rerender(reference)));
    this._disposeOnNewModel.add(this._preview.onMouseDown((e) => {
      const { event, target } = e;
      if (event.detail !== 2) {
        return;
      }
      const element = this._getFocusedReference();
      if (!element) {
        return;
      }
      this._onDidSelectReference.fire({
        element: { uri: element.uri, range: target.range },
        kind: event.ctrlKey || event.metaKey || event.altKey ? "side" : "open",
        source: "editor"
      });
    }));
    this.container.classList.add("results-loaded");
    show(this._treeContainer);
    show(this._previewContainer);
    this._splitView.layout(this._dim.width);
    this.focusOnReferenceTree();
    return this._tree.setInput(this._model.groups.length === 1 ? this._model.groups[0] : this._model);
  }
  _getFocusedReference() {
    const [element] = this._tree.getFocus();
    if (element instanceof OneReference) {
      return element;
    } else if (element instanceof FileReferences) {
      if (element.children.length > 0) {
        return element.children[0];
      }
    }
    return void 0;
  }
  revealReference(reference) {
    return __awaiter$16(this, void 0, void 0, function* () {
      yield this._revealReference(reference, false);
      this._onDidSelectReference.fire({ element: reference, kind: "goto", source: "tree" });
    });
  }
  _revealReference(reference, revealParent) {
    return __awaiter$16(this, void 0, void 0, function* () {
      if (this._revealedReference === reference) {
        return;
      }
      this._revealedReference = reference;
      if (reference.uri.scheme !== Schemas.inMemory) {
        this.setTitle(basenameOrAuthority(reference.uri), this._uriLabel.getUriLabel(dirname$3(reference.uri)));
      } else {
        this.setTitle(localize("peekView.alternateTitle", "References"));
      }
      const promise = this._textModelResolverService.createModelReference(reference.uri);
      if (this._tree.getInput() === reference.parent) {
        this._tree.reveal(reference);
      } else {
        if (revealParent) {
          this._tree.reveal(reference.parent);
        }
        yield this._tree.expand(reference.parent);
        this._tree.reveal(reference);
      }
      const ref2 = yield promise;
      if (!this._model) {
        ref2.dispose();
        return;
      }
      dispose(this._previewModelReference);
      const model = ref2.object;
      if (model) {
        const scrollType = this._preview.getModel() === model.textEditorModel ? 0 : 1;
        const sel = Range$2.lift(reference.range).collapseToStart();
        this._previewModelReference = ref2;
        this._preview.setModel(model.textEditorModel);
        this._preview.setSelection(sel);
        this._preview.revealRangeInCenter(sel, scrollType);
      } else {
        this._preview.setModel(this._previewNotAvailableMessage);
        ref2.dispose();
      }
    });
  }
};
ReferenceWidget = __decorate$1B([
  __param$1z(3, IThemeService),
  __param$1z(4, ITextModelService),
  __param$1z(5, IInstantiationService),
  __param$1z(6, IPeekViewService),
  __param$1z(7, ILabelService),
  __param$1z(8, IUndoRedoService),
  __param$1z(9, IKeybindingService),
  __param$1z(10, ILanguageService),
  __param$1z(11, ILanguageConfigurationService)
], ReferenceWidget);
var __decorate$1A = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1y = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$15 = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
const ctxReferenceSearchVisible = new RawContextKey("referenceSearchVisible", false, localize("referenceSearchVisible", "Whether reference peek is visible, like 'Peek References' or 'Peek Definition'"));
let ReferencesController = class ReferencesController2 {
  static get(editor2) {
    return editor2.getContribution(ReferencesController2.ID);
  }
  constructor(_defaultTreeKeyboardSupport, _editor, contextKeyService, _editorService, _notificationService, _instantiationService, _storageService, _configurationService) {
    this._defaultTreeKeyboardSupport = _defaultTreeKeyboardSupport;
    this._editor = _editor;
    this._editorService = _editorService;
    this._notificationService = _notificationService;
    this._instantiationService = _instantiationService;
    this._storageService = _storageService;
    this._configurationService = _configurationService;
    this._disposables = new DisposableStore();
    this._requestIdPool = 0;
    this._ignoreModelChangeEvent = false;
    this._referenceSearchVisible = ctxReferenceSearchVisible.bindTo(contextKeyService);
  }
  dispose() {
    var _a2, _b2;
    this._referenceSearchVisible.reset();
    this._disposables.dispose();
    (_a2 = this._widget) === null || _a2 === void 0 ? void 0 : _a2.dispose();
    (_b2 = this._model) === null || _b2 === void 0 ? void 0 : _b2.dispose();
    this._widget = void 0;
    this._model = void 0;
  }
  toggleWidget(range2, modelPromise, peekMode) {
    let widgetPosition;
    if (this._widget) {
      widgetPosition = this._widget.position;
    }
    this.closeWidget();
    if (!!widgetPosition && range2.containsPosition(widgetPosition)) {
      return;
    }
    this._peekMode = peekMode;
    this._referenceSearchVisible.set(true);
    this._disposables.add(this._editor.onDidChangeModelLanguage(() => {
      this.closeWidget();
    }));
    this._disposables.add(this._editor.onDidChangeModel(() => {
      if (!this._ignoreModelChangeEvent) {
        this.closeWidget();
      }
    }));
    const storageKey = "peekViewLayout";
    const data = LayoutData.fromJSON(this._storageService.get(storageKey, 0, "{}"));
    this._widget = this._instantiationService.createInstance(ReferenceWidget, this._editor, this._defaultTreeKeyboardSupport, data);
    this._widget.setTitle(localize("labelLoading", "Loading..."));
    this._widget.show(range2);
    this._disposables.add(this._widget.onDidClose(() => {
      modelPromise.cancel();
      if (this._widget) {
        this._storageService.store(
          storageKey,
          JSON.stringify(this._widget.layoutData),
          0,
          1
          /* StorageTarget.MACHINE */
        );
        this._widget = void 0;
      }
      this.closeWidget();
    }));
    this._disposables.add(this._widget.onDidSelectReference((event) => {
      const { element, kind } = event;
      if (!element) {
        return;
      }
      switch (kind) {
        case "open":
          if (event.source !== "editor" || !this._configurationService.getValue("editor.stablePeek")) {
            this.openReference(element, false, false);
          }
          break;
        case "side":
          this.openReference(element, true, false);
          break;
        case "goto":
          if (peekMode) {
            this._gotoReference(element, true);
          } else {
            this.openReference(element, false, true);
          }
          break;
      }
    }));
    const requestId = ++this._requestIdPool;
    modelPromise.then((model) => {
      var _a2;
      if (requestId !== this._requestIdPool || !this._widget) {
        model.dispose();
        return void 0;
      }
      (_a2 = this._model) === null || _a2 === void 0 ? void 0 : _a2.dispose();
      this._model = model;
      return this._widget.setModel(this._model).then(() => {
        if (this._widget && this._model && this._editor.hasModel()) {
          if (!this._model.isEmpty) {
            this._widget.setMetaTitle(localize("metaTitle.N", "{0} ({1})", this._model.title, this._model.references.length));
          } else {
            this._widget.setMetaTitle("");
          }
          const uri = this._editor.getModel().uri;
          const pos = new Position$2(range2.startLineNumber, range2.startColumn);
          const selection = this._model.nearestReference(uri, pos);
          if (selection) {
            return this._widget.setSelection(selection).then(() => {
              if (this._widget && this._editor.getOption(
                85
                /* EditorOption.peekWidgetDefaultFocus */
              ) === "editor") {
                this._widget.focusOnPreviewEditor();
              }
            });
          }
        }
        return void 0;
      });
    }, (error2) => {
      this._notificationService.error(error2);
    });
  }
  changeFocusBetweenPreviewAndReferences() {
    if (!this._widget) {
      return;
    }
    if (this._widget.isPreviewEditorFocused()) {
      this._widget.focusOnReferenceTree();
    } else {
      this._widget.focusOnPreviewEditor();
    }
  }
  goToNextOrPreviousReference(fwd) {
    return __awaiter$15(this, void 0, void 0, function* () {
      if (!this._editor.hasModel() || !this._model || !this._widget) {
        return;
      }
      const currentPosition = this._widget.position;
      if (!currentPosition) {
        return;
      }
      const source = this._model.nearestReference(this._editor.getModel().uri, currentPosition);
      if (!source) {
        return;
      }
      const target = this._model.nextOrPreviousReference(source, fwd);
      const editorFocus = this._editor.hasTextFocus();
      const previewEditorFocus = this._widget.isPreviewEditorFocused();
      yield this._widget.setSelection(target);
      yield this._gotoReference(target, false);
      if (editorFocus) {
        this._editor.focus();
      } else if (this._widget && previewEditorFocus) {
        this._widget.focusOnPreviewEditor();
      }
    });
  }
  revealReference(reference) {
    return __awaiter$15(this, void 0, void 0, function* () {
      if (!this._editor.hasModel() || !this._model || !this._widget) {
        return;
      }
      yield this._widget.revealReference(reference);
    });
  }
  closeWidget(focusEditor = true) {
    var _a2, _b2;
    (_a2 = this._widget) === null || _a2 === void 0 ? void 0 : _a2.dispose();
    (_b2 = this._model) === null || _b2 === void 0 ? void 0 : _b2.dispose();
    this._referenceSearchVisible.reset();
    this._disposables.clear();
    this._widget = void 0;
    this._model = void 0;
    if (focusEditor) {
      this._editor.focus();
    }
    this._requestIdPool += 1;
  }
  _gotoReference(ref2, pinned) {
    var _a2;
    (_a2 = this._widget) === null || _a2 === void 0 ? void 0 : _a2.hide();
    this._ignoreModelChangeEvent = true;
    const range2 = Range$2.lift(ref2.range).collapseToStart();
    return this._editorService.openCodeEditor({
      resource: ref2.uri,
      options: { selection: range2, selectionSource: "code.jump", pinned }
    }, this._editor).then((openedEditor) => {
      var _a3;
      this._ignoreModelChangeEvent = false;
      if (!openedEditor || !this._widget) {
        this.closeWidget();
        return;
      }
      if (this._editor === openedEditor) {
        this._widget.show(range2);
        this._widget.focusOnReferenceTree();
      } else {
        const other = ReferencesController2.get(openedEditor);
        const model = this._model.clone();
        this.closeWidget();
        openedEditor.focus();
        other === null || other === void 0 ? void 0 : other.toggleWidget(range2, createCancelablePromise((_) => Promise.resolve(model)), (_a3 = this._peekMode) !== null && _a3 !== void 0 ? _a3 : false);
      }
    }, (err) => {
      this._ignoreModelChangeEvent = false;
      onUnexpectedError(err);
    });
  }
  openReference(ref2, sideBySide, pinned) {
    if (!sideBySide) {
      this.closeWidget();
    }
    const { uri, range: range2 } = ref2;
    this._editorService.openCodeEditor({
      resource: uri,
      options: { selection: range2, selectionSource: "code.jump", pinned }
    }, this._editor, sideBySide);
  }
};
ReferencesController.ID = "editor.contrib.referencesController";
ReferencesController = __decorate$1A([
  __param$1y(2, IContextKeyService),
  __param$1y(3, ICodeEditorService),
  __param$1y(4, INotificationService),
  __param$1y(5, IInstantiationService),
  __param$1y(6, IStorageService),
  __param$1y(7, IConfigurationService)
], ReferencesController);
function withController(accessor, fn) {
  const outerEditor = getOuterEditor(accessor);
  if (!outerEditor) {
    return;
  }
  const controller = ReferencesController.get(outerEditor);
  if (controller) {
    fn(controller);
  }
}
KeybindingsRegistry.registerCommandAndKeybindingRule({
  id: "togglePeekWidgetFocus",
  weight: 100,
  primary: KeyChord(
    2048 | 41,
    60
    /* KeyCode.F2 */
  ),
  when: ContextKeyExpr.or(ctxReferenceSearchVisible, PeekContext.inPeekEditor),
  handler(accessor) {
    withController(accessor, (controller) => {
      controller.changeFocusBetweenPreviewAndReferences();
    });
  }
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
  id: "goToNextReference",
  weight: 100 - 10,
  primary: 62,
  secondary: [
    70
    /* KeyCode.F12 */
  ],
  when: ContextKeyExpr.or(ctxReferenceSearchVisible, PeekContext.inPeekEditor),
  handler(accessor) {
    withController(accessor, (controller) => {
      controller.goToNextOrPreviousReference(true);
    });
  }
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
  id: "goToPreviousReference",
  weight: 100 - 10,
  primary: 1024 | 62,
  secondary: [
    1024 | 70
    /* KeyCode.F12 */
  ],
  when: ContextKeyExpr.or(ctxReferenceSearchVisible, PeekContext.inPeekEditor),
  handler(accessor) {
    withController(accessor, (controller) => {
      controller.goToNextOrPreviousReference(false);
    });
  }
});
CommandsRegistry.registerCommandAlias("goToNextReferenceFromEmbeddedEditor", "goToNextReference");
CommandsRegistry.registerCommandAlias("goToPreviousReferenceFromEmbeddedEditor", "goToPreviousReference");
CommandsRegistry.registerCommandAlias("closeReferenceSearchEditor", "closeReferenceSearch");
CommandsRegistry.registerCommand("closeReferenceSearch", (accessor) => withController(accessor, (controller) => controller.closeWidget()));
KeybindingsRegistry.registerKeybindingRule({
  id: "closeReferenceSearch",
  weight: 100 - 101,
  primary: 9,
  secondary: [
    1024 | 9
    /* KeyCode.Escape */
  ],
  when: ContextKeyExpr.and(PeekContext.inPeekEditor, ContextKeyExpr.not("config.editor.stablePeek"))
});
KeybindingsRegistry.registerKeybindingRule({
  id: "closeReferenceSearch",
  weight: 200 + 50,
  primary: 9,
  secondary: [
    1024 | 9
    /* KeyCode.Escape */
  ],
  when: ContextKeyExpr.and(ctxReferenceSearchVisible, ContextKeyExpr.not("config.editor.stablePeek"))
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
  id: "revealReference",
  weight: 200,
  primary: 3,
  mac: {
    primary: 3,
    secondary: [
      2048 | 18
      /* KeyCode.DownArrow */
    ]
  },
  when: ContextKeyExpr.and(ctxReferenceSearchVisible, WorkbenchListFocusContextKey, WorkbenchTreeElementCanCollapse.negate(), WorkbenchTreeElementCanExpand.negate()),
  handler(accessor) {
    var _a2;
    const listService = accessor.get(IListService);
    const focus = (_a2 = listService.lastFocusedList) === null || _a2 === void 0 ? void 0 : _a2.getFocus();
    if (Array.isArray(focus) && focus[0] instanceof OneReference) {
      withController(accessor, (controller) => controller.revealReference(focus[0]));
    }
  }
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
  id: "openReferenceToSide",
  weight: 100,
  primary: 2048 | 3,
  mac: {
    primary: 256 | 3
    /* KeyCode.Enter */
  },
  when: ContextKeyExpr.and(ctxReferenceSearchVisible, WorkbenchListFocusContextKey, WorkbenchTreeElementCanCollapse.negate(), WorkbenchTreeElementCanExpand.negate()),
  handler(accessor) {
    var _a2;
    const listService = accessor.get(IListService);
    const focus = (_a2 = listService.lastFocusedList) === null || _a2 === void 0 ? void 0 : _a2.getFocus();
    if (Array.isArray(focus) && focus[0] instanceof OneReference) {
      withController(accessor, (controller) => controller.openReference(focus[0], true, true));
    }
  }
});
CommandsRegistry.registerCommand("openReference", (accessor) => {
  var _a2;
  const listService = accessor.get(IListService);
  const focus = (_a2 = listService.lastFocusedList) === null || _a2 === void 0 ? void 0 : _a2.getFocus();
  if (Array.isArray(focus) && focus[0] instanceof OneReference) {
    withController(accessor, (controller) => controller.openReference(focus[0], false, true));
  }
});
var __decorate$1z = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1x = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
const ctxHasSymbols = new RawContextKey("hasSymbols", false, localize("hasSymbols", "Whether there are symbol locations that can be navigated via keyboard-only."));
const ISymbolNavigationService = createDecorator("ISymbolNavigationService");
let SymbolNavigationService = class SymbolNavigationService2 {
  constructor(contextKeyService, _editorService, _notificationService, _keybindingService) {
    this._editorService = _editorService;
    this._notificationService = _notificationService;
    this._keybindingService = _keybindingService;
    this._currentModel = void 0;
    this._currentIdx = -1;
    this._ignoreEditorChange = false;
    this._ctxHasSymbols = ctxHasSymbols.bindTo(contextKeyService);
  }
  reset() {
    var _a2, _b2;
    this._ctxHasSymbols.reset();
    (_a2 = this._currentState) === null || _a2 === void 0 ? void 0 : _a2.dispose();
    (_b2 = this._currentMessage) === null || _b2 === void 0 ? void 0 : _b2.dispose();
    this._currentModel = void 0;
    this._currentIdx = -1;
  }
  put(anchor) {
    const refModel = anchor.parent.parent;
    if (refModel.references.length <= 1) {
      this.reset();
      return;
    }
    this._currentModel = refModel;
    this._currentIdx = refModel.references.indexOf(anchor);
    this._ctxHasSymbols.set(true);
    this._showMessage();
    const editorState = new EditorState2(this._editorService);
    const listener = editorState.onDidChange((_) => {
      if (this._ignoreEditorChange) {
        return;
      }
      const editor2 = this._editorService.getActiveCodeEditor();
      if (!editor2) {
        return;
      }
      const model = editor2.getModel();
      const position = editor2.getPosition();
      if (!model || !position) {
        return;
      }
      let seenUri = false;
      let seenPosition = false;
      for (const reference of refModel.references) {
        if (isEqual(reference.uri, model.uri)) {
          seenUri = true;
          seenPosition = seenPosition || Range$2.containsPosition(reference.range, position);
        } else if (seenUri) {
          break;
        }
      }
      if (!seenUri || !seenPosition) {
        this.reset();
      }
    });
    this._currentState = combinedDisposable(editorState, listener);
  }
  revealNext(source) {
    if (!this._currentModel) {
      return Promise.resolve();
    }
    this._currentIdx += 1;
    this._currentIdx %= this._currentModel.references.length;
    const reference = this._currentModel.references[this._currentIdx];
    this._showMessage();
    this._ignoreEditorChange = true;
    return this._editorService.openCodeEditor({
      resource: reference.uri,
      options: {
        selection: Range$2.collapseToStart(reference.range),
        selectionRevealType: 3
        /* TextEditorSelectionRevealType.NearTopIfOutsideViewport */
      }
    }, source).finally(() => {
      this._ignoreEditorChange = false;
    });
  }
  _showMessage() {
    var _a2;
    (_a2 = this._currentMessage) === null || _a2 === void 0 ? void 0 : _a2.dispose();
    const kb = this._keybindingService.lookupKeybinding("editor.gotoNextSymbolFromResult");
    const message = kb ? localize("location.kb", "Symbol {0} of {1}, {2} for next", this._currentIdx + 1, this._currentModel.references.length, kb.getLabel()) : localize("location", "Symbol {0} of {1}", this._currentIdx + 1, this._currentModel.references.length);
    this._currentMessage = this._notificationService.status(message);
  }
};
SymbolNavigationService = __decorate$1z([
  __param$1x(0, IContextKeyService),
  __param$1x(1, ICodeEditorService),
  __param$1x(2, INotificationService),
  __param$1x(3, IKeybindingService)
], SymbolNavigationService);
registerSingleton(
  ISymbolNavigationService,
  SymbolNavigationService,
  1
  /* InstantiationType.Delayed */
);
registerEditorCommand(new class extends EditorCommand {
  constructor() {
    super({
      id: "editor.gotoNextSymbolFromResult",
      precondition: ctxHasSymbols,
      kbOpts: {
        weight: 100,
        primary: 70
        /* KeyCode.F12 */
      }
    });
  }
  runEditorCommand(accessor, editor2) {
    return accessor.get(ISymbolNavigationService).revealNext(editor2);
  }
}());
KeybindingsRegistry.registerCommandAndKeybindingRule({
  id: "editor.gotoNextSymbolFromResult.cancel",
  weight: 100,
  when: ctxHasSymbols,
  primary: 9,
  handler(accessor) {
    accessor.get(ISymbolNavigationService).reset();
  }
});
let EditorState2 = class EditorState3 {
  constructor(editorService) {
    this._listener = /* @__PURE__ */ new Map();
    this._disposables = new DisposableStore();
    this._onDidChange = new Emitter$1();
    this.onDidChange = this._onDidChange.event;
    this._disposables.add(editorService.onCodeEditorRemove(this._onDidRemoveEditor, this));
    this._disposables.add(editorService.onCodeEditorAdd(this._onDidAddEditor, this));
    editorService.listCodeEditors().forEach(this._onDidAddEditor, this);
  }
  dispose() {
    this._disposables.dispose();
    this._onDidChange.dispose();
    dispose(this._listener.values());
  }
  _onDidAddEditor(editor2) {
    this._listener.set(editor2, combinedDisposable(editor2.onDidChangeCursorPosition((_) => this._onDidChange.fire({ editor: editor2 })), editor2.onDidChangeModelContent((_) => this._onDidChange.fire({ editor: editor2 }))));
  }
  _onDidRemoveEditor(editor2) {
    var _a2;
    (_a2 = this._listener.get(editor2)) === null || _a2 === void 0 ? void 0 : _a2.dispose();
    this._listener.delete(editor2);
  }
};
EditorState2 = __decorate$1z([
  __param$1x(0, ICodeEditorService)
], EditorState2);
var __awaiter$14 = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
function getLocationLinks(model, position, registry, provide2) {
  return __awaiter$14(this, void 0, void 0, function* () {
    const provider = registry.ordered(model);
    const promises = provider.map((provider2) => {
      return Promise.resolve(provide2(provider2, model, position)).then(void 0, (err) => {
        onUnexpectedExternalError(err);
        return void 0;
      });
    });
    const values = yield Promise.all(promises);
    return coalesce(values.flat());
  });
}
function getDefinitionsAtPosition(registry, model, position, token) {
  return getLocationLinks(model, position, registry, (provider, model2, position2) => {
    return provider.provideDefinition(model2, position2, token);
  });
}
function getDeclarationsAtPosition(registry, model, position, token) {
  return getLocationLinks(model, position, registry, (provider, model2, position2) => {
    return provider.provideDeclaration(model2, position2, token);
  });
}
function getImplementationsAtPosition(registry, model, position, token) {
  return getLocationLinks(model, position, registry, (provider, model2, position2) => {
    return provider.provideImplementation(model2, position2, token);
  });
}
function getTypeDefinitionsAtPosition(registry, model, position, token) {
  return getLocationLinks(model, position, registry, (provider, model2, position2) => {
    return provider.provideTypeDefinition(model2, position2, token);
  });
}
function getReferencesAtPosition(registry, model, position, compact, token) {
  return getLocationLinks(model, position, registry, (provider, model2, position2) => __awaiter$14(this, void 0, void 0, function* () {
    const result2 = yield provider.provideReferences(model2, position2, { includeDeclaration: true }, token);
    if (!compact || !result2 || result2.length !== 2) {
      return result2;
    }
    const resultWithoutDeclaration = yield provider.provideReferences(model2, position2, { includeDeclaration: false }, token);
    if (resultWithoutDeclaration && resultWithoutDeclaration.length === 1) {
      return resultWithoutDeclaration;
    }
    return result2;
  }));
}
function _sortedAndDeduped(callback) {
  return __awaiter$14(this, void 0, void 0, function* () {
    const rawLinks = yield callback();
    const model = new ReferencesModel(rawLinks, "");
    const modelLinks = model.references.map((ref2) => ref2.link);
    model.dispose();
    return modelLinks;
  });
}
registerModelAndPositionCommand("_executeDefinitionProvider", (accessor, model, position) => {
  const languageFeaturesService = accessor.get(ILanguageFeaturesService);
  const promise = getDefinitionsAtPosition(languageFeaturesService.definitionProvider, model, position, CancellationToken.None);
  return _sortedAndDeduped(() => promise);
});
registerModelAndPositionCommand("_executeTypeDefinitionProvider", (accessor, model, position) => {
  const languageFeaturesService = accessor.get(ILanguageFeaturesService);
  const promise = getTypeDefinitionsAtPosition(languageFeaturesService.typeDefinitionProvider, model, position, CancellationToken.None);
  return _sortedAndDeduped(() => promise);
});
registerModelAndPositionCommand("_executeDeclarationProvider", (accessor, model, position) => {
  const languageFeaturesService = accessor.get(ILanguageFeaturesService);
  const promise = getDeclarationsAtPosition(languageFeaturesService.declarationProvider, model, position, CancellationToken.None);
  return _sortedAndDeduped(() => promise);
});
registerModelAndPositionCommand("_executeReferenceProvider", (accessor, model, position) => {
  const languageFeaturesService = accessor.get(ILanguageFeaturesService);
  const promise = getReferencesAtPosition(languageFeaturesService.referenceProvider, model, position, false, CancellationToken.None);
  return _sortedAndDeduped(() => promise);
});
registerModelAndPositionCommand("_executeImplementationProvider", (accessor, model, position) => {
  const languageFeaturesService = accessor.get(ILanguageFeaturesService);
  const promise = getImplementationsAtPosition(languageFeaturesService.implementationProvider, model, position, CancellationToken.None);
  return _sortedAndDeduped(() => promise);
});
var __awaiter$13 = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var _a$1, _b, _c, _d, _e, _f, _g, _h;
MenuRegistry.appendMenuItem(MenuId.EditorContext, {
  submenu: MenuId.EditorContextPeek,
  title: localize("peek.submenu", "Peek"),
  group: "navigation",
  order: 100
});
class SymbolNavigationAnchor {
  static is(thing) {
    if (!thing || typeof thing !== "object") {
      return false;
    }
    if (thing instanceof SymbolNavigationAnchor) {
      return true;
    }
    if (Position$2.isIPosition(thing.position) && thing.model) {
      return true;
    }
    return false;
  }
  constructor(model, position) {
    this.model = model;
    this.position = position;
  }
}
class SymbolNavigationAction extends EditorAction2 {
  static all() {
    return SymbolNavigationAction._allSymbolNavigationCommands.values();
  }
  static _patchConfig(opts) {
    const result2 = Object.assign(Object.assign({}, opts), { f1: true });
    if (result2.menu) {
      for (const item of Iterable.wrap(result2.menu)) {
        if (item.id === MenuId.EditorContext || item.id === MenuId.EditorContextPeek) {
          item.when = ContextKeyExpr.and(opts.precondition, item.when);
        }
      }
    }
    return result2;
  }
  constructor(configuration, opts) {
    super(SymbolNavigationAction._patchConfig(opts));
    this.configuration = configuration;
    SymbolNavigationAction._allSymbolNavigationCommands.set(opts.id, this);
  }
  runEditorCommand(accessor, editor2, arg, range2) {
    if (!editor2.hasModel()) {
      return Promise.resolve(void 0);
    }
    const notificationService = accessor.get(INotificationService);
    const editorService = accessor.get(ICodeEditorService);
    const progressService = accessor.get(IEditorProgressService);
    const symbolNavService = accessor.get(ISymbolNavigationService);
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const instaService = accessor.get(IInstantiationService);
    const model = editor2.getModel();
    const position = editor2.getPosition();
    const anchor = SymbolNavigationAnchor.is(arg) ? arg : new SymbolNavigationAnchor(model, position);
    const cts = new EditorStateCancellationTokenSource(
      editor2,
      1 | 4
      /* CodeEditorStateFlag.Position */
    );
    const promise = raceCancellation(this._getLocationModel(languageFeaturesService, anchor.model, anchor.position, cts.token), cts.token).then((references) => __awaiter$13(this, void 0, void 0, function* () {
      var _j;
      if (!references || cts.token.isCancellationRequested) {
        return;
      }
      alert(references.ariaMessage);
      let altAction;
      if (references.referenceAt(model.uri, position)) {
        const altActionId = this._getAlternativeCommand(editor2);
        if (!SymbolNavigationAction._activeAlternativeCommands.has(altActionId) && SymbolNavigationAction._allSymbolNavigationCommands.has(altActionId)) {
          altAction = SymbolNavigationAction._allSymbolNavigationCommands.get(altActionId);
        }
      }
      const referenceCount = references.references.length;
      if (referenceCount === 0) {
        if (!this.configuration.muteMessage) {
          const info = model.getWordAtPosition(position);
          (_j = MessageController.get(editor2)) === null || _j === void 0 ? void 0 : _j.showMessage(this._getNoResultFoundMessage(info), position);
        }
      } else if (referenceCount === 1 && altAction) {
        SymbolNavigationAction._activeAlternativeCommands.add(this.desc.id);
        instaService.invokeFunction((accessor2) => altAction.runEditorCommand(accessor2, editor2, arg, range2).finally(() => {
          SymbolNavigationAction._activeAlternativeCommands.delete(this.desc.id);
        }));
      } else {
        return this._onResult(editorService, symbolNavService, editor2, references, range2);
      }
    }), (err) => {
      notificationService.error(err);
    }).finally(() => {
      cts.dispose();
    });
    progressService.showWhile(promise, 250);
    return promise;
  }
  _onResult(editorService, symbolNavService, editor2, model, range2) {
    return __awaiter$13(this, void 0, void 0, function* () {
      const gotoLocation = this._getGoToPreference(editor2);
      if (!(editor2 instanceof EmbeddedCodeEditorWidget) && (this.configuration.openInPeek || gotoLocation === "peek" && model.references.length > 1)) {
        this._openInPeek(editor2, model, range2);
      } else {
        const next = model.firstReference();
        const peek = model.references.length > 1 && gotoLocation === "gotoAndPeek";
        const targetEditor = yield this._openReference(editor2, editorService, next, this.configuration.openToSide, !peek);
        if (peek && targetEditor) {
          this._openInPeek(targetEditor, model, range2);
        } else {
          model.dispose();
        }
        if (gotoLocation === "goto") {
          symbolNavService.put(next);
        }
      }
    });
  }
  _openReference(editor2, editorService, reference, sideBySide, highlight) {
    return __awaiter$13(this, void 0, void 0, function* () {
      let range2 = void 0;
      if (isLocationLink(reference)) {
        range2 = reference.targetSelectionRange;
      }
      if (!range2) {
        range2 = reference.range;
      }
      if (!range2) {
        return void 0;
      }
      const targetEditor = yield editorService.openCodeEditor({
        resource: reference.uri,
        options: {
          selection: Range$2.collapseToStart(range2),
          selectionRevealType: 3,
          selectionSource: "code.jump"
          /* TextEditorSelectionSource.JUMP */
        }
      }, editor2, sideBySide);
      if (!targetEditor) {
        return void 0;
      }
      if (highlight) {
        const modelNow = targetEditor.getModel();
        const decorations2 = targetEditor.createDecorationsCollection([{ range: range2, options: { description: "symbol-navigate-action-highlight", className: "symbolHighlight" } }]);
        setTimeout(() => {
          if (targetEditor.getModel() === modelNow) {
            decorations2.clear();
          }
        }, 350);
      }
      return targetEditor;
    });
  }
  _openInPeek(target, model, range2) {
    const controller = ReferencesController.get(target);
    if (controller && target.hasModel()) {
      controller.toggleWidget(range2 !== null && range2 !== void 0 ? range2 : target.getSelection(), createCancelablePromise((_) => Promise.resolve(model)), this.configuration.openInPeek);
    } else {
      model.dispose();
    }
  }
}
SymbolNavigationAction._allSymbolNavigationCommands = /* @__PURE__ */ new Map();
SymbolNavigationAction._activeAlternativeCommands = /* @__PURE__ */ new Set();
class DefinitionAction extends SymbolNavigationAction {
  _getLocationModel(languageFeaturesService, model, position, token) {
    return __awaiter$13(this, void 0, void 0, function* () {
      return new ReferencesModel(yield getDefinitionsAtPosition(languageFeaturesService.definitionProvider, model, position, token), localize("def.title", "Definitions"));
    });
  }
  _getNoResultFoundMessage(info) {
    return info && info.word ? localize("noResultWord", "No definition found for '{0}'", info.word) : localize("generic.noResults", "No definition found");
  }
  _getAlternativeCommand(editor2) {
    return editor2.getOption(
      57
      /* EditorOption.gotoLocation */
    ).alternativeDefinitionCommand;
  }
  _getGoToPreference(editor2) {
    return editor2.getOption(
      57
      /* EditorOption.gotoLocation */
    ).multipleDefinitions;
  }
}
registerAction2((_a$1 = class GoToDefinitionAction extends DefinitionAction {
  constructor() {
    super({
      openToSide: false,
      openInPeek: false,
      muteMessage: false
    }, {
      id: GoToDefinitionAction.id,
      title: {
        value: localize("actions.goToDecl.label", "Go to Definition"),
        original: "Go to Definition",
        mnemonicTitle: localize({ key: "miGotoDefinition", comment: ["&& denotes a mnemonic"] }, "Go to &&Definition")
      },
      precondition: ContextKeyExpr.and(EditorContextKeys.hasDefinitionProvider, EditorContextKeys.isInWalkThroughSnippet.toNegated()),
      keybinding: [{
        when: EditorContextKeys.editorTextFocus,
        primary: 70,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }, {
        when: ContextKeyExpr.and(EditorContextKeys.editorTextFocus, IsWebContext),
        primary: 2048 | 70,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }],
      menu: [{
        id: MenuId.EditorContext,
        group: "navigation",
        order: 1.1
      }, {
        id: MenuId.MenubarGoMenu,
        precondition: null,
        group: "4_symbol_nav",
        order: 2
      }]
    });
    CommandsRegistry.registerCommandAlias("editor.action.goToDeclaration", GoToDefinitionAction.id);
  }
}, _a$1.id = "editor.action.revealDefinition", _a$1));
registerAction2((_b = class OpenDefinitionToSideAction extends DefinitionAction {
  constructor() {
    super({
      openToSide: true,
      openInPeek: false,
      muteMessage: false
    }, {
      id: OpenDefinitionToSideAction.id,
      title: {
        value: localize("actions.goToDeclToSide.label", "Open Definition to the Side"),
        original: "Open Definition to the Side"
      },
      precondition: ContextKeyExpr.and(EditorContextKeys.hasDefinitionProvider, EditorContextKeys.isInWalkThroughSnippet.toNegated()),
      keybinding: [{
        when: EditorContextKeys.editorTextFocus,
        primary: KeyChord(
          2048 | 41,
          70
          /* KeyCode.F12 */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }, {
        when: ContextKeyExpr.and(EditorContextKeys.editorTextFocus, IsWebContext),
        primary: KeyChord(
          2048 | 41,
          2048 | 70
          /* KeyCode.F12 */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }]
    });
    CommandsRegistry.registerCommandAlias("editor.action.openDeclarationToTheSide", OpenDefinitionToSideAction.id);
  }
}, _b.id = "editor.action.revealDefinitionAside", _b));
registerAction2((_c = class PeekDefinitionAction extends DefinitionAction {
  constructor() {
    super({
      openToSide: false,
      openInPeek: true,
      muteMessage: false
    }, {
      id: PeekDefinitionAction.id,
      title: {
        value: localize("actions.previewDecl.label", "Peek Definition"),
        original: "Peek Definition"
      },
      precondition: ContextKeyExpr.and(EditorContextKeys.hasDefinitionProvider, PeekContext.notInPeekEditor, EditorContextKeys.isInWalkThroughSnippet.toNegated()),
      keybinding: {
        when: EditorContextKeys.editorTextFocus,
        primary: 512 | 70,
        linux: {
          primary: 2048 | 1024 | 68
          /* KeyCode.F10 */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menu: {
        id: MenuId.EditorContextPeek,
        group: "peek",
        order: 2
      }
    });
    CommandsRegistry.registerCommandAlias("editor.action.previewDeclaration", PeekDefinitionAction.id);
  }
}, _c.id = "editor.action.peekDefinition", _c));
class DeclarationAction extends SymbolNavigationAction {
  _getLocationModel(languageFeaturesService, model, position, token) {
    return __awaiter$13(this, void 0, void 0, function* () {
      return new ReferencesModel(yield getDeclarationsAtPosition(languageFeaturesService.declarationProvider, model, position, token), localize("decl.title", "Declarations"));
    });
  }
  _getNoResultFoundMessage(info) {
    return info && info.word ? localize("decl.noResultWord", "No declaration found for '{0}'", info.word) : localize("decl.generic.noResults", "No declaration found");
  }
  _getAlternativeCommand(editor2) {
    return editor2.getOption(
      57
      /* EditorOption.gotoLocation */
    ).alternativeDeclarationCommand;
  }
  _getGoToPreference(editor2) {
    return editor2.getOption(
      57
      /* EditorOption.gotoLocation */
    ).multipleDeclarations;
  }
}
registerAction2((_d = class GoToDeclarationAction extends DeclarationAction {
  constructor() {
    super({
      openToSide: false,
      openInPeek: false,
      muteMessage: false
    }, {
      id: GoToDeclarationAction.id,
      title: {
        value: localize("actions.goToDeclaration.label", "Go to Declaration"),
        original: "Go to Declaration",
        mnemonicTitle: localize({ key: "miGotoDeclaration", comment: ["&& denotes a mnemonic"] }, "Go to &&Declaration")
      },
      precondition: ContextKeyExpr.and(EditorContextKeys.hasDeclarationProvider, EditorContextKeys.isInWalkThroughSnippet.toNegated()),
      menu: [{
        id: MenuId.EditorContext,
        group: "navigation",
        order: 1.3
      }, {
        id: MenuId.MenubarGoMenu,
        precondition: null,
        group: "4_symbol_nav",
        order: 3
      }]
    });
  }
  _getNoResultFoundMessage(info) {
    return info && info.word ? localize("decl.noResultWord", "No declaration found for '{0}'", info.word) : localize("decl.generic.noResults", "No declaration found");
  }
}, _d.id = "editor.action.revealDeclaration", _d));
registerAction2(class PeekDeclarationAction extends DeclarationAction {
  constructor() {
    super({
      openToSide: false,
      openInPeek: true,
      muteMessage: false
    }, {
      id: "editor.action.peekDeclaration",
      title: {
        value: localize("actions.peekDecl.label", "Peek Declaration"),
        original: "Peek Declaration"
      },
      precondition: ContextKeyExpr.and(EditorContextKeys.hasDeclarationProvider, PeekContext.notInPeekEditor, EditorContextKeys.isInWalkThroughSnippet.toNegated()),
      menu: {
        id: MenuId.EditorContextPeek,
        group: "peek",
        order: 3
      }
    });
  }
});
class TypeDefinitionAction extends SymbolNavigationAction {
  _getLocationModel(languageFeaturesService, model, position, token) {
    return __awaiter$13(this, void 0, void 0, function* () {
      return new ReferencesModel(yield getTypeDefinitionsAtPosition(languageFeaturesService.typeDefinitionProvider, model, position, token), localize("typedef.title", "Type Definitions"));
    });
  }
  _getNoResultFoundMessage(info) {
    return info && info.word ? localize("goToTypeDefinition.noResultWord", "No type definition found for '{0}'", info.word) : localize("goToTypeDefinition.generic.noResults", "No type definition found");
  }
  _getAlternativeCommand(editor2) {
    return editor2.getOption(
      57
      /* EditorOption.gotoLocation */
    ).alternativeTypeDefinitionCommand;
  }
  _getGoToPreference(editor2) {
    return editor2.getOption(
      57
      /* EditorOption.gotoLocation */
    ).multipleTypeDefinitions;
  }
}
registerAction2((_e = class GoToTypeDefinitionAction extends TypeDefinitionAction {
  constructor() {
    super({
      openToSide: false,
      openInPeek: false,
      muteMessage: false
    }, {
      id: GoToTypeDefinitionAction.ID,
      title: {
        value: localize("actions.goToTypeDefinition.label", "Go to Type Definition"),
        original: "Go to Type Definition",
        mnemonicTitle: localize({ key: "miGotoTypeDefinition", comment: ["&& denotes a mnemonic"] }, "Go to &&Type Definition")
      },
      precondition: ContextKeyExpr.and(EditorContextKeys.hasTypeDefinitionProvider, EditorContextKeys.isInWalkThroughSnippet.toNegated()),
      keybinding: {
        when: EditorContextKeys.editorTextFocus,
        primary: 0,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menu: [{
        id: MenuId.EditorContext,
        group: "navigation",
        order: 1.4
      }, {
        id: MenuId.MenubarGoMenu,
        precondition: null,
        group: "4_symbol_nav",
        order: 3
      }]
    });
  }
}, _e.ID = "editor.action.goToTypeDefinition", _e));
registerAction2((_f = class PeekTypeDefinitionAction extends TypeDefinitionAction {
  constructor() {
    super({
      openToSide: false,
      openInPeek: true,
      muteMessage: false
    }, {
      id: PeekTypeDefinitionAction.ID,
      title: {
        value: localize("actions.peekTypeDefinition.label", "Peek Type Definition"),
        original: "Peek Type Definition"
      },
      precondition: ContextKeyExpr.and(EditorContextKeys.hasTypeDefinitionProvider, PeekContext.notInPeekEditor, EditorContextKeys.isInWalkThroughSnippet.toNegated()),
      menu: {
        id: MenuId.EditorContextPeek,
        group: "peek",
        order: 4
      }
    });
  }
}, _f.ID = "editor.action.peekTypeDefinition", _f));
class ImplementationAction extends SymbolNavigationAction {
  _getLocationModel(languageFeaturesService, model, position, token) {
    return __awaiter$13(this, void 0, void 0, function* () {
      return new ReferencesModel(yield getImplementationsAtPosition(languageFeaturesService.implementationProvider, model, position, token), localize("impl.title", "Implementations"));
    });
  }
  _getNoResultFoundMessage(info) {
    return info && info.word ? localize("goToImplementation.noResultWord", "No implementation found for '{0}'", info.word) : localize("goToImplementation.generic.noResults", "No implementation found");
  }
  _getAlternativeCommand(editor2) {
    return editor2.getOption(
      57
      /* EditorOption.gotoLocation */
    ).alternativeImplementationCommand;
  }
  _getGoToPreference(editor2) {
    return editor2.getOption(
      57
      /* EditorOption.gotoLocation */
    ).multipleImplementations;
  }
}
registerAction2((_g = class GoToImplementationAction extends ImplementationAction {
  constructor() {
    super({
      openToSide: false,
      openInPeek: false,
      muteMessage: false
    }, {
      id: GoToImplementationAction.ID,
      title: {
        value: localize("actions.goToImplementation.label", "Go to Implementations"),
        original: "Go to Implementations",
        mnemonicTitle: localize({ key: "miGotoImplementation", comment: ["&& denotes a mnemonic"] }, "Go to &&Implementations")
      },
      precondition: ContextKeyExpr.and(EditorContextKeys.hasImplementationProvider, EditorContextKeys.isInWalkThroughSnippet.toNegated()),
      keybinding: {
        when: EditorContextKeys.editorTextFocus,
        primary: 2048 | 70,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menu: [{
        id: MenuId.EditorContext,
        group: "navigation",
        order: 1.45
      }, {
        id: MenuId.MenubarGoMenu,
        precondition: null,
        group: "4_symbol_nav",
        order: 4
      }]
    });
  }
}, _g.ID = "editor.action.goToImplementation", _g));
registerAction2((_h = class PeekImplementationAction extends ImplementationAction {
  constructor() {
    super({
      openToSide: false,
      openInPeek: true,
      muteMessage: false
    }, {
      id: PeekImplementationAction.ID,
      title: {
        value: localize("actions.peekImplementation.label", "Peek Implementations"),
        original: "Peek Implementations"
      },
      precondition: ContextKeyExpr.and(EditorContextKeys.hasImplementationProvider, PeekContext.notInPeekEditor, EditorContextKeys.isInWalkThroughSnippet.toNegated()),
      keybinding: {
        when: EditorContextKeys.editorTextFocus,
        primary: 2048 | 1024 | 70,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menu: {
        id: MenuId.EditorContextPeek,
        group: "peek",
        order: 5
      }
    });
  }
}, _h.ID = "editor.action.peekImplementation", _h));
class ReferencesAction extends SymbolNavigationAction {
  _getNoResultFoundMessage(info) {
    return info ? localize("references.no", "No references found for '{0}'", info.word) : localize("references.noGeneric", "No references found");
  }
  _getAlternativeCommand(editor2) {
    return editor2.getOption(
      57
      /* EditorOption.gotoLocation */
    ).alternativeReferenceCommand;
  }
  _getGoToPreference(editor2) {
    return editor2.getOption(
      57
      /* EditorOption.gotoLocation */
    ).multipleReferences;
  }
}
registerAction2(class GoToReferencesAction extends ReferencesAction {
  constructor() {
    super({
      openToSide: false,
      openInPeek: false,
      muteMessage: false
    }, {
      id: "editor.action.goToReferences",
      title: {
        value: localize("goToReferences.label", "Go to References"),
        original: "Go to References",
        mnemonicTitle: localize({ key: "miGotoReference", comment: ["&& denotes a mnemonic"] }, "Go to &&References")
      },
      precondition: ContextKeyExpr.and(EditorContextKeys.hasReferenceProvider, PeekContext.notInPeekEditor, EditorContextKeys.isInWalkThroughSnippet.toNegated()),
      keybinding: {
        when: EditorContextKeys.editorTextFocus,
        primary: 1024 | 70,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menu: [{
        id: MenuId.EditorContext,
        group: "navigation",
        order: 1.45
      }, {
        id: MenuId.MenubarGoMenu,
        precondition: null,
        group: "4_symbol_nav",
        order: 5
      }]
    });
  }
  _getLocationModel(languageFeaturesService, model, position, token) {
    return __awaiter$13(this, void 0, void 0, function* () {
      return new ReferencesModel(yield getReferencesAtPosition(languageFeaturesService.referenceProvider, model, position, true, token), localize("ref.title", "References"));
    });
  }
});
registerAction2(class PeekReferencesAction extends ReferencesAction {
  constructor() {
    super({
      openToSide: false,
      openInPeek: true,
      muteMessage: false
    }, {
      id: "editor.action.referenceSearch.trigger",
      title: {
        value: localize("references.action.label", "Peek References"),
        original: "Peek References"
      },
      precondition: ContextKeyExpr.and(EditorContextKeys.hasReferenceProvider, PeekContext.notInPeekEditor, EditorContextKeys.isInWalkThroughSnippet.toNegated()),
      menu: {
        id: MenuId.EditorContextPeek,
        group: "peek",
        order: 6
      }
    });
  }
  _getLocationModel(languageFeaturesService, model, position, token) {
    return __awaiter$13(this, void 0, void 0, function* () {
      return new ReferencesModel(yield getReferencesAtPosition(languageFeaturesService.referenceProvider, model, position, false, token), localize("ref.title", "References"));
    });
  }
});
class GenericGoToLocationAction extends SymbolNavigationAction {
  constructor(config2, _references, _gotoMultipleBehaviour) {
    super(config2, {
      id: "editor.action.goToLocation",
      title: {
        value: localize("label.generic", "Go to Any Symbol"),
        original: "Go to Any Symbol"
      },
      precondition: ContextKeyExpr.and(PeekContext.notInPeekEditor, EditorContextKeys.isInWalkThroughSnippet.toNegated())
    });
    this._references = _references;
    this._gotoMultipleBehaviour = _gotoMultipleBehaviour;
  }
  _getLocationModel(languageFeaturesService, _model, _position, _token) {
    return __awaiter$13(this, void 0, void 0, function* () {
      return new ReferencesModel(this._references, localize("generic.title", "Locations"));
    });
  }
  _getNoResultFoundMessage(info) {
    return info && localize("generic.noResult", "No results for '{0}'", info.word) || "";
  }
  _getGoToPreference(editor2) {
    var _j;
    return (_j = this._gotoMultipleBehaviour) !== null && _j !== void 0 ? _j : editor2.getOption(
      57
      /* EditorOption.gotoLocation */
    ).multipleReferences;
  }
  _getAlternativeCommand() {
    return "";
  }
}
CommandsRegistry.registerCommand({
  id: "editor.action.goToLocations",
  description: {
    description: "Go to locations from a position in a file",
    args: [
      { name: "uri", description: "The text document in which to start", constraint: URI },
      { name: "position", description: "The position at which to start", constraint: Position$2.isIPosition },
      { name: "locations", description: "An array of locations.", constraint: Array },
      { name: "multiple", description: "Define what to do when having multiple results, either `peek`, `gotoAndPeek`, or `goto" },
      { name: "noResultsMessage", description: "Human readable message that shows when locations is empty." }
    ]
  },
  handler: (accessor, resource, position, references, multiple, noResultsMessage, openInPeek) => __awaiter$13(void 0, void 0, void 0, function* () {
    assertType(URI.isUri(resource));
    assertType(Position$2.isIPosition(position));
    assertType(Array.isArray(references));
    assertType(typeof multiple === "undefined" || typeof multiple === "string");
    assertType(typeof openInPeek === "undefined" || typeof openInPeek === "boolean");
    const editorService = accessor.get(ICodeEditorService);
    const editor2 = yield editorService.openCodeEditor({ resource }, editorService.getFocusedCodeEditor());
    if (isCodeEditor(editor2)) {
      editor2.setPosition(position);
      editor2.revealPositionInCenterIfOutsideViewport(
        position,
        0
        /* ScrollType.Smooth */
      );
      return editor2.invokeWithinContext((accessor2) => {
        const command = new class extends GenericGoToLocationAction {
          _getNoResultFoundMessage(info) {
            return noResultsMessage || super._getNoResultFoundMessage(info);
          }
        }({
          muteMessage: !Boolean(noResultsMessage),
          openInPeek: Boolean(openInPeek),
          openToSide: false
        }, references, multiple);
        accessor2.get(IInstantiationService).invokeFunction(command.run.bind(command), editor2);
      });
    }
  })
});
CommandsRegistry.registerCommand({
  id: "editor.action.peekLocations",
  description: {
    description: "Peek locations from a position in a file",
    args: [
      { name: "uri", description: "The text document in which to start", constraint: URI },
      { name: "position", description: "The position at which to start", constraint: Position$2.isIPosition },
      { name: "locations", description: "An array of locations.", constraint: Array },
      { name: "multiple", description: "Define what to do when having multiple results, either `peek`, `gotoAndPeek`, or `goto" }
    ]
  },
  handler: (accessor, resource, position, references, multiple) => __awaiter$13(void 0, void 0, void 0, function* () {
    accessor.get(ICommandService).executeCommand("editor.action.goToLocations", resource, position, references, multiple, void 0, true);
  })
});
CommandsRegistry.registerCommand({
  id: "editor.action.findReferences",
  handler: (accessor, resource, position) => {
    assertType(URI.isUri(resource));
    assertType(Position$2.isIPosition(position));
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const codeEditorService = accessor.get(ICodeEditorService);
    return codeEditorService.openCodeEditor({ resource }, codeEditorService.getFocusedCodeEditor()).then((control) => {
      if (!isCodeEditor(control) || !control.hasModel()) {
        return void 0;
      }
      const controller = ReferencesController.get(control);
      if (!controller) {
        return void 0;
      }
      const references = createCancelablePromise((token) => getReferencesAtPosition(languageFeaturesService.referenceProvider, control.getModel(), Position$2.lift(position), false, token).then((references2) => new ReferencesModel(references2, localize("ref.title", "References"))));
      const range2 = new Range$2(position.lineNumber, position.column, position.lineNumber, position.column);
      return Promise.resolve(controller.toggleWidget(range2, references, false));
    });
  }
});
CommandsRegistry.registerCommandAlias("editor.action.showReferences", "editor.action.peekLocations");
var __decorate$1y = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1w = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$12 = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
let GotoDefinitionAtPositionEditorContribution = class GotoDefinitionAtPositionEditorContribution2 {
  constructor(editor2, textModelResolverService, languageService, languageFeaturesService) {
    this.textModelResolverService = textModelResolverService;
    this.languageService = languageService;
    this.languageFeaturesService = languageFeaturesService;
    this.toUnhook = new DisposableStore();
    this.toUnhookForKeyboard = new DisposableStore();
    this.currentWordAtPosition = null;
    this.previousPromise = null;
    this.editor = editor2;
    this.linkDecorations = this.editor.createDecorationsCollection();
    const linkGesture = new ClickLinkGesture(editor2);
    this.toUnhook.add(linkGesture);
    this.toUnhook.add(linkGesture.onMouseMoveOrRelevantKeyDown(([mouseEvent, keyboardEvent]) => {
      this.startFindDefinitionFromMouse(mouseEvent, withNullAsUndefined(keyboardEvent));
    }));
    this.toUnhook.add(linkGesture.onExecute((mouseEvent) => {
      if (this.isEnabled(mouseEvent)) {
        this.gotoDefinition(mouseEvent.target.position, mouseEvent.hasSideBySideModifier).catch((error2) => {
          onUnexpectedError(error2);
        }).finally(() => {
          this.removeLinkDecorations();
        });
      }
    }));
    this.toUnhook.add(linkGesture.onCancel(() => {
      this.removeLinkDecorations();
      this.currentWordAtPosition = null;
    }));
  }
  static get(editor2) {
    return editor2.getContribution(GotoDefinitionAtPositionEditorContribution2.ID);
  }
  startFindDefinitionFromCursor(position) {
    return __awaiter$12(this, void 0, void 0, function* () {
      yield this.startFindDefinition(position);
      this.toUnhookForKeyboard.add(this.editor.onDidChangeCursorPosition(() => {
        this.currentWordAtPosition = null;
        this.removeLinkDecorations();
        this.toUnhookForKeyboard.clear();
      }));
      this.toUnhookForKeyboard.add(this.editor.onKeyDown((e) => {
        if (e) {
          this.currentWordAtPosition = null;
          this.removeLinkDecorations();
          this.toUnhookForKeyboard.clear();
        }
      }));
    });
  }
  startFindDefinitionFromMouse(mouseEvent, withKey) {
    if (mouseEvent.target.type === 9 && this.linkDecorations.length > 0) {
      return;
    }
    if (!this.editor.hasModel() || !this.isEnabled(mouseEvent, withKey)) {
      this.currentWordAtPosition = null;
      this.removeLinkDecorations();
      return;
    }
    const position = mouseEvent.target.position;
    this.startFindDefinition(position);
  }
  startFindDefinition(position) {
    var _a2;
    return __awaiter$12(this, void 0, void 0, function* () {
      this.toUnhookForKeyboard.clear();
      const word2 = position ? (_a2 = this.editor.getModel()) === null || _a2 === void 0 ? void 0 : _a2.getWordAtPosition(position) : null;
      if (!word2) {
        this.currentWordAtPosition = null;
        this.removeLinkDecorations();
        return;
      }
      if (this.currentWordAtPosition && this.currentWordAtPosition.startColumn === word2.startColumn && this.currentWordAtPosition.endColumn === word2.endColumn && this.currentWordAtPosition.word === word2.word) {
        return;
      }
      this.currentWordAtPosition = word2;
      const state = new EditorState$1(
        this.editor,
        4 | 1 | 2 | 8
        /* CodeEditorStateFlag.Scroll */
      );
      if (this.previousPromise) {
        this.previousPromise.cancel();
        this.previousPromise = null;
      }
      this.previousPromise = createCancelablePromise((token) => this.findDefinition(position, token));
      let results;
      try {
        results = yield this.previousPromise;
      } catch (error2) {
        onUnexpectedError(error2);
        return;
      }
      if (!results || !results.length || !state.validate(this.editor)) {
        this.removeLinkDecorations();
        return;
      }
      const linkRange = results[0].originSelectionRange ? Range$2.lift(results[0].originSelectionRange) : new Range$2(position.lineNumber, word2.startColumn, position.lineNumber, word2.endColumn);
      if (results.length > 1) {
        let combinedRange = linkRange;
        for (const { originSelectionRange } of results) {
          if (originSelectionRange) {
            combinedRange = Range$2.plusRange(combinedRange, originSelectionRange);
          }
        }
        this.addDecoration(combinedRange, new MarkdownString().appendText(localize("multipleResults", "Click to show {0} definitions.", results.length)));
      } else {
        const result2 = results[0];
        if (!result2.uri) {
          return;
        }
        this.textModelResolverService.createModelReference(result2.uri).then((ref2) => {
          if (!ref2.object || !ref2.object.textEditorModel) {
            ref2.dispose();
            return;
          }
          const { object: { textEditorModel } } = ref2;
          const { startLineNumber } = result2.range;
          if (startLineNumber < 1 || startLineNumber > textEditorModel.getLineCount()) {
            ref2.dispose();
            return;
          }
          const previewValue = this.getPreviewValue(textEditorModel, startLineNumber, result2);
          const languageId = this.languageService.guessLanguageIdByFilepathOrFirstLine(textEditorModel.uri);
          this.addDecoration(linkRange, previewValue ? new MarkdownString().appendCodeblock(languageId ? languageId : "", previewValue) : void 0);
          ref2.dispose();
        });
      }
    });
  }
  getPreviewValue(textEditorModel, startLineNumber, result2) {
    let rangeToUse = result2.range;
    const numberOfLinesInRange = rangeToUse.endLineNumber - rangeToUse.startLineNumber;
    if (numberOfLinesInRange >= GotoDefinitionAtPositionEditorContribution2.MAX_SOURCE_PREVIEW_LINES) {
      rangeToUse = this.getPreviewRangeBasedOnIndentation(textEditorModel, startLineNumber);
    }
    const previewValue = this.stripIndentationFromPreviewRange(textEditorModel, startLineNumber, rangeToUse);
    return previewValue;
  }
  stripIndentationFromPreviewRange(textEditorModel, startLineNumber, previewRange) {
    const startIndent = textEditorModel.getLineFirstNonWhitespaceColumn(startLineNumber);
    let minIndent = startIndent;
    for (let endLineNumber = startLineNumber + 1; endLineNumber < previewRange.endLineNumber; endLineNumber++) {
      const endIndent = textEditorModel.getLineFirstNonWhitespaceColumn(endLineNumber);
      minIndent = Math.min(minIndent, endIndent);
    }
    const previewValue = textEditorModel.getValueInRange(previewRange).replace(new RegExp(`^\\s{${minIndent - 1}}`, "gm"), "").trim();
    return previewValue;
  }
  getPreviewRangeBasedOnIndentation(textEditorModel, startLineNumber) {
    const startIndent = textEditorModel.getLineFirstNonWhitespaceColumn(startLineNumber);
    const maxLineNumber = Math.min(textEditorModel.getLineCount(), startLineNumber + GotoDefinitionAtPositionEditorContribution2.MAX_SOURCE_PREVIEW_LINES);
    let endLineNumber = startLineNumber + 1;
    for (; endLineNumber < maxLineNumber; endLineNumber++) {
      const endIndent = textEditorModel.getLineFirstNonWhitespaceColumn(endLineNumber);
      if (startIndent === endIndent) {
        break;
      }
    }
    return new Range$2(startLineNumber, 1, endLineNumber + 1, 1);
  }
  addDecoration(range2, hoverMessage) {
    const newDecorations = {
      range: range2,
      options: {
        description: "goto-definition-link",
        inlineClassName: "goto-definition-link",
        hoverMessage
      }
    };
    this.linkDecorations.set([newDecorations]);
  }
  removeLinkDecorations() {
    this.linkDecorations.clear();
  }
  isEnabled(mouseEvent, withKey) {
    var _a2;
    return this.editor.hasModel() && mouseEvent.isLeftClick && mouseEvent.isNoneOrSingleMouseDown && mouseEvent.target.type === 6 && !(((_a2 = mouseEvent.target.detail.injectedText) === null || _a2 === void 0 ? void 0 : _a2.options) instanceof ModelDecorationInjectedTextOptions) && (mouseEvent.hasTriggerModifier || (withKey ? withKey.keyCodeIsTriggerKey : false)) && this.languageFeaturesService.definitionProvider.has(this.editor.getModel());
  }
  findDefinition(position, token) {
    const model = this.editor.getModel();
    if (!model) {
      return Promise.resolve(null);
    }
    return getDefinitionsAtPosition(this.languageFeaturesService.definitionProvider, model, position, token);
  }
  gotoDefinition(position, openToSide) {
    this.editor.setPosition(position);
    return this.editor.invokeWithinContext((accessor) => {
      const canPeek = !openToSide && this.editor.getOption(
        86
        /* EditorOption.definitionLinkOpensInPeek */
      ) && !this.isInPeekEditor(accessor);
      const action = new DefinitionAction({ openToSide, openInPeek: canPeek, muteMessage: true }, { title: { value: "", original: "" }, id: "", precondition: void 0 });
      return action.run(accessor);
    });
  }
  isInPeekEditor(accessor) {
    const contextKeyService = accessor.get(IContextKeyService);
    return PeekContext.inPeekEditor.getValue(contextKeyService);
  }
  dispose() {
    this.toUnhook.dispose();
    this.toUnhookForKeyboard.dispose();
  }
};
GotoDefinitionAtPositionEditorContribution.ID = "editor.contrib.gotodefinitionatposition";
GotoDefinitionAtPositionEditorContribution.MAX_SOURCE_PREVIEW_LINES = 8;
GotoDefinitionAtPositionEditorContribution = __decorate$1y([
  __param$1w(1, ITextModelService),
  __param$1w(2, ILanguageService),
  __param$1w(3, ILanguageFeaturesService)
], GotoDefinitionAtPositionEditorContribution);
registerEditorContribution(
  GotoDefinitionAtPositionEditorContribution.ID,
  GotoDefinitionAtPositionEditorContribution,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);
const hover$1 = "";
const $$8 = $$d;
class HoverWidget extends Disposable {
  constructor() {
    super();
    this.containerDomNode = document.createElement("div");
    this.containerDomNode.className = "monaco-hover";
    this.containerDomNode.tabIndex = 0;
    this.containerDomNode.setAttribute("role", "tooltip");
    this.contentsDomNode = document.createElement("div");
    this.contentsDomNode.className = "monaco-hover-content";
    this.scrollbar = this._register(new DomScrollableElement(this.contentsDomNode, {
      consumeMouseWheelIfScrollbarIsNeeded: true
    }));
    this.containerDomNode.appendChild(this.scrollbar.getDomNode());
  }
  onContentsChanged() {
    this.scrollbar.scanDomNode();
  }
}
class HoverAction extends Disposable {
  static render(parent, actionOptions, keybindingLabel2) {
    return new HoverAction(parent, actionOptions, keybindingLabel2);
  }
  constructor(parent, actionOptions, keybindingLabel2) {
    super();
    this.actionContainer = append$1(parent, $$8("div.action-container"));
    this.actionContainer.setAttribute("tabindex", "0");
    this.action = append$1(this.actionContainer, $$8("a.action"));
    this.action.setAttribute("role", "button");
    if (actionOptions.iconClass) {
      append$1(this.action, $$8(`span.icon.${actionOptions.iconClass}`));
    }
    const label = append$1(this.action, $$8("span"));
    label.textContent = keybindingLabel2 ? `${actionOptions.label} (${keybindingLabel2})` : actionOptions.label;
    this._register(addDisposableListener(this.actionContainer, EventType$1.CLICK, (e) => {
      e.stopPropagation();
      e.preventDefault();
      actionOptions.run(this.actionContainer);
    }));
    this._register(addDisposableListener(this.actionContainer, EventType$1.KEY_DOWN, (e) => {
      const event = new StandardKeyboardEvent(e);
      if (event.equals(
        3
        /* KeyCode.Enter */
      ) || event.equals(
        10
        /* KeyCode.Space */
      )) {
        e.stopPropagation();
        e.preventDefault();
        actionOptions.run(this.actionContainer);
      }
    }));
    this.setEnabled(true);
  }
  setEnabled(enabled) {
    if (enabled) {
      this.actionContainer.classList.remove("disabled");
      this.actionContainer.removeAttribute("aria-disabled");
    } else {
      this.actionContainer.classList.add("disabled");
      this.actionContainer.setAttribute("aria-disabled", "true");
    }
  }
}
var __awaiter$11 = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var __asyncValues$1 = globalThis && globalThis.__asyncValues || function(o) {
  if (!Symbol.asyncIterator)
    throw new TypeError("Symbol.asyncIterator is not defined.");
  var m = o[Symbol.asyncIterator], i;
  return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
    return this;
  }, i);
  function verb(n2) {
    i[n2] = o[n2] && function(v) {
      return new Promise(function(resolve2, reject) {
        v = o[n2](v), settle(resolve2, reject, v.done, v.value);
      });
    };
  }
  function settle(resolve2, reject, d, v) {
    Promise.resolve(v).then(function(v2) {
      resolve2({ value: v2, done: d });
    }, reject);
  }
};
let HoverResult$1 = class HoverResult {
  constructor(value, isComplete, hasLoadingMessage) {
    this.value = value;
    this.isComplete = isComplete;
    this.hasLoadingMessage = hasLoadingMessage;
  }
};
class HoverOperation extends Disposable {
  constructor(_editor, _computer) {
    super();
    this._editor = _editor;
    this._computer = _computer;
    this._onResult = this._register(new Emitter$1());
    this.onResult = this._onResult.event;
    this._firstWaitScheduler = this._register(new RunOnceScheduler(() => this._triggerAsyncComputation(), 0));
    this._secondWaitScheduler = this._register(new RunOnceScheduler(() => this._triggerSyncComputation(), 0));
    this._loadingMessageScheduler = this._register(new RunOnceScheduler(() => this._triggerLoadingMessage(), 0));
    this._state = 0;
    this._asyncIterable = null;
    this._asyncIterableDone = false;
    this._result = [];
  }
  dispose() {
    if (this._asyncIterable) {
      this._asyncIterable.cancel();
      this._asyncIterable = null;
    }
    super.dispose();
  }
  get _hoverTime() {
    return this._editor.getOption(
      59
      /* EditorOption.hover */
    ).delay;
  }
  get _firstWaitTime() {
    return this._hoverTime / 2;
  }
  get _secondWaitTime() {
    return this._hoverTime - this._firstWaitTime;
  }
  get _loadingMessageTime() {
    return 3 * this._hoverTime;
  }
  _setState(state, fireResult = true) {
    this._state = state;
    if (fireResult) {
      this._fireResult();
    }
  }
  _triggerAsyncComputation() {
    this._setState(
      2
      /* HoverOperationState.SecondWait */
    );
    this._secondWaitScheduler.schedule(this._secondWaitTime);
    if (this._computer.computeAsync) {
      this._asyncIterableDone = false;
      this._asyncIterable = createCancelableAsyncIterable((token) => this._computer.computeAsync(token));
      (() => __awaiter$11(this, void 0, void 0, function* () {
        var _a2, e_1, _b2, _c2;
        try {
          try {
            for (var _d2 = true, _e2 = __asyncValues$1(this._asyncIterable), _f2; _f2 = yield _e2.next(), _a2 = _f2.done, !_a2; _d2 = true) {
              _c2 = _f2.value;
              _d2 = false;
              const item = _c2;
              if (item) {
                this._result.push(item);
                this._fireResult();
              }
            }
          } catch (e_1_1) {
            e_1 = { error: e_1_1 };
          } finally {
            try {
              if (!_d2 && !_a2 && (_b2 = _e2.return))
                yield _b2.call(_e2);
            } finally {
              if (e_1)
                throw e_1.error;
            }
          }
          this._asyncIterableDone = true;
          if (this._state === 3 || this._state === 4) {
            this._setState(
              0
              /* HoverOperationState.Idle */
            );
          }
        } catch (e) {
          onUnexpectedError(e);
        }
      }))();
    } else {
      this._asyncIterableDone = true;
    }
  }
  _triggerSyncComputation() {
    if (this._computer.computeSync) {
      this._result = this._result.concat(this._computer.computeSync());
    }
    this._setState(
      this._asyncIterableDone ? 0 : 3
      /* HoverOperationState.WaitingForAsync */
    );
  }
  _triggerLoadingMessage() {
    if (this._state === 3) {
      this._setState(
        4
        /* HoverOperationState.WaitingForAsyncShowingLoading */
      );
    }
  }
  _fireResult() {
    if (this._state === 1 || this._state === 2) {
      return;
    }
    const isComplete = this._state === 0;
    const hasLoadingMessage = this._state === 4;
    this._onResult.fire(new HoverResult$1(this._result.slice(0), isComplete, hasLoadingMessage));
  }
  start(mode) {
    if (mode === 0) {
      if (this._state === 0) {
        this._setState(
          1
          /* HoverOperationState.FirstWait */
        );
        this._firstWaitScheduler.schedule(this._firstWaitTime);
        this._loadingMessageScheduler.schedule(this._loadingMessageTime);
      }
    } else {
      switch (this._state) {
        case 0:
          this._triggerAsyncComputation();
          this._secondWaitScheduler.cancel();
          this._triggerSyncComputation();
          break;
        case 2:
          this._secondWaitScheduler.cancel();
          this._triggerSyncComputation();
          break;
      }
    }
  }
  cancel() {
    this._firstWaitScheduler.cancel();
    this._secondWaitScheduler.cancel();
    this._loadingMessageScheduler.cancel();
    if (this._asyncIterable) {
      this._asyncIterable.cancel();
      this._asyncIterable = null;
    }
    this._result = [];
    this._setState(0, false);
  }
}
class HoverRangeAnchor {
  constructor(priority, range2, initialMousePosX, initialMousePosY) {
    this.priority = priority;
    this.range = range2;
    this.initialMousePosX = initialMousePosX;
    this.initialMousePosY = initialMousePosY;
    this.type = 1;
  }
  equals(other) {
    return other.type === 1 && this.range.equalsRange(other.range);
  }
  canAdoptVisibleHover(lastAnchor, showAtPosition) {
    return lastAnchor.type === 1 && showAtPosition.lineNumber === this.range.startLineNumber;
  }
}
class HoverForeignElementAnchor {
  constructor(priority, owner, range2, initialMousePosX, initialMousePosY, supportsMarkerHover) {
    this.priority = priority;
    this.owner = owner;
    this.range = range2;
    this.initialMousePosX = initialMousePosX;
    this.initialMousePosY = initialMousePosY;
    this.supportsMarkerHover = supportsMarkerHover;
    this.type = 2;
  }
  equals(other) {
    return other.type === 2 && this.owner === other.owner;
  }
  canAdoptVisibleHover(lastAnchor, showAtPosition) {
    return lastAnchor.type === 2 && this.owner === lastAnchor.owner;
  }
}
const HoverParticipantRegistry = new class HoverParticipantRegistry2 {
  constructor() {
    this._participants = [];
  }
  register(ctor) {
    this._participants.push(ctor);
  }
  getAll() {
    return this._participants;
  }
}();
class ResizableHTMLElement {
  constructor() {
    this._onDidWillResize = new Emitter$1();
    this.onDidWillResize = this._onDidWillResize.event;
    this._onDidResize = new Emitter$1();
    this.onDidResize = this._onDidResize.event;
    this._sashListener = new DisposableStore();
    this._size = new Dimension(0, 0);
    this._minSize = new Dimension(0, 0);
    this._maxSize = new Dimension(Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
    this.domNode = document.createElement("div");
    this._eastSash = new Sash(this.domNode, { getVerticalSashLeft: () => this._size.width }, {
      orientation: 0
      /* Orientation.VERTICAL */
    });
    this._westSash = new Sash(this.domNode, { getVerticalSashLeft: () => 0 }, {
      orientation: 0
      /* Orientation.VERTICAL */
    });
    this._northSash = new Sash(this.domNode, { getHorizontalSashTop: () => 0 }, { orientation: 1, orthogonalEdge: OrthogonalEdge.North });
    this._southSash = new Sash(this.domNode, { getHorizontalSashTop: () => this._size.height }, { orientation: 1, orthogonalEdge: OrthogonalEdge.South });
    this._northSash.orthogonalStartSash = this._westSash;
    this._northSash.orthogonalEndSash = this._eastSash;
    this._southSash.orthogonalStartSash = this._westSash;
    this._southSash.orthogonalEndSash = this._eastSash;
    let currentSize;
    let deltaY = 0;
    let deltaX = 0;
    this._sashListener.add(Event$1.any(this._northSash.onDidStart, this._eastSash.onDidStart, this._southSash.onDidStart, this._westSash.onDidStart)(() => {
      if (currentSize === void 0) {
        this._onDidWillResize.fire();
        currentSize = this._size;
        deltaY = 0;
        deltaX = 0;
      }
    }));
    this._sashListener.add(Event$1.any(this._northSash.onDidEnd, this._eastSash.onDidEnd, this._southSash.onDidEnd, this._westSash.onDidEnd)(() => {
      if (currentSize !== void 0) {
        currentSize = void 0;
        deltaY = 0;
        deltaX = 0;
        this._onDidResize.fire({ dimension: this._size, done: true });
      }
    }));
    this._sashListener.add(this._eastSash.onDidChange((e) => {
      if (currentSize) {
        deltaX = e.currentX - e.startX;
        this.layout(currentSize.height + deltaY, currentSize.width + deltaX);
        this._onDidResize.fire({ dimension: this._size, done: false, east: true });
      }
    }));
    this._sashListener.add(this._westSash.onDidChange((e) => {
      if (currentSize) {
        deltaX = -(e.currentX - e.startX);
        this.layout(currentSize.height + deltaY, currentSize.width + deltaX);
        this._onDidResize.fire({ dimension: this._size, done: false, west: true });
      }
    }));
    this._sashListener.add(this._northSash.onDidChange((e) => {
      if (currentSize) {
        deltaY = -(e.currentY - e.startY);
        this.layout(currentSize.height + deltaY, currentSize.width + deltaX);
        this._onDidResize.fire({ dimension: this._size, done: false, north: true });
      }
    }));
    this._sashListener.add(this._southSash.onDidChange((e) => {
      if (currentSize) {
        deltaY = e.currentY - e.startY;
        this.layout(currentSize.height + deltaY, currentSize.width + deltaX);
        this._onDidResize.fire({ dimension: this._size, done: false, south: true });
      }
    }));
    this._sashListener.add(Event$1.any(this._eastSash.onDidReset, this._westSash.onDidReset)((e) => {
      if (this._preferredSize) {
        this.layout(this._size.height, this._preferredSize.width);
        this._onDidResize.fire({ dimension: this._size, done: true });
      }
    }));
    this._sashListener.add(Event$1.any(this._northSash.onDidReset, this._southSash.onDidReset)((e) => {
      if (this._preferredSize) {
        this.layout(this._preferredSize.height, this._size.width);
        this._onDidResize.fire({ dimension: this._size, done: true });
      }
    }));
  }
  dispose() {
    this._northSash.dispose();
    this._southSash.dispose();
    this._eastSash.dispose();
    this._westSash.dispose();
    this._sashListener.dispose();
    this._onDidResize.dispose();
    this._onDidWillResize.dispose();
    this.domNode.remove();
  }
  enableSashes(north, east, south, west) {
    this._northSash.state = north ? 3 : 0;
    this._eastSash.state = east ? 3 : 0;
    this._southSash.state = south ? 3 : 0;
    this._westSash.state = west ? 3 : 0;
  }
  layout(height = this.size.height, width = this.size.width) {
    const { height: minHeight, width: minWidth } = this._minSize;
    const { height: maxHeight, width: maxWidth } = this._maxSize;
    height = Math.max(minHeight, Math.min(maxHeight, height));
    width = Math.max(minWidth, Math.min(maxWidth, width));
    const newSize = new Dimension(width, height);
    if (!Dimension.equals(newSize, this._size)) {
      this.domNode.style.height = height + "px";
      this.domNode.style.width = width + "px";
      this._size = newSize;
      this._northSash.layout();
      this._eastSash.layout();
      this._southSash.layout();
      this._westSash.layout();
    }
  }
  clearSashHoverState() {
    this._eastSash.clearSashHoverState();
    this._westSash.clearSashHoverState();
    this._northSash.clearSashHoverState();
    this._southSash.clearSashHoverState();
  }
  get size() {
    return this._size;
  }
  set maxSize(value) {
    this._maxSize = value;
  }
  get maxSize() {
    return this._maxSize;
  }
  set minSize(value) {
    this._minSize = value;
  }
  get minSize() {
    return this._minSize;
  }
  set preferredSize(value) {
    this._preferredSize = value;
  }
  get preferredSize() {
    return this._preferredSize;
  }
}
const TOP_HEIGHT = 30;
const BOTTOM_HEIGHT = 24;
class ResizableContentWidget extends Disposable {
  constructor(_editor, minimumSize = new Dimension(10, 10)) {
    super();
    this._editor = _editor;
    this.allowEditorOverflow = true;
    this.suppressMouseDown = false;
    this._resizableNode = this._register(new ResizableHTMLElement());
    this._contentPosition = null;
    this._isResizing = false;
    this._resizableNode.domNode.style.position = "absolute";
    this._resizableNode.minSize = Dimension.lift(minimumSize);
    this._resizableNode.layout(minimumSize.height, minimumSize.width);
    this._resizableNode.enableSashes(true, true, true, true);
    this._register(this._resizableNode.onDidResize((e) => {
      this._resize(new Dimension(e.dimension.width, e.dimension.height));
      if (e.done) {
        this._isResizing = false;
      }
    }));
    this._register(this._resizableNode.onDidWillResize(() => {
      this._isResizing = true;
    }));
  }
  get isResizing() {
    return this._isResizing;
  }
  getDomNode() {
    return this._resizableNode.domNode;
  }
  getPosition() {
    return this._contentPosition;
  }
  get position() {
    var _a2;
    return ((_a2 = this._contentPosition) === null || _a2 === void 0 ? void 0 : _a2.position) ? Position$2.lift(this._contentPosition.position) : void 0;
  }
  _availableVerticalSpaceAbove(position) {
    const editorDomNode = this._editor.getDomNode();
    const mouseBox = this._editor.getScrolledVisiblePosition(position);
    if (!editorDomNode || !mouseBox) {
      return;
    }
    const editorBox = getDomNodePagePosition(editorDomNode);
    return editorBox.top + mouseBox.top - TOP_HEIGHT;
  }
  _availableVerticalSpaceBelow(position) {
    const editorDomNode = this._editor.getDomNode();
    const mouseBox = this._editor.getScrolledVisiblePosition(position);
    if (!editorDomNode || !mouseBox) {
      return;
    }
    const editorBox = getDomNodePagePosition(editorDomNode);
    const bodyBox = getClientArea(document.body);
    const mouseBottom = editorBox.top + mouseBox.top + mouseBox.height;
    return bodyBox.height - mouseBottom - BOTTOM_HEIGHT;
  }
  _findPositionPreference(widgetHeight, showAtPosition) {
    var _a2, _b2;
    const maxHeightBelow = Math.min((_a2 = this._availableVerticalSpaceBelow(showAtPosition)) !== null && _a2 !== void 0 ? _a2 : Infinity, widgetHeight);
    const maxHeightAbove = Math.min((_b2 = this._availableVerticalSpaceAbove(showAtPosition)) !== null && _b2 !== void 0 ? _b2 : Infinity, widgetHeight);
    const maxHeight = Math.min(Math.max(maxHeightAbove, maxHeightBelow), widgetHeight);
    const height = Math.min(widgetHeight, maxHeight);
    let renderingAbove;
    if (this._editor.getOption(
      59
      /* EditorOption.hover */
    ).above) {
      renderingAbove = height <= maxHeightAbove ? 1 : 2;
    } else {
      renderingAbove = height <= maxHeightBelow ? 2 : 1;
    }
    if (renderingAbove === 1) {
      this._resizableNode.enableSashes(true, true, false, false);
    } else {
      this._resizableNode.enableSashes(false, true, true, false);
    }
    return renderingAbove;
  }
  _resize(dimension) {
    this._resizableNode.layout(dimension.height, dimension.width);
  }
}
var __decorate$1x = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1v = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
const $$7 = $$d;
let ContentHoverController = class ContentHoverController2 extends Disposable {
  constructor(_editor, _instantiationService, _keybindingService) {
    super();
    this._editor = _editor;
    this._instantiationService = _instantiationService;
    this._keybindingService = _keybindingService;
    this._currentResult = null;
    const minimumHeight = this._editor.getOption(
      65
      /* EditorOption.lineHeight */
    ) + 8;
    const minimumWidth = 4 / 3 * minimumHeight;
    const minimumSize = new Dimension(minimumWidth, minimumHeight);
    this._widget = this._register(this._instantiationService.createInstance(ContentHoverWidget, this._editor, minimumSize));
    this._participants = [];
    for (const participant of HoverParticipantRegistry.getAll()) {
      this._participants.push(this._instantiationService.createInstance(participant, this._editor));
    }
    this._participants.sort((p1, p2) => p1.hoverOrdinal - p2.hoverOrdinal);
    this._computer = new ContentHoverComputer(this._editor, this._participants);
    this._hoverOperation = this._register(new HoverOperation(this._editor, this._computer));
    this._register(this._hoverOperation.onResult((result2) => {
      if (!this._computer.anchor) {
        return;
      }
      const messages = result2.hasLoadingMessage ? this._addLoadingMessage(result2.value) : result2.value;
      this._withResult(new HoverResult2(this._computer.anchor, messages, result2.isComplete));
    }));
    this._register(addStandardDisposableListener(this._widget.getDomNode(), "keydown", (e) => {
      if (e.equals(
        9
        /* KeyCode.Escape */
      )) {
        this.hide();
      }
    }));
    this._register(TokenizationRegistry2.onDidChange(() => {
      if (this._widget.position && this._currentResult) {
        this._setCurrentResult(this._currentResult);
      }
    }));
  }
  get widget() {
    return this._widget;
  }
  /**
   * Returns true if the hover shows now or will show.
   */
  maybeShowAt(mouseEvent) {
    if (this._widget.isResizing) {
      return true;
    }
    const anchorCandidates = [];
    for (const participant of this._participants) {
      if (participant.suggestHoverAnchor) {
        const anchor = participant.suggestHoverAnchor(mouseEvent);
        if (anchor) {
          anchorCandidates.push(anchor);
        }
      }
    }
    const target = mouseEvent.target;
    if (target.type === 6) {
      anchorCandidates.push(new HoverRangeAnchor(0, target.range, mouseEvent.event.posx, mouseEvent.event.posy));
    }
    if (target.type === 7) {
      const epsilon = this._editor.getOption(
        49
        /* EditorOption.fontInfo */
      ).typicalHalfwidthCharacterWidth / 2;
      if (!target.detail.isAfterLines && typeof target.detail.horizontalDistanceToText === "number" && target.detail.horizontalDistanceToText < epsilon) {
        anchorCandidates.push(new HoverRangeAnchor(0, target.range, mouseEvent.event.posx, mouseEvent.event.posy));
      }
    }
    if (anchorCandidates.length === 0) {
      return this._startShowingOrUpdateHover(null, 0, 0, false, mouseEvent);
    }
    anchorCandidates.sort((a, b) => b.priority - a.priority);
    return this._startShowingOrUpdateHover(anchorCandidates[0], 0, 0, false, mouseEvent);
  }
  startShowingAtRange(range2, mode, source, focus) {
    this._startShowingOrUpdateHover(new HoverRangeAnchor(0, range2, void 0, void 0), mode, source, focus, null);
  }
  /**
   * Returns true if the hover shows now or will show.
   */
  _startShowingOrUpdateHover(anchor, mode, source, focus, mouseEvent) {
    if (!this._widget.position || !this._currentResult) {
      if (anchor) {
        this._startHoverOperationIfNecessary(anchor, mode, source, focus, false);
        return true;
      }
      return false;
    }
    const hoverIsSticky = this._editor.getOption(
      59
      /* EditorOption.hover */
    ).sticky;
    const isGettingCloser = hoverIsSticky && mouseEvent && this._widget.isMouseGettingCloser(mouseEvent.event.posx, mouseEvent.event.posy);
    if (isGettingCloser) {
      if (anchor) {
        this._startHoverOperationIfNecessary(anchor, mode, source, focus, true);
      }
      return true;
    }
    if (!anchor) {
      this._setCurrentResult(null);
      return false;
    }
    if (anchor && this._currentResult.anchor.equals(anchor)) {
      return true;
    }
    if (!anchor.canAdoptVisibleHover(this._currentResult.anchor, this._widget.position)) {
      this._setCurrentResult(null);
      this._startHoverOperationIfNecessary(anchor, mode, source, focus, false);
      return true;
    }
    this._setCurrentResult(this._currentResult.filter(anchor));
    this._startHoverOperationIfNecessary(anchor, mode, source, focus, false);
    return true;
  }
  _startHoverOperationIfNecessary(anchor, mode, source, focus, insistOnKeepingHoverVisible) {
    if (this._computer.anchor && this._computer.anchor.equals(anchor)) {
      return;
    }
    this._hoverOperation.cancel();
    this._computer.anchor = anchor;
    this._computer.shouldFocus = focus;
    this._computer.source = source;
    this._computer.insistOnKeepingHoverVisible = insistOnKeepingHoverVisible;
    this._hoverOperation.start(mode);
  }
  _setCurrentResult(hoverResult) {
    if (this._currentResult === hoverResult) {
      return;
    }
    if (hoverResult && hoverResult.messages.length === 0) {
      hoverResult = null;
    }
    this._currentResult = hoverResult;
    if (this._currentResult) {
      this._renderMessages(this._currentResult.anchor, this._currentResult.messages);
    } else {
      this._widget.hide();
    }
  }
  hide() {
    this._computer.anchor = null;
    this._hoverOperation.cancel();
    this._setCurrentResult(null);
  }
  get isColorPickerVisible() {
    return this._widget.isColorPickerVisible;
  }
  get isVisibleFromKeyboard() {
    return this._widget.isVisibleFromKeyboard;
  }
  get isVisible() {
    return this._widget.isVisible;
  }
  get isFocused() {
    return this._widget.isFocused;
  }
  get isResizing() {
    return this._widget.isResizing;
  }
  containsNode(node2) {
    return node2 ? this._widget.getDomNode().contains(node2) : false;
  }
  _addLoadingMessage(result2) {
    if (this._computer.anchor) {
      for (const participant of this._participants) {
        if (participant.createLoadingMessage) {
          const loadingMessage = participant.createLoadingMessage(this._computer.anchor);
          if (loadingMessage) {
            return result2.slice(0).concat([loadingMessage]);
          }
        }
      }
    }
    return result2;
  }
  _withResult(hoverResult) {
    if (this._widget.position && this._currentResult && this._currentResult.isComplete) {
      if (!hoverResult.isComplete) {
        return;
      }
      if (this._computer.insistOnKeepingHoverVisible && hoverResult.messages.length === 0) {
        return;
      }
    }
    this._setCurrentResult(hoverResult);
  }
  _renderMessages(anchor, messages) {
    const { showAtPosition, showAtSecondaryPosition, highlightRange } = ContentHoverController2.computeHoverRanges(this._editor, anchor.range, messages);
    const disposables = new DisposableStore();
    const statusBar = disposables.add(new EditorHoverStatusBar(this._keybindingService));
    const fragment = document.createDocumentFragment();
    let colorPicker2 = null;
    const context = {
      fragment,
      statusBar,
      setColorPicker: (widget) => colorPicker2 = widget,
      onContentsChanged: () => this._widget.onContentsChanged(),
      setMinimumDimensions: (dimensions) => this._widget.setMinimumDimensions(dimensions),
      hide: () => this.hide()
    };
    for (const participant of this._participants) {
      const hoverParts = messages.filter((msg) => msg.owner === participant);
      if (hoverParts.length > 0) {
        disposables.add(participant.renderHoverParts(context, hoverParts));
      }
    }
    const isBeforeContent = messages.some((m) => m.isBeforeContent);
    if (statusBar.hasContent) {
      fragment.appendChild(statusBar.hoverElement);
    }
    if (fragment.hasChildNodes()) {
      if (highlightRange) {
        const highlightDecoration = this._editor.createDecorationsCollection();
        highlightDecoration.set([{
          range: highlightRange,
          options: ContentHoverController2._DECORATION_OPTIONS
        }]);
        disposables.add(toDisposable(() => {
          highlightDecoration.clear();
        }));
      }
      this._widget.showAt(fragment, new ContentHoverVisibleData(colorPicker2, showAtPosition, showAtSecondaryPosition, this._editor.getOption(
        59
        /* EditorOption.hover */
      ).above, this._computer.shouldFocus, this._computer.source, isBeforeContent, anchor.initialMousePosX, anchor.initialMousePosY, disposables));
    } else {
      disposables.dispose();
    }
  }
  static computeHoverRanges(editor2, anchorRange, messages) {
    let startColumnBoundary = 1;
    if (editor2.hasModel()) {
      const viewModel = editor2._getViewModel();
      const coordinatesConverter = viewModel.coordinatesConverter;
      const anchorViewRange = coordinatesConverter.convertModelRangeToViewRange(anchorRange);
      const anchorViewRangeStart = new Position$2(anchorViewRange.startLineNumber, viewModel.getLineMinColumn(anchorViewRange.startLineNumber));
      startColumnBoundary = coordinatesConverter.convertViewPositionToModelPosition(anchorViewRangeStart).column;
    }
    const anchorLineNumber = anchorRange.startLineNumber;
    let renderStartColumn = anchorRange.startColumn;
    let highlightRange = messages[0].range;
    let forceShowAtRange = null;
    for (const msg of messages) {
      highlightRange = Range$2.plusRange(highlightRange, msg.range);
      if (msg.range.startLineNumber === anchorLineNumber && msg.range.endLineNumber === anchorLineNumber) {
        renderStartColumn = Math.max(Math.min(renderStartColumn, msg.range.startColumn), startColumnBoundary);
      }
      if (msg.forceShowAtRange) {
        forceShowAtRange = msg.range;
      }
    }
    return {
      showAtPosition: forceShowAtRange ? forceShowAtRange.getStartPosition() : new Position$2(anchorLineNumber, anchorRange.startColumn),
      showAtSecondaryPosition: forceShowAtRange ? forceShowAtRange.getStartPosition() : new Position$2(anchorLineNumber, renderStartColumn),
      highlightRange
    };
  }
  focus() {
    this._widget.focus();
  }
  scrollUp() {
    this._widget.scrollUp();
  }
  scrollDown() {
    this._widget.scrollDown();
  }
  scrollLeft() {
    this._widget.scrollLeft();
  }
  scrollRight() {
    this._widget.scrollRight();
  }
  pageUp() {
    this._widget.pageUp();
  }
  pageDown() {
    this._widget.pageDown();
  }
  goToTop() {
    this._widget.goToTop();
  }
  goToBottom() {
    this._widget.goToBottom();
  }
};
ContentHoverController._DECORATION_OPTIONS = ModelDecorationOptions.register({
  description: "content-hover-highlight",
  className: "hoverHighlight"
});
ContentHoverController = __decorate$1x([
  __param$1v(1, IInstantiationService),
  __param$1v(2, IKeybindingService)
], ContentHoverController);
class HoverResult2 {
  constructor(anchor, messages, isComplete) {
    this.anchor = anchor;
    this.messages = messages;
    this.isComplete = isComplete;
  }
  filter(anchor) {
    const filteredMessages = this.messages.filter((m) => m.isValidForHoverAnchor(anchor));
    if (filteredMessages.length === this.messages.length) {
      return this;
    }
    return new FilteredHoverResult(this, this.anchor, filteredMessages, this.isComplete);
  }
}
class FilteredHoverResult extends HoverResult2 {
  constructor(original, anchor, messages, isComplete) {
    super(anchor, messages, isComplete);
    this.original = original;
  }
  filter(anchor) {
    return this.original.filter(anchor);
  }
}
class ContentHoverVisibleData {
  constructor(colorPicker2, showAtPosition, showAtSecondaryPosition, preferAbove, stoleFocus, source, isBeforeContent, initialMousePosX, initialMousePosY, disposables) {
    this.colorPicker = colorPicker2;
    this.showAtPosition = showAtPosition;
    this.showAtSecondaryPosition = showAtSecondaryPosition;
    this.preferAbove = preferAbove;
    this.stoleFocus = stoleFocus;
    this.source = source;
    this.isBeforeContent = isBeforeContent;
    this.initialMousePosX = initialMousePosX;
    this.initialMousePosY = initialMousePosY;
    this.disposables = disposables;
    this.closestMouseDistance = void 0;
  }
}
const HORIZONTAL_SCROLLING_BY = 30;
const SCROLLBAR_WIDTH = 10;
const CONTAINER_HEIGHT_PADDING = 6;
let ContentHoverWidget = class ContentHoverWidget2 extends ResizableContentWidget {
  get isColorPickerVisible() {
    var _a2;
    return Boolean((_a2 = this._visibleData) === null || _a2 === void 0 ? void 0 : _a2.colorPicker);
  }
  get isVisibleFromKeyboard() {
    var _a2;
    return ((_a2 = this._visibleData) === null || _a2 === void 0 ? void 0 : _a2.source) === 1;
  }
  get isVisible() {
    var _a2;
    return (_a2 = this._hoverVisibleKey.get()) !== null && _a2 !== void 0 ? _a2 : false;
  }
  get isFocused() {
    var _a2;
    return (_a2 = this._hoverFocusedKey.get()) !== null && _a2 !== void 0 ? _a2 : false;
  }
  constructor(editor2, minimumSize, contextKeyService) {
    super(editor2, minimumSize);
    this._hover = this._register(new HoverWidget());
    this._hoverVisibleKey = EditorContextKeys.hoverVisible.bindTo(contextKeyService);
    this._hoverFocusedKey = EditorContextKeys.hoverFocused.bindTo(contextKeyService);
    append$1(this._resizableNode.domNode, this._hover.containerDomNode);
    this._resizableNode.domNode.style.zIndex = "50";
    this._register(this._editor.onDidLayoutChange(() => this._layout()));
    this._register(this._editor.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        49
        /* EditorOption.fontInfo */
      )) {
        this._updateFont();
      }
    }));
    const focusTracker = this._register(trackFocus(this._resizableNode.domNode));
    this._register(focusTracker.onDidFocus(() => {
      this._hoverFocusedKey.set(true);
    }));
    this._register(focusTracker.onDidBlur(() => {
      this._hoverFocusedKey.set(false);
    }));
    this._setHoverData(void 0);
    this._layout();
    this._editor.addContentWidget(this);
  }
  dispose() {
    var _a2;
    super.dispose();
    (_a2 = this._visibleData) === null || _a2 === void 0 ? void 0 : _a2.disposables.dispose();
    this._editor.removeContentWidget(this);
  }
  getId() {
    return ContentHoverWidget2.ID;
  }
  static _applyDimensions(container2, width, height) {
    const transformedWidth = typeof width === "number" ? `${width}px` : width;
    const transformedHeight = typeof height === "number" ? `${height}px` : height;
    container2.style.width = transformedWidth;
    container2.style.height = transformedHeight;
  }
  _setContentsDomNodeDimensions(width, height) {
    const contentsDomNode = this._hover.contentsDomNode;
    return ContentHoverWidget2._applyDimensions(contentsDomNode, width, height);
  }
  _setContainerDomNodeDimensions(width, height) {
    const containerDomNode = this._hover.containerDomNode;
    return ContentHoverWidget2._applyDimensions(containerDomNode, width, height);
  }
  _setHoverWidgetDimensions(width, height) {
    this._setContentsDomNodeDimensions(width, height);
    this._setContainerDomNodeDimensions(width, height);
    this._layoutContentWidget();
  }
  static _applyMaxDimensions(container2, width, height) {
    const transformedWidth = typeof width === "number" ? `${width}px` : width;
    const transformedHeight = typeof height === "number" ? `${height}px` : height;
    container2.style.maxWidth = transformedWidth;
    container2.style.maxHeight = transformedHeight;
  }
  _setHoverWidgetMaxDimensions(width, height) {
    ContentHoverWidget2._applyMaxDimensions(this._hover.contentsDomNode, width, height);
    ContentHoverWidget2._applyMaxDimensions(this._hover.containerDomNode, width, height);
    this._hover.containerDomNode.style.setProperty("--hover-maxWidth", typeof width === "number" ? `${width}px` : width);
    this._layoutContentWidget();
  }
  _hasHorizontalScrollbar() {
    const scrollDimensions = this._hover.scrollbar.getScrollDimensions();
    const hasHorizontalScrollbar = scrollDimensions.scrollWidth > scrollDimensions.width;
    return hasHorizontalScrollbar;
  }
  _adjustContentsBottomPadding() {
    const contentsDomNode = this._hover.contentsDomNode;
    const extraBottomPadding = `${this._hover.scrollbar.options.horizontalScrollbarSize}px`;
    if (contentsDomNode.style.paddingBottom !== extraBottomPadding) {
      contentsDomNode.style.paddingBottom = extraBottomPadding;
    }
  }
  _setAdjustedHoverWidgetDimensions(size2) {
    this._setHoverWidgetMaxDimensions("none", "none");
    const width = size2.width;
    const height = size2.height;
    this._setHoverWidgetDimensions(width, height);
    if (this._hasHorizontalScrollbar()) {
      this._adjustContentsBottomPadding();
      this._setContentsDomNodeDimensions(width, height - SCROLLBAR_WIDTH);
    }
  }
  _setResizableNodeMaxDimensions() {
    var _a2, _b2;
    const maxRenderingWidth = (_a2 = this._findMaximumRenderingWidth()) !== null && _a2 !== void 0 ? _a2 : Infinity;
    const maxRenderingHeight = (_b2 = this._findMaximumRenderingHeight()) !== null && _b2 !== void 0 ? _b2 : Infinity;
    this._resizableNode.maxSize = new Dimension(maxRenderingWidth, maxRenderingHeight);
    this._setHoverWidgetMaxDimensions(maxRenderingWidth, maxRenderingHeight);
  }
  _resize(size2) {
    var _a2, _b2;
    ContentHoverWidget2._lastDimensions = new Dimension(size2.width, size2.height);
    this._setAdjustedHoverWidgetDimensions(size2);
    this._resizableNode.layout(size2.height, size2.width);
    this._setResizableNodeMaxDimensions();
    this._hover.scrollbar.scanDomNode();
    this._editor.layoutContentWidget(this);
    (_b2 = (_a2 = this._visibleData) === null || _a2 === void 0 ? void 0 : _a2.colorPicker) === null || _b2 === void 0 ? void 0 : _b2.layout();
  }
  _findAvailableSpaceVertically() {
    var _a2;
    const position = (_a2 = this._visibleData) === null || _a2 === void 0 ? void 0 : _a2.showAtPosition;
    if (!position) {
      return;
    }
    return this._positionPreference === 1 ? this._availableVerticalSpaceAbove(position) : this._availableVerticalSpaceBelow(position);
  }
  _findMaximumRenderingHeight() {
    const availableSpace = this._findAvailableSpaceVertically();
    if (!availableSpace) {
      return;
    }
    let maximumHeight = CONTAINER_HEIGHT_PADDING;
    Array.from(this._hover.contentsDomNode.children).forEach((hoverPart) => {
      maximumHeight += hoverPart.clientHeight;
    });
    if (this._hasHorizontalScrollbar()) {
      maximumHeight += SCROLLBAR_WIDTH;
    }
    return Math.min(availableSpace, maximumHeight);
  }
  _findMaximumRenderingWidth() {
    if (!this._editor || !this._editor.hasModel()) {
      return;
    }
    const bodyBoxWidth = getClientArea(document.body).width;
    const horizontalPadding = 14;
    return bodyBoxWidth - horizontalPadding;
  }
  isMouseGettingCloser(posx, posy) {
    if (!this._visibleData) {
      return false;
    }
    if (typeof this._visibleData.initialMousePosX === "undefined" || typeof this._visibleData.initialMousePosY === "undefined") {
      this._visibleData.initialMousePosX = posx;
      this._visibleData.initialMousePosY = posy;
      return false;
    }
    const widgetRect = getDomNodePagePosition(this.getDomNode());
    if (typeof this._visibleData.closestMouseDistance === "undefined") {
      this._visibleData.closestMouseDistance = computeDistanceFromPointToRectangle(this._visibleData.initialMousePosX, this._visibleData.initialMousePosY, widgetRect.left, widgetRect.top, widgetRect.width, widgetRect.height);
    }
    const distance = computeDistanceFromPointToRectangle(posx, posy, widgetRect.left, widgetRect.top, widgetRect.width, widgetRect.height);
    if (distance > this._visibleData.closestMouseDistance + 4) {
      return false;
    }
    this._visibleData.closestMouseDistance = Math.min(this._visibleData.closestMouseDistance, distance);
    return true;
  }
  _setHoverData(hoverData) {
    var _a2;
    (_a2 = this._visibleData) === null || _a2 === void 0 ? void 0 : _a2.disposables.dispose();
    this._visibleData = hoverData;
    this._hoverVisibleKey.set(!!hoverData);
    this._hover.containerDomNode.classList.toggle("hidden", !hoverData);
  }
  _layout() {
    const { fontSize, lineHeight } = this._editor.getOption(
      49
      /* EditorOption.fontInfo */
    );
    const contentsDomNode = this._hover.contentsDomNode;
    contentsDomNode.style.fontSize = `${fontSize}px`;
    contentsDomNode.style.lineHeight = `${lineHeight / fontSize}`;
    this._updateMaxDimensions();
  }
  _updateFont() {
    const codeClasses = Array.prototype.slice.call(this._hover.contentsDomNode.getElementsByClassName("code"));
    codeClasses.forEach((node2) => this._editor.applyFontInfo(node2));
  }
  _updateContent(node2) {
    const contentsDomNode = this._hover.contentsDomNode;
    contentsDomNode.style.paddingBottom = "";
    contentsDomNode.textContent = "";
    contentsDomNode.appendChild(node2);
  }
  _layoutContentWidget() {
    this._editor.layoutContentWidget(this);
    this._hover.onContentsChanged();
  }
  _updateMaxDimensions() {
    const height = Math.max(this._editor.getLayoutInfo().height / 4, 250, ContentHoverWidget2._lastDimensions.height);
    const width = Math.max(this._editor.getLayoutInfo().width * 0.66, 500, ContentHoverWidget2._lastDimensions.width);
    this._setHoverWidgetMaxDimensions(width, height);
  }
  _render(node2, hoverData) {
    this._setHoverData(hoverData);
    this._updateFont();
    this._updateContent(node2);
    this._updateMaxDimensions();
    this.onContentsChanged();
    this._editor.render();
  }
  getPosition() {
    var _a2;
    if (!this._visibleData) {
      return null;
    }
    return {
      position: this._visibleData.showAtPosition,
      secondaryPosition: this._visibleData.showAtSecondaryPosition,
      positionAffinity: this._visibleData.isBeforeContent ? 3 : void 0,
      preference: [
        (_a2 = this._positionPreference) !== null && _a2 !== void 0 ? _a2 : 1
        /* ContentWidgetPositionPreference.ABOVE */
      ]
    };
  }
  showAt(node2, hoverData) {
    var _a2, _b2;
    if (!this._editor || !this._editor.hasModel()) {
      return;
    }
    this._render(node2, hoverData);
    const widgetHeight = getTotalHeight(this._hover.containerDomNode);
    const widgetPosition = hoverData.showAtPosition;
    this._positionPreference = (_a2 = this._findPositionPreference(widgetHeight, widgetPosition)) !== null && _a2 !== void 0 ? _a2 : 1;
    this.onContentsChanged();
    if (hoverData.stoleFocus) {
      this._hover.containerDomNode.focus();
    }
    (_b2 = hoverData.colorPicker) === null || _b2 === void 0 ? void 0 : _b2.layout();
  }
  hide() {
    if (!this._visibleData) {
      return;
    }
    const stoleFocus = this._visibleData.stoleFocus || this._hoverFocusedKey.get();
    this._setHoverData(void 0);
    this._resizableNode.maxSize = new Dimension(Infinity, Infinity);
    this._resizableNode.clearSashHoverState();
    this._hoverFocusedKey.set(false);
    this._editor.layoutContentWidget(this);
    if (stoleFocus) {
      this._editor.focus();
    }
  }
  _removeConstraintsRenderNormally() {
    const layoutInfo = this._editor.getLayoutInfo();
    this._resizableNode.layout(layoutInfo.height, layoutInfo.width);
    this._setHoverWidgetDimensions("auto", "auto");
  }
  _adjustHoverHeightForScrollbar(height) {
    var _a2;
    const containerDomNode = this._hover.containerDomNode;
    const contentsDomNode = this._hover.contentsDomNode;
    const maxRenderingHeight = (_a2 = this._findMaximumRenderingHeight()) !== null && _a2 !== void 0 ? _a2 : Infinity;
    this._setContainerDomNodeDimensions(getTotalWidth(containerDomNode), Math.min(maxRenderingHeight, height));
    this._setContentsDomNodeDimensions(getTotalWidth(contentsDomNode), Math.min(maxRenderingHeight, height - SCROLLBAR_WIDTH));
  }
  setMinimumDimensions(dimensions) {
    this._resizableNode.minSize = dimensions;
  }
  onContentsChanged() {
    var _a2;
    this._removeConstraintsRenderNormally();
    const containerDomNode = this._hover.containerDomNode;
    let height = getTotalHeight(containerDomNode);
    let width = getTotalWidth(containerDomNode);
    this._resizableNode.layout(height, width);
    this._setHoverWidgetDimensions(width, height);
    height = getTotalHeight(containerDomNode);
    width = getTotalWidth(containerDomNode);
    this._resizableNode.layout(height, width);
    if (this._hasHorizontalScrollbar()) {
      this._adjustContentsBottomPadding();
      this._adjustHoverHeightForScrollbar(height);
    }
    if ((_a2 = this._visibleData) === null || _a2 === void 0 ? void 0 : _a2.showAtPosition) {
      const widgetHeight = getTotalHeight(this._hover.containerDomNode);
      this._positionPreference = this._findPositionPreference(widgetHeight, this._visibleData.showAtPosition);
    }
    this._layoutContentWidget();
  }
  focus() {
    this._hover.containerDomNode.focus();
  }
  scrollUp() {
    const scrollTop = this._hover.scrollbar.getScrollPosition().scrollTop;
    const fontInfo = this._editor.getOption(
      49
      /* EditorOption.fontInfo */
    );
    this._hover.scrollbar.setScrollPosition({ scrollTop: scrollTop - fontInfo.lineHeight });
  }
  scrollDown() {
    const scrollTop = this._hover.scrollbar.getScrollPosition().scrollTop;
    const fontInfo = this._editor.getOption(
      49
      /* EditorOption.fontInfo */
    );
    this._hover.scrollbar.setScrollPosition({ scrollTop: scrollTop + fontInfo.lineHeight });
  }
  scrollLeft() {
    const scrollLeft = this._hover.scrollbar.getScrollPosition().scrollLeft;
    this._hover.scrollbar.setScrollPosition({ scrollLeft: scrollLeft - HORIZONTAL_SCROLLING_BY });
  }
  scrollRight() {
    const scrollLeft = this._hover.scrollbar.getScrollPosition().scrollLeft;
    this._hover.scrollbar.setScrollPosition({ scrollLeft: scrollLeft + HORIZONTAL_SCROLLING_BY });
  }
  pageUp() {
    const scrollTop = this._hover.scrollbar.getScrollPosition().scrollTop;
    const scrollHeight = this._hover.scrollbar.getScrollDimensions().height;
    this._hover.scrollbar.setScrollPosition({ scrollTop: scrollTop - scrollHeight });
  }
  pageDown() {
    const scrollTop = this._hover.scrollbar.getScrollPosition().scrollTop;
    const scrollHeight = this._hover.scrollbar.getScrollDimensions().height;
    this._hover.scrollbar.setScrollPosition({ scrollTop: scrollTop + scrollHeight });
  }
  goToTop() {
    this._hover.scrollbar.setScrollPosition({ scrollTop: 0 });
  }
  goToBottom() {
    this._hover.scrollbar.setScrollPosition({ scrollTop: this._hover.scrollbar.getScrollDimensions().scrollHeight });
  }
};
ContentHoverWidget.ID = "editor.contrib.resizableContentHoverWidget";
ContentHoverWidget._lastDimensions = new Dimension(0, 0);
ContentHoverWidget = __decorate$1x([
  __param$1v(2, IContextKeyService)
], ContentHoverWidget);
let EditorHoverStatusBar = class EditorHoverStatusBar2 extends Disposable {
  get hasContent() {
    return this._hasContent;
  }
  constructor(_keybindingService) {
    super();
    this._keybindingService = _keybindingService;
    this._hasContent = false;
    this.hoverElement = $$7("div.hover-row.status-bar");
    this.actionsElement = append$1(this.hoverElement, $$7("div.actions"));
  }
  addAction(actionOptions) {
    const keybinding = this._keybindingService.lookupKeybinding(actionOptions.commandId);
    const keybindingLabel2 = keybinding ? keybinding.getLabel() : null;
    this._hasContent = true;
    return this._register(HoverAction.render(this.actionsElement, actionOptions, keybindingLabel2));
  }
  append(element) {
    const result2 = append$1(this.actionsElement, element);
    this._hasContent = true;
    return result2;
  }
};
EditorHoverStatusBar = __decorate$1x([
  __param$1v(0, IKeybindingService)
], EditorHoverStatusBar);
class ContentHoverComputer {
  get anchor() {
    return this._anchor;
  }
  set anchor(value) {
    this._anchor = value;
  }
  get shouldFocus() {
    return this._shouldFocus;
  }
  set shouldFocus(value) {
    this._shouldFocus = value;
  }
  get source() {
    return this._source;
  }
  set source(value) {
    this._source = value;
  }
  get insistOnKeepingHoverVisible() {
    return this._insistOnKeepingHoverVisible;
  }
  set insistOnKeepingHoverVisible(value) {
    this._insistOnKeepingHoverVisible = value;
  }
  constructor(_editor, _participants) {
    this._editor = _editor;
    this._participants = _participants;
    this._anchor = null;
    this._shouldFocus = false;
    this._source = 0;
    this._insistOnKeepingHoverVisible = false;
  }
  static _getLineDecorations(editor2, anchor) {
    if (anchor.type !== 1 && !anchor.supportsMarkerHover) {
      return [];
    }
    const model = editor2.getModel();
    const lineNumber = anchor.range.startLineNumber;
    if (lineNumber > model.getLineCount()) {
      return [];
    }
    const maxColumn = model.getLineMaxColumn(lineNumber);
    return editor2.getLineDecorations(lineNumber).filter((d) => {
      if (d.options.isWholeLine) {
        return true;
      }
      const startColumn = d.range.startLineNumber === lineNumber ? d.range.startColumn : 1;
      const endColumn = d.range.endLineNumber === lineNumber ? d.range.endColumn : maxColumn;
      if (d.options.showIfCollapsed) {
        if (startColumn > anchor.range.startColumn + 1 || anchor.range.endColumn - 1 > endColumn) {
          return false;
        }
      } else {
        if (startColumn > anchor.range.startColumn || anchor.range.endColumn > endColumn) {
          return false;
        }
      }
      return true;
    });
  }
  computeAsync(token) {
    const anchor = this._anchor;
    if (!this._editor.hasModel() || !anchor) {
      return AsyncIterableObject.EMPTY;
    }
    const lineDecorations = ContentHoverComputer._getLineDecorations(this._editor, anchor);
    return AsyncIterableObject.merge(this._participants.map((participant) => {
      if (!participant.computeAsync) {
        return AsyncIterableObject.EMPTY;
      }
      return participant.computeAsync(anchor, lineDecorations, token);
    }));
  }
  computeSync() {
    if (!this._editor.hasModel() || !this._anchor) {
      return [];
    }
    const lineDecorations = ContentHoverComputer._getLineDecorations(this._editor, this._anchor);
    let result2 = [];
    for (const participant of this._participants) {
      result2 = result2.concat(participant.computeSync(this._anchor, lineDecorations));
    }
    return coalesce(result2);
  }
}
function computeDistanceFromPointToRectangle(pointX, pointY, left, top, width, height) {
  const x = left + width / 2;
  const y = top + height / 2;
  const dx = Math.max(Math.abs(pointX - x) - width / 2, 0);
  const dy = Math.max(Math.abs(pointY - y) - height / 2, 0);
  return Math.sqrt(dx * dx + dy * dy);
}
const $$6 = $$d;
class MarginHoverWidget extends Disposable {
  constructor(editor2, languageService, openerService) {
    super();
    this._renderDisposeables = this._register(new DisposableStore());
    this._editor = editor2;
    this._isVisible = false;
    this._messages = [];
    this._hover = this._register(new HoverWidget());
    this._hover.containerDomNode.classList.toggle("hidden", !this._isVisible);
    this._markdownRenderer = this._register(new MarkdownRenderer({ editor: this._editor }, languageService, openerService));
    this._computer = new MarginHoverComputer(this._editor);
    this._hoverOperation = this._register(new HoverOperation(this._editor, this._computer));
    this._register(this._hoverOperation.onResult((result2) => {
      this._withResult(result2.value);
    }));
    this._register(this._editor.onDidChangeModelDecorations(() => this._onModelDecorationsChanged()));
    this._register(this._editor.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        49
        /* EditorOption.fontInfo */
      )) {
        this._updateFont();
      }
    }));
    this._editor.addOverlayWidget(this);
  }
  dispose() {
    this._editor.removeOverlayWidget(this);
    super.dispose();
  }
  getId() {
    return MarginHoverWidget.ID;
  }
  getDomNode() {
    return this._hover.containerDomNode;
  }
  getPosition() {
    return null;
  }
  _updateFont() {
    const codeClasses = Array.prototype.slice.call(this._hover.contentsDomNode.getElementsByClassName("code"));
    codeClasses.forEach((node2) => this._editor.applyFontInfo(node2));
  }
  _onModelDecorationsChanged() {
    if (this._isVisible) {
      this._hoverOperation.cancel();
      this._hoverOperation.start(
        0
        /* HoverStartMode.Delayed */
      );
    }
  }
  startShowingAt(lineNumber) {
    if (this._computer.lineNumber === lineNumber) {
      return;
    }
    this._hoverOperation.cancel();
    this.hide();
    this._computer.lineNumber = lineNumber;
    this._hoverOperation.start(
      0
      /* HoverStartMode.Delayed */
    );
  }
  hide() {
    this._computer.lineNumber = -1;
    this._hoverOperation.cancel();
    if (!this._isVisible) {
      return;
    }
    this._isVisible = false;
    this._hover.containerDomNode.classList.toggle("hidden", !this._isVisible);
  }
  _withResult(result2) {
    this._messages = result2;
    if (this._messages.length > 0) {
      this._renderMessages(this._computer.lineNumber, this._messages);
    } else {
      this.hide();
    }
  }
  _renderMessages(lineNumber, messages) {
    this._renderDisposeables.clear();
    const fragment = document.createDocumentFragment();
    for (const msg of messages) {
      const markdownHoverElement = $$6("div.hover-row.markdown-hover");
      const hoverContentsElement = append$1(markdownHoverElement, $$6("div.hover-contents"));
      const renderedContents = this._renderDisposeables.add(this._markdownRenderer.render(msg.value));
      hoverContentsElement.appendChild(renderedContents.element);
      fragment.appendChild(markdownHoverElement);
    }
    this._updateContents(fragment);
    this._showAt(lineNumber);
  }
  _updateContents(node2) {
    this._hover.contentsDomNode.textContent = "";
    this._hover.contentsDomNode.appendChild(node2);
    this._updateFont();
  }
  _showAt(lineNumber) {
    if (!this._isVisible) {
      this._isVisible = true;
      this._hover.containerDomNode.classList.toggle("hidden", !this._isVisible);
    }
    const editorLayout = this._editor.getLayoutInfo();
    const topForLineNumber = this._editor.getTopForLineNumber(lineNumber);
    const editorScrollTop = this._editor.getScrollTop();
    const lineHeight = this._editor.getOption(
      65
      /* EditorOption.lineHeight */
    );
    const nodeHeight = this._hover.containerDomNode.clientHeight;
    const top = topForLineNumber - editorScrollTop - (nodeHeight - lineHeight) / 2;
    this._hover.containerDomNode.style.left = `${editorLayout.glyphMarginLeft + editorLayout.glyphMarginWidth}px`;
    this._hover.containerDomNode.style.top = `${Math.max(Math.round(top), 0)}px`;
  }
}
MarginHoverWidget.ID = "editor.contrib.modesGlyphHoverWidget";
class MarginHoverComputer {
  get lineNumber() {
    return this._lineNumber;
  }
  set lineNumber(value) {
    this._lineNumber = value;
  }
  constructor(_editor) {
    this._editor = _editor;
    this._lineNumber = -1;
  }
  computeSync() {
    const toHoverMessage = (contents) => {
      return {
        value: contents
      };
    };
    const lineDecorations = this._editor.getLineDecorations(this._lineNumber);
    const result2 = [];
    if (!lineDecorations) {
      return result2;
    }
    for (const d of lineDecorations) {
      if (!d.options.glyphMarginClassName) {
        continue;
      }
      const hoverMessage = d.options.glyphMarginHoverMessage;
      if (!hoverMessage || isEmptyMarkdownString(hoverMessage)) {
        continue;
      }
      result2.push(...asArray(hoverMessage).map(toHoverMessage));
    }
    return result2;
  }
}
var __awaiter$10 = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class HoverProviderResult {
  constructor(provider, hover2, ordinal) {
    this.provider = provider;
    this.hover = hover2;
    this.ordinal = ordinal;
  }
}
function executeProvider(provider, ordinal, model, position, token) {
  return __awaiter$10(this, void 0, void 0, function* () {
    try {
      const result2 = yield Promise.resolve(provider.provideHover(model, position, token));
      if (result2 && isValid(result2)) {
        return new HoverProviderResult(provider, result2, ordinal);
      }
    } catch (err) {
      onUnexpectedExternalError(err);
    }
    return void 0;
  });
}
function getHover(registry, model, position, token) {
  const providers = registry.ordered(model);
  const promises = providers.map((provider, index) => executeProvider(provider, index, model, position, token));
  return AsyncIterableObject.fromPromises(promises).coalesce();
}
function getHoverPromise(registry, model, position, token) {
  return getHover(registry, model, position, token).map((item) => item.hover).toPromise();
}
registerModelAndPositionCommand("_executeHoverProvider", (accessor, model, position) => {
  const languageFeaturesService = accessor.get(ILanguageFeaturesService);
  return getHoverPromise(languageFeaturesService.hoverProvider, model, position, CancellationToken.None);
});
function isValid(result2) {
  const hasRange = typeof result2.range !== "undefined";
  const hasHtmlContent = typeof result2.contents !== "undefined" && result2.contents && result2.contents.length > 0;
  return hasRange && hasHtmlContent;
}
var __decorate$1w = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1u = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
const $$5 = $$d;
class MarkdownHover {
  constructor(owner, range2, contents, isBeforeContent, ordinal) {
    this.owner = owner;
    this.range = range2;
    this.contents = contents;
    this.isBeforeContent = isBeforeContent;
    this.ordinal = ordinal;
  }
  isValidForHoverAnchor(anchor) {
    return anchor.type === 1 && this.range.startColumn <= anchor.range.startColumn && this.range.endColumn >= anchor.range.endColumn;
  }
}
let MarkdownHoverParticipant = class MarkdownHoverParticipant2 {
  constructor(_editor, _languageService, _openerService, _configurationService, _languageFeaturesService) {
    this._editor = _editor;
    this._languageService = _languageService;
    this._openerService = _openerService;
    this._configurationService = _configurationService;
    this._languageFeaturesService = _languageFeaturesService;
    this.hoverOrdinal = 3;
  }
  createLoadingMessage(anchor) {
    return new MarkdownHover(this, anchor.range, [new MarkdownString().appendText(localize("modesContentHover.loading", "Loading..."))], false, 2e3);
  }
  computeSync(anchor, lineDecorations) {
    if (!this._editor.hasModel() || anchor.type !== 1) {
      return [];
    }
    const model = this._editor.getModel();
    const lineNumber = anchor.range.startLineNumber;
    const maxColumn = model.getLineMaxColumn(lineNumber);
    const result2 = [];
    let index = 1e3;
    const lineLength = model.getLineLength(lineNumber);
    const languageId = model.getLanguageIdAtPosition(anchor.range.startLineNumber, anchor.range.startColumn);
    const stopRenderingLineAfter = this._editor.getOption(
      115
      /* EditorOption.stopRenderingLineAfter */
    );
    const maxTokenizationLineLength = this._configurationService.getValue("editor.maxTokenizationLineLength", {
      overrideIdentifier: languageId
    });
    let stopRenderingMessage = false;
    if (stopRenderingLineAfter >= 0 && lineLength > stopRenderingLineAfter && anchor.range.startColumn >= stopRenderingLineAfter) {
      stopRenderingMessage = true;
      result2.push(new MarkdownHover(this, anchor.range, [{
        value: localize("stopped rendering", "Rendering paused for long line for performance reasons. This can be configured via `editor.stopRenderingLineAfter`.")
      }], false, index++));
    }
    if (!stopRenderingMessage && typeof maxTokenizationLineLength === "number" && lineLength >= maxTokenizationLineLength) {
      result2.push(new MarkdownHover(this, anchor.range, [{
        value: localize("too many characters", "Tokenization is skipped for long lines for performance reasons. This can be configured via `editor.maxTokenizationLineLength`.")
      }], false, index++));
    }
    let isBeforeContent = false;
    for (const d of lineDecorations) {
      const startColumn = d.range.startLineNumber === lineNumber ? d.range.startColumn : 1;
      const endColumn = d.range.endLineNumber === lineNumber ? d.range.endColumn : maxColumn;
      const hoverMessage = d.options.hoverMessage;
      if (!hoverMessage || isEmptyMarkdownString(hoverMessage)) {
        continue;
      }
      if (d.options.beforeContentClassName) {
        isBeforeContent = true;
      }
      const range2 = new Range$2(anchor.range.startLineNumber, startColumn, anchor.range.startLineNumber, endColumn);
      result2.push(new MarkdownHover(this, range2, asArray(hoverMessage), isBeforeContent, index++));
    }
    return result2;
  }
  computeAsync(anchor, lineDecorations, token) {
    if (!this._editor.hasModel() || anchor.type !== 1) {
      return AsyncIterableObject.EMPTY;
    }
    const model = this._editor.getModel();
    if (!this._languageFeaturesService.hoverProvider.has(model)) {
      return AsyncIterableObject.EMPTY;
    }
    const position = new Position$2(anchor.range.startLineNumber, anchor.range.startColumn);
    return getHover(this._languageFeaturesService.hoverProvider, model, position, token).filter((item) => !isEmptyMarkdownString(item.hover.contents)).map((item) => {
      const rng = item.hover.range ? Range$2.lift(item.hover.range) : anchor.range;
      return new MarkdownHover(this, rng, item.hover.contents, false, item.ordinal);
    });
  }
  renderHoverParts(context, hoverParts) {
    return renderMarkdownHovers(context, hoverParts, this._editor, this._languageService, this._openerService);
  }
};
MarkdownHoverParticipant = __decorate$1w([
  __param$1u(1, ILanguageService),
  __param$1u(2, IOpenerService),
  __param$1u(3, IConfigurationService),
  __param$1u(4, ILanguageFeaturesService)
], MarkdownHoverParticipant);
function renderMarkdownHovers(context, hoverParts, editor2, languageService, openerService) {
  hoverParts.sort((a, b) => a.ordinal - b.ordinal);
  const disposables = new DisposableStore();
  for (const hoverPart of hoverParts) {
    for (const contents of hoverPart.contents) {
      if (isEmptyMarkdownString(contents)) {
        continue;
      }
      const markdownHoverElement = $$5("div.hover-row.markdown-hover");
      const hoverContentsElement = append$1(markdownHoverElement, $$5("div.hover-contents"));
      const renderer2 = disposables.add(new MarkdownRenderer({ editor: editor2 }, languageService, openerService));
      disposables.add(renderer2.onDidRenderAsync(() => {
        hoverContentsElement.className = "hover-contents code-hover-contents";
        context.onContentsChanged();
      }));
      const renderedContents = disposables.add(renderer2.render(contents));
      hoverContentsElement.appendChild(renderedContents.element);
      context.fragment.appendChild(markdownHoverElement);
    }
  }
  return disposables;
}
var __decorate$1v = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1t = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
class MarkerCoordinate {
  constructor(marker, index, total) {
    this.marker = marker;
    this.index = index;
    this.total = total;
  }
}
let MarkerList = class MarkerList2 {
  constructor(resourceFilter, _markerService, _configService) {
    this._markerService = _markerService;
    this._configService = _configService;
    this._onDidChange = new Emitter$1();
    this.onDidChange = this._onDidChange.event;
    this._dispoables = new DisposableStore();
    this._markers = [];
    this._nextIdx = -1;
    if (URI.isUri(resourceFilter)) {
      this._resourceFilter = (uri) => uri.toString() === resourceFilter.toString();
    } else if (resourceFilter) {
      this._resourceFilter = resourceFilter;
    }
    const compareOrder = this._configService.getValue("problems.sortOrder");
    const compareMarker = (a, b) => {
      let res = compare(a.resource.toString(), b.resource.toString());
      if (res === 0) {
        if (compareOrder === "position") {
          res = Range$2.compareRangesUsingStarts(a, b) || MarkerSeverity$2.compare(a.severity, b.severity);
        } else {
          res = MarkerSeverity$2.compare(a.severity, b.severity) || Range$2.compareRangesUsingStarts(a, b);
        }
      }
      return res;
    };
    const updateMarker = () => {
      this._markers = this._markerService.read({
        resource: URI.isUri(resourceFilter) ? resourceFilter : void 0,
        severities: MarkerSeverity$2.Error | MarkerSeverity$2.Warning | MarkerSeverity$2.Info
      });
      if (typeof resourceFilter === "function") {
        this._markers = this._markers.filter((m) => this._resourceFilter(m.resource));
      }
      this._markers.sort(compareMarker);
    };
    updateMarker();
    this._dispoables.add(_markerService.onMarkerChanged((uris) => {
      if (!this._resourceFilter || uris.some((uri) => this._resourceFilter(uri))) {
        updateMarker();
        this._nextIdx = -1;
        this._onDidChange.fire();
      }
    }));
  }
  dispose() {
    this._dispoables.dispose();
    this._onDidChange.dispose();
  }
  matches(uri) {
    if (!this._resourceFilter && !uri) {
      return true;
    }
    if (!this._resourceFilter || !uri) {
      return false;
    }
    return this._resourceFilter(uri);
  }
  get selected() {
    const marker = this._markers[this._nextIdx];
    return marker && new MarkerCoordinate(marker, this._nextIdx + 1, this._markers.length);
  }
  _initIdx(model, position, fwd) {
    let found = false;
    let idx = this._markers.findIndex((marker) => marker.resource.toString() === model.uri.toString());
    if (idx < 0) {
      idx = binarySearch$4(this._markers, { resource: model.uri }, (a, b) => compare(a.resource.toString(), b.resource.toString()));
      if (idx < 0) {
        idx = ~idx;
      }
    }
    for (let i = idx; i < this._markers.length; i++) {
      let range2 = Range$2.lift(this._markers[i]);
      if (range2.isEmpty()) {
        const word2 = model.getWordAtPosition(range2.getStartPosition());
        if (word2) {
          range2 = new Range$2(range2.startLineNumber, word2.startColumn, range2.startLineNumber, word2.endColumn);
        }
      }
      if (position && (range2.containsPosition(position) || position.isBeforeOrEqual(range2.getStartPosition()))) {
        this._nextIdx = i;
        found = true;
        break;
      }
      if (this._markers[i].resource.toString() !== model.uri.toString()) {
        break;
      }
    }
    if (!found) {
      this._nextIdx = fwd ? 0 : this._markers.length - 1;
    }
    if (this._nextIdx < 0) {
      this._nextIdx = this._markers.length - 1;
    }
  }
  resetIndex() {
    this._nextIdx = -1;
  }
  move(fwd, model, position) {
    if (this._markers.length === 0) {
      return false;
    }
    const oldIdx = this._nextIdx;
    if (this._nextIdx === -1) {
      this._initIdx(model, position, fwd);
    } else if (fwd) {
      this._nextIdx = (this._nextIdx + 1) % this._markers.length;
    } else if (!fwd) {
      this._nextIdx = (this._nextIdx - 1 + this._markers.length) % this._markers.length;
    }
    if (oldIdx !== this._nextIdx) {
      return true;
    }
    return false;
  }
  find(uri, position) {
    let idx = this._markers.findIndex((marker) => marker.resource.toString() === uri.toString());
    if (idx < 0) {
      return void 0;
    }
    for (; idx < this._markers.length; idx++) {
      if (Range$2.containsPosition(this._markers[idx], position)) {
        return new MarkerCoordinate(this._markers[idx], idx + 1, this._markers.length);
      }
    }
    return void 0;
  }
};
MarkerList = __decorate$1v([
  __param$1t(1, IMarkerService),
  __param$1t(2, IConfigurationService)
], MarkerList);
const IMarkerNavigationService = createDecorator("IMarkerNavigationService");
let MarkerNavigationService = class MarkerNavigationService2 {
  constructor(_markerService, _configService) {
    this._markerService = _markerService;
    this._configService = _configService;
    this._provider = new LinkedList();
  }
  getMarkerList(resource) {
    for (const provider of this._provider) {
      const result2 = provider.getMarkerList(resource);
      if (result2) {
        return result2;
      }
    }
    return new MarkerList(resource, this._markerService, this._configService);
  }
};
MarkerNavigationService = __decorate$1v([
  __param$1t(0, IMarkerService),
  __param$1t(1, IConfigurationService)
], MarkerNavigationService);
registerSingleton(
  IMarkerNavigationService,
  MarkerNavigationService,
  1
  /* InstantiationType.Delayed */
);
const gotoErrorWidget = "";
const severityIcon = "";
var SeverityIcon;
(function(SeverityIcon2) {
  function className3(severity) {
    switch (severity) {
      case Severity$2.Ignore:
        return "severity-ignore " + ThemeIcon.asClassName(Codicon.info);
      case Severity$2.Info:
        return ThemeIcon.asClassName(Codicon.info);
      case Severity$2.Warning:
        return ThemeIcon.asClassName(Codicon.warning);
      case Severity$2.Error:
        return ThemeIcon.asClassName(Codicon.error);
      default:
        return "";
    }
  }
  SeverityIcon2.className = className3;
})(SeverityIcon || (SeverityIcon = {}));
var __decorate$1u = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1s = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
class MessageWidget2 {
  constructor(parent, editor2, onRelatedInformation, _openerService, _labelService) {
    this._openerService = _openerService;
    this._labelService = _labelService;
    this._lines = 0;
    this._longestLineLength = 0;
    this._relatedDiagnostics = /* @__PURE__ */ new WeakMap();
    this._disposables = new DisposableStore();
    this._editor = editor2;
    const domNode = document.createElement("div");
    domNode.className = "descriptioncontainer";
    this._messageBlock = document.createElement("div");
    this._messageBlock.classList.add("message");
    this._messageBlock.setAttribute("aria-live", "assertive");
    this._messageBlock.setAttribute("role", "alert");
    domNode.appendChild(this._messageBlock);
    this._relatedBlock = document.createElement("div");
    domNode.appendChild(this._relatedBlock);
    this._disposables.add(addStandardDisposableListener(this._relatedBlock, "click", (event) => {
      event.preventDefault();
      const related = this._relatedDiagnostics.get(event.target);
      if (related) {
        onRelatedInformation(related);
      }
    }));
    this._scrollable = new ScrollableElement(domNode, {
      horizontal: 1,
      vertical: 1,
      useShadows: false,
      horizontalScrollbarSize: 6,
      verticalScrollbarSize: 6
    });
    parent.appendChild(this._scrollable.getDomNode());
    this._disposables.add(this._scrollable.onScroll((e) => {
      domNode.style.left = `-${e.scrollLeft}px`;
      domNode.style.top = `-${e.scrollTop}px`;
    }));
    this._disposables.add(this._scrollable);
  }
  dispose() {
    dispose(this._disposables);
  }
  update(marker) {
    const { source, message, relatedInformation, code } = marker;
    let sourceAndCodeLength = ((source === null || source === void 0 ? void 0 : source.length) || 0) + "()".length;
    if (code) {
      if (typeof code === "string") {
        sourceAndCodeLength += code.length;
      } else {
        sourceAndCodeLength += code.value.length;
      }
    }
    const lines = splitLines(message);
    this._lines = lines.length;
    this._longestLineLength = 0;
    for (const line of lines) {
      this._longestLineLength = Math.max(line.length + sourceAndCodeLength, this._longestLineLength);
    }
    clearNode(this._messageBlock);
    this._messageBlock.setAttribute("aria-label", this.getAriaLabel(marker));
    this._editor.applyFontInfo(this._messageBlock);
    let lastLineElement = this._messageBlock;
    for (const line of lines) {
      lastLineElement = document.createElement("div");
      lastLineElement.innerText = line;
      if (line === "") {
        lastLineElement.style.height = this._messageBlock.style.lineHeight;
      }
      this._messageBlock.appendChild(lastLineElement);
    }
    if (source || code) {
      const detailsElement = document.createElement("span");
      detailsElement.classList.add("details");
      lastLineElement.appendChild(detailsElement);
      if (source) {
        const sourceElement = document.createElement("span");
        sourceElement.innerText = source;
        sourceElement.classList.add("source");
        detailsElement.appendChild(sourceElement);
      }
      if (code) {
        if (typeof code === "string") {
          const codeElement = document.createElement("span");
          codeElement.innerText = `(${code})`;
          codeElement.classList.add("code");
          detailsElement.appendChild(codeElement);
        } else {
          this._codeLink = $$d("a.code-link");
          this._codeLink.setAttribute("href", `${code.target.toString()}`);
          this._codeLink.onclick = (e) => {
            this._openerService.open(code.target, { allowCommands: true });
            e.preventDefault();
            e.stopPropagation();
          };
          const codeElement = append$1(this._codeLink, $$d("span"));
          codeElement.innerText = code.value;
          detailsElement.appendChild(this._codeLink);
        }
      }
    }
    clearNode(this._relatedBlock);
    this._editor.applyFontInfo(this._relatedBlock);
    if (isNonEmptyArray(relatedInformation)) {
      const relatedInformationNode = this._relatedBlock.appendChild(document.createElement("div"));
      relatedInformationNode.style.paddingTop = `${Math.floor(this._editor.getOption(
        65
        /* EditorOption.lineHeight */
      ) * 0.66)}px`;
      this._lines += 1;
      for (const related of relatedInformation) {
        const container2 = document.createElement("div");
        const relatedResource = document.createElement("a");
        relatedResource.classList.add("filename");
        relatedResource.innerText = `${this._labelService.getUriBasenameLabel(related.resource)}(${related.startLineNumber}, ${related.startColumn}): `;
        relatedResource.title = this._labelService.getUriLabel(related.resource);
        this._relatedDiagnostics.set(relatedResource, related);
        const relatedMessage = document.createElement("span");
        relatedMessage.innerText = related.message;
        container2.appendChild(relatedResource);
        container2.appendChild(relatedMessage);
        this._lines += 1;
        relatedInformationNode.appendChild(container2);
      }
    }
    const fontInfo = this._editor.getOption(
      49
      /* EditorOption.fontInfo */
    );
    const scrollWidth = Math.ceil(fontInfo.typicalFullwidthCharacterWidth * this._longestLineLength * 0.75);
    const scrollHeight = fontInfo.lineHeight * this._lines;
    this._scrollable.setScrollDimensions({ scrollWidth, scrollHeight });
  }
  layout(height, width) {
    this._scrollable.getDomNode().style.height = `${height}px`;
    this._scrollable.getDomNode().style.width = `${width}px`;
    this._scrollable.setScrollDimensions({ width, height });
  }
  getHeightInLines() {
    return Math.min(17, this._lines);
  }
  getAriaLabel(marker) {
    let severityLabel = "";
    switch (marker.severity) {
      case MarkerSeverity$2.Error:
        severityLabel = localize("Error", "Error");
        break;
      case MarkerSeverity$2.Warning:
        severityLabel = localize("Warning", "Warning");
        break;
      case MarkerSeverity$2.Info:
        severityLabel = localize("Info", "Info");
        break;
      case MarkerSeverity$2.Hint:
        severityLabel = localize("Hint", "Hint");
        break;
    }
    let ariaLabel = localize("marker aria", "{0} at {1}. ", severityLabel, marker.startLineNumber + ":" + marker.startColumn);
    const model = this._editor.getModel();
    if (model && marker.startLineNumber <= model.getLineCount() && marker.startLineNumber >= 1) {
      const lineContent = model.getLineContent(marker.startLineNumber);
      ariaLabel = `${lineContent}, ${ariaLabel}`;
    }
    return ariaLabel;
  }
}
let MarkerNavigationWidget = class MarkerNavigationWidget2 extends PeekViewWidget {
  constructor(editor2, _themeService, _openerService, _menuService, instantiationService, _contextKeyService, _labelService) {
    super(editor2, { showArrow: true, showFrame: true, isAccessible: true, frameWidth: 1 }, instantiationService);
    this._themeService = _themeService;
    this._openerService = _openerService;
    this._menuService = _menuService;
    this._contextKeyService = _contextKeyService;
    this._labelService = _labelService;
    this._callOnDispose = new DisposableStore();
    this._onDidSelectRelatedInformation = new Emitter$1();
    this.onDidSelectRelatedInformation = this._onDidSelectRelatedInformation.event;
    this._severity = MarkerSeverity$2.Warning;
    this._backgroundColor = Color.white;
    this._applyTheme(_themeService.getColorTheme());
    this._callOnDispose.add(_themeService.onDidColorThemeChange(this._applyTheme.bind(this)));
    this.create();
  }
  _applyTheme(theme) {
    this._backgroundColor = theme.getColor(editorMarkerNavigationBackground);
    let colorId = editorMarkerNavigationError;
    let headerBackground = editorMarkerNavigationErrorHeader;
    if (this._severity === MarkerSeverity$2.Warning) {
      colorId = editorMarkerNavigationWarning;
      headerBackground = editorMarkerNavigationWarningHeader;
    } else if (this._severity === MarkerSeverity$2.Info) {
      colorId = editorMarkerNavigationInfo;
      headerBackground = editorMarkerNavigationInfoHeader;
    }
    const frameColor = theme.getColor(colorId);
    const headerBg = theme.getColor(headerBackground);
    this.style({
      arrowColor: frameColor,
      frameColor,
      headerBackgroundColor: headerBg,
      primaryHeadingColor: theme.getColor(peekViewTitleForeground),
      secondaryHeadingColor: theme.getColor(peekViewTitleInfoForeground)
    });
  }
  _applyStyles() {
    if (this._parentContainer) {
      this._parentContainer.style.backgroundColor = this._backgroundColor ? this._backgroundColor.toString() : "";
    }
    super._applyStyles();
  }
  dispose() {
    this._callOnDispose.dispose();
    super.dispose();
  }
  _fillHead(container2) {
    super._fillHead(container2);
    this._disposables.add(this._actionbarWidget.actionRunner.onWillRun((e) => this.editor.focus()));
    const actions = [];
    const menu = this._menuService.createMenu(MarkerNavigationWidget2.TitleMenu, this._contextKeyService);
    createAndFillInActionBarActions(menu, void 0, actions);
    this._actionbarWidget.push(actions, { label: false, icon: true, index: 0 });
    menu.dispose();
  }
  _fillTitleIcon(container2) {
    this._icon = append$1(container2, $$d(""));
  }
  _fillBody(container2) {
    this._parentContainer = container2;
    container2.classList.add("marker-widget");
    this._parentContainer.tabIndex = 0;
    this._parentContainer.setAttribute("role", "tooltip");
    this._container = document.createElement("div");
    container2.appendChild(this._container);
    this._message = new MessageWidget2(this._container, this.editor, (related) => this._onDidSelectRelatedInformation.fire(related), this._openerService, this._labelService);
    this._disposables.add(this._message);
  }
  show() {
    throw new Error("call showAtMarker");
  }
  showAtMarker(marker, markerIdx, markerCount) {
    this._container.classList.remove("stale");
    this._message.update(marker);
    this._severity = marker.severity;
    this._applyTheme(this._themeService.getColorTheme());
    const range2 = Range$2.lift(marker);
    const editorPosition = this.editor.getPosition();
    const position = editorPosition && range2.containsPosition(editorPosition) ? editorPosition : range2.getStartPosition();
    super.show(position, this.computeRequiredHeight());
    const model = this.editor.getModel();
    if (model) {
      const detail = markerCount > 1 ? localize("problems", "{0} of {1} problems", markerIdx, markerCount) : localize("change", "{0} of {1} problem", markerIdx, markerCount);
      this.setTitle(basename$1(model.uri), detail);
    }
    this._icon.className = `codicon ${SeverityIcon.className(MarkerSeverity$2.toSeverity(this._severity))}`;
    this.editor.revealPositionNearTop(
      position,
      0
      /* ScrollType.Smooth */
    );
    this.editor.focus();
  }
  updateMarker(marker) {
    this._container.classList.remove("stale");
    this._message.update(marker);
  }
  showStale() {
    this._container.classList.add("stale");
    this._relayout();
  }
  _doLayoutBody(heightInPixel, widthInPixel) {
    super._doLayoutBody(heightInPixel, widthInPixel);
    this._heightInPixel = heightInPixel;
    this._message.layout(heightInPixel, widthInPixel);
    this._container.style.height = `${heightInPixel}px`;
  }
  _onWidth(widthInPixel) {
    this._message.layout(this._heightInPixel, widthInPixel);
  }
  _relayout() {
    super._relayout(this.computeRequiredHeight());
  }
  computeRequiredHeight() {
    return 3 + this._message.getHeightInLines();
  }
};
MarkerNavigationWidget.TitleMenu = new MenuId("gotoErrorTitleMenu");
MarkerNavigationWidget = __decorate$1u([
  __param$1s(1, IThemeService),
  __param$1s(2, IOpenerService),
  __param$1s(3, IMenuService),
  __param$1s(4, IInstantiationService),
  __param$1s(5, IContextKeyService),
  __param$1s(6, ILabelService)
], MarkerNavigationWidget);
const errorDefault = oneOf(editorErrorForeground, editorErrorBorder);
const warningDefault = oneOf(editorWarningForeground, editorWarningBorder);
const infoDefault = oneOf(editorInfoForeground, editorInfoBorder);
const editorMarkerNavigationError = registerColor("editorMarkerNavigationError.background", { dark: errorDefault, light: errorDefault, hcDark: contrastBorder, hcLight: contrastBorder }, localize("editorMarkerNavigationError", "Editor marker navigation widget error color."));
const editorMarkerNavigationErrorHeader = registerColor("editorMarkerNavigationError.headerBackground", { dark: transparent(editorMarkerNavigationError, 0.1), light: transparent(editorMarkerNavigationError, 0.1), hcDark: null, hcLight: null }, localize("editorMarkerNavigationErrorHeaderBackground", "Editor marker navigation widget error heading background."));
const editorMarkerNavigationWarning = registerColor("editorMarkerNavigationWarning.background", { dark: warningDefault, light: warningDefault, hcDark: contrastBorder, hcLight: contrastBorder }, localize("editorMarkerNavigationWarning", "Editor marker navigation widget warning color."));
const editorMarkerNavigationWarningHeader = registerColor("editorMarkerNavigationWarning.headerBackground", { dark: transparent(editorMarkerNavigationWarning, 0.1), light: transparent(editorMarkerNavigationWarning, 0.1), hcDark: "#0C141F", hcLight: transparent(editorMarkerNavigationWarning, 0.2) }, localize("editorMarkerNavigationWarningBackground", "Editor marker navigation widget warning heading background."));
const editorMarkerNavigationInfo = registerColor("editorMarkerNavigationInfo.background", { dark: infoDefault, light: infoDefault, hcDark: contrastBorder, hcLight: contrastBorder }, localize("editorMarkerNavigationInfo", "Editor marker navigation widget info color."));
const editorMarkerNavigationInfoHeader = registerColor("editorMarkerNavigationInfo.headerBackground", { dark: transparent(editorMarkerNavigationInfo, 0.1), light: transparent(editorMarkerNavigationInfo, 0.1), hcDark: null, hcLight: null }, localize("editorMarkerNavigationInfoHeaderBackground", "Editor marker navigation widget info heading background."));
const editorMarkerNavigationBackground = registerColor("editorMarkerNavigation.background", { dark: editorBackground, light: editorBackground, hcDark: editorBackground, hcLight: editorBackground }, localize("editorMarkerNavigationBackground", "Editor marker navigation widget background."));
var __decorate$1t = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1r = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$$ = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
let MarkerController = class MarkerController2 {
  static get(editor2) {
    return editor2.getContribution(MarkerController2.ID);
  }
  constructor(editor2, _markerNavigationService, _contextKeyService, _editorService, _instantiationService) {
    this._markerNavigationService = _markerNavigationService;
    this._contextKeyService = _contextKeyService;
    this._editorService = _editorService;
    this._instantiationService = _instantiationService;
    this._sessionDispoables = new DisposableStore();
    this._editor = editor2;
    this._widgetVisible = CONTEXT_MARKERS_NAVIGATION_VISIBLE.bindTo(this._contextKeyService);
  }
  dispose() {
    this._cleanUp();
    this._sessionDispoables.dispose();
  }
  _cleanUp() {
    this._widgetVisible.reset();
    this._sessionDispoables.clear();
    this._widget = void 0;
    this._model = void 0;
  }
  _getOrCreateModel(uri) {
    if (this._model && this._model.matches(uri)) {
      return this._model;
    }
    let reusePosition = false;
    if (this._model) {
      reusePosition = true;
      this._cleanUp();
    }
    this._model = this._markerNavigationService.getMarkerList(uri);
    if (reusePosition) {
      this._model.move(true, this._editor.getModel(), this._editor.getPosition());
    }
    this._widget = this._instantiationService.createInstance(MarkerNavigationWidget, this._editor);
    this._widget.onDidClose(() => this.close(), this, this._sessionDispoables);
    this._widgetVisible.set(true);
    this._sessionDispoables.add(this._model);
    this._sessionDispoables.add(this._widget);
    this._sessionDispoables.add(this._editor.onDidChangeCursorPosition((e) => {
      var _a2, _b2, _c2;
      if (!((_a2 = this._model) === null || _a2 === void 0 ? void 0 : _a2.selected) || !Range$2.containsPosition((_b2 = this._model) === null || _b2 === void 0 ? void 0 : _b2.selected.marker, e.position)) {
        (_c2 = this._model) === null || _c2 === void 0 ? void 0 : _c2.resetIndex();
      }
    }));
    this._sessionDispoables.add(this._model.onDidChange(() => {
      if (!this._widget || !this._widget.position || !this._model) {
        return;
      }
      const info = this._model.find(this._editor.getModel().uri, this._widget.position);
      if (info) {
        this._widget.updateMarker(info.marker);
      } else {
        this._widget.showStale();
      }
    }));
    this._sessionDispoables.add(this._widget.onDidSelectRelatedInformation((related) => {
      this._editorService.openCodeEditor({
        resource: related.resource,
        options: { pinned: true, revealIfOpened: true, selection: Range$2.lift(related).collapseToStart() }
      }, this._editor);
      this.close(false);
    }));
    this._sessionDispoables.add(this._editor.onDidChangeModel(() => this._cleanUp()));
    return this._model;
  }
  close(focusEditor = true) {
    this._cleanUp();
    if (focusEditor) {
      this._editor.focus();
    }
  }
  showAtMarker(marker) {
    if (this._editor.hasModel()) {
      const model = this._getOrCreateModel(this._editor.getModel().uri);
      model.resetIndex();
      model.move(true, this._editor.getModel(), new Position$2(marker.startLineNumber, marker.startColumn));
      if (model.selected) {
        this._widget.showAtMarker(model.selected.marker, model.selected.index, model.selected.total);
      }
    }
  }
  nagivate(next, multiFile) {
    var _a2, _b2;
    return __awaiter$$(this, void 0, void 0, function* () {
      if (this._editor.hasModel()) {
        const model = this._getOrCreateModel(multiFile ? void 0 : this._editor.getModel().uri);
        model.move(next, this._editor.getModel(), this._editor.getPosition());
        if (!model.selected) {
          return;
        }
        if (model.selected.marker.resource.toString() !== this._editor.getModel().uri.toString()) {
          this._cleanUp();
          const otherEditor = yield this._editorService.openCodeEditor({
            resource: model.selected.marker.resource,
            options: { pinned: false, revealIfOpened: true, selectionRevealType: 2, selection: model.selected.marker }
          }, this._editor);
          if (otherEditor) {
            (_a2 = MarkerController2.get(otherEditor)) === null || _a2 === void 0 ? void 0 : _a2.close();
            (_b2 = MarkerController2.get(otherEditor)) === null || _b2 === void 0 ? void 0 : _b2.nagivate(next, multiFile);
          }
        } else {
          this._widget.showAtMarker(model.selected.marker, model.selected.index, model.selected.total);
        }
      }
    });
  }
};
MarkerController.ID = "editor.contrib.markerController";
MarkerController = __decorate$1t([
  __param$1r(1, IMarkerNavigationService),
  __param$1r(2, IContextKeyService),
  __param$1r(3, ICodeEditorService),
  __param$1r(4, IInstantiationService)
], MarkerController);
class MarkerNavigationAction extends EditorAction {
  constructor(_next, _multiFile, opts) {
    super(opts);
    this._next = _next;
    this._multiFile = _multiFile;
  }
  run(_accessor, editor2) {
    var _a2;
    return __awaiter$$(this, void 0, void 0, function* () {
      if (editor2.hasModel()) {
        (_a2 = MarkerController.get(editor2)) === null || _a2 === void 0 ? void 0 : _a2.nagivate(this._next, this._multiFile);
      }
    });
  }
}
class NextMarkerAction extends MarkerNavigationAction {
  constructor() {
    super(true, false, {
      id: NextMarkerAction.ID,
      label: NextMarkerAction.LABEL,
      alias: "Go to Next Problem (Error, Warning, Info)",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.focus,
        primary: 512 | 66,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: MarkerNavigationWidget.TitleMenu,
        title: NextMarkerAction.LABEL,
        icon: registerIcon("marker-navigation-next", Codicon.arrowDown, localize("nextMarkerIcon", "Icon for goto next marker.")),
        group: "navigation",
        order: 1
      }
    });
  }
}
NextMarkerAction.ID = "editor.action.marker.next";
NextMarkerAction.LABEL = localize("markerAction.next.label", "Go to Next Problem (Error, Warning, Info)");
class PrevMarkerAction extends MarkerNavigationAction {
  constructor() {
    super(false, false, {
      id: PrevMarkerAction.ID,
      label: PrevMarkerAction.LABEL,
      alias: "Go to Previous Problem (Error, Warning, Info)",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.focus,
        primary: 1024 | 512 | 66,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: MarkerNavigationWidget.TitleMenu,
        title: PrevMarkerAction.LABEL,
        icon: registerIcon("marker-navigation-previous", Codicon.arrowUp, localize("previousMarkerIcon", "Icon for goto previous marker.")),
        group: "navigation",
        order: 2
      }
    });
  }
}
PrevMarkerAction.ID = "editor.action.marker.prev";
PrevMarkerAction.LABEL = localize("markerAction.previous.label", "Go to Previous Problem (Error, Warning, Info)");
class NextMarkerInFilesAction extends MarkerNavigationAction {
  constructor() {
    super(true, true, {
      id: "editor.action.marker.nextInFiles",
      label: localize("markerAction.nextInFiles.label", "Go to Next Problem in Files (Error, Warning, Info)"),
      alias: "Go to Next Problem in Files (Error, Warning, Info)",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.focus,
        primary: 66,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: MenuId.MenubarGoMenu,
        title: localize({ key: "miGotoNextProblem", comment: ["&& denotes a mnemonic"] }, "Next &&Problem"),
        group: "6_problem_nav",
        order: 1
      }
    });
  }
}
class PrevMarkerInFilesAction extends MarkerNavigationAction {
  constructor() {
    super(false, true, {
      id: "editor.action.marker.prevInFiles",
      label: localize("markerAction.previousInFiles.label", "Go to Previous Problem in Files (Error, Warning, Info)"),
      alias: "Go to Previous Problem in Files (Error, Warning, Info)",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.focus,
        primary: 1024 | 66,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: MenuId.MenubarGoMenu,
        title: localize({ key: "miGotoPreviousProblem", comment: ["&& denotes a mnemonic"] }, "Previous &&Problem"),
        group: "6_problem_nav",
        order: 2
      }
    });
  }
}
registerEditorContribution(
  MarkerController.ID,
  MarkerController,
  4
  /* EditorContributionInstantiation.Lazy */
);
registerEditorAction(NextMarkerAction);
registerEditorAction(PrevMarkerAction);
registerEditorAction(NextMarkerInFilesAction);
registerEditorAction(PrevMarkerInFilesAction);
const CONTEXT_MARKERS_NAVIGATION_VISIBLE = new RawContextKey("markersNavigationVisible", false);
const MarkerCommand = EditorCommand.bindToContribution(MarkerController.get);
registerEditorCommand(new MarkerCommand({
  id: "closeMarkersNavigation",
  precondition: CONTEXT_MARKERS_NAVIGATION_VISIBLE,
  handler: (x) => x.close(),
  kbOpts: {
    weight: 100 + 50,
    kbExpr: EditorContextKeys.focus,
    primary: 9,
    secondary: [
      1024 | 9
      /* KeyCode.Escape */
    ]
  }
}));
var __decorate$1s = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1q = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
const $$4 = $$d;
class MarkerHover {
  constructor(owner, range2, marker) {
    this.owner = owner;
    this.range = range2;
    this.marker = marker;
  }
  isValidForHoverAnchor(anchor) {
    return anchor.type === 1 && this.range.startColumn <= anchor.range.startColumn && this.range.endColumn >= anchor.range.endColumn;
  }
}
const markerCodeActionTrigger = {
  type: 1,
  filter: { include: CodeActionKind.QuickFix },
  triggerAction: CodeActionTriggerSource.QuickFixHover
};
let MarkerHoverParticipant = class MarkerHoverParticipant2 {
  constructor(_editor, _markerDecorationsService, _openerService, _languageFeaturesService) {
    this._editor = _editor;
    this._markerDecorationsService = _markerDecorationsService;
    this._openerService = _openerService;
    this._languageFeaturesService = _languageFeaturesService;
    this.hoverOrdinal = 1;
    this.recentMarkerCodeActionsInfo = void 0;
  }
  computeSync(anchor, lineDecorations) {
    if (!this._editor.hasModel() || anchor.type !== 1 && !anchor.supportsMarkerHover) {
      return [];
    }
    const model = this._editor.getModel();
    const lineNumber = anchor.range.startLineNumber;
    const maxColumn = model.getLineMaxColumn(lineNumber);
    const result2 = [];
    for (const d of lineDecorations) {
      const startColumn = d.range.startLineNumber === lineNumber ? d.range.startColumn : 1;
      const endColumn = d.range.endLineNumber === lineNumber ? d.range.endColumn : maxColumn;
      const marker = this._markerDecorationsService.getMarker(model.uri, d);
      if (!marker) {
        continue;
      }
      const range2 = new Range$2(anchor.range.startLineNumber, startColumn, anchor.range.startLineNumber, endColumn);
      result2.push(new MarkerHover(this, range2, marker));
    }
    return result2;
  }
  renderHoverParts(context, hoverParts) {
    if (!hoverParts.length) {
      return Disposable.None;
    }
    const disposables = new DisposableStore();
    hoverParts.forEach((msg) => context.fragment.appendChild(this.renderMarkerHover(msg, disposables)));
    const markerHoverForStatusbar = hoverParts.length === 1 ? hoverParts[0] : hoverParts.sort((a, b) => MarkerSeverity$2.compare(a.marker.severity, b.marker.severity))[0];
    this.renderMarkerStatusbar(context, markerHoverForStatusbar, disposables);
    return disposables;
  }
  renderMarkerHover(markerHover, disposables) {
    const hoverElement = $$4("div.hover-row");
    const markerElement = append$1(hoverElement, $$4("div.marker.hover-contents"));
    const { source, message, code, relatedInformation } = markerHover.marker;
    this._editor.applyFontInfo(markerElement);
    const messageElement = append$1(markerElement, $$4("span"));
    messageElement.style.whiteSpace = "pre-wrap";
    messageElement.innerText = message;
    if (source || code) {
      if (code && typeof code !== "string") {
        const sourceAndCodeElement = $$4("span");
        if (source) {
          const sourceElement = append$1(sourceAndCodeElement, $$4("span"));
          sourceElement.innerText = source;
        }
        const codeLink = append$1(sourceAndCodeElement, $$4("a.code-link"));
        codeLink.setAttribute("href", code.target.toString());
        disposables.add(addDisposableListener(codeLink, "click", (e) => {
          this._openerService.open(code.target, { allowCommands: true });
          e.preventDefault();
          e.stopPropagation();
        }));
        const codeElement = append$1(codeLink, $$4("span"));
        codeElement.innerText = code.value;
        const detailsElement = append$1(markerElement, sourceAndCodeElement);
        detailsElement.style.opacity = "0.6";
        detailsElement.style.paddingLeft = "6px";
      } else {
        const detailsElement = append$1(markerElement, $$4("span"));
        detailsElement.style.opacity = "0.6";
        detailsElement.style.paddingLeft = "6px";
        detailsElement.innerText = source && code ? `${source}(${code})` : source ? source : `(${code})`;
      }
    }
    if (isNonEmptyArray(relatedInformation)) {
      for (const { message: message2, resource, startLineNumber, startColumn } of relatedInformation) {
        const relatedInfoContainer = append$1(markerElement, $$4("div"));
        relatedInfoContainer.style.marginTop = "8px";
        const a = append$1(relatedInfoContainer, $$4("a"));
        a.innerText = `${basename$1(resource)}(${startLineNumber}, ${startColumn}): `;
        a.style.cursor = "pointer";
        disposables.add(addDisposableListener(a, "click", (e) => {
          e.stopPropagation();
          e.preventDefault();
          if (this._openerService) {
            this._openerService.open(resource, {
              fromUserGesture: true,
              editorOptions: { selection: { startLineNumber, startColumn } }
            }).catch(onUnexpectedError);
          }
        }));
        const messageElement2 = append$1(relatedInfoContainer, $$4("span"));
        messageElement2.innerText = message2;
        this._editor.applyFontInfo(messageElement2);
      }
    }
    return hoverElement;
  }
  renderMarkerStatusbar(context, markerHover, disposables) {
    if (markerHover.marker.severity === MarkerSeverity$2.Error || markerHover.marker.severity === MarkerSeverity$2.Warning || markerHover.marker.severity === MarkerSeverity$2.Info) {
      context.statusBar.addAction({
        label: localize("view problem", "View Problem"),
        commandId: NextMarkerAction.ID,
        run: () => {
          var _a2;
          context.hide();
          (_a2 = MarkerController.get(this._editor)) === null || _a2 === void 0 ? void 0 : _a2.showAtMarker(markerHover.marker);
          this._editor.focus();
        }
      });
    }
    if (!this._editor.getOption(
      89
      /* EditorOption.readOnly */
    )) {
      const quickfixPlaceholderElement = context.statusBar.append($$4("div"));
      if (this.recentMarkerCodeActionsInfo) {
        if (IMarkerData.makeKey(this.recentMarkerCodeActionsInfo.marker) === IMarkerData.makeKey(markerHover.marker)) {
          if (!this.recentMarkerCodeActionsInfo.hasCodeActions) {
            quickfixPlaceholderElement.textContent = localize("noQuickFixes", "No quick fixes available");
          }
        } else {
          this.recentMarkerCodeActionsInfo = void 0;
        }
      }
      const updatePlaceholderDisposable = this.recentMarkerCodeActionsInfo && !this.recentMarkerCodeActionsInfo.hasCodeActions ? Disposable.None : disposables.add(disposableTimeout(() => quickfixPlaceholderElement.textContent = localize("checkingForQuickFixes", "Checking for quick fixes..."), 200));
      if (!quickfixPlaceholderElement.textContent) {
        quickfixPlaceholderElement.textContent = String.fromCharCode(160);
      }
      const codeActionsPromise = this.getCodeActions(markerHover.marker);
      disposables.add(toDisposable(() => codeActionsPromise.cancel()));
      codeActionsPromise.then((actions) => {
        updatePlaceholderDisposable.dispose();
        this.recentMarkerCodeActionsInfo = { marker: markerHover.marker, hasCodeActions: actions.validActions.length > 0 };
        if (!this.recentMarkerCodeActionsInfo.hasCodeActions) {
          actions.dispose();
          quickfixPlaceholderElement.textContent = localize("noQuickFixes", "No quick fixes available");
          return;
        }
        quickfixPlaceholderElement.style.display = "none";
        let showing = false;
        disposables.add(toDisposable(() => {
          if (!showing) {
            actions.dispose();
          }
        }));
        context.statusBar.addAction({
          label: localize("quick fixes", "Quick Fix..."),
          commandId: quickFixCommandId,
          run: (target) => {
            showing = true;
            const controller = CodeActionController.get(this._editor);
            const elementPosition = getDomNodePagePosition(target);
            context.hide();
            controller === null || controller === void 0 ? void 0 : controller.showCodeActions(markerCodeActionTrigger, actions, {
              x: elementPosition.left,
              y: elementPosition.top,
              width: elementPosition.width,
              height: elementPosition.height
            });
          }
        });
      }, onUnexpectedError);
    }
  }
  getCodeActions(marker) {
    return createCancelablePromise((cancellationToken) => {
      return getCodeActions(this._languageFeaturesService.codeActionProvider, this._editor.getModel(), new Range$2(marker.startLineNumber, marker.startColumn, marker.endLineNumber, marker.endColumn), markerCodeActionTrigger, Progress.None, cancellationToken);
    });
  }
};
MarkerHoverParticipant = __decorate$1s([
  __param$1q(1, IMarkerDecorationsService),
  __param$1q(2, IOpenerService),
  __param$1q(3, ILanguageFeaturesService)
], MarkerHoverParticipant);
let globalObservableLogger;
function getLogger() {
  return globalObservableLogger;
}
let _derived;
function _setDerived(derived2) {
  _derived = derived2;
}
class ConvenientObservable {
  get TChange() {
    return null;
  }
  reportChanges() {
    this.get();
  }
  /** @sealed */
  read(reader) {
    if (reader) {
      return reader.readObservable(this);
    } else {
      return this.get();
    }
  }
  /** @sealed */
  map(fn) {
    return _derived(() => {
      const name = getFunctionName(fn);
      return name !== void 0 ? name : `${this.debugName} (mapped)`;
    }, (reader) => fn(this.read(reader), reader));
  }
}
class BaseObservable extends ConvenientObservable {
  constructor() {
    super(...arguments);
    this.observers = /* @__PURE__ */ new Set();
  }
  addObserver(observer) {
    const len = this.observers.size;
    this.observers.add(observer);
    if (len === 0) {
      this.onFirstObserverAdded();
    }
  }
  removeObserver(observer) {
    const deleted = this.observers.delete(observer);
    if (deleted && this.observers.size === 0) {
      this.onLastObserverRemoved();
    }
  }
  onFirstObserverAdded() {
  }
  onLastObserverRemoved() {
  }
}
function transaction(fn, getDebugName) {
  var _a2, _b2;
  const tx = new TransactionImpl(fn, getDebugName);
  try {
    (_a2 = getLogger()) === null || _a2 === void 0 ? void 0 : _a2.handleBeginTransaction(tx);
    fn(tx);
  } finally {
    tx.finish();
    (_b2 = getLogger()) === null || _b2 === void 0 ? void 0 : _b2.handleEndTransaction();
  }
}
function subtransaction(tx, fn, getDebugName) {
  if (!tx) {
    transaction(fn, getDebugName);
  } else {
    fn(tx);
  }
}
class TransactionImpl {
  constructor(fn, _getDebugName) {
    this.fn = fn;
    this._getDebugName = _getDebugName;
    this.updatingObservers = [];
  }
  getDebugName() {
    if (this._getDebugName) {
      return this._getDebugName();
    }
    return getFunctionName(this.fn);
  }
  updateObserver(observer, observable) {
    this.updatingObservers.push({ observer, observable });
    observer.beginUpdate(observable);
  }
  finish() {
    const updatingObservers = this.updatingObservers;
    this.updatingObservers = null;
    for (const { observer, observable } of updatingObservers) {
      observer.endUpdate(observable);
    }
  }
}
function getFunctionName(fn) {
  const fnSrc = fn.toString();
  const regexp = /\/\*\*\s*@description\s*([^*]*)\*\//;
  const match2 = regexp.exec(fnSrc);
  const result2 = match2 ? match2[1] : void 0;
  return result2 === null || result2 === void 0 ? void 0 : result2.trim();
}
function observableValue(name, initialValue) {
  return new ObservableValue(name, initialValue);
}
class ObservableValue extends BaseObservable {
  constructor(debugName, initialValue) {
    super();
    this.debugName = debugName;
    this._value = initialValue;
  }
  get() {
    return this._value;
  }
  set(value, tx, change) {
    var _a2;
    if (this._value === value) {
      return;
    }
    let _tx;
    if (!tx) {
      tx = _tx = new TransactionImpl(() => {
      }, () => `Setting ${this.debugName}`);
    }
    try {
      const oldValue = this._value;
      this._setValue(value);
      (_a2 = getLogger()) === null || _a2 === void 0 ? void 0 : _a2.handleObservableChanged(this, { oldValue, newValue: value, change, didChange: true });
      for (const observer of this.observers) {
        tx.updateObserver(observer, this);
        observer.handleChange(this, change);
      }
    } finally {
      if (_tx) {
        _tx.finish();
      }
    }
  }
  toString() {
    return `${this.debugName}: ${this._value}`;
  }
  _setValue(newValue) {
    this._value = newValue;
  }
}
function disposableObservableValue(name, initialValue) {
  return new DisposableObservableValue(name, initialValue);
}
class DisposableObservableValue extends ObservableValue {
  _setValue(newValue) {
    if (this._value === newValue) {
      return;
    }
    if (this._value) {
      this._value.dispose();
    }
    this._value = newValue;
  }
  dispose() {
    var _a2;
    (_a2 = this._value) === null || _a2 === void 0 ? void 0 : _a2.dispose();
  }
}
function derived(debugName, computeFn) {
  return new Derived(debugName, computeFn, void 0, void 0, void 0);
}
function derivedHandleChanges(debugName, options, computeFn) {
  return new Derived(debugName, computeFn, options.createEmptyChangeSummary, options.handleChange, void 0);
}
function derivedWithStore(name, computeFn) {
  const store = new DisposableStore();
  return new Derived(name, (r) => {
    store.clear();
    return computeFn(r, store);
  }, void 0, void 0, () => store.dispose());
}
_setDerived(derived);
class Derived extends BaseObservable {
  get debugName() {
    return typeof this._debugName === "function" ? this._debugName() : this._debugName;
  }
  constructor(_debugName, computeFn, createChangeSummary, _handleChange, _handleLastObserverRemoved = void 0) {
    var _a2, _b2;
    super();
    this._debugName = _debugName;
    this.computeFn = computeFn;
    this.createChangeSummary = createChangeSummary;
    this._handleChange = _handleChange;
    this._handleLastObserverRemoved = _handleLastObserverRemoved;
    this.state = 0;
    this.value = void 0;
    this.updateCount = 0;
    this.dependencies = /* @__PURE__ */ new Set();
    this.dependenciesToBeRemoved = /* @__PURE__ */ new Set();
    this.changeSummary = void 0;
    this.changeSummary = (_a2 = this.createChangeSummary) === null || _a2 === void 0 ? void 0 : _a2.call(this);
    (_b2 = getLogger()) === null || _b2 === void 0 ? void 0 : _b2.handleDerivedCreated(this);
  }
  onLastObserverRemoved() {
    var _a2;
    this.state = 0;
    this.value = void 0;
    for (const d of this.dependencies) {
      d.removeObserver(this);
    }
    this.dependencies.clear();
    (_a2 = this._handleLastObserverRemoved) === null || _a2 === void 0 ? void 0 : _a2.call(this);
  }
  get() {
    var _a2;
    if (this.observers.size === 0) {
      const result2 = this.computeFn(this, (_a2 = this.createChangeSummary) === null || _a2 === void 0 ? void 0 : _a2.call(this));
      this.onLastObserverRemoved();
      return result2;
    } else {
      do {
        if (this.state === 1) {
          this.state = 3;
          for (const d of this.dependencies) {
            d.reportChanges();
            if (this.state === 2) {
              break;
            }
          }
        }
        this._recomputeIfNeeded();
      } while (this.state !== 3);
      return this.value;
    }
  }
  _recomputeIfNeeded() {
    var _a2, _b2;
    if (this.state === 3) {
      return;
    }
    const emptySet = this.dependenciesToBeRemoved;
    this.dependenciesToBeRemoved = this.dependencies;
    this.dependencies = emptySet;
    const hadValue = this.state !== 0;
    const oldValue = this.value;
    this.state = 3;
    const changeSummary = this.changeSummary;
    this.changeSummary = (_a2 = this.createChangeSummary) === null || _a2 === void 0 ? void 0 : _a2.call(this);
    try {
      this.value = this.computeFn(this, changeSummary);
    } finally {
      for (const o of this.dependenciesToBeRemoved) {
        o.removeObserver(this);
      }
      this.dependenciesToBeRemoved.clear();
    }
    const didChange = hadValue && oldValue !== this.value;
    (_b2 = getLogger()) === null || _b2 === void 0 ? void 0 : _b2.handleDerivedRecomputed(this, {
      oldValue,
      newValue: this.value,
      change: void 0,
      didChange
    });
    if (didChange) {
      for (const r of this.observers) {
        r.handleChange(this, void 0);
      }
    }
  }
  toString() {
    return `LazyDerived<${this.debugName}>`;
  }
  // IObserver Implementation
  beginUpdate(_observable) {
    this.updateCount++;
    const propagateBeginUpdate = this.updateCount === 1;
    if (this.state === 3) {
      this.state = 1;
      if (!propagateBeginUpdate) {
        for (const r of this.observers) {
          r.handlePossibleChange(this);
        }
      }
    }
    if (propagateBeginUpdate) {
      for (const r of this.observers) {
        r.beginUpdate(this);
      }
    }
  }
  endUpdate(_observable) {
    this.updateCount--;
    if (this.updateCount === 0) {
      const observers = [...this.observers];
      for (const r of observers) {
        r.endUpdate(this);
      }
    }
    if (this.updateCount < 0) {
      throw new BugIndicatingError();
    }
  }
  handlePossibleChange(observable) {
    if (this.state === 3 && this.dependencies.has(observable) && !this.dependenciesToBeRemoved.has(observable)) {
      this.state = 1;
      for (const r of this.observers) {
        r.handlePossibleChange(this);
      }
    }
  }
  handleChange(observable, change) {
    if (this.dependencies.has(observable) && !this.dependenciesToBeRemoved.has(observable)) {
      const shouldReact = this._handleChange ? this._handleChange({
        changedObservable: observable,
        change,
        didChange: (o) => o === observable
      }, this.changeSummary) : true;
      const wasUpToDate = this.state === 3;
      if (shouldReact && (this.state === 1 || wasUpToDate)) {
        this.state = 2;
        if (wasUpToDate) {
          for (const r of this.observers) {
            r.handlePossibleChange(this);
          }
        }
      }
    }
  }
  // IReader Implementation
  readObservable(observable) {
    observable.addObserver(this);
    const value = observable.get();
    this.dependencies.add(observable);
    this.dependenciesToBeRemoved.delete(observable);
    return value;
  }
  addObserver(observer) {
    const shouldCallBeginUpdate = !this.observers.has(observer) && this.updateCount > 0;
    super.addObserver(observer);
    if (shouldCallBeginUpdate) {
      observer.beginUpdate(this);
    }
  }
  removeObserver(observer) {
    const shouldCallEndUpdate = this.observers.has(observer) && this.updateCount > 0;
    super.removeObserver(observer);
    if (shouldCallEndUpdate) {
      observer.endUpdate(this);
    }
  }
}
function autorun(debugName, fn) {
  return new AutorunObserver(debugName, fn, void 0, void 0);
}
function autorunHandleChanges(debugName, options, fn) {
  return new AutorunObserver(debugName, fn, options.createEmptyChangeSummary, options.handleChange);
}
function autorunWithStore2(debugName, fn) {
  return autorunWithStore(fn, debugName);
}
function autorunWithStore(fn, debugName) {
  const store = new DisposableStore();
  const disposable = autorun(debugName, (reader) => {
    store.clear();
    fn(reader, store);
  });
  return toDisposable(() => {
    disposable.dispose();
    store.dispose();
  });
}
class AutorunObserver {
  constructor(debugName, runFn, createChangeSummary, _handleChange) {
    var _a2, _b2;
    this.debugName = debugName;
    this.runFn = runFn;
    this.createChangeSummary = createChangeSummary;
    this._handleChange = _handleChange;
    this.state = 2;
    this.updateCount = 0;
    this.disposed = false;
    this.dependencies = /* @__PURE__ */ new Set();
    this.dependenciesToBeRemoved = /* @__PURE__ */ new Set();
    this.changeSummary = (_a2 = this.createChangeSummary) === null || _a2 === void 0 ? void 0 : _a2.call(this);
    (_b2 = getLogger()) === null || _b2 === void 0 ? void 0 : _b2.handleAutorunCreated(this);
    this._runIfNeeded();
  }
  dispose() {
    this.disposed = true;
    for (const o of this.dependencies) {
      o.removeObserver(this);
    }
    this.dependencies.clear();
  }
  _runIfNeeded() {
    var _a2, _b2;
    if (this.state === 3) {
      return;
    }
    const emptySet = this.dependenciesToBeRemoved;
    this.dependenciesToBeRemoved = this.dependencies;
    this.dependencies = emptySet;
    this.state = 3;
    (_a2 = getLogger()) === null || _a2 === void 0 ? void 0 : _a2.handleAutorunTriggered(this);
    try {
      const changeSummary = this.changeSummary;
      this.changeSummary = (_b2 = this.createChangeSummary) === null || _b2 === void 0 ? void 0 : _b2.call(this);
      this.runFn(this, changeSummary);
    } finally {
      for (const o of this.dependenciesToBeRemoved) {
        o.removeObserver(this);
      }
      this.dependenciesToBeRemoved.clear();
    }
  }
  toString() {
    return `Autorun<${this.debugName}>`;
  }
  // IObserver implementation
  beginUpdate() {
    if (this.state === 3) {
      this.state = 1;
    }
    this.updateCount++;
  }
  endUpdate() {
    if (this.updateCount === 1) {
      do {
        if (this.state === 1) {
          this.state = 3;
          for (const d of this.dependencies) {
            d.reportChanges();
            if (this.state === 2) {
              break;
            }
          }
        }
        this._runIfNeeded();
      } while (this.state !== 3);
    }
    this.updateCount--;
    assertFn(() => this.updateCount >= 0);
  }
  handlePossibleChange(observable) {
    if (this.state === 3 && this.dependencies.has(observable) && !this.dependenciesToBeRemoved.has(observable)) {
      this.state = 1;
    }
  }
  handleChange(observable, change) {
    if (this.dependencies.has(observable) && !this.dependenciesToBeRemoved.has(observable)) {
      const shouldReact = this._handleChange ? this._handleChange({
        changedObservable: observable,
        change,
        didChange: (o) => o === observable
      }, this.changeSummary) : true;
      if (shouldReact) {
        this.state = 2;
      }
    }
  }
  // IReader implementation
  readObservable(observable) {
    if (this.disposed) {
      return observable.get();
    }
    observable.addObserver(this);
    const value = observable.get();
    this.dependencies.add(observable);
    this.dependenciesToBeRemoved.delete(observable);
    return value;
  }
}
(function(autorun2) {
  autorun2.Observer = AutorunObserver;
})(autorun || (autorun = {}));
function constObservable(value) {
  return new ConstObservable(value);
}
class ConstObservable extends ConvenientObservable {
  constructor(value) {
    super();
    this.value = value;
  }
  get debugName() {
    return this.toString();
  }
  get() {
    return this.value;
  }
  addObserver(observer) {
  }
  removeObserver(observer) {
  }
  toString() {
    return `Const: ${this.value}`;
  }
}
function waitForState(observable, predicate) {
  return new Promise((resolve2) => {
    let didRun = false;
    let shouldDispose = false;
    const d = autorun("waitForState", (reader) => {
      const currentState = observable.read(reader);
      if (predicate(currentState)) {
        if (!didRun) {
          shouldDispose = true;
        } else {
          d.dispose();
        }
        resolve2(currentState);
      }
    });
    didRun = true;
    if (shouldDispose) {
      d.dispose();
    }
  });
}
function observableFromEvent(event, getValue2) {
  return new FromEventObservable(event, getValue2);
}
class FromEventObservable extends BaseObservable {
  constructor(event, getValue2) {
    super();
    this.event = event;
    this.getValue = getValue2;
    this.hasValue = false;
    this.handleEvent = (args) => {
      var _a2;
      const newValue = this.getValue(args);
      const didChange = !this.hasValue || this.value !== newValue;
      (_a2 = getLogger()) === null || _a2 === void 0 ? void 0 : _a2.handleFromEventObservableTriggered(this, { oldValue: this.value, newValue, change: void 0, didChange });
      if (didChange) {
        this.value = newValue;
        if (this.hasValue) {
          transaction((tx) => {
            for (const o of this.observers) {
              tx.updateObserver(o, this);
              o.handleChange(this, void 0);
            }
          }, () => {
            const name = this.getDebugName();
            return "Event fired" + (name ? `: ${name}` : "");
          });
        }
        this.hasValue = true;
      }
    };
  }
  getDebugName() {
    return getFunctionName(this.getValue);
  }
  get debugName() {
    const name = this.getDebugName();
    return "From Event" + (name ? `: ${name}` : "");
  }
  onFirstObserverAdded() {
    this.subscription = this.event(this.handleEvent);
  }
  onLastObserverRemoved() {
    this.subscription.dispose();
    this.subscription = void 0;
    this.hasValue = false;
    this.value = void 0;
  }
  get() {
    if (this.subscription) {
      if (!this.hasValue) {
        this.handleEvent(void 0);
      }
      return this.value;
    } else {
      return this.getValue(void 0);
    }
  }
}
(function(observableFromEvent2) {
  observableFromEvent2.Observer = FromEventObservable;
})(observableFromEvent || (observableFromEvent = {}));
function observableSignalFromEvent(debugName, event) {
  return new FromEventObservableSignal(debugName, event);
}
class FromEventObservableSignal extends BaseObservable {
  constructor(debugName, event) {
    super();
    this.debugName = debugName;
    this.event = event;
    this.handleEvent = () => {
      transaction((tx) => {
        for (const o of this.observers) {
          tx.updateObserver(o, this);
          o.handleChange(this, void 0);
        }
      }, () => this.debugName);
    };
  }
  onFirstObserverAdded() {
    this.subscription = this.event(this.handleEvent);
  }
  onLastObserverRemoved() {
    this.subscription.dispose();
    this.subscription = void 0;
  }
  get() {
  }
}
function observableSignal(debugName) {
  return new ObservableSignal(debugName);
}
class ObservableSignal extends BaseObservable {
  constructor(debugName) {
    super();
    this.debugName = debugName;
  }
  trigger(tx, change) {
    if (!tx) {
      transaction((tx2) => {
        this.trigger(tx2, change);
      }, () => `Trigger signal ${this.debugName}`);
      return;
    }
    for (const o of this.observers) {
      tx.updateObserver(o, this);
      o.handleChange(this, change);
    }
  }
  get() {
  }
}
function keepAlive(observable, forceRecompute) {
  const o = new KeepAliveObserver(forceRecompute !== null && forceRecompute !== void 0 ? forceRecompute : false);
  observable.addObserver(o);
  if (forceRecompute) {
    observable.reportChanges();
  }
  return toDisposable(() => {
    observable.removeObserver(o);
  });
}
class KeepAliveObserver {
  constructor(forceRecompute) {
    this.forceRecompute = forceRecompute;
    this.counter = 0;
  }
  beginUpdate(observable) {
    this.counter++;
  }
  endUpdate(observable) {
    this.counter--;
    if (this.counter === 0 && this.forceRecompute) {
      observable.reportChanges();
    }
  }
  handlePossibleChange(observable) {
  }
  handleChange(observable, change) {
  }
}
const inlineCompletionsHintsWidget = "";
const inlineSuggestCommitId = "editor.action.inlineSuggest.commit";
const showPreviousInlineSuggestionActionId = "editor.action.inlineSuggest.showPrevious";
const showNextInlineSuggestionActionId = "editor.action.inlineSuggest.showNext";
const toolbar = "";
var __awaiter$_ = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class ToolBar extends Disposable {
  constructor(container2, contextMenuProvider, options = {
    orientation: 0
    /* ActionsOrientation.HORIZONTAL */
  }) {
    super();
    this.submenuActionViewItems = [];
    this.hasSecondaryActions = false;
    this._onDidChangeDropdownVisibility = this._register(new EventMultiplexer());
    this.onDidChangeDropdownVisibility = this._onDidChangeDropdownVisibility.event;
    this.disposables = new DisposableStore();
    this.options = options;
    this.lookupKeybindings = typeof this.options.getKeyBinding === "function";
    this.toggleMenuAction = this._register(new ToggleMenuAction(() => {
      var _a2;
      return (_a2 = this.toggleMenuActionViewItem) === null || _a2 === void 0 ? void 0 : _a2.show();
    }, options.toggleMenuTitle));
    this.element = document.createElement("div");
    this.element.className = "monaco-toolbar";
    container2.appendChild(this.element);
    this.actionBar = this._register(new ActionBar(this.element, {
      orientation: options.orientation,
      ariaLabel: options.ariaLabel,
      actionRunner: options.actionRunner,
      allowContextMenu: options.allowContextMenu,
      actionViewItemProvider: (action, viewItemOptions) => {
        var _a2;
        if (action.id === ToggleMenuAction.ID) {
          this.toggleMenuActionViewItem = new DropdownMenuActionViewItem(action, action.menuActions, contextMenuProvider, {
            actionViewItemProvider: this.options.actionViewItemProvider,
            actionRunner: this.actionRunner,
            keybindingProvider: this.options.getKeyBinding,
            classNames: ThemeIcon.asClassNameArray((_a2 = options.moreIcon) !== null && _a2 !== void 0 ? _a2 : Codicon.toolBarMore),
            anchorAlignmentProvider: this.options.anchorAlignmentProvider,
            menuAsChild: !!this.options.renderDropdownAsChildElement,
            skipTelemetry: this.options.skipTelemetry
          });
          this.toggleMenuActionViewItem.setActionContext(this.actionBar.context);
          this.disposables.add(this._onDidChangeDropdownVisibility.add(this.toggleMenuActionViewItem.onDidChangeVisibility));
          return this.toggleMenuActionViewItem;
        }
        if (options.actionViewItemProvider) {
          const result2 = options.actionViewItemProvider(action, viewItemOptions);
          if (result2) {
            return result2;
          }
        }
        if (action instanceof SubmenuAction) {
          const result2 = new DropdownMenuActionViewItem(action, action.actions, contextMenuProvider, {
            actionViewItemProvider: this.options.actionViewItemProvider,
            actionRunner: this.actionRunner,
            keybindingProvider: this.options.getKeyBinding,
            classNames: action.class,
            anchorAlignmentProvider: this.options.anchorAlignmentProvider,
            menuAsChild: !!this.options.renderDropdownAsChildElement,
            skipTelemetry: this.options.skipTelemetry
          });
          result2.setActionContext(this.actionBar.context);
          this.submenuActionViewItems.push(result2);
          this.disposables.add(this._onDidChangeDropdownVisibility.add(result2.onDidChangeVisibility));
          return result2;
        }
        return void 0;
      }
    }));
  }
  set actionRunner(actionRunner) {
    this.actionBar.actionRunner = actionRunner;
  }
  get actionRunner() {
    return this.actionBar.actionRunner;
  }
  getElement() {
    return this.element;
  }
  getItemAction(indexOrElement) {
    return this.actionBar.getAction(indexOrElement);
  }
  setActions(primaryActions, secondaryActions) {
    this.clear();
    const primaryActionsToSet = primaryActions ? primaryActions.slice(0) : [];
    this.hasSecondaryActions = !!(secondaryActions && secondaryActions.length > 0);
    if (this.hasSecondaryActions && secondaryActions) {
      this.toggleMenuAction.menuActions = secondaryActions.slice(0);
      primaryActionsToSet.push(this.toggleMenuAction);
    }
    primaryActionsToSet.forEach((action) => {
      this.actionBar.push(action, { icon: true, label: false, keybinding: this.getKeybindingLabel(action) });
    });
  }
  getKeybindingLabel(action) {
    var _a2, _b2;
    const key = this.lookupKeybindings ? (_b2 = (_a2 = this.options).getKeyBinding) === null || _b2 === void 0 ? void 0 : _b2.call(_a2, action) : void 0;
    return withNullAsUndefined(key === null || key === void 0 ? void 0 : key.getLabel());
  }
  clear() {
    this.submenuActionViewItems = [];
    this.disposables.clear();
    this.actionBar.clear();
  }
  dispose() {
    this.clear();
    super.dispose();
  }
}
class ToggleMenuAction extends Action {
  constructor(toggleDropdownMenu, title2) {
    title2 = title2 || localize("moreActions", "More Actions...");
    super(ToggleMenuAction.ID, title2, void 0, true);
    this._menuActions = [];
    this.toggleDropdownMenu = toggleDropdownMenu;
  }
  run() {
    return __awaiter$_(this, void 0, void 0, function* () {
      this.toggleDropdownMenu();
    });
  }
  get menuActions() {
    return this._menuActions;
  }
  set menuActions(actions) {
    this._menuActions = actions;
  }
}
ToggleMenuAction.ID = "toolbar.toggle.more";
var __decorate$1r = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1p = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let WorkbenchToolBar = class WorkbenchToolBar2 extends ToolBar {
  constructor(container2, _options, _menuService, _contextKeyService, _contextMenuService, keybindingService, telemetryService) {
    super(container2, _contextMenuService, Object.assign(Object.assign({
      // defaults
      getKeyBinding: (action) => {
        var _a2;
        return (_a2 = keybindingService.lookupKeybinding(action.id)) !== null && _a2 !== void 0 ? _a2 : void 0;
      }
    }, _options), {
      // mandatory (overide options)
      allowContextMenu: true,
      skipTelemetry: typeof (_options === null || _options === void 0 ? void 0 : _options.telemetrySource) === "string"
    }));
    this._options = _options;
    this._menuService = _menuService;
    this._contextKeyService = _contextKeyService;
    this._contextMenuService = _contextMenuService;
    this._sessionDisposables = this._store.add(new DisposableStore());
    const telemetrySource = _options === null || _options === void 0 ? void 0 : _options.telemetrySource;
    if (telemetrySource) {
      this._store.add(this.actionBar.onDidRun((e) => telemetryService.publicLog2("workbenchActionExecuted", { id: e.action.id, from: telemetrySource })));
    }
  }
  setActions(_primary, _secondary = [], menuIds) {
    var _a2, _b2, _c2;
    this._sessionDisposables.clear();
    const primary = _primary.slice();
    const secondary = _secondary.slice();
    const toggleActions = [];
    let toggleActionsCheckedCount = 0;
    const extraSecondary = [];
    let someAreHidden = false;
    if (((_a2 = this._options) === null || _a2 === void 0 ? void 0 : _a2.hiddenItemStrategy) !== -1) {
      for (let i = 0; i < primary.length; i++) {
        const action = primary[i];
        if (!(action instanceof MenuItemAction) && !(action instanceof SubmenuItemAction)) {
          continue;
        }
        if (!action.hideActions) {
          continue;
        }
        toggleActions.push(action.hideActions.toggle);
        if (action.hideActions.toggle.checked) {
          toggleActionsCheckedCount++;
        }
        if (action.hideActions.isHidden) {
          someAreHidden = true;
          primary[i] = void 0;
          if (((_b2 = this._options) === null || _b2 === void 0 ? void 0 : _b2.hiddenItemStrategy) !== 0) {
            extraSecondary[i] = action;
          }
        }
      }
    }
    if (((_c2 = this._options) === null || _c2 === void 0 ? void 0 : _c2.maxNumberOfItems) !== void 0) {
      let count = 0;
      for (let i = 0; i < primary.length; i++) {
        const action = primary[i];
        if (!action) {
          continue;
        }
        if (++count >= this._options.maxNumberOfItems) {
          primary[i] = void 0;
          extraSecondary[i] = action;
        }
      }
    }
    coalesceInPlace(primary);
    coalesceInPlace(extraSecondary);
    super.setActions(primary, Separator.join(extraSecondary, secondary));
    if (toggleActions.length > 0) {
      this._sessionDisposables.add(addDisposableListener(this.getElement(), "contextmenu", (e) => {
        var _a3, _b3, _c3, _d2, _e2;
        const event = new StandardMouseEvent(e);
        const action = this.getItemAction(event.target);
        if (!action) {
          return;
        }
        event.preventDefault();
        event.stopPropagation();
        let noHide = false;
        if (toggleActionsCheckedCount === 1 && ((_a3 = this._options) === null || _a3 === void 0 ? void 0 : _a3.hiddenItemStrategy) === 0) {
          noHide = true;
          for (let i = 0; i < toggleActions.length; i++) {
            if (toggleActions[i].checked) {
              toggleActions[i] = toAction({
                id: action.id,
                label: action.label,
                checked: true,
                enabled: false,
                run() {
                }
              });
              break;
            }
          }
        }
        let hideAction;
        if (!noHide && (action instanceof MenuItemAction || action instanceof SubmenuItemAction)) {
          if (!action.hideActions) {
            return;
          }
          hideAction = action.hideActions.hide;
        } else {
          hideAction = toAction({
            id: "label",
            label: localize("hide", "Hide"),
            enabled: false,
            run() {
            }
          });
        }
        const actions = Separator.join([hideAction], toggleActions);
        if (((_b3 = this._options) === null || _b3 === void 0 ? void 0 : _b3.resetMenu) && !menuIds) {
          menuIds = [this._options.resetMenu];
        }
        if (someAreHidden && menuIds) {
          actions.push(new Separator());
          actions.push(toAction({
            id: "resetThisMenu",
            label: localize("resetThisMenu", "Reset Menu"),
            run: () => this._menuService.resetHiddenStates(menuIds)
          }));
        }
        this._contextMenuService.showContextMenu({
          getAnchor: () => event,
          getActions: () => actions,
          // add context menu actions (iff appicable)
          menuId: (_c3 = this._options) === null || _c3 === void 0 ? void 0 : _c3.contextMenu,
          menuActionOptions: Object.assign({ renderShortTitle: true }, (_d2 = this._options) === null || _d2 === void 0 ? void 0 : _d2.menuOptions),
          skipTelemetry: typeof ((_e2 = this._options) === null || _e2 === void 0 ? void 0 : _e2.telemetrySource) === "string",
          contextKeyService: this._contextKeyService
        });
      }));
    }
  }
};
WorkbenchToolBar = __decorate$1r([
  __param$1p(2, IMenuService),
  __param$1p(3, IContextKeyService),
  __param$1p(4, IContextMenuService),
  __param$1p(5, IKeybindingService),
  __param$1p(6, ITelemetryService)
], WorkbenchToolBar);
var __decorate$1q = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1o = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let InlineCompletionsHintsWidget = class InlineCompletionsHintsWidget2 extends Disposable {
  constructor(editor2, model, instantiationService) {
    super();
    this.editor = editor2;
    this.model = model;
    this.instantiationService = instantiationService;
    this.alwaysShowToolbar = observableFromEvent(this.editor.onDidChangeConfiguration, () => this.editor.getOption(
      61
      /* EditorOption.inlineSuggest */
    ).showToolbar === "always");
    this.sessionPosition = void 0;
    this.position = derived("position", (reader) => {
      var _a2, _b2, _c2;
      const ghostText2 = (_a2 = this.model.read(reader)) === null || _a2 === void 0 ? void 0 : _a2.ghostText.read(reader);
      if (!this.alwaysShowToolbar.read(reader) || !ghostText2 || ghostText2.parts.length === 0) {
        this.sessionPosition = void 0;
        return null;
      }
      const firstColumn = ghostText2.parts[0].column;
      if (this.sessionPosition && this.sessionPosition.lineNumber !== ghostText2.lineNumber) {
        this.sessionPosition = void 0;
      }
      const position = new Position$2(ghostText2.lineNumber, Math.min(firstColumn, (_c2 = (_b2 = this.sessionPosition) === null || _b2 === void 0 ? void 0 : _b2.column) !== null && _c2 !== void 0 ? _c2 : Number.MAX_SAFE_INTEGER));
      this.sessionPosition = position;
      return position;
    });
    this._register(autorunWithStore2("setup content widget", (reader, store) => {
      const model2 = this.model.read(reader);
      if (!model2 || !this.alwaysShowToolbar.read(reader)) {
        return;
      }
      const contentWidget = store.add(this.instantiationService.createInstance(InlineSuggestionHintsContentWidget, this.editor, true, this.position, model2.selectedInlineCompletionIndex, model2.inlineCompletionsCount, model2.selectedInlineCompletion.map((v) => {
        var _a2;
        return (_a2 = v === null || v === void 0 ? void 0 : v.inlineCompletion.source.inlineCompletions.commands) !== null && _a2 !== void 0 ? _a2 : [];
      })));
      editor2.addContentWidget(contentWidget);
      store.add(toDisposable(() => editor2.removeContentWidget(contentWidget)));
      store.add(autorun("request explicit", (reader2) => {
        const position = this.position.read(reader2);
        if (!position) {
          return;
        }
        if (model2.lastTriggerKind.read(reader2) !== InlineCompletionTriggerKind$1.Explicit) {
          model2.triggerExplicitly();
        }
      }));
    }));
  }
};
InlineCompletionsHintsWidget = __decorate$1q([
  __param$1o(2, IInstantiationService)
], InlineCompletionsHintsWidget);
const inlineSuggestionHintsNextIcon = registerIcon("inline-suggestion-hints-next", Codicon.chevronRight, localize("parameterHintsNextIcon", "Icon for show next parameter hint."));
const inlineSuggestionHintsPreviousIcon = registerIcon("inline-suggestion-hints-previous", Codicon.chevronLeft, localize("parameterHintsPreviousIcon", "Icon for show previous parameter hint."));
let InlineSuggestionHintsContentWidget = class InlineSuggestionHintsContentWidget2 extends Disposable {
  static get dropDownVisible() {
    return this._dropDownVisible;
  }
  createCommandAction(commandId, label, iconClassName) {
    const action = new Action(commandId, label, iconClassName, true, () => this._commandService.executeCommand(commandId));
    const kb = this.keybindingService.lookupKeybinding(commandId, this._contextKeyService);
    let tooltip = label;
    if (kb) {
      tooltip = localize({ key: "content", comment: ["A label", "A keybinding"] }, "{0} ({1})", label, kb.getLabel());
    }
    action.tooltip = tooltip;
    return action;
  }
  constructor(editor2, withBorder, _position, _currentSuggestionIdx, _suggestionCount, _extraCommands, _commandService, instantiationService, keybindingService, _contextKeyService, _menuService) {
    super();
    this.editor = editor2;
    this.withBorder = withBorder;
    this._position = _position;
    this._currentSuggestionIdx = _currentSuggestionIdx;
    this._suggestionCount = _suggestionCount;
    this._extraCommands = _extraCommands;
    this._commandService = _commandService;
    this.keybindingService = keybindingService;
    this._contextKeyService = _contextKeyService;
    this._menuService = _menuService;
    this.id = `InlineSuggestionHintsContentWidget${InlineSuggestionHintsContentWidget2.id++}`;
    this.allowEditorOverflow = true;
    this.suppressMouseDown = false;
    this.nodes = h("div.inlineSuggestionsHints", { className: this.withBorder ? ".withBorder" : "" }, [
      h("div", { style: { display: "flex" } }, [
        h("div@actionBar", { className: "custom-actions" }),
        h("div@toolBar")
      ])
    ]);
    this.previousAction = this.createCommandAction(showPreviousInlineSuggestionActionId, localize("previous", "Previous"), ThemeIcon.asClassName(inlineSuggestionHintsPreviousIcon));
    this.availableSuggestionCountAction = new Action("inlineSuggestionHints.availableSuggestionCount", "", void 0, false);
    this.nextAction = this.createCommandAction(showNextInlineSuggestionActionId, localize("next", "Next"), ThemeIcon.asClassName(inlineSuggestionHintsNextIcon));
    this.inlineCompletionsActionsMenus = this._register(this._menuService.createMenu(MenuId.InlineCompletionsActions, this._contextKeyService));
    this.clearAvailableSuggestionCountLabelDebounced = this._register(new RunOnceScheduler(() => {
      this.availableSuggestionCountAction.label = "";
    }, 100));
    this.disableButtonsDebounced = this._register(new RunOnceScheduler(() => {
      this.previousAction.enabled = this.nextAction.enabled = false;
    }, 100));
    this.lastCommands = [];
    const actionBar = this._register(new ActionBar(this.nodes.actionBar));
    actionBar.push(this.previousAction, { icon: true, label: false });
    actionBar.push(this.availableSuggestionCountAction);
    actionBar.push(this.nextAction, { icon: true, label: false });
    this.toolBar = this._register(instantiationService.createInstance(CustomizedMenuWorkbenchToolBar, this.nodes.toolBar, MenuId.InlineSuggestionToolbar, {
      menuOptions: { renderShortTitle: true },
      toolbarOptions: { primaryGroup: (g) => g.startsWith("primary") },
      actionViewItemProvider: (action, options) => {
        return action instanceof MenuItemAction ? instantiationService.createInstance(StatusBarViewItem$1, action, void 0) : void 0;
      },
      telemetrySource: "InlineSuggestionToolbar"
    }));
    this._register(this.toolBar.onDidChangeDropdownVisibility((e) => {
      InlineSuggestionHintsContentWidget2._dropDownVisible = e;
    }));
    this._register(autorun("update position", (reader) => {
      this._position.read(reader);
      this.editor.layoutContentWidget(this);
    }));
    this._register(autorun("counts", (reader) => {
      const suggestionCount = this._suggestionCount.read(reader);
      const currentSuggestionIdx = this._currentSuggestionIdx.read(reader);
      if (suggestionCount !== void 0) {
        this.clearAvailableSuggestionCountLabelDebounced.cancel();
        this.availableSuggestionCountAction.label = `${currentSuggestionIdx + 1}/${suggestionCount}`;
      } else {
        this.clearAvailableSuggestionCountLabelDebounced.schedule();
      }
      if (suggestionCount !== void 0 && suggestionCount > 1) {
        this.disableButtonsDebounced.cancel();
        this.previousAction.enabled = this.nextAction.enabled = true;
      } else {
        this.disableButtonsDebounced.schedule();
      }
    }));
    this._register(autorun("extra commands", (reader) => {
      const extraCommands = this._extraCommands.read(reader);
      if (equals$3(this.lastCommands, extraCommands)) {
        return;
      }
      this.lastCommands = extraCommands;
      const extraActions = extraCommands.map((c) => ({
        class: void 0,
        id: c.id,
        enabled: true,
        tooltip: c.tooltip || "",
        label: c.title,
        run: (event) => {
          return this._commandService.executeCommand(c.id);
        }
      }));
      for (const [_, group2] of this.inlineCompletionsActionsMenus.getActions()) {
        for (const action of group2) {
          if (action instanceof MenuItemAction) {
            extraActions.push(action);
          }
        }
      }
      if (extraActions.length > 0) {
        extraActions.unshift(new Separator());
      }
      this.toolBar.setAdditionalSecondaryActions(extraActions);
    }));
  }
  getId() {
    return this.id;
  }
  getDomNode() {
    return this.nodes.root;
  }
  getPosition() {
    return {
      position: this._position.get(),
      preference: [
        1,
        2
        /* ContentWidgetPositionPreference.BELOW */
      ],
      positionAffinity: 3
    };
  }
};
InlineSuggestionHintsContentWidget._dropDownVisible = false;
InlineSuggestionHintsContentWidget.id = 0;
InlineSuggestionHintsContentWidget = __decorate$1q([
  __param$1o(6, ICommandService),
  __param$1o(7, IInstantiationService),
  __param$1o(8, IKeybindingService),
  __param$1o(9, IContextKeyService),
  __param$1o(10, IMenuService)
], InlineSuggestionHintsContentWidget);
let StatusBarViewItem$1 = class StatusBarViewItem extends MenuEntryActionViewItem {
  updateLabel() {
    const kb = this._keybindingService.lookupKeybinding(this._action.id, this._contextKeyService);
    if (!kb) {
      return super.updateLabel();
    }
    if (this.label) {
      const div = h("div.keybinding").root;
      const k = new KeybindingLabel(div, OS, Object.assign({ disableTitle: true }, unthemedKeybindingLabelOptions));
      k.set(kb);
      this.label.textContent = this._action.label;
      this.label.appendChild(div);
      this.label.classList.add("inlineSuggestionStatusBarItemLabel");
    }
  }
};
let CustomizedMenuWorkbenchToolBar = class CustomizedMenuWorkbenchToolBar2 extends WorkbenchToolBar {
  constructor(container2, menuId, options2, menuService, contextKeyService, contextMenuService, keybindingService, telemetryService) {
    super(container2, Object.assign({ resetMenu: menuId }, options2), menuService, contextKeyService, contextMenuService, keybindingService, telemetryService);
    this.menuId = menuId;
    this.options2 = options2;
    this.menuService = menuService;
    this.contextKeyService = contextKeyService;
    this.menu = this._store.add(this.menuService.createMenu(this.menuId, this.contextKeyService, { emitEventsForSubmenuChanges: true }));
    this.additionalActions = [];
    this._store.add(this.menu.onDidChange(() => this.updateToolbar()));
    this.updateToolbar();
  }
  updateToolbar() {
    var _a2, _b2, _c2, _d2, _e2, _f2, _g2;
    const primary = [];
    const secondary = [];
    createAndFillInActionBarActions(this.menu, (_a2 = this.options2) === null || _a2 === void 0 ? void 0 : _a2.menuOptions, { primary, secondary }, (_c2 = (_b2 = this.options2) === null || _b2 === void 0 ? void 0 : _b2.toolbarOptions) === null || _c2 === void 0 ? void 0 : _c2.primaryGroup, (_e2 = (_d2 = this.options2) === null || _d2 === void 0 ? void 0 : _d2.toolbarOptions) === null || _e2 === void 0 ? void 0 : _e2.shouldInlineSubmenu, (_g2 = (_f2 = this.options2) === null || _f2 === void 0 ? void 0 : _f2.toolbarOptions) === null || _g2 === void 0 ? void 0 : _g2.useSeparatorsInPrimaryActions);
    secondary.push(...this.additionalActions);
    this.setActions(primary, secondary);
  }
  setAdditionalSecondaryActions(actions) {
    if (equals$3(this.additionalActions, actions, (a, b) => a === b)) {
      return;
    }
    this.additionalActions = actions;
    this.updateToolbar();
  }
};
CustomizedMenuWorkbenchToolBar = __decorate$1q([
  __param$1o(3, IMenuService),
  __param$1o(4, IContextKeyService),
  __param$1o(5, IContextMenuService),
  __param$1o(6, IKeybindingService),
  __param$1o(7, ITelemetryService)
], CustomizedMenuWorkbenchToolBar);
const hover = "";
var __decorate$1p = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1n = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
const _sticky = false;
let ModesHoverController = class ModesHoverController2 {
  static get(editor2) {
    return editor2.getContribution(ModesHoverController2.ID);
  }
  constructor(_editor, _instantiationService, _openerService, _languageService, _keybindingService) {
    this._editor = _editor;
    this._instantiationService = _instantiationService;
    this._openerService = _openerService;
    this._languageService = _languageService;
    this._keybindingService = _keybindingService;
    this._toUnhook = new DisposableStore();
    this._hoverActivatedByColorDecoratorClick = false;
    this._isMouseDown = false;
    this._hoverClicked = false;
    this._contentWidget = null;
    this._glyphWidget = null;
    this._hookEvents();
    this._didChangeConfigurationHandler = this._editor.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        59
        /* EditorOption.hover */
      )) {
        this._unhookEvents();
        this._hookEvents();
      }
    });
  }
  _hookEvents() {
    const hideWidgetsEventHandler = () => this._hideWidgets();
    const hoverOpts = this._editor.getOption(
      59
      /* EditorOption.hover */
    );
    this._isHoverEnabled = hoverOpts.enabled;
    this._isHoverSticky = hoverOpts.sticky;
    if (this._isHoverEnabled) {
      this._toUnhook.add(this._editor.onMouseDown((e) => this._onEditorMouseDown(e)));
      this._toUnhook.add(this._editor.onMouseUp((e) => this._onEditorMouseUp(e)));
      this._toUnhook.add(this._editor.onMouseMove((e) => this._onEditorMouseMove(e)));
      this._toUnhook.add(this._editor.onKeyDown((e) => this._onKeyDown(e)));
    } else {
      this._toUnhook.add(this._editor.onMouseMove((e) => this._onEditorMouseMove(e)));
      this._toUnhook.add(this._editor.onKeyDown((e) => this._onKeyDown(e)));
    }
    this._toUnhook.add(this._editor.onMouseLeave((e) => this._onEditorMouseLeave(e)));
    this._toUnhook.add(this._editor.onDidChangeModel(hideWidgetsEventHandler));
    this._toUnhook.add(this._editor.onDidScrollChange((e) => this._onEditorScrollChanged(e)));
  }
  _unhookEvents() {
    this._toUnhook.clear();
  }
  _onEditorScrollChanged(e) {
    if (e.scrollTopChanged || e.scrollLeftChanged) {
      this._hideWidgets();
    }
  }
  _onEditorMouseDown(mouseEvent) {
    var _a2;
    this._isMouseDown = true;
    const target = mouseEvent.target;
    if (target.type === 9 && target.detail === ContentHoverWidget.ID) {
      this._hoverClicked = true;
      return;
    }
    if (target.type === 12 && target.detail === MarginHoverWidget.ID) {
      return;
    }
    if (target.type !== 12) {
      this._hoverClicked = false;
    }
    if (!((_a2 = this._contentWidget) === null || _a2 === void 0 ? void 0 : _a2.widget.isResizing)) {
      this._hideWidgets();
    }
  }
  _onEditorMouseUp(mouseEvent) {
    this._isMouseDown = false;
  }
  _onEditorMouseLeave(mouseEvent) {
    var _a2, _b2;
    const targetEm = mouseEvent.event.browserEvent.relatedTarget;
    if (((_a2 = this._contentWidget) === null || _a2 === void 0 ? void 0 : _a2.widget.isResizing) || ((_b2 = this._contentWidget) === null || _b2 === void 0 ? void 0 : _b2.containsNode(targetEm))) {
      return;
    }
    {
      this._hideWidgets();
    }
  }
  _onEditorMouseMove(mouseEvent) {
    var _a2, _b2, _c2, _d2, _e2, _f2, _g2, _h2, _j, _k, _l;
    const target = mouseEvent.target;
    if (((_a2 = this._contentWidget) === null || _a2 === void 0 ? void 0 : _a2.isFocused) || ((_b2 = this._contentWidget) === null || _b2 === void 0 ? void 0 : _b2.isResizing)) {
      return;
    }
    if (this._isMouseDown && this._hoverClicked) {
      return;
    }
    if (this._isHoverSticky && target.type === 9 && target.detail === ContentHoverWidget.ID) {
      return;
    }
    if (this._isHoverSticky && ((_c2 = this._contentWidget) === null || _c2 === void 0 ? void 0 : _c2.containsNode((_d2 = mouseEvent.event.browserEvent.view) === null || _d2 === void 0 ? void 0 : _d2.document.activeElement)) && !((_f2 = (_e2 = mouseEvent.event.browserEvent.view) === null || _e2 === void 0 ? void 0 : _e2.getSelection()) === null || _f2 === void 0 ? void 0 : _f2.isCollapsed)) {
      return;
    }
    if (!this._isHoverSticky && target.type === 9 && target.detail === ContentHoverWidget.ID && ((_g2 = this._contentWidget) === null || _g2 === void 0 ? void 0 : _g2.isColorPickerVisible)) {
      return;
    }
    if (this._isHoverSticky && target.type === 12 && target.detail === MarginHoverWidget.ID) {
      return;
    }
    if (this._isHoverSticky && ((_h2 = this._contentWidget) === null || _h2 === void 0 ? void 0 : _h2.isVisibleFromKeyboard)) {
      return;
    }
    const mouseOnDecorator = (_j = target.element) === null || _j === void 0 ? void 0 : _j.classList.contains("colorpicker-color-decoration");
    const decoratorActivatedOn = this._editor.getOption(
      145
      /* EditorOption.colorDecoratorsActivatedOn */
    );
    if (mouseOnDecorator && (decoratorActivatedOn === "click" && !this._hoverActivatedByColorDecoratorClick || decoratorActivatedOn === "hover" && !this._isHoverEnabled && !_sticky || decoratorActivatedOn === "clickAndHover" && !this._isHoverEnabled && !this._hoverActivatedByColorDecoratorClick) || !mouseOnDecorator && !this._isHoverEnabled && !this._hoverActivatedByColorDecoratorClick) {
      this._hideWidgets();
      return;
    }
    const contentWidget = this._getOrCreateContentWidget();
    if (contentWidget.maybeShowAt(mouseEvent)) {
      (_k = this._glyphWidget) === null || _k === void 0 ? void 0 : _k.hide();
      return;
    }
    if (target.type === 2 && target.position) {
      (_l = this._contentWidget) === null || _l === void 0 ? void 0 : _l.hide();
      if (!this._glyphWidget) {
        this._glyphWidget = new MarginHoverWidget(this._editor, this._languageService, this._openerService);
      }
      this._glyphWidget.startShowingAt(target.position.lineNumber);
      return;
    }
    this._hideWidgets();
  }
  _onKeyDown(e) {
    var _a2;
    if (!this._editor.hasModel()) {
      return;
    }
    const resolvedKeyboardEvent = this._keybindingService.softDispatch(e, this._editor.getDomNode());
    const mightTriggerFocus = resolvedKeyboardEvent.kind === 1 || resolvedKeyboardEvent.kind === 2 && resolvedKeyboardEvent.commandId === "editor.action.showHover" && ((_a2 = this._contentWidget) === null || _a2 === void 0 ? void 0 : _a2.isVisible);
    if (e.keyCode !== 5 && e.keyCode !== 6 && e.keyCode !== 57 && e.keyCode !== 4 && !mightTriggerFocus) {
      this._hideWidgets();
    }
  }
  _hideWidgets() {
    var _a2, _b2, _c2;
    if (this._isMouseDown && this._hoverClicked && ((_a2 = this._contentWidget) === null || _a2 === void 0 ? void 0 : _a2.isColorPickerVisible) || InlineSuggestionHintsContentWidget.dropDownVisible) {
      return;
    }
    this._hoverActivatedByColorDecoratorClick = false;
    this._hoverClicked = false;
    (_b2 = this._glyphWidget) === null || _b2 === void 0 ? void 0 : _b2.hide();
    (_c2 = this._contentWidget) === null || _c2 === void 0 ? void 0 : _c2.hide();
  }
  _getOrCreateContentWidget() {
    if (!this._contentWidget) {
      this._contentWidget = this._instantiationService.createInstance(ContentHoverController, this._editor);
    }
    return this._contentWidget;
  }
  showContentHover(range2, mode, source, focus, activatedByColorDecoratorClick = false) {
    this._hoverActivatedByColorDecoratorClick = activatedByColorDecoratorClick;
    this._getOrCreateContentWidget().startShowingAtRange(range2, mode, source, focus);
  }
  focus() {
    var _a2;
    (_a2 = this._contentWidget) === null || _a2 === void 0 ? void 0 : _a2.focus();
  }
  scrollUp() {
    var _a2;
    (_a2 = this._contentWidget) === null || _a2 === void 0 ? void 0 : _a2.scrollUp();
  }
  scrollDown() {
    var _a2;
    (_a2 = this._contentWidget) === null || _a2 === void 0 ? void 0 : _a2.scrollDown();
  }
  scrollLeft() {
    var _a2;
    (_a2 = this._contentWidget) === null || _a2 === void 0 ? void 0 : _a2.scrollLeft();
  }
  scrollRight() {
    var _a2;
    (_a2 = this._contentWidget) === null || _a2 === void 0 ? void 0 : _a2.scrollRight();
  }
  pageUp() {
    var _a2;
    (_a2 = this._contentWidget) === null || _a2 === void 0 ? void 0 : _a2.pageUp();
  }
  pageDown() {
    var _a2;
    (_a2 = this._contentWidget) === null || _a2 === void 0 ? void 0 : _a2.pageDown();
  }
  goToTop() {
    var _a2;
    (_a2 = this._contentWidget) === null || _a2 === void 0 ? void 0 : _a2.goToTop();
  }
  goToBottom() {
    var _a2;
    (_a2 = this._contentWidget) === null || _a2 === void 0 ? void 0 : _a2.goToBottom();
  }
  get isColorPickerVisible() {
    var _a2;
    return (_a2 = this._contentWidget) === null || _a2 === void 0 ? void 0 : _a2.isColorPickerVisible;
  }
  get isHoverVisible() {
    var _a2;
    return (_a2 = this._contentWidget) === null || _a2 === void 0 ? void 0 : _a2.isVisible;
  }
  dispose() {
    var _a2, _b2;
    this._unhookEvents();
    this._toUnhook.dispose();
    this._didChangeConfigurationHandler.dispose();
    (_a2 = this._glyphWidget) === null || _a2 === void 0 ? void 0 : _a2.dispose();
    (_b2 = this._contentWidget) === null || _b2 === void 0 ? void 0 : _b2.dispose();
  }
};
ModesHoverController.ID = "editor.contrib.hover";
ModesHoverController = __decorate$1p([
  __param$1n(1, IInstantiationService),
  __param$1n(2, IOpenerService),
  __param$1n(3, ILanguageService),
  __param$1n(4, IKeybindingService)
], ModesHoverController);
class ShowOrFocusHoverAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.showHover",
      label: localize({
        key: "showOrFocusHover",
        comment: [
          "Label for action that will trigger the showing/focusing of a hover in the editor.",
          "If the hover is not visible, it will show the hover.",
          "This allows for users to show the hover without using the mouse.",
          "If the hover is already visible, it will take focus."
        ]
      }, "Show or Focus Hover"),
      description: {
        description: `Show or Focus Hover`,
        args: [{
          name: "args",
          schema: {
            type: "object",
            properties: {
              "focus": {
                description: "Controls if when triggered with the keyboard, the hover should take focus immediately.",
                type: "boolean",
                default: false
              }
            }
          }
        }]
      },
      alias: "Show or Focus Hover",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: KeyChord(
          2048 | 41,
          2048 | 39
          /* KeyCode.KeyI */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor2, args) {
    var _a2;
    const configurationService = accessor.get(IConfigurationService);
    const accessibilityService = accessor.get(IAccessibilityService);
    const keybindingService = accessor.get(IKeybindingService);
    if (!editor2.hasModel()) {
      return;
    }
    const controller = ModesHoverController.get(editor2);
    if (!controller) {
      return;
    }
    const position = editor2.getPosition();
    const range2 = new Range$2(position.lineNumber, position.column, position.lineNumber, position.column);
    const focus = editor2.getOption(
      2
      /* EditorOption.accessibilitySupport */
    ) === 2 || !!(args === null || args === void 0 ? void 0 : args.focus);
    if (controller.isHoverVisible) {
      controller.focus();
    } else {
      controller.showContentHover(range2, 1, 1, focus);
    }
    if (configurationService.getValue("accessibility.verbosity.hover") && accessibilityService.isScreenReaderOptimized()) {
      const keybinding = (_a2 = keybindingService.lookupKeybinding("editor.action.accessibleView")) === null || _a2 === void 0 ? void 0 : _a2.getAriaLabel();
      const hint = keybinding ? localize("chatAccessibleViewHint", "Inspect this in the accessible view with {0}", keybinding) : localize("chatAccessibleViewHintNoKb", "Inspect this in the accessible view via the command Open Accessible View which is currently not triggerable via keybinding");
      status(hint);
    }
  }
}
class ShowDefinitionPreviewHoverAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.showDefinitionPreviewHover",
      label: localize({
        key: "showDefinitionPreviewHover",
        comment: [
          "Label for action that will trigger the showing of definition preview hover in the editor.",
          "This allows for users to show the definition preview hover without using the mouse."
        ]
      }, "Show Definition Preview Hover"),
      alias: "Show Definition Preview Hover",
      precondition: void 0
    });
  }
  run(accessor, editor2) {
    const controller = ModesHoverController.get(editor2);
    if (!controller) {
      return;
    }
    const position = editor2.getPosition();
    if (!position) {
      return;
    }
    const range2 = new Range$2(position.lineNumber, position.column, position.lineNumber, position.column);
    const goto = GotoDefinitionAtPositionEditorContribution.get(editor2);
    if (!goto) {
      return;
    }
    const promise = goto.startFindDefinitionFromCursor(position);
    promise.then(() => {
      controller.showContentHover(range2, 1, 1, true);
    });
  }
}
class ScrollUpHoverAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.scrollUpHover",
      label: localize({
        key: "scrollUpHover",
        comment: [
          "Action that allows to scroll up in the hover widget with the up arrow when the hover widget is focused."
        ]
      }, "Scroll Up Hover"),
      alias: "Scroll Up Hover",
      precondition: EditorContextKeys.hoverFocused,
      kbOpts: {
        kbExpr: EditorContextKeys.hoverFocused,
        primary: 16,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor2) {
    const controller = ModesHoverController.get(editor2);
    if (!controller) {
      return;
    }
    controller.scrollUp();
  }
}
class ScrollDownHoverAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.scrollDownHover",
      label: localize({
        key: "scrollDownHover",
        comment: [
          "Action that allows to scroll down in the hover widget with the up arrow when the hover widget is focused."
        ]
      }, "Scroll Down Hover"),
      alias: "Scroll Down Hover",
      precondition: EditorContextKeys.hoverFocused,
      kbOpts: {
        kbExpr: EditorContextKeys.hoverFocused,
        primary: 18,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor2) {
    const controller = ModesHoverController.get(editor2);
    if (!controller) {
      return;
    }
    controller.scrollDown();
  }
}
class ScrollLeftHoverAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.scrollLeftHover",
      label: localize({
        key: "scrollLeftHover",
        comment: [
          "Action that allows to scroll left in the hover widget with the left arrow when the hover widget is focused."
        ]
      }, "Scroll Left Hover"),
      alias: "Scroll Left Hover",
      precondition: EditorContextKeys.hoverFocused,
      kbOpts: {
        kbExpr: EditorContextKeys.hoverFocused,
        primary: 15,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor2) {
    const controller = ModesHoverController.get(editor2);
    if (!controller) {
      return;
    }
    controller.scrollLeft();
  }
}
class ScrollRightHoverAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.scrollRightHover",
      label: localize({
        key: "scrollRightHover",
        comment: [
          "Action that allows to scroll right in the hover widget with the right arrow when the hover widget is focused."
        ]
      }, "Scroll Right Hover"),
      alias: "Scroll Right Hover",
      precondition: EditorContextKeys.hoverFocused,
      kbOpts: {
        kbExpr: EditorContextKeys.hoverFocused,
        primary: 17,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor2) {
    const controller = ModesHoverController.get(editor2);
    if (!controller) {
      return;
    }
    controller.scrollRight();
  }
}
class PageUpHoverAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.pageUpHover",
      label: localize({
        key: "pageUpHover",
        comment: [
          "Action that allows to page up in the hover widget with the page up command when the hover widget is focused."
        ]
      }, "Page Up Hover"),
      alias: "Page Up Hover",
      precondition: EditorContextKeys.hoverFocused,
      kbOpts: {
        kbExpr: EditorContextKeys.hoverFocused,
        primary: 11,
        secondary: [
          512 | 16
          /* KeyCode.UpArrow */
        ],
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor2) {
    const controller = ModesHoverController.get(editor2);
    if (!controller) {
      return;
    }
    controller.pageUp();
  }
}
class PageDownHoverAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.pageDownHover",
      label: localize({
        key: "pageDownHover",
        comment: [
          "Action that allows to page down in the hover widget with the page down command when the hover widget is focused."
        ]
      }, "Page Down Hover"),
      alias: "Page Down Hover",
      precondition: EditorContextKeys.hoverFocused,
      kbOpts: {
        kbExpr: EditorContextKeys.hoverFocused,
        primary: 12,
        secondary: [
          512 | 18
          /* KeyCode.DownArrow */
        ],
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor2) {
    const controller = ModesHoverController.get(editor2);
    if (!controller) {
      return;
    }
    controller.pageDown();
  }
}
class GoToTopHoverAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.goToTopHover",
      label: localize({
        key: "goToTopHover",
        comment: [
          "Action that allows to go to the top of the hover widget with the home command when the hover widget is focused."
        ]
      }, "Go To Top Hover"),
      alias: "Go To Bottom Hover",
      precondition: EditorContextKeys.hoverFocused,
      kbOpts: {
        kbExpr: EditorContextKeys.hoverFocused,
        primary: 14,
        secondary: [
          2048 | 16
          /* KeyCode.UpArrow */
        ],
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor2) {
    const controller = ModesHoverController.get(editor2);
    if (!controller) {
      return;
    }
    controller.goToTop();
  }
}
class GoToBottomHoverAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.goToBottomHover",
      label: localize({
        key: "goToBottomHover",
        comment: [
          "Action that allows to go to the bottom in the hover widget with the end command when the hover widget is focused."
        ]
      }, "Go To Bottom Hover"),
      alias: "Go To Bottom Hover",
      precondition: EditorContextKeys.hoverFocused,
      kbOpts: {
        kbExpr: EditorContextKeys.hoverFocused,
        primary: 13,
        secondary: [
          2048 | 18
          /* KeyCode.DownArrow */
        ],
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor2) {
    const controller = ModesHoverController.get(editor2);
    if (!controller) {
      return;
    }
    controller.goToBottom();
  }
}
registerEditorContribution(
  ModesHoverController.ID,
  ModesHoverController,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);
registerEditorAction(ShowOrFocusHoverAction);
registerEditorAction(ShowDefinitionPreviewHoverAction);
registerEditorAction(ScrollUpHoverAction);
registerEditorAction(ScrollDownHoverAction);
registerEditorAction(ScrollLeftHoverAction);
registerEditorAction(ScrollRightHoverAction);
registerEditorAction(PageUpHoverAction);
registerEditorAction(PageDownHoverAction);
registerEditorAction(GoToTopHoverAction);
registerEditorAction(GoToBottomHoverAction);
HoverParticipantRegistry.register(MarkdownHoverParticipant);
HoverParticipantRegistry.register(MarkerHoverParticipant);
registerThemingParticipant((theme, collector) => {
  const hoverBorder = theme.getColor(editorHoverBorder);
  if (hoverBorder) {
    collector.addRule(`.monaco-editor .monaco-hover .hover-row:not(:first-child):not(:empty) { border-top: 1px solid ${hoverBorder.transparent(0.5)}; }`);
    collector.addRule(`.monaco-editor .monaco-hover hr { border-top: 1px solid ${hoverBorder.transparent(0.5)}; }`);
    collector.addRule(`.monaco-editor .monaco-hover hr { border-bottom: 0px solid ${hoverBorder.transparent(0.5)}; }`);
  }
});
class ColorContribution extends Disposable {
  constructor(_editor) {
    super();
    this._editor = _editor;
    this._register(_editor.onMouseDown((e) => this.onMouseDown(e)));
  }
  dispose() {
    super.dispose();
  }
  onMouseDown(mouseEvent) {
    const colorDecoratorsActivatedOn = this._editor.getOption(
      145
      /* EditorOption.colorDecoratorsActivatedOn */
    );
    if (colorDecoratorsActivatedOn !== "click" && colorDecoratorsActivatedOn !== "clickAndHover") {
      return;
    }
    const target = mouseEvent.target;
    if (target.type !== 6) {
      return;
    }
    if (!target.detail.injectedText) {
      return;
    }
    if (target.detail.injectedText.options.attachedData !== ColorDecorationInjectedTextMarker) {
      return;
    }
    if (!target.range) {
      return;
    }
    const hoverController = this._editor.getContribution(ModesHoverController.ID);
    if (!hoverController) {
      return;
    }
    if (!hoverController.isColorPickerVisible) {
      const range2 = new Range$2(target.range.startLineNumber, target.range.startColumn + 1, target.range.endLineNumber, target.range.endColumn + 1);
      hoverController.showContentHover(range2, 1, 0, false, true);
    }
  }
}
ColorContribution.ID = "editor.contrib.colorContribution";
registerEditorContribution(
  ColorContribution.ID,
  ColorContribution,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);
HoverParticipantRegistry.register(ColorHoverParticipant);
var __decorate$1o = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1m = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$Z = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
let StandaloneColorPickerController = class StandaloneColorPickerController2 extends Disposable {
  constructor(_editor, _contextKeyService, _modelService, _keybindingService, _instantiationService, _languageFeatureService, _languageConfigurationService) {
    super();
    this._editor = _editor;
    this._modelService = _modelService;
    this._keybindingService = _keybindingService;
    this._instantiationService = _instantiationService;
    this._languageFeatureService = _languageFeatureService;
    this._languageConfigurationService = _languageConfigurationService;
    this._standaloneColorPickerWidget = null;
    this._standaloneColorPickerVisible = EditorContextKeys.standaloneColorPickerVisible.bindTo(_contextKeyService);
    this._standaloneColorPickerFocused = EditorContextKeys.standaloneColorPickerFocused.bindTo(_contextKeyService);
  }
  showOrFocus() {
    var _a2;
    if (!this._editor.hasModel()) {
      return;
    }
    if (!this._standaloneColorPickerVisible.get()) {
      this._standaloneColorPickerWidget = new StandaloneColorPickerWidget(this._editor, this._standaloneColorPickerVisible, this._standaloneColorPickerFocused, this._instantiationService, this._modelService, this._keybindingService, this._languageFeatureService, this._languageConfigurationService);
    } else if (!this._standaloneColorPickerFocused.get()) {
      (_a2 = this._standaloneColorPickerWidget) === null || _a2 === void 0 ? void 0 : _a2.focus();
    }
  }
  hide() {
    var _a2;
    this._standaloneColorPickerFocused.set(false);
    this._standaloneColorPickerVisible.set(false);
    (_a2 = this._standaloneColorPickerWidget) === null || _a2 === void 0 ? void 0 : _a2.hide();
    this._editor.focus();
  }
  insertColor() {
    var _a2;
    (_a2 = this._standaloneColorPickerWidget) === null || _a2 === void 0 ? void 0 : _a2.updateEditor();
    this.hide();
  }
  static get(editor2) {
    return editor2.getContribution(StandaloneColorPickerController2.ID);
  }
};
StandaloneColorPickerController.ID = "editor.contrib.standaloneColorPickerController";
StandaloneColorPickerController = __decorate$1o([
  __param$1m(1, IContextKeyService),
  __param$1m(2, IModelService),
  __param$1m(3, IKeybindingService),
  __param$1m(4, IInstantiationService),
  __param$1m(5, ILanguageFeaturesService),
  __param$1m(6, ILanguageConfigurationService)
], StandaloneColorPickerController);
registerEditorContribution(
  StandaloneColorPickerController.ID,
  StandaloneColorPickerController,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
const PADDING = 8;
const CLOSE_BUTTON_WIDTH = 22;
let StandaloneColorPickerWidget = class StandaloneColorPickerWidget2 extends Disposable {
  constructor(_editor, _standaloneColorPickerVisible, _standaloneColorPickerFocused, _instantiationService, _modelService, _keybindingService, _languageFeaturesService, _languageConfigurationService) {
    var _a2;
    super();
    this._editor = _editor;
    this._standaloneColorPickerVisible = _standaloneColorPickerVisible;
    this._standaloneColorPickerFocused = _standaloneColorPickerFocused;
    this._modelService = _modelService;
    this._keybindingService = _keybindingService;
    this._languageFeaturesService = _languageFeaturesService;
    this._languageConfigurationService = _languageConfigurationService;
    this.allowEditorOverflow = true;
    this.body = document.createElement("div");
    this._position = void 0;
    this._colorHover = null;
    this._selectionSetInEditor = false;
    this._onResult = this._register(new Emitter$1());
    this.onResult = this._onResult.event;
    this._standaloneColorPickerVisible.set(true);
    this._standaloneColorPickerParticipant = _instantiationService.createInstance(StandaloneColorPickerParticipant, this._editor);
    this._position = (_a2 = this._editor._getViewModel()) === null || _a2 === void 0 ? void 0 : _a2.getPrimaryCursorState().modelState.position;
    const editorSelection = this._editor.getSelection();
    const selection = editorSelection ? {
      startLineNumber: editorSelection.startLineNumber,
      startColumn: editorSelection.startColumn,
      endLineNumber: editorSelection.endLineNumber,
      endColumn: editorSelection.endColumn
    } : { startLineNumber: 0, endLineNumber: 0, endColumn: 0, startColumn: 0 };
    const focusTracker = this._register(trackFocus(this.body));
    this._register(focusTracker.onDidBlur((_) => {
      this.hide();
    }));
    this._register(focusTracker.onDidFocus((_) => {
      this.focus();
    }));
    this._register(this._editor.onDidChangeCursorPosition(() => {
      if (!this._selectionSetInEditor) {
        this.hide();
      } else {
        this._selectionSetInEditor = false;
      }
    }));
    this._register(this._editor.onMouseMove((e) => {
      var _a3;
      const classList = (_a3 = e.target.element) === null || _a3 === void 0 ? void 0 : _a3.classList;
      if (classList && classList.contains("colorpicker-color-decoration")) {
        this.hide();
      }
    }));
    this._register(this.onResult((result2) => {
      this._render(result2.value, result2.foundInEditor);
    }));
    this._start(selection);
    this._editor.addContentWidget(this);
  }
  updateEditor() {
    if (this._colorHover) {
      this._standaloneColorPickerParticipant.updateEditorModel(this._colorHover);
    }
  }
  getId() {
    return StandaloneColorPickerWidget2.ID;
  }
  getDomNode() {
    return this.body;
  }
  getPosition() {
    if (!this._position) {
      return null;
    }
    const positionPreference = this._editor.getOption(
      59
      /* EditorOption.hover */
    ).above;
    return {
      position: this._position,
      secondaryPosition: this._position,
      preference: positionPreference ? [
        1,
        2
        /* ContentWidgetPositionPreference.BELOW */
      ] : [
        2,
        1
        /* ContentWidgetPositionPreference.ABOVE */
      ],
      positionAffinity: 2
      /* PositionAffinity.None */
    };
  }
  hide() {
    this.dispose();
    this._standaloneColorPickerVisible.set(false);
    this._standaloneColorPickerFocused.set(false);
    this._editor.removeContentWidget(this);
    this._editor.focus();
  }
  focus() {
    this._standaloneColorPickerFocused.set(true);
    this.body.focus();
  }
  _start(selection) {
    return __awaiter$Z(this, void 0, void 0, function* () {
      const computeAsyncResult = yield this._computeAsync(selection);
      if (!computeAsyncResult) {
        return;
      }
      this._onResult.fire(new StandaloneColorPickerResult(computeAsyncResult.result, computeAsyncResult.foundInEditor));
    });
  }
  _computeAsync(range2) {
    return __awaiter$Z(this, void 0, void 0, function* () {
      if (!this._editor.hasModel()) {
        return null;
      }
      const colorInfo = {
        range: range2,
        color: { red: 0, green: 0, blue: 0, alpha: 1 }
      };
      const colorHoverResult = yield this._standaloneColorPickerParticipant.createColorHover(colorInfo, new DefaultDocumentColorProvider(this._modelService, this._languageConfigurationService), this._languageFeaturesService.colorProvider);
      if (!colorHoverResult) {
        return null;
      }
      return { result: colorHoverResult.colorHover, foundInEditor: colorHoverResult.foundInEditor };
    });
  }
  _render(colorHover, foundInEditor) {
    const fragment = document.createDocumentFragment();
    const statusBar = this._register(new EditorHoverStatusBar(this._keybindingService));
    let colorPickerWidget;
    const context = {
      fragment,
      statusBar,
      setColorPicker: (widget) => colorPickerWidget = widget,
      onContentsChanged: () => {
      },
      hide: () => this.hide()
    };
    this._colorHover = colorHover;
    this._register(this._standaloneColorPickerParticipant.renderHoverParts(context, [colorHover]));
    if (colorPickerWidget === void 0) {
      return;
    }
    this.body.classList.add("standalone-colorpicker-body");
    this.body.style.maxHeight = Math.max(this._editor.getLayoutInfo().height / 4, 250) + "px";
    this.body.style.maxWidth = Math.max(this._editor.getLayoutInfo().width * 0.66, 500) + "px";
    this.body.tabIndex = 0;
    this.body.appendChild(fragment);
    colorPickerWidget.layout();
    const colorPickerBody = colorPickerWidget.body;
    const saturationBoxWidth = colorPickerBody.saturationBox.domNode.clientWidth;
    const widthOfOriginalColorBox = colorPickerBody.domNode.clientWidth - saturationBoxWidth - CLOSE_BUTTON_WIDTH - PADDING;
    const enterButton = colorPickerWidget.body.enterButton;
    enterButton === null || enterButton === void 0 ? void 0 : enterButton.onClicked(() => {
      this.updateEditor();
      this.hide();
    });
    const colorPickerHeader = colorPickerWidget.header;
    const pickedColorNode = colorPickerHeader.pickedColorNode;
    pickedColorNode.style.width = saturationBoxWidth + PADDING + "px";
    const originalColorNode = colorPickerHeader.originalColorNode;
    originalColorNode.style.width = widthOfOriginalColorBox + "px";
    const closeButton = colorPickerWidget.header.closeButton;
    closeButton === null || closeButton === void 0 ? void 0 : closeButton.onClicked(() => {
      this.hide();
    });
    if (foundInEditor) {
      if (enterButton) {
        enterButton.button.textContent = "Replace";
      }
      this._selectionSetInEditor = true;
      this._editor.setSelection(colorHover.range);
    }
    this._editor.layoutContentWidget(this);
  }
};
StandaloneColorPickerWidget.ID = "editor.contrib.standaloneColorPickerWidget";
StandaloneColorPickerWidget = __decorate$1o([
  __param$1m(3, IInstantiationService),
  __param$1m(4, IModelService),
  __param$1m(5, IKeybindingService),
  __param$1m(6, ILanguageFeaturesService),
  __param$1m(7, ILanguageConfigurationService)
], StandaloneColorPickerWidget);
class StandaloneColorPickerResult {
  // The color picker result consists of: an array of color results and a boolean indicating if the color was found in the editor
  constructor(value, foundInEditor) {
    this.value = value;
    this.foundInEditor = foundInEditor;
  }
}
class ShowOrFocusStandaloneColorPicker extends EditorAction2 {
  constructor() {
    super({
      id: "editor.action.showOrFocusStandaloneColorPicker",
      title: {
        value: localize("showOrFocusStandaloneColorPicker", "Show or Focus Standalone Color Picker"),
        mnemonicTitle: localize({ key: "mishowOrFocusStandaloneColorPicker", comment: ["&& denotes a mnemonic"] }, "&&Show or Focus Standalone Color Picker"),
        original: "Show or Focus Standalone Color Picker"
      },
      precondition: void 0,
      menu: [
        { id: MenuId.CommandPalette }
      ]
    });
  }
  runEditorCommand(_accessor, editor2) {
    var _a2;
    (_a2 = StandaloneColorPickerController.get(editor2)) === null || _a2 === void 0 ? void 0 : _a2.showOrFocus();
  }
}
class HideStandaloneColorPicker extends EditorAction {
  constructor() {
    super({
      id: "editor.action.hideColorPicker",
      label: localize({
        key: "hideColorPicker",
        comment: [
          "Action that hides the color picker"
        ]
      }, "Hide the Color Picker"),
      alias: "Hide the Color Picker",
      precondition: EditorContextKeys.standaloneColorPickerVisible.isEqualTo(true),
      kbOpts: {
        primary: 9,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(_accessor, editor2) {
    var _a2;
    (_a2 = StandaloneColorPickerController.get(editor2)) === null || _a2 === void 0 ? void 0 : _a2.hide();
  }
}
class InsertColorWithStandaloneColorPicker extends EditorAction {
  constructor() {
    super({
      id: "editor.action.insertColorWithStandaloneColorPicker",
      label: localize({
        key: "insertColorWithStandaloneColorPicker",
        comment: [
          "Action that inserts color with standalone color picker"
        ]
      }, "Insert Color with Standalone Color Picker"),
      alias: "Insert Color with Standalone Color Picker",
      precondition: EditorContextKeys.standaloneColorPickerFocused.isEqualTo(true),
      kbOpts: {
        primary: 3,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(_accessor, editor2) {
    var _a2;
    (_a2 = StandaloneColorPickerController.get(editor2)) === null || _a2 === void 0 ? void 0 : _a2.insertColor();
  }
}
registerEditorAction(HideStandaloneColorPicker);
registerEditorAction(InsertColorWithStandaloneColorPicker);
registerAction2(ShowOrFocusStandaloneColorPicker);
class EditOperation {
  static insert(position, text2) {
    return {
      range: new Range$2(position.lineNumber, position.column, position.lineNumber, position.column),
      text: text2,
      forceMoveMarkers: true
    };
  }
  static delete(range2) {
    return {
      range: range2,
      text: null
    };
  }
  static replace(range2, text2) {
    return {
      range: range2,
      text: text2
    };
  }
  static replaceMove(range2, text2) {
    return {
      range: range2,
      text: text2,
      forceMoveMarkers: true
    };
  }
}
class BlockCommentCommand {
  constructor(selection, insertSpace, languageConfigurationService) {
    this.languageConfigurationService = languageConfigurationService;
    this._selection = selection;
    this._insertSpace = insertSpace;
    this._usedEndToken = null;
  }
  static _haystackHasNeedleAtOffset(haystack, needle, offset) {
    if (offset < 0) {
      return false;
    }
    const needleLength = needle.length;
    const haystackLength = haystack.length;
    if (offset + needleLength > haystackLength) {
      return false;
    }
    for (let i = 0; i < needleLength; i++) {
      const codeA = haystack.charCodeAt(offset + i);
      const codeB = needle.charCodeAt(i);
      if (codeA === codeB) {
        continue;
      }
      if (codeA >= 65 && codeA <= 90 && codeA + 32 === codeB) {
        continue;
      }
      if (codeB >= 65 && codeB <= 90 && codeB + 32 === codeA) {
        continue;
      }
      return false;
    }
    return true;
  }
  _createOperationsForBlockComment(selection, startToken, endToken, insertSpace, model, builder) {
    const startLineNumber = selection.startLineNumber;
    const startColumn = selection.startColumn;
    const endLineNumber = selection.endLineNumber;
    const endColumn = selection.endColumn;
    const startLineText = model.getLineContent(startLineNumber);
    const endLineText = model.getLineContent(endLineNumber);
    let startTokenIndex = startLineText.lastIndexOf(startToken, startColumn - 1 + startToken.length);
    let endTokenIndex = endLineText.indexOf(endToken, endColumn - 1 - endToken.length);
    if (startTokenIndex !== -1 && endTokenIndex !== -1) {
      if (startLineNumber === endLineNumber) {
        const lineBetweenTokens = startLineText.substring(startTokenIndex + startToken.length, endTokenIndex);
        if (lineBetweenTokens.indexOf(endToken) >= 0) {
          startTokenIndex = -1;
          endTokenIndex = -1;
        }
      } else {
        const startLineAfterStartToken = startLineText.substring(startTokenIndex + startToken.length);
        const endLineBeforeEndToken = endLineText.substring(0, endTokenIndex);
        if (startLineAfterStartToken.indexOf(endToken) >= 0 || endLineBeforeEndToken.indexOf(endToken) >= 0) {
          startTokenIndex = -1;
          endTokenIndex = -1;
        }
      }
    }
    let ops;
    if (startTokenIndex !== -1 && endTokenIndex !== -1) {
      if (insertSpace && startTokenIndex + startToken.length < startLineText.length && startLineText.charCodeAt(startTokenIndex + startToken.length) === 32) {
        startToken = startToken + " ";
      }
      if (insertSpace && endTokenIndex > 0 && endLineText.charCodeAt(endTokenIndex - 1) === 32) {
        endToken = " " + endToken;
        endTokenIndex -= 1;
      }
      ops = BlockCommentCommand._createRemoveBlockCommentOperations(new Range$2(startLineNumber, startTokenIndex + startToken.length + 1, endLineNumber, endTokenIndex + 1), startToken, endToken);
    } else {
      ops = BlockCommentCommand._createAddBlockCommentOperations(selection, startToken, endToken, this._insertSpace);
      this._usedEndToken = ops.length === 1 ? endToken : null;
    }
    for (const op of ops) {
      builder.addTrackedEditOperation(op.range, op.text);
    }
  }
  static _createRemoveBlockCommentOperations(r, startToken, endToken) {
    const res = [];
    if (!Range$2.isEmpty(r)) {
      res.push(EditOperation.delete(new Range$2(r.startLineNumber, r.startColumn - startToken.length, r.startLineNumber, r.startColumn)));
      res.push(EditOperation.delete(new Range$2(r.endLineNumber, r.endColumn, r.endLineNumber, r.endColumn + endToken.length)));
    } else {
      res.push(EditOperation.delete(new Range$2(r.startLineNumber, r.startColumn - startToken.length, r.endLineNumber, r.endColumn + endToken.length)));
    }
    return res;
  }
  static _createAddBlockCommentOperations(r, startToken, endToken, insertSpace) {
    const res = [];
    if (!Range$2.isEmpty(r)) {
      res.push(EditOperation.insert(new Position$2(r.startLineNumber, r.startColumn), startToken + (insertSpace ? " " : "")));
      res.push(EditOperation.insert(new Position$2(r.endLineNumber, r.endColumn), (insertSpace ? " " : "") + endToken));
    } else {
      res.push(EditOperation.replace(new Range$2(r.startLineNumber, r.startColumn, r.endLineNumber, r.endColumn), startToken + "  " + endToken));
    }
    return res;
  }
  getEditOperations(model, builder) {
    const startLineNumber = this._selection.startLineNumber;
    const startColumn = this._selection.startColumn;
    model.tokenization.tokenizeIfCheap(startLineNumber);
    const languageId = model.getLanguageIdAtPosition(startLineNumber, startColumn);
    const config2 = this.languageConfigurationService.getLanguageConfiguration(languageId).comments;
    if (!config2 || !config2.blockCommentStartToken || !config2.blockCommentEndToken) {
      return;
    }
    this._createOperationsForBlockComment(this._selection, config2.blockCommentStartToken, config2.blockCommentEndToken, this._insertSpace, model, builder);
  }
  computeCursorState(model, helper) {
    const inverseEditOperations = helper.getInverseEditOperations();
    if (inverseEditOperations.length === 2) {
      const startTokenEditOperation = inverseEditOperations[0];
      const endTokenEditOperation = inverseEditOperations[1];
      return new Selection$1(startTokenEditOperation.range.endLineNumber, startTokenEditOperation.range.endColumn, endTokenEditOperation.range.startLineNumber, endTokenEditOperation.range.startColumn);
    } else {
      const srcRange = inverseEditOperations[0].range;
      const deltaColumn = this._usedEndToken ? -this._usedEndToken.length - 1 : 0;
      return new Selection$1(srcRange.endLineNumber, srcRange.endColumn + deltaColumn, srcRange.endLineNumber, srcRange.endColumn + deltaColumn);
    }
  }
}
class LineCommentCommand {
  constructor(languageConfigurationService, selection, tabSize, type, insertSpace, ignoreEmptyLines, ignoreFirstLine) {
    this.languageConfigurationService = languageConfigurationService;
    this._selection = selection;
    this._tabSize = tabSize;
    this._type = type;
    this._insertSpace = insertSpace;
    this._selectionId = null;
    this._deltaColumn = 0;
    this._moveEndPositionDown = false;
    this._ignoreEmptyLines = ignoreEmptyLines;
    this._ignoreFirstLine = ignoreFirstLine || false;
  }
  /**
   * Do an initial pass over the lines and gather info about the line comment string.
   * Returns null if any of the lines doesn't support a line comment string.
   */
  static _gatherPreflightCommentStrings(model, startLineNumber, endLineNumber, languageConfigurationService) {
    model.tokenization.tokenizeIfCheap(startLineNumber);
    const languageId = model.getLanguageIdAtPosition(startLineNumber, 1);
    const config2 = languageConfigurationService.getLanguageConfiguration(languageId).comments;
    const commentStr = config2 ? config2.lineCommentToken : null;
    if (!commentStr) {
      return null;
    }
    const lines = [];
    for (let i = 0, lineCount = endLineNumber - startLineNumber + 1; i < lineCount; i++) {
      lines[i] = {
        ignore: false,
        commentStr,
        commentStrOffset: 0,
        commentStrLength: commentStr.length
      };
    }
    return lines;
  }
  /**
   * Analyze lines and decide which lines are relevant and what the toggle should do.
   * Also, build up several offsets and lengths useful in the generation of editor operations.
   */
  static _analyzeLines(type, insertSpace, model, lines, startLineNumber, ignoreEmptyLines, ignoreFirstLine, languageConfigurationService) {
    let onlyWhitespaceLines = true;
    let shouldRemoveComments;
    if (type === 0) {
      shouldRemoveComments = true;
    } else if (type === 1) {
      shouldRemoveComments = false;
    } else {
      shouldRemoveComments = true;
    }
    for (let i = 0, lineCount = lines.length; i < lineCount; i++) {
      const lineData = lines[i];
      const lineNumber = startLineNumber + i;
      if (lineNumber === startLineNumber && ignoreFirstLine) {
        lineData.ignore = true;
        continue;
      }
      const lineContent = model.getLineContent(lineNumber);
      const lineContentStartOffset = firstNonWhitespaceIndex(lineContent);
      if (lineContentStartOffset === -1) {
        lineData.ignore = ignoreEmptyLines;
        lineData.commentStrOffset = lineContent.length;
        continue;
      }
      onlyWhitespaceLines = false;
      lineData.ignore = false;
      lineData.commentStrOffset = lineContentStartOffset;
      if (shouldRemoveComments && !BlockCommentCommand._haystackHasNeedleAtOffset(lineContent, lineData.commentStr, lineContentStartOffset)) {
        if (type === 0) {
          shouldRemoveComments = false;
        } else if (type === 1)
          ;
        else {
          lineData.ignore = true;
        }
      }
      if (shouldRemoveComments && insertSpace) {
        const commentStrEndOffset = lineContentStartOffset + lineData.commentStrLength;
        if (commentStrEndOffset < lineContent.length && lineContent.charCodeAt(commentStrEndOffset) === 32) {
          lineData.commentStrLength += 1;
        }
      }
    }
    if (type === 0 && onlyWhitespaceLines) {
      shouldRemoveComments = false;
      for (let i = 0, lineCount = lines.length; i < lineCount; i++) {
        lines[i].ignore = false;
      }
    }
    return {
      supported: true,
      shouldRemoveComments,
      lines
    };
  }
  /**
   * Analyze all lines and decide exactly what to do => not supported | insert line comments | remove line comments
   */
  static _gatherPreflightData(type, insertSpace, model, startLineNumber, endLineNumber, ignoreEmptyLines, ignoreFirstLine, languageConfigurationService) {
    const lines = LineCommentCommand._gatherPreflightCommentStrings(model, startLineNumber, endLineNumber, languageConfigurationService);
    if (lines === null) {
      return {
        supported: false
      };
    }
    return LineCommentCommand._analyzeLines(type, insertSpace, model, lines, startLineNumber, ignoreEmptyLines, ignoreFirstLine, languageConfigurationService);
  }
  /**
   * Given a successful analysis, execute either insert line comments, either remove line comments
   */
  _executeLineComments(model, builder, data, s) {
    let ops;
    if (data.shouldRemoveComments) {
      ops = LineCommentCommand._createRemoveLineCommentsOperations(data.lines, s.startLineNumber);
    } else {
      LineCommentCommand._normalizeInsertionPoint(model, data.lines, s.startLineNumber, this._tabSize);
      ops = this._createAddLineCommentsOperations(data.lines, s.startLineNumber);
    }
    const cursorPosition = new Position$2(s.positionLineNumber, s.positionColumn);
    for (let i = 0, len = ops.length; i < len; i++) {
      builder.addEditOperation(ops[i].range, ops[i].text);
      if (Range$2.isEmpty(ops[i].range) && Range$2.getStartPosition(ops[i].range).equals(cursorPosition)) {
        const lineContent = model.getLineContent(cursorPosition.lineNumber);
        if (lineContent.length + 1 === cursorPosition.column) {
          this._deltaColumn = (ops[i].text || "").length;
        }
      }
    }
    this._selectionId = builder.trackSelection(s);
  }
  _attemptRemoveBlockComment(model, s, startToken, endToken) {
    let startLineNumber = s.startLineNumber;
    let endLineNumber = s.endLineNumber;
    const startTokenAllowedBeforeColumn = endToken.length + Math.max(model.getLineFirstNonWhitespaceColumn(s.startLineNumber), s.startColumn);
    let startTokenIndex = model.getLineContent(startLineNumber).lastIndexOf(startToken, startTokenAllowedBeforeColumn - 1);
    let endTokenIndex = model.getLineContent(endLineNumber).indexOf(endToken, s.endColumn - 1 - startToken.length);
    if (startTokenIndex !== -1 && endTokenIndex === -1) {
      endTokenIndex = model.getLineContent(startLineNumber).indexOf(endToken, startTokenIndex + startToken.length);
      endLineNumber = startLineNumber;
    }
    if (startTokenIndex === -1 && endTokenIndex !== -1) {
      startTokenIndex = model.getLineContent(endLineNumber).lastIndexOf(startToken, endTokenIndex);
      startLineNumber = endLineNumber;
    }
    if (s.isEmpty() && (startTokenIndex === -1 || endTokenIndex === -1)) {
      startTokenIndex = model.getLineContent(startLineNumber).indexOf(startToken);
      if (startTokenIndex !== -1) {
        endTokenIndex = model.getLineContent(startLineNumber).indexOf(endToken, startTokenIndex + startToken.length);
      }
    }
    if (startTokenIndex !== -1 && model.getLineContent(startLineNumber).charCodeAt(startTokenIndex + startToken.length) === 32) {
      startToken += " ";
    }
    if (endTokenIndex !== -1 && model.getLineContent(endLineNumber).charCodeAt(endTokenIndex - 1) === 32) {
      endToken = " " + endToken;
      endTokenIndex -= 1;
    }
    if (startTokenIndex !== -1 && endTokenIndex !== -1) {
      return BlockCommentCommand._createRemoveBlockCommentOperations(new Range$2(startLineNumber, startTokenIndex + startToken.length + 1, endLineNumber, endTokenIndex + 1), startToken, endToken);
    }
    return null;
  }
  /**
   * Given an unsuccessful analysis, delegate to the block comment command
   */
  _executeBlockComment(model, builder, s) {
    model.tokenization.tokenizeIfCheap(s.startLineNumber);
    const languageId = model.getLanguageIdAtPosition(s.startLineNumber, 1);
    const config2 = this.languageConfigurationService.getLanguageConfiguration(languageId).comments;
    if (!config2 || !config2.blockCommentStartToken || !config2.blockCommentEndToken) {
      return;
    }
    const startToken = config2.blockCommentStartToken;
    const endToken = config2.blockCommentEndToken;
    let ops = this._attemptRemoveBlockComment(model, s, startToken, endToken);
    if (!ops) {
      if (s.isEmpty()) {
        const lineContent = model.getLineContent(s.startLineNumber);
        let firstNonWhitespaceIndex$1 = firstNonWhitespaceIndex(lineContent);
        if (firstNonWhitespaceIndex$1 === -1) {
          firstNonWhitespaceIndex$1 = lineContent.length;
        }
        ops = BlockCommentCommand._createAddBlockCommentOperations(new Range$2(s.startLineNumber, firstNonWhitespaceIndex$1 + 1, s.startLineNumber, lineContent.length + 1), startToken, endToken, this._insertSpace);
      } else {
        ops = BlockCommentCommand._createAddBlockCommentOperations(new Range$2(s.startLineNumber, model.getLineFirstNonWhitespaceColumn(s.startLineNumber), s.endLineNumber, model.getLineMaxColumn(s.endLineNumber)), startToken, endToken, this._insertSpace);
      }
      if (ops.length === 1) {
        this._deltaColumn = startToken.length + 1;
      }
    }
    this._selectionId = builder.trackSelection(s);
    for (const op of ops) {
      builder.addEditOperation(op.range, op.text);
    }
  }
  getEditOperations(model, builder) {
    let s = this._selection;
    this._moveEndPositionDown = false;
    if (s.startLineNumber === s.endLineNumber && this._ignoreFirstLine) {
      builder.addEditOperation(new Range$2(s.startLineNumber, model.getLineMaxColumn(s.startLineNumber), s.startLineNumber + 1, 1), s.startLineNumber === model.getLineCount() ? "" : "\n");
      this._selectionId = builder.trackSelection(s);
      return;
    }
    if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) {
      this._moveEndPositionDown = true;
      s = s.setEndPosition(s.endLineNumber - 1, model.getLineMaxColumn(s.endLineNumber - 1));
    }
    const data = LineCommentCommand._gatherPreflightData(this._type, this._insertSpace, model, s.startLineNumber, s.endLineNumber, this._ignoreEmptyLines, this._ignoreFirstLine, this.languageConfigurationService);
    if (data.supported) {
      return this._executeLineComments(model, builder, data, s);
    }
    return this._executeBlockComment(model, builder, s);
  }
  computeCursorState(model, helper) {
    let result2 = helper.getTrackedSelection(this._selectionId);
    if (this._moveEndPositionDown) {
      result2 = result2.setEndPosition(result2.endLineNumber + 1, 1);
    }
    return new Selection$1(result2.selectionStartLineNumber, result2.selectionStartColumn + this._deltaColumn, result2.positionLineNumber, result2.positionColumn + this._deltaColumn);
  }
  /**
   * Generate edit operations in the remove line comment case
   */
  static _createRemoveLineCommentsOperations(lines, startLineNumber) {
    const res = [];
    for (let i = 0, len = lines.length; i < len; i++) {
      const lineData = lines[i];
      if (lineData.ignore) {
        continue;
      }
      res.push(EditOperation.delete(new Range$2(startLineNumber + i, lineData.commentStrOffset + 1, startLineNumber + i, lineData.commentStrOffset + lineData.commentStrLength + 1)));
    }
    return res;
  }
  /**
   * Generate edit operations in the add line comment case
   */
  _createAddLineCommentsOperations(lines, startLineNumber) {
    const res = [];
    const afterCommentStr = this._insertSpace ? " " : "";
    for (let i = 0, len = lines.length; i < len; i++) {
      const lineData = lines[i];
      if (lineData.ignore) {
        continue;
      }
      res.push(EditOperation.insert(new Position$2(startLineNumber + i, lineData.commentStrOffset + 1), lineData.commentStr + afterCommentStr));
    }
    return res;
  }
  static nextVisibleColumn(currentVisibleColumn, tabSize, isTab, columnSize) {
    if (isTab) {
      return currentVisibleColumn + (tabSize - currentVisibleColumn % tabSize);
    }
    return currentVisibleColumn + columnSize;
  }
  /**
   * Adjust insertion points to have them vertically aligned in the add line comment case
   */
  static _normalizeInsertionPoint(model, lines, startLineNumber, tabSize) {
    let minVisibleColumn = 1073741824;
    let j;
    let lenJ;
    for (let i = 0, len = lines.length; i < len; i++) {
      if (lines[i].ignore) {
        continue;
      }
      const lineContent = model.getLineContent(startLineNumber + i);
      let currentVisibleColumn = 0;
      for (let j2 = 0, lenJ2 = lines[i].commentStrOffset; currentVisibleColumn < minVisibleColumn && j2 < lenJ2; j2++) {
        currentVisibleColumn = LineCommentCommand.nextVisibleColumn(currentVisibleColumn, tabSize, lineContent.charCodeAt(j2) === 9, 1);
      }
      if (currentVisibleColumn < minVisibleColumn) {
        minVisibleColumn = currentVisibleColumn;
      }
    }
    minVisibleColumn = Math.floor(minVisibleColumn / tabSize) * tabSize;
    for (let i = 0, len = lines.length; i < len; i++) {
      if (lines[i].ignore) {
        continue;
      }
      const lineContent = model.getLineContent(startLineNumber + i);
      let currentVisibleColumn = 0;
      for (j = 0, lenJ = lines[i].commentStrOffset; currentVisibleColumn < minVisibleColumn && j < lenJ; j++) {
        currentVisibleColumn = LineCommentCommand.nextVisibleColumn(currentVisibleColumn, tabSize, lineContent.charCodeAt(j) === 9, 1);
      }
      if (currentVisibleColumn > minVisibleColumn) {
        lines[i].commentStrOffset = j - 1;
      } else {
        lines[i].commentStrOffset = j;
      }
    }
  }
}
class CommentLineAction extends EditorAction {
  constructor(type, opts) {
    super(opts);
    this._type = type;
  }
  run(accessor, editor2) {
    const languageConfigurationService = accessor.get(ILanguageConfigurationService);
    if (!editor2.hasModel()) {
      return;
    }
    const model = editor2.getModel();
    const commands = [];
    const modelOptions = model.getOptions();
    const commentsOptions = editor2.getOption(
      22
      /* EditorOption.comments */
    );
    const selections2 = editor2.getSelections().map((selection, index) => ({ selection, index, ignoreFirstLine: false }));
    selections2.sort((a, b) => Range$2.compareRangesUsingStarts(a.selection, b.selection));
    let prev = selections2[0];
    for (let i = 1; i < selections2.length; i++) {
      const curr = selections2[i];
      if (prev.selection.endLineNumber === curr.selection.startLineNumber) {
        if (prev.index < curr.index) {
          curr.ignoreFirstLine = true;
        } else {
          prev.ignoreFirstLine = true;
          prev = curr;
        }
      }
    }
    for (const selection of selections2) {
      commands.push(new LineCommentCommand(languageConfigurationService, selection.selection, modelOptions.tabSize, this._type, commentsOptions.insertSpace, commentsOptions.ignoreEmptyLines, selection.ignoreFirstLine));
    }
    editor2.pushUndoStop();
    editor2.executeCommands(this.id, commands);
    editor2.pushUndoStop();
  }
}
class ToggleCommentLineAction extends CommentLineAction {
  constructor() {
    super(0, {
      id: "editor.action.commentLine",
      label: localize("comment.line", "Toggle Line Comment"),
      alias: "Toggle Line Comment",
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 90,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: MenuId.MenubarEditMenu,
        group: "5_insert",
        title: localize({ key: "miToggleLineComment", comment: ["&& denotes a mnemonic"] }, "&&Toggle Line Comment"),
        order: 1
      }
    });
  }
}
class AddLineCommentAction extends CommentLineAction {
  constructor() {
    super(1, {
      id: "editor.action.addCommentLine",
      label: localize("comment.line.add", "Add Line Comment"),
      alias: "Add Line Comment",
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: KeyChord(
          2048 | 41,
          2048 | 33
          /* KeyCode.KeyC */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
}
class RemoveLineCommentAction extends CommentLineAction {
  constructor() {
    super(2, {
      id: "editor.action.removeCommentLine",
      label: localize("comment.line.remove", "Remove Line Comment"),
      alias: "Remove Line Comment",
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: KeyChord(
          2048 | 41,
          2048 | 51
          /* KeyCode.KeyU */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
}
class BlockCommentAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.blockComment",
      label: localize("comment.block", "Toggle Block Comment"),
      alias: "Toggle Block Comment",
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 1024 | 512 | 31,
        linux: {
          primary: 2048 | 1024 | 31
          /* KeyCode.KeyA */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: MenuId.MenubarEditMenu,
        group: "5_insert",
        title: localize({ key: "miToggleBlockComment", comment: ["&& denotes a mnemonic"] }, "Toggle &&Block Comment"),
        order: 2
      }
    });
  }
  run(accessor, editor2) {
    const languageConfigurationService = accessor.get(ILanguageConfigurationService);
    if (!editor2.hasModel()) {
      return;
    }
    const commentsOptions = editor2.getOption(
      22
      /* EditorOption.comments */
    );
    const commands = [];
    const selections2 = editor2.getSelections();
    for (const selection of selections2) {
      commands.push(new BlockCommentCommand(selection, commentsOptions.insertSpace, languageConfigurationService));
    }
    editor2.pushUndoStop();
    editor2.executeCommands(this.id, commands);
    editor2.pushUndoStop();
  }
}
registerEditorAction(ToggleCommentLineAction);
registerEditorAction(AddLineCommentAction);
registerEditorAction(RemoveLineCommentAction);
registerEditorAction(BlockCommentAction);
class StringIterator {
  constructor() {
    this._value = "";
    this._pos = 0;
  }
  reset(key) {
    this._value = key;
    this._pos = 0;
    return this;
  }
  next() {
    this._pos += 1;
    return this;
  }
  hasNext() {
    return this._pos < this._value.length - 1;
  }
  cmp(a) {
    const aCode = a.charCodeAt(0);
    const thisCode = this._value.charCodeAt(this._pos);
    return aCode - thisCode;
  }
  value() {
    return this._value[this._pos];
  }
}
class ConfigKeysIterator {
  constructor(_caseSensitive = true) {
    this._caseSensitive = _caseSensitive;
  }
  reset(key) {
    this._value = key;
    this._from = 0;
    this._to = 0;
    return this.next();
  }
  hasNext() {
    return this._to < this._value.length;
  }
  next() {
    this._from = this._to;
    let justSeps = true;
    for (; this._to < this._value.length; this._to++) {
      const ch = this._value.charCodeAt(this._to);
      if (ch === 46) {
        if (justSeps) {
          this._from++;
        } else {
          break;
        }
      } else {
        justSeps = false;
      }
    }
    return this;
  }
  cmp(a) {
    return this._caseSensitive ? compareSubstring(a, this._value, 0, a.length, this._from, this._to) : compareSubstringIgnoreCase(a, this._value, 0, a.length, this._from, this._to);
  }
  value() {
    return this._value.substring(this._from, this._to);
  }
}
class PathIterator {
  constructor(_splitOnBackslash = true, _caseSensitive = true) {
    this._splitOnBackslash = _splitOnBackslash;
    this._caseSensitive = _caseSensitive;
  }
  reset(key) {
    this._from = 0;
    this._to = 0;
    this._value = key;
    this._valueLen = key.length;
    for (let pos = key.length - 1; pos >= 0; pos--, this._valueLen--) {
      const ch = this._value.charCodeAt(pos);
      if (!(ch === 47 || this._splitOnBackslash && ch === 92)) {
        break;
      }
    }
    return this.next();
  }
  hasNext() {
    return this._to < this._valueLen;
  }
  next() {
    this._from = this._to;
    let justSeps = true;
    for (; this._to < this._valueLen; this._to++) {
      const ch = this._value.charCodeAt(this._to);
      if (ch === 47 || this._splitOnBackslash && ch === 92) {
        if (justSeps) {
          this._from++;
        } else {
          break;
        }
      } else {
        justSeps = false;
      }
    }
    return this;
  }
  cmp(a) {
    return this._caseSensitive ? compareSubstring(a, this._value, 0, a.length, this._from, this._to) : compareSubstringIgnoreCase(a, this._value, 0, a.length, this._from, this._to);
  }
  value() {
    return this._value.substring(this._from, this._to);
  }
}
class UriIterator {
  constructor(_ignorePathCasing, _ignoreQueryAndFragment) {
    this._ignorePathCasing = _ignorePathCasing;
    this._ignoreQueryAndFragment = _ignoreQueryAndFragment;
    this._states = [];
    this._stateIdx = 0;
  }
  reset(key) {
    this._value = key;
    this._states = [];
    if (this._value.scheme) {
      this._states.push(
        1
        /* UriIteratorState.Scheme */
      );
    }
    if (this._value.authority) {
      this._states.push(
        2
        /* UriIteratorState.Authority */
      );
    }
    if (this._value.path) {
      this._pathIterator = new PathIterator(false, !this._ignorePathCasing(key));
      this._pathIterator.reset(key.path);
      if (this._pathIterator.value()) {
        this._states.push(
          3
          /* UriIteratorState.Path */
        );
      }
    }
    if (!this._ignoreQueryAndFragment(key)) {
      if (this._value.query) {
        this._states.push(
          4
          /* UriIteratorState.Query */
        );
      }
      if (this._value.fragment) {
        this._states.push(
          5
          /* UriIteratorState.Fragment */
        );
      }
    }
    this._stateIdx = 0;
    return this;
  }
  next() {
    if (this._states[this._stateIdx] === 3 && this._pathIterator.hasNext()) {
      this._pathIterator.next();
    } else {
      this._stateIdx += 1;
    }
    return this;
  }
  hasNext() {
    return this._states[this._stateIdx] === 3 && this._pathIterator.hasNext() || this._stateIdx < this._states.length - 1;
  }
  cmp(a) {
    if (this._states[this._stateIdx] === 1) {
      return compareIgnoreCase(a, this._value.scheme);
    } else if (this._states[this._stateIdx] === 2) {
      return compareIgnoreCase(a, this._value.authority);
    } else if (this._states[this._stateIdx] === 3) {
      return this._pathIterator.cmp(a);
    } else if (this._states[this._stateIdx] === 4) {
      return compare(a, this._value.query);
    } else if (this._states[this._stateIdx] === 5) {
      return compare(a, this._value.fragment);
    }
    throw new Error();
  }
  value() {
    if (this._states[this._stateIdx] === 1) {
      return this._value.scheme;
    } else if (this._states[this._stateIdx] === 2) {
      return this._value.authority;
    } else if (this._states[this._stateIdx] === 3) {
      return this._pathIterator.value();
    } else if (this._states[this._stateIdx] === 4) {
      return this._value.query;
    } else if (this._states[this._stateIdx] === 5) {
      return this._value.fragment;
    }
    throw new Error();
  }
}
class TernarySearchTreeNode {
  constructor() {
    this.height = 1;
  }
  rotateLeft() {
    const tmp = this.right;
    this.right = tmp.left;
    tmp.left = this;
    this.updateHeight();
    tmp.updateHeight();
    return tmp;
  }
  rotateRight() {
    const tmp = this.left;
    this.left = tmp.right;
    tmp.right = this;
    this.updateHeight();
    tmp.updateHeight();
    return tmp;
  }
  updateHeight() {
    this.height = 1 + Math.max(this.heightLeft, this.heightRight);
  }
  balanceFactor() {
    return this.heightRight - this.heightLeft;
  }
  get heightLeft() {
    var _a2, _b2;
    return (_b2 = (_a2 = this.left) === null || _a2 === void 0 ? void 0 : _a2.height) !== null && _b2 !== void 0 ? _b2 : 0;
  }
  get heightRight() {
    var _a2, _b2;
    return (_b2 = (_a2 = this.right) === null || _a2 === void 0 ? void 0 : _a2.height) !== null && _b2 !== void 0 ? _b2 : 0;
  }
}
class TernarySearchTree {
  static forUris(ignorePathCasing = () => false, ignoreQueryAndFragment = () => false) {
    return new TernarySearchTree(new UriIterator(ignorePathCasing, ignoreQueryAndFragment));
  }
  static forStrings() {
    return new TernarySearchTree(new StringIterator());
  }
  static forConfigKeys() {
    return new TernarySearchTree(new ConfigKeysIterator());
  }
  constructor(segments) {
    this._iter = segments;
  }
  clear() {
    this._root = void 0;
  }
  set(key, element) {
    const iter = this._iter.reset(key);
    let node2;
    if (!this._root) {
      this._root = new TernarySearchTreeNode();
      this._root.segment = iter.value();
    }
    const stack = [];
    node2 = this._root;
    while (true) {
      const val = iter.cmp(node2.segment);
      if (val > 0) {
        if (!node2.left) {
          node2.left = new TernarySearchTreeNode();
          node2.left.segment = iter.value();
        }
        stack.push([-1, node2]);
        node2 = node2.left;
      } else if (val < 0) {
        if (!node2.right) {
          node2.right = new TernarySearchTreeNode();
          node2.right.segment = iter.value();
        }
        stack.push([1, node2]);
        node2 = node2.right;
      } else if (iter.hasNext()) {
        iter.next();
        if (!node2.mid) {
          node2.mid = new TernarySearchTreeNode();
          node2.mid.segment = iter.value();
        }
        stack.push([0, node2]);
        node2 = node2.mid;
      } else {
        break;
      }
    }
    const oldElement = node2.value;
    node2.value = element;
    node2.key = key;
    for (let i = stack.length - 1; i >= 0; i--) {
      const node3 = stack[i][1];
      node3.updateHeight();
      const bf = node3.balanceFactor();
      if (bf < -1 || bf > 1) {
        const d1 = stack[i][0];
        const d2 = stack[i + 1][0];
        if (d1 === 1 && d2 === 1) {
          stack[i][1] = node3.rotateLeft();
        } else if (d1 === -1 && d2 === -1) {
          stack[i][1] = node3.rotateRight();
        } else if (d1 === 1 && d2 === -1) {
          node3.right = stack[i + 1][1] = stack[i + 1][1].rotateRight();
          stack[i][1] = node3.rotateLeft();
        } else if (d1 === -1 && d2 === 1) {
          node3.left = stack[i + 1][1] = stack[i + 1][1].rotateLeft();
          stack[i][1] = node3.rotateRight();
        } else {
          throw new Error();
        }
        if (i > 0) {
          switch (stack[i - 1][0]) {
            case -1:
              stack[i - 1][1].left = stack[i][1];
              break;
            case 1:
              stack[i - 1][1].right = stack[i][1];
              break;
            case 0:
              stack[i - 1][1].mid = stack[i][1];
              break;
          }
        } else {
          this._root = stack[0][1];
        }
      }
    }
    return oldElement;
  }
  get(key) {
    var _a2;
    return (_a2 = this._getNode(key)) === null || _a2 === void 0 ? void 0 : _a2.value;
  }
  _getNode(key) {
    const iter = this._iter.reset(key);
    let node2 = this._root;
    while (node2) {
      const val = iter.cmp(node2.segment);
      if (val > 0) {
        node2 = node2.left;
      } else if (val < 0) {
        node2 = node2.right;
      } else if (iter.hasNext()) {
        iter.next();
        node2 = node2.mid;
      } else {
        break;
      }
    }
    return node2;
  }
  has(key) {
    const node2 = this._getNode(key);
    return !((node2 === null || node2 === void 0 ? void 0 : node2.value) === void 0 && (node2 === null || node2 === void 0 ? void 0 : node2.mid) === void 0);
  }
  delete(key) {
    return this._delete(key, false);
  }
  deleteSuperstr(key) {
    return this._delete(key, true);
  }
  _delete(key, superStr) {
    var _a2;
    const iter = this._iter.reset(key);
    const stack = [];
    let node2 = this._root;
    while (node2) {
      const val = iter.cmp(node2.segment);
      if (val > 0) {
        stack.push([-1, node2]);
        node2 = node2.left;
      } else if (val < 0) {
        stack.push([1, node2]);
        node2 = node2.right;
      } else if (iter.hasNext()) {
        iter.next();
        stack.push([0, node2]);
        node2 = node2.mid;
      } else {
        break;
      }
    }
    if (!node2) {
      return;
    }
    if (superStr) {
      node2.left = void 0;
      node2.mid = void 0;
      node2.right = void 0;
      node2.height = 1;
    } else {
      node2.key = void 0;
      node2.value = void 0;
    }
    if (!node2.mid && !node2.value) {
      if (node2.left && node2.right) {
        const min = this._min(node2.right);
        if (min.key) {
          const { key: key2, value, segment } = min;
          this._delete(min.key, false);
          node2.key = key2;
          node2.value = value;
          node2.segment = segment;
        }
      } else {
        const newChild = (_a2 = node2.left) !== null && _a2 !== void 0 ? _a2 : node2.right;
        if (stack.length > 0) {
          const [dir, parent] = stack[stack.length - 1];
          switch (dir) {
            case -1:
              parent.left = newChild;
              break;
            case 0:
              parent.mid = newChild;
              break;
            case 1:
              parent.right = newChild;
              break;
          }
        } else {
          this._root = newChild;
        }
      }
    }
    for (let i = stack.length - 1; i >= 0; i--) {
      const node3 = stack[i][1];
      node3.updateHeight();
      const bf = node3.balanceFactor();
      if (bf > 1) {
        if (node3.right.balanceFactor() >= 0) {
          stack[i][1] = node3.rotateLeft();
        } else {
          node3.right = node3.right.rotateRight();
          stack[i][1] = node3.rotateLeft();
        }
      } else if (bf < -1) {
        if (node3.left.balanceFactor() <= 0) {
          stack[i][1] = node3.rotateRight();
        } else {
          node3.left = node3.left.rotateLeft();
          stack[i][1] = node3.rotateRight();
        }
      }
      if (i > 0) {
        switch (stack[i - 1][0]) {
          case -1:
            stack[i - 1][1].left = stack[i][1];
            break;
          case 1:
            stack[i - 1][1].right = stack[i][1];
            break;
          case 0:
            stack[i - 1][1].mid = stack[i][1];
            break;
        }
      } else {
        this._root = stack[0][1];
      }
    }
  }
  _min(node2) {
    while (node2.left) {
      node2 = node2.left;
    }
    return node2;
  }
  findSubstr(key) {
    const iter = this._iter.reset(key);
    let node2 = this._root;
    let candidate = void 0;
    while (node2) {
      const val = iter.cmp(node2.segment);
      if (val > 0) {
        node2 = node2.left;
      } else if (val < 0) {
        node2 = node2.right;
      } else if (iter.hasNext()) {
        iter.next();
        candidate = node2.value || candidate;
        node2 = node2.mid;
      } else {
        break;
      }
    }
    return node2 && node2.value || candidate;
  }
  findSuperstr(key) {
    return this._findSuperstrOrElement(key, false);
  }
  _findSuperstrOrElement(key, allowValue) {
    const iter = this._iter.reset(key);
    let node2 = this._root;
    while (node2) {
      const val = iter.cmp(node2.segment);
      if (val > 0) {
        node2 = node2.left;
      } else if (val < 0) {
        node2 = node2.right;
      } else if (iter.hasNext()) {
        iter.next();
        node2 = node2.mid;
      } else {
        if (!node2.mid) {
          if (allowValue) {
            return node2.value;
          } else {
            return void 0;
          }
        } else {
          return this._entries(node2.mid);
        }
      }
    }
    return void 0;
  }
  forEach(callback) {
    for (const [key, value] of this) {
      callback(value, key);
    }
  }
  *[Symbol.iterator]() {
    yield* this._entries(this._root);
  }
  _entries(node2) {
    const result2 = [];
    this._dfsEntries(node2, result2);
    return result2[Symbol.iterator]();
  }
  _dfsEntries(node2, bucket) {
    if (!node2) {
      return;
    }
    if (node2.left) {
      this._dfsEntries(node2.left, bucket);
    }
    if (node2.value) {
      bucket.push([node2.key, node2.value]);
    }
    if (node2.mid) {
      this._dfsEntries(node2.mid, bucket);
    }
    if (node2.right) {
      this._dfsEntries(node2.right, bucket);
    }
  }
}
const IWorkspaceContextService = createDecorator("contextService");
function isSingleFolderWorkspaceIdentifier(obj) {
  const singleFolderIdentifier = obj;
  return typeof (singleFolderIdentifier === null || singleFolderIdentifier === void 0 ? void 0 : singleFolderIdentifier.id) === "string" && URI.isUri(singleFolderIdentifier.uri);
}
function isEmptyWorkspaceIdentifier(obj) {
  const emptyWorkspaceIdentifier = obj;
  return typeof (emptyWorkspaceIdentifier === null || emptyWorkspaceIdentifier === void 0 ? void 0 : emptyWorkspaceIdentifier.id) === "string" && !isSingleFolderWorkspaceIdentifier(obj) && !isWorkspaceIdentifier(obj);
}
const EXTENSION_DEVELOPMENT_EMPTY_WINDOW_WORKSPACE = { id: "ext-dev" };
const UNKNOWN_EMPTY_WINDOW_WORKSPACE = { id: "empty-window" };
function toWorkspaceIdentifier(arg0, isExtensionDevelopment) {
  if (typeof arg0 === "string" || typeof arg0 === "undefined") {
    if (typeof arg0 === "string") {
      return {
        id: basename$2(arg0)
      };
    }
    if (isExtensionDevelopment) {
      return EXTENSION_DEVELOPMENT_EMPTY_WINDOW_WORKSPACE;
    }
    return UNKNOWN_EMPTY_WINDOW_WORKSPACE;
  }
  const workspace = arg0;
  if (workspace.configuration) {
    return {
      id: workspace.id,
      configPath: workspace.configuration
    };
  }
  if (workspace.folders.length === 1) {
    return {
      id: workspace.id,
      uri: workspace.folders[0].uri
    };
  }
  return {
    id: workspace.id
  };
}
function isWorkspaceIdentifier(obj) {
  const workspaceIdentifier = obj;
  return typeof (workspaceIdentifier === null || workspaceIdentifier === void 0 ? void 0 : workspaceIdentifier.id) === "string" && URI.isUri(workspaceIdentifier.configPath);
}
class WorkspaceFolder {
  constructor(data, raw) {
    this.raw = raw;
    this.uri = data.uri;
    this.index = data.index;
    this.name = data.name;
  }
  toJSON() {
    return { uri: this.uri, name: this.name, index: this.index };
  }
}
const WORKSPACE_EXTENSION = "code-workspace";
[{ name: localize("codeWorkspace", "Code Workspace"), extensions: [WORKSPACE_EXTENSION] }];
const STANDALONE_EDITOR_WORKSPACE_ID = "4064f6ec-cb38-4ad0-af64-ee6467e63c82";
function isStandaloneEditorWorkspace(workspace) {
  return workspace.id === STANDALONE_EDITOR_WORKSPACE_ID;
}
var __decorate$1n = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1l = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let ContextMenuController = class ContextMenuController2 {
  static get(editor2) {
    return editor2.getContribution(ContextMenuController2.ID);
  }
  constructor(editor2, _contextMenuService, _contextViewService, _contextKeyService, _keybindingService, _menuService, _configurationService, _workspaceContextService) {
    this._contextMenuService = _contextMenuService;
    this._contextViewService = _contextViewService;
    this._contextKeyService = _contextKeyService;
    this._keybindingService = _keybindingService;
    this._menuService = _menuService;
    this._configurationService = _configurationService;
    this._workspaceContextService = _workspaceContextService;
    this._toDispose = new DisposableStore();
    this._contextMenuIsBeingShownCount = 0;
    this._editor = editor2;
    this._toDispose.add(this._editor.onContextMenu((e) => this._onContextMenu(e)));
    this._toDispose.add(this._editor.onMouseWheel((e) => {
      if (this._contextMenuIsBeingShownCount > 0) {
        const view = this._contextViewService.getContextViewElement();
        const target = e.srcElement;
        if (!(target.shadowRoot && getShadowRoot(view) === target.shadowRoot)) {
          this._contextViewService.hideContextView();
        }
      }
    }));
    this._toDispose.add(this._editor.onKeyDown((e) => {
      if (!this._editor.getOption(
        23
        /* EditorOption.contextmenu */
      )) {
        return;
      }
      if (e.keyCode === 58) {
        e.preventDefault();
        e.stopPropagation();
        this.showContextMenu();
      }
    }));
  }
  _onContextMenu(e) {
    if (!this._editor.hasModel()) {
      return;
    }
    if (!this._editor.getOption(
      23
      /* EditorOption.contextmenu */
    )) {
      this._editor.focus();
      if (e.target.position && !this._editor.getSelection().containsPosition(e.target.position)) {
        this._editor.setPosition(e.target.position);
      }
      return;
    }
    if (e.target.type === 12) {
      return;
    }
    if (e.target.type === 6 && e.target.detail.injectedText) {
      return;
    }
    e.event.preventDefault();
    e.event.stopPropagation();
    if (e.target.type === 11) {
      return this._showScrollbarContextMenu(e.event);
    }
    if (e.target.type !== 6 && e.target.type !== 7 && e.target.type !== 1) {
      return;
    }
    this._editor.focus();
    if (e.target.position) {
      let hasSelectionAtPosition = false;
      for (const selection of this._editor.getSelections()) {
        if (selection.containsPosition(e.target.position)) {
          hasSelectionAtPosition = true;
          break;
        }
      }
      if (!hasSelectionAtPosition) {
        this._editor.setPosition(e.target.position);
      }
    }
    let anchor = null;
    if (e.target.type !== 1) {
      anchor = e.event;
    }
    this.showContextMenu(anchor);
  }
  showContextMenu(anchor) {
    if (!this._editor.getOption(
      23
      /* EditorOption.contextmenu */
    )) {
      return;
    }
    if (!this._editor.hasModel()) {
      return;
    }
    const menuActions = this._getMenuActions(this._editor.getModel(), this._editor.isSimpleWidget ? MenuId.SimpleEditorContext : MenuId.EditorContext);
    if (menuActions.length > 0) {
      this._doShowContextMenu(menuActions, anchor);
    }
  }
  _getMenuActions(model, menuId) {
    const result2 = [];
    const menu = this._menuService.createMenu(menuId, this._contextKeyService);
    const groups = menu.getActions({ arg: model.uri });
    menu.dispose();
    for (const group2 of groups) {
      const [, actions] = group2;
      let addedItems = 0;
      for (const action of actions) {
        if (action instanceof SubmenuItemAction) {
          const subActions = this._getMenuActions(model, action.item.submenu);
          if (subActions.length > 0) {
            result2.push(new SubmenuAction(action.id, action.label, subActions));
            addedItems++;
          }
        } else {
          result2.push(action);
          addedItems++;
        }
      }
      if (addedItems) {
        result2.push(new Separator());
      }
    }
    if (result2.length) {
      result2.pop();
    }
    return result2;
  }
  _doShowContextMenu(actions, event = null) {
    if (!this._editor.hasModel()) {
      return;
    }
    const oldHoverSetting = this._editor.getOption(
      59
      /* EditorOption.hover */
    );
    this._editor.updateOptions({
      hover: {
        enabled: false
      }
    });
    let anchor = event;
    if (!anchor) {
      this._editor.revealPosition(
        this._editor.getPosition(),
        1
        /* ScrollType.Immediate */
      );
      this._editor.render();
      const cursorCoords = this._editor.getScrolledVisiblePosition(this._editor.getPosition());
      const editorCoords = getDomNodePagePosition(this._editor.getDomNode());
      const posx = editorCoords.left + cursorCoords.left;
      const posy = editorCoords.top + cursorCoords.top + cursorCoords.height;
      anchor = { x: posx, y: posy };
    }
    const useShadowDOM = this._editor.getOption(
      125
      /* EditorOption.useShadowDOM */
    ) && !isIOS;
    this._contextMenuIsBeingShownCount++;
    this._contextMenuService.showContextMenu({
      domForShadowRoot: useShadowDOM ? this._editor.getDomNode() : void 0,
      getAnchor: () => anchor,
      getActions: () => actions,
      getActionViewItem: (action) => {
        const keybinding = this._keybindingFor(action);
        if (keybinding) {
          return new ActionViewItem(action, action, { label: true, keybinding: keybinding.getLabel(), isMenu: true });
        }
        const customActionViewItem = action;
        if (typeof customActionViewItem.getActionViewItem === "function") {
          return customActionViewItem.getActionViewItem();
        }
        return new ActionViewItem(action, action, { icon: true, label: true, isMenu: true });
      },
      getKeyBinding: (action) => {
        return this._keybindingFor(action);
      },
      onHide: (wasCancelled) => {
        this._contextMenuIsBeingShownCount--;
        this._editor.updateOptions({
          hover: oldHoverSetting
        });
      }
    });
  }
  _showScrollbarContextMenu(anchor) {
    if (!this._editor.hasModel()) {
      return;
    }
    if (isStandaloneEditorWorkspace(this._workspaceContextService.getWorkspace())) {
      return;
    }
    const minimapOptions = this._editor.getOption(
      71
      /* EditorOption.minimap */
    );
    let lastId = 0;
    const createAction = (opts) => {
      return {
        id: `menu-action-${++lastId}`,
        label: opts.label,
        tooltip: "",
        class: void 0,
        enabled: typeof opts.enabled === "undefined" ? true : opts.enabled,
        checked: opts.checked,
        run: opts.run
      };
    };
    const createSubmenuAction = (label, actions2) => {
      return new SubmenuAction(`menu-action-${++lastId}`, label, actions2, void 0);
    };
    const createEnumAction = (label, enabled, configName, configuredValue, options) => {
      if (!enabled) {
        return createAction({ label, enabled, run: () => {
        } });
      }
      const createRunner = (value) => {
        return () => {
          this._configurationService.updateValue(configName, value);
        };
      };
      const actions2 = [];
      for (const option of options) {
        actions2.push(createAction({
          label: option.label,
          checked: configuredValue === option.value,
          run: createRunner(option.value)
        }));
      }
      return createSubmenuAction(label, actions2);
    };
    const actions = [];
    actions.push(createAction({
      label: localize("context.minimap.minimap", "Minimap"),
      checked: minimapOptions.enabled,
      run: () => {
        this._configurationService.updateValue(`editor.minimap.enabled`, !minimapOptions.enabled);
      }
    }));
    actions.push(new Separator());
    actions.push(createAction({
      label: localize("context.minimap.renderCharacters", "Render Characters"),
      enabled: minimapOptions.enabled,
      checked: minimapOptions.renderCharacters,
      run: () => {
        this._configurationService.updateValue(`editor.minimap.renderCharacters`, !minimapOptions.renderCharacters);
      }
    }));
    actions.push(createEnumAction(localize("context.minimap.size", "Vertical size"), minimapOptions.enabled, "editor.minimap.size", minimapOptions.size, [{
      label: localize("context.minimap.size.proportional", "Proportional"),
      value: "proportional"
    }, {
      label: localize("context.minimap.size.fill", "Fill"),
      value: "fill"
    }, {
      label: localize("context.minimap.size.fit", "Fit"),
      value: "fit"
    }]));
    actions.push(createEnumAction(localize("context.minimap.slider", "Slider"), minimapOptions.enabled, "editor.minimap.showSlider", minimapOptions.showSlider, [{
      label: localize("context.minimap.slider.mouseover", "Mouse Over"),
      value: "mouseover"
    }, {
      label: localize("context.minimap.slider.always", "Always"),
      value: "always"
    }]));
    const useShadowDOM = this._editor.getOption(
      125
      /* EditorOption.useShadowDOM */
    ) && !isIOS;
    this._contextMenuIsBeingShownCount++;
    this._contextMenuService.showContextMenu({
      domForShadowRoot: useShadowDOM ? this._editor.getDomNode() : void 0,
      getAnchor: () => anchor,
      getActions: () => actions,
      onHide: (wasCancelled) => {
        this._contextMenuIsBeingShownCount--;
        this._editor.focus();
      }
    });
  }
  _keybindingFor(action) {
    return this._keybindingService.lookupKeybinding(action.id);
  }
  dispose() {
    if (this._contextMenuIsBeingShownCount > 0) {
      this._contextViewService.hideContextView();
    }
    this._toDispose.dispose();
  }
};
ContextMenuController.ID = "editor.contrib.contextmenu";
ContextMenuController = __decorate$1n([
  __param$1l(1, IContextMenuService),
  __param$1l(2, IContextViewService),
  __param$1l(3, IContextKeyService),
  __param$1l(4, IKeybindingService),
  __param$1l(5, IMenuService),
  __param$1l(6, IConfigurationService),
  __param$1l(7, IWorkspaceContextService)
], ContextMenuController);
class ShowContextMenu extends EditorAction {
  constructor() {
    super({
      id: "editor.action.showContextMenu",
      label: localize("action.showContextMenu.label", "Show Editor Context Menu"),
      alias: "Show Editor Context Menu",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 1024 | 68,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor2) {
    var _a2;
    (_a2 = ContextMenuController.get(editor2)) === null || _a2 === void 0 ? void 0 : _a2.showContextMenu();
  }
}
registerEditorContribution(
  ContextMenuController.ID,
  ContextMenuController,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);
registerEditorAction(ShowContextMenu);
class CursorState2 {
  constructor(selections2) {
    this.selections = selections2;
  }
  equals(other) {
    const thisLen = this.selections.length;
    const otherLen = other.selections.length;
    if (thisLen !== otherLen) {
      return false;
    }
    for (let i = 0; i < thisLen; i++) {
      if (!this.selections[i].equalsSelection(other.selections[i])) {
        return false;
      }
    }
    return true;
  }
}
class StackElement {
  constructor(cursorState, scrollTop, scrollLeft) {
    this.cursorState = cursorState;
    this.scrollTop = scrollTop;
    this.scrollLeft = scrollLeft;
  }
}
class CursorUndoRedoController extends Disposable {
  static get(editor2) {
    return editor2.getContribution(CursorUndoRedoController.ID);
  }
  constructor(editor2) {
    super();
    this._editor = editor2;
    this._isCursorUndoRedo = false;
    this._undoStack = [];
    this._redoStack = [];
    this._register(editor2.onDidChangeModel((e) => {
      this._undoStack = [];
      this._redoStack = [];
    }));
    this._register(editor2.onDidChangeModelContent((e) => {
      this._undoStack = [];
      this._redoStack = [];
    }));
    this._register(editor2.onDidChangeCursorSelection((e) => {
      if (this._isCursorUndoRedo) {
        return;
      }
      if (!e.oldSelections) {
        return;
      }
      if (e.oldModelVersionId !== e.modelVersionId) {
        return;
      }
      const prevState = new CursorState2(e.oldSelections);
      const isEqualToLastUndoStack = this._undoStack.length > 0 && this._undoStack[this._undoStack.length - 1].cursorState.equals(prevState);
      if (!isEqualToLastUndoStack) {
        this._undoStack.push(new StackElement(prevState, editor2.getScrollTop(), editor2.getScrollLeft()));
        this._redoStack = [];
        if (this._undoStack.length > 50) {
          this._undoStack.shift();
        }
      }
    }));
  }
  cursorUndo() {
    if (!this._editor.hasModel() || this._undoStack.length === 0) {
      return;
    }
    this._redoStack.push(new StackElement(new CursorState2(this._editor.getSelections()), this._editor.getScrollTop(), this._editor.getScrollLeft()));
    this._applyState(this._undoStack.pop());
  }
  cursorRedo() {
    if (!this._editor.hasModel() || this._redoStack.length === 0) {
      return;
    }
    this._undoStack.push(new StackElement(new CursorState2(this._editor.getSelections()), this._editor.getScrollTop(), this._editor.getScrollLeft()));
    this._applyState(this._redoStack.pop());
  }
  _applyState(stackElement) {
    this._isCursorUndoRedo = true;
    this._editor.setSelections(stackElement.cursorState.selections);
    this._editor.setScrollPosition({
      scrollTop: stackElement.scrollTop,
      scrollLeft: stackElement.scrollLeft
    });
    this._isCursorUndoRedo = false;
  }
}
CursorUndoRedoController.ID = "editor.contrib.cursorUndoRedoController";
class CursorUndo extends EditorAction {
  constructor() {
    super({
      id: "cursorUndo",
      label: localize("cursor.undo", "Cursor Undo"),
      alias: "Cursor Undo",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 2048 | 51,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor2, args) {
    var _a2;
    (_a2 = CursorUndoRedoController.get(editor2)) === null || _a2 === void 0 ? void 0 : _a2.cursorUndo();
  }
}
class CursorRedo extends EditorAction {
  constructor() {
    super({
      id: "cursorRedo",
      label: localize("cursor.redo", "Cursor Redo"),
      alias: "Cursor Redo",
      precondition: void 0
    });
  }
  run(accessor, editor2, args) {
    var _a2;
    (_a2 = CursorUndoRedoController.get(editor2)) === null || _a2 === void 0 ? void 0 : _a2.cursorRedo();
  }
}
registerEditorContribution(
  CursorUndoRedoController.ID,
  CursorUndoRedoController,
  0
  /* EditorContributionInstantiation.Eager */
);
registerEditorAction(CursorUndo);
registerEditorAction(CursorRedo);
const dnd = "";
class DragAndDropCommand {
  constructor(selection, targetPosition, copy2) {
    this.selection = selection;
    this.targetPosition = targetPosition;
    this.copy = copy2;
    this.targetSelection = null;
  }
  getEditOperations(model, builder) {
    const text2 = model.getValueInRange(this.selection);
    if (!this.copy) {
      builder.addEditOperation(this.selection, null);
    }
    builder.addEditOperation(new Range$2(this.targetPosition.lineNumber, this.targetPosition.column, this.targetPosition.lineNumber, this.targetPosition.column), text2);
    if (this.selection.containsPosition(this.targetPosition) && !(this.copy && (this.selection.getEndPosition().equals(this.targetPosition) || this.selection.getStartPosition().equals(this.targetPosition)))) {
      this.targetSelection = this.selection;
      return;
    }
    if (this.copy) {
      this.targetSelection = new Selection$1(this.targetPosition.lineNumber, this.targetPosition.column, this.selection.endLineNumber - this.selection.startLineNumber + this.targetPosition.lineNumber, this.selection.startLineNumber === this.selection.endLineNumber ? this.targetPosition.column + this.selection.endColumn - this.selection.startColumn : this.selection.endColumn);
      return;
    }
    if (this.targetPosition.lineNumber > this.selection.endLineNumber) {
      this.targetSelection = new Selection$1(this.targetPosition.lineNumber - this.selection.endLineNumber + this.selection.startLineNumber, this.targetPosition.column, this.targetPosition.lineNumber, this.selection.startLineNumber === this.selection.endLineNumber ? this.targetPosition.column + this.selection.endColumn - this.selection.startColumn : this.selection.endColumn);
      return;
    }
    if (this.targetPosition.lineNumber < this.selection.endLineNumber) {
      this.targetSelection = new Selection$1(this.targetPosition.lineNumber, this.targetPosition.column, this.targetPosition.lineNumber + this.selection.endLineNumber - this.selection.startLineNumber, this.selection.startLineNumber === this.selection.endLineNumber ? this.targetPosition.column + this.selection.endColumn - this.selection.startColumn : this.selection.endColumn);
      return;
    }
    if (this.selection.endColumn <= this.targetPosition.column) {
      this.targetSelection = new Selection$1(this.targetPosition.lineNumber - this.selection.endLineNumber + this.selection.startLineNumber, this.selection.startLineNumber === this.selection.endLineNumber ? this.targetPosition.column - this.selection.endColumn + this.selection.startColumn : this.targetPosition.column - this.selection.endColumn + this.selection.startColumn, this.targetPosition.lineNumber, this.selection.startLineNumber === this.selection.endLineNumber ? this.targetPosition.column : this.selection.endColumn);
    } else {
      this.targetSelection = new Selection$1(this.targetPosition.lineNumber - this.selection.endLineNumber + this.selection.startLineNumber, this.targetPosition.column, this.targetPosition.lineNumber, this.targetPosition.column + this.selection.endColumn - this.selection.startColumn);
    }
  }
  computeCursorState(model, helper) {
    return this.targetSelection;
  }
}
function hasTriggerModifier(e) {
  if (isMacintosh) {
    return e.altKey;
  } else {
    return e.ctrlKey;
  }
}
class DragAndDropController extends Disposable {
  constructor(editor2) {
    super();
    this._editor = editor2;
    this._dndDecorationIds = this._editor.createDecorationsCollection();
    this._register(this._editor.onMouseDown((e) => this._onEditorMouseDown(e)));
    this._register(this._editor.onMouseUp((e) => this._onEditorMouseUp(e)));
    this._register(this._editor.onMouseDrag((e) => this._onEditorMouseDrag(e)));
    this._register(this._editor.onMouseDrop((e) => this._onEditorMouseDrop(e)));
    this._register(this._editor.onMouseDropCanceled(() => this._onEditorMouseDropCanceled()));
    this._register(this._editor.onKeyDown((e) => this.onEditorKeyDown(e)));
    this._register(this._editor.onKeyUp((e) => this.onEditorKeyUp(e)));
    this._register(this._editor.onDidBlurEditorWidget(() => this.onEditorBlur()));
    this._register(this._editor.onDidBlurEditorText(() => this.onEditorBlur()));
    this._mouseDown = false;
    this._modifierPressed = false;
    this._dragSelection = null;
  }
  onEditorBlur() {
    this._removeDecoration();
    this._dragSelection = null;
    this._mouseDown = false;
    this._modifierPressed = false;
  }
  onEditorKeyDown(e) {
    if (!this._editor.getOption(
      34
      /* EditorOption.dragAndDrop */
    ) || this._editor.getOption(
      21
      /* EditorOption.columnSelection */
    )) {
      return;
    }
    if (hasTriggerModifier(e)) {
      this._modifierPressed = true;
    }
    if (this._mouseDown && hasTriggerModifier(e)) {
      this._editor.updateOptions({
        mouseStyle: "copy"
      });
    }
  }
  onEditorKeyUp(e) {
    if (!this._editor.getOption(
      34
      /* EditorOption.dragAndDrop */
    ) || this._editor.getOption(
      21
      /* EditorOption.columnSelection */
    )) {
      return;
    }
    if (hasTriggerModifier(e)) {
      this._modifierPressed = false;
    }
    if (this._mouseDown && e.keyCode === DragAndDropController.TRIGGER_KEY_VALUE) {
      this._editor.updateOptions({
        mouseStyle: "default"
      });
    }
  }
  _onEditorMouseDown(mouseEvent) {
    this._mouseDown = true;
  }
  _onEditorMouseUp(mouseEvent) {
    this._mouseDown = false;
    this._editor.updateOptions({
      mouseStyle: "text"
    });
  }
  _onEditorMouseDrag(mouseEvent) {
    const target = mouseEvent.target;
    if (this._dragSelection === null) {
      const selections2 = this._editor.getSelections() || [];
      const possibleSelections = selections2.filter((selection) => target.position && selection.containsPosition(target.position));
      if (possibleSelections.length === 1) {
        this._dragSelection = possibleSelections[0];
      } else {
        return;
      }
    }
    if (hasTriggerModifier(mouseEvent.event)) {
      this._editor.updateOptions({
        mouseStyle: "copy"
      });
    } else {
      this._editor.updateOptions({
        mouseStyle: "default"
      });
    }
    if (target.position) {
      if (this._dragSelection.containsPosition(target.position)) {
        this._removeDecoration();
      } else {
        this.showAt(target.position);
      }
    }
  }
  _onEditorMouseDropCanceled() {
    this._editor.updateOptions({
      mouseStyle: "text"
    });
    this._removeDecoration();
    this._dragSelection = null;
    this._mouseDown = false;
  }
  _onEditorMouseDrop(mouseEvent) {
    if (mouseEvent.target && (this._hitContent(mouseEvent.target) || this._hitMargin(mouseEvent.target)) && mouseEvent.target.position) {
      const newCursorPosition = new Position$2(mouseEvent.target.position.lineNumber, mouseEvent.target.position.column);
      if (this._dragSelection === null) {
        let newSelections = null;
        if (mouseEvent.event.shiftKey) {
          const primarySelection = this._editor.getSelection();
          if (primarySelection) {
            const { selectionStartLineNumber, selectionStartColumn } = primarySelection;
            newSelections = [new Selection$1(selectionStartLineNumber, selectionStartColumn, newCursorPosition.lineNumber, newCursorPosition.column)];
          }
        } else {
          newSelections = (this._editor.getSelections() || []).map((selection) => {
            if (selection.containsPosition(newCursorPosition)) {
              return new Selection$1(newCursorPosition.lineNumber, newCursorPosition.column, newCursorPosition.lineNumber, newCursorPosition.column);
            } else {
              return selection;
            }
          });
        }
        this._editor.setSelections(
          newSelections || [],
          "mouse",
          3
          /* CursorChangeReason.Explicit */
        );
      } else if (!this._dragSelection.containsPosition(newCursorPosition) || (hasTriggerModifier(mouseEvent.event) || this._modifierPressed) && (this._dragSelection.getEndPosition().equals(newCursorPosition) || this._dragSelection.getStartPosition().equals(newCursorPosition))) {
        this._editor.pushUndoStop();
        this._editor.executeCommand(DragAndDropController.ID, new DragAndDropCommand(this._dragSelection, newCursorPosition, hasTriggerModifier(mouseEvent.event) || this._modifierPressed));
        this._editor.pushUndoStop();
      }
    }
    this._editor.updateOptions({
      mouseStyle: "text"
    });
    this._removeDecoration();
    this._dragSelection = null;
    this._mouseDown = false;
  }
  showAt(position) {
    this._dndDecorationIds.set([{
      range: new Range$2(position.lineNumber, position.column, position.lineNumber, position.column),
      options: DragAndDropController._DECORATION_OPTIONS
    }]);
    this._editor.revealPosition(
      position,
      1
      /* ScrollType.Immediate */
    );
  }
  _removeDecoration() {
    this._dndDecorationIds.clear();
  }
  _hitContent(target) {
    return target.type === 6 || target.type === 7;
  }
  _hitMargin(target) {
    return target.type === 2 || target.type === 3 || target.type === 4;
  }
  dispose() {
    this._removeDecoration();
    this._dragSelection = null;
    this._mouseDown = false;
    this._modifierPressed = false;
    super.dispose();
  }
}
DragAndDropController.ID = "editor.contrib.dragAndDrop";
DragAndDropController.TRIGGER_KEY_VALUE = isMacintosh ? 6 : 5;
DragAndDropController._DECORATION_OPTIONS = ModelDecorationOptions.register({
  description: "dnd-target",
  className: "dnd-target"
});
registerEditorContribution(
  DragAndDropController.ID,
  DragAndDropController,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);
const generateUuid = function() {
  if (typeof crypto === "object" && typeof crypto.randomUUID === "function") {
    return crypto.randomUUID.bind(crypto);
  }
  let getRandomValues;
  if (typeof crypto === "object" && typeof crypto.getRandomValues === "function") {
    getRandomValues = crypto.getRandomValues.bind(crypto);
  } else {
    getRandomValues = function(bucket) {
      for (let i = 0; i < bucket.length; i++) {
        bucket[i] = Math.floor(Math.random() * 256);
      }
      return bucket;
    };
  }
  const _data = new Uint8Array(16);
  const _hex = [];
  for (let i = 0; i < 256; i++) {
    _hex.push(i.toString(16).padStart(2, "0"));
  }
  return function generateUuid2() {
    getRandomValues(_data);
    _data[6] = _data[6] & 15 | 64;
    _data[8] = _data[8] & 63 | 128;
    let i = 0;
    let result2 = "";
    result2 += _hex[_data[i++]];
    result2 += _hex[_data[i++]];
    result2 += _hex[_data[i++]];
    result2 += _hex[_data[i++]];
    result2 += "-";
    result2 += _hex[_data[i++]];
    result2 += _hex[_data[i++]];
    result2 += "-";
    result2 += _hex[_data[i++]];
    result2 += _hex[_data[i++]];
    result2 += "-";
    result2 += _hex[_data[i++]];
    result2 += _hex[_data[i++]];
    result2 += "-";
    result2 += _hex[_data[i++]];
    result2 += _hex[_data[i++]];
    result2 += _hex[_data[i++]];
    result2 += _hex[_data[i++]];
    result2 += _hex[_data[i++]];
    result2 += _hex[_data[i++]];
    return result2;
  };
}();
var __awaiter$Y = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
function createStringDataTransferItem(stringOrPromise) {
  return {
    asString: () => __awaiter$Y(this, void 0, void 0, function* () {
      return stringOrPromise;
    }),
    asFile: () => void 0,
    value: typeof stringOrPromise === "string" ? stringOrPromise : void 0
  };
}
function createFileDataTransferItem(fileName, uri, data) {
  const file = { id: generateUuid(), name: fileName, uri, data };
  return {
    asString: () => __awaiter$Y(this, void 0, void 0, function* () {
      return "";
    }),
    asFile: () => file,
    value: void 0
  };
}
class VSDataTransfer {
  constructor() {
    this._entries = /* @__PURE__ */ new Map();
  }
  get size() {
    let size2 = 0;
    for (const _ of this._entries) {
      size2++;
    }
    return size2;
  }
  has(mimeType) {
    return this._entries.has(this.toKey(mimeType));
  }
  matches(pattern) {
    const mimes = [...this._entries.keys()];
    if (Iterable.some(this, ([_, item]) => item.asFile())) {
      mimes.push("files");
    }
    return matchesMimeType_normalized(normalizeMimeType(pattern), mimes);
  }
  get(mimeType) {
    var _a2;
    return (_a2 = this._entries.get(this.toKey(mimeType))) === null || _a2 === void 0 ? void 0 : _a2[0];
  }
  /**
   * Add a new entry to this data transfer.
   *
   * This does not replace existing entries for `mimeType`.
   */
  append(mimeType, value) {
    const existing = this._entries.get(mimeType);
    if (existing) {
      existing.push(value);
    } else {
      this._entries.set(this.toKey(mimeType), [value]);
    }
  }
  /**
   * Set the entry for a given mime type.
   *
   * This replaces all existing entries for `mimeType`.
   */
  replace(mimeType, value) {
    this._entries.set(this.toKey(mimeType), [value]);
  }
  /**
   * Remove all entries for `mimeType`.
   */
  delete(mimeType) {
    this._entries.delete(this.toKey(mimeType));
  }
  /**
   * Iterate over all `[mime, item]` pairs in this data transfer.
   *
   * There may be multiple entries for each mime type.
   */
  *[Symbol.iterator]() {
    for (const [mine, items] of this._entries) {
      for (const item of items) {
        yield [mine, item];
      }
    }
  }
  toKey(mimeType) {
    return normalizeMimeType(mimeType);
  }
}
function normalizeMimeType(mimeType) {
  return mimeType.toLowerCase();
}
function matchesMimeType(pattern, mimeTypes) {
  return matchesMimeType_normalized(normalizeMimeType(pattern), mimeTypes.map(normalizeMimeType));
}
function matchesMimeType_normalized(normalizedPattern, normalizedMimeTypes) {
  if (normalizedPattern === "*/*") {
    return normalizedMimeTypes.length > 0;
  }
  if (normalizedMimeTypes.includes(normalizedPattern)) {
    return true;
  }
  const wildcard = normalizedPattern.match(/^([a-z]+)\/([a-z]+|\*)$/i);
  if (!wildcard) {
    return false;
  }
  const [_, type, subtype] = wildcard;
  if (subtype === "*") {
    return normalizedMimeTypes.some((mime) => mime.startsWith(type + "/"));
  }
  return false;
}
const UriList = Object.freeze({
  // http://amundsen.com/hypermedia/urilist/
  create: (entries) => {
    return distinct(entries.map((x) => x.toString())).join("\r\n");
  },
  split: (str2) => {
    return str2.split("\r\n");
  },
  parse: (str2) => {
    return UriList.split(str2).filter((value) => !value.startsWith("#"));
  }
});
const CodeDataTransfers = {
  EDITORS: "CodeEditors",
  FILES: "CodeFiles"
};
class DragAndDropContributionRegistry {
}
const Extensions$1 = {
  DragAndDropContribution: "workbench.contributions.dragAndDrop"
};
Registry.add(Extensions$1.DragAndDropContribution, new DragAndDropContributionRegistry());
class LocalSelectionTransfer {
  constructor() {
  }
  static getInstance() {
    return LocalSelectionTransfer.INSTANCE;
  }
  hasData(proto) {
    return proto && proto === this.proto;
  }
  getData(proto) {
    if (this.hasData(proto)) {
      return this.data;
    }
    return void 0;
  }
}
LocalSelectionTransfer.INSTANCE = new LocalSelectionTransfer();
var __awaiter$X = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
function toVSDataTransfer(dataTransfer) {
  const vsDataTransfer = new VSDataTransfer();
  for (const item of dataTransfer.items) {
    const type = item.type;
    if (item.kind === "string") {
      const asStringValue = new Promise((resolve2) => item.getAsString(resolve2));
      vsDataTransfer.append(type, createStringDataTransferItem(asStringValue));
    } else if (item.kind === "file") {
      const file = item.getAsFile();
      if (file) {
        vsDataTransfer.append(type, createFileDataTransferItemFromFile(file));
      }
    }
  }
  return vsDataTransfer;
}
function createFileDataTransferItemFromFile(file) {
  const uri = file.path ? URI.parse(file.path) : void 0;
  return createFileDataTransferItem(file.name, uri, () => __awaiter$X(this, void 0, void 0, function* () {
    return new Uint8Array(yield file.arrayBuffer());
  }));
}
const INTERNAL_DND_MIME_TYPES = Object.freeze([
  CodeDataTransfers.EDITORS,
  CodeDataTransfers.FILES,
  DataTransfers.RESOURCES,
  DataTransfers.INTERNAL_URI_LIST
]);
function toExternalVSDataTransfer(sourceDataTransfer, overwriteUriList = false) {
  const vsDataTransfer = toVSDataTransfer(sourceDataTransfer);
  const uriList = vsDataTransfer.get(DataTransfers.INTERNAL_URI_LIST);
  if (uriList) {
    vsDataTransfer.replace(Mimes.uriList, uriList);
  } else {
    if (overwriteUriList || !vsDataTransfer.has(Mimes.uriList)) {
      const editorData = [];
      for (const item of sourceDataTransfer.items) {
        const file = item.getAsFile();
        if (file) {
          const path2 = file.path;
          try {
            if (path2) {
              editorData.push(URI.file(path2).toString());
            } else {
              editorData.push(URI.parse(file.name, true).toString());
            }
          } catch (_a2) {
          }
        }
      }
      if (editorData.length) {
        vsDataTransfer.replace(Mimes.uriList, createStringDataTransferItem(UriList.create(editorData)));
      }
    }
  }
  for (const internal of INTERNAL_DND_MIME_TYPES) {
    vsDataTransfer.delete(internal);
  }
  return vsDataTransfer;
}
function createCombinedWorkspaceEdit(uri, ranges, edit) {
  var _a2, _b2;
  return {
    edits: [
      ...ranges.map((range2) => new ResourceTextEdit(uri, typeof edit.insertText === "string" ? { range: range2, text: edit.insertText, insertAsSnippet: false } : { range: range2, text: edit.insertText.snippet, insertAsSnippet: true })),
      ...(_b2 = (_a2 = edit.additionalEdit) === null || _a2 === void 0 ? void 0 : _a2.edits) !== null && _b2 !== void 0 ? _b2 : []
    ]
  };
}
const inlineProgressWidget = "";
var __decorate$1m = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1k = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$W = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
const inlineProgressDecoration = ModelDecorationOptions.register({
  description: "inline-progress-widget",
  stickiness: 1,
  showIfCollapsed: true,
  after: {
    content: noBreakWhitespace,
    inlineClassName: "inline-editor-progress-decoration",
    inlineClassNameAffectsLetterSpacing: true
  }
});
class InlineProgressWidget extends Disposable {
  constructor(typeId, editor2, range2, title2, delegate) {
    super();
    this.typeId = typeId;
    this.editor = editor2;
    this.range = range2;
    this.delegate = delegate;
    this.allowEditorOverflow = false;
    this.suppressMouseDown = true;
    this.create(title2);
    this.editor.addContentWidget(this);
    this.editor.layoutContentWidget(this);
  }
  create(title2) {
    this.domNode = $$d(".inline-progress-widget");
    this.domNode.role = "button";
    this.domNode.title = title2;
    const iconElement = $$d("span.icon");
    this.domNode.append(iconElement);
    iconElement.classList.add(...ThemeIcon.asClassNameArray(Codicon.loading), "codicon-modifier-spin");
    const updateSize = () => {
      const lineHeight = this.editor.getOption(
        65
        /* EditorOption.lineHeight */
      );
      this.domNode.style.height = `${lineHeight}px`;
      this.domNode.style.width = `${Math.ceil(0.8 * lineHeight)}px`;
    };
    updateSize();
    this._register(this.editor.onDidChangeConfiguration((c) => {
      if (c.hasChanged(
        51
        /* EditorOption.fontSize */
      ) || c.hasChanged(
        65
        /* EditorOption.lineHeight */
      )) {
        updateSize();
      }
    }));
    this._register(addDisposableListener(this.domNode, EventType$1.CLICK, (e) => {
      this.delegate.cancel();
    }));
  }
  getId() {
    return InlineProgressWidget.baseId + "." + this.typeId;
  }
  getDomNode() {
    return this.domNode;
  }
  getPosition() {
    return {
      position: { lineNumber: this.range.startLineNumber, column: this.range.startColumn },
      preference: [
        0
        /* ContentWidgetPositionPreference.EXACT */
      ]
    };
  }
  dispose() {
    super.dispose();
    this.editor.removeContentWidget(this);
  }
}
InlineProgressWidget.baseId = "editor.widget.inlineProgressWidget";
let InlineProgressManager = class InlineProgressManager2 extends Disposable {
  constructor(id3, _editor, _instantiationService) {
    super();
    this.id = id3;
    this._editor = _editor;
    this._instantiationService = _instantiationService;
    this._showDelay = 500;
    this._showPromise = this._register(new MutableDisposable());
    this._currentWidget = new MutableDisposable();
    this._operationIdPool = 0;
    this._currentDecorations = _editor.createDecorationsCollection();
  }
  showWhile(position, title2, promise) {
    return __awaiter$W(this, void 0, void 0, function* () {
      const operationId = this._operationIdPool++;
      this._currentOperation = operationId;
      this.clear();
      this._showPromise.value = disposableTimeout(() => {
        const range2 = Range$2.fromPositions(position);
        const decorationIds = this._currentDecorations.set([{
          range: range2,
          options: inlineProgressDecoration
        }]);
        if (decorationIds.length > 0) {
          this._currentWidget.value = this._instantiationService.createInstance(InlineProgressWidget, this.id, this._editor, range2, title2, promise);
        }
      }, this._showDelay);
      try {
        return yield promise;
      } finally {
        if (this._currentOperation === operationId) {
          this.clear();
          this._currentOperation = void 0;
        }
      }
    });
  }
  clear() {
    this._showPromise.clear();
    this._currentDecorations.clear();
    this._currentWidget.clear();
  }
};
InlineProgressManager = __decorate$1m([
  __param$1k(2, IInstantiationService)
], InlineProgressManager);
const button = "";
({
  buttonBackground: "#0E639C",
  buttonHoverBackground: "#006BB3",
  buttonSeparator: Color.white.toString(),
  buttonForeground: Color.white.toString(),
  buttonBorder: void 0,
  buttonSecondaryBackground: void 0,
  buttonSecondaryForeground: void 0,
  buttonSecondaryHoverBackground: void 0
});
class Button extends Disposable {
  get onDidClick() {
    return this._onDidClick.event;
  }
  constructor(container2, options) {
    super();
    this._label = "";
    this._onDidClick = this._register(new Emitter$1());
    this.options = options;
    this._element = document.createElement("a");
    this._element.classList.add("monaco-button");
    this._element.tabIndex = 0;
    this._element.setAttribute("role", "button");
    this._element.classList.toggle("secondary", !!options.secondary);
    const background = options.secondary ? options.buttonSecondaryBackground : options.buttonBackground;
    const foreground2 = options.secondary ? options.buttonSecondaryForeground : options.buttonForeground;
    this._element.style.color = foreground2 || "";
    this._element.style.backgroundColor = background || "";
    if (options.supportShortLabel) {
      this._labelShortElement = document.createElement("div");
      this._labelShortElement.classList.add("monaco-button-label-short");
      this._element.appendChild(this._labelShortElement);
      this._labelElement = document.createElement("div");
      this._labelElement.classList.add("monaco-button-label");
      this._element.appendChild(this._labelElement);
      this._element.classList.add("monaco-text-button-with-short-label");
    }
    container2.appendChild(this._element);
    this._register(Gesture.addTarget(this._element));
    [EventType$1.CLICK, EventType.Tap].forEach((eventType) => {
      this._register(addDisposableListener(this._element, eventType, (e) => {
        if (!this.enabled) {
          EventHelper.stop(e);
          return;
        }
        this._onDidClick.fire(e);
      }));
    });
    this._register(addDisposableListener(this._element, EventType$1.KEY_DOWN, (e) => {
      const event = new StandardKeyboardEvent(e);
      let eventHandled = false;
      if (this.enabled && (event.equals(
        3
        /* KeyCode.Enter */
      ) || event.equals(
        10
        /* KeyCode.Space */
      ))) {
        this._onDidClick.fire(e);
        eventHandled = true;
      } else if (event.equals(
        9
        /* KeyCode.Escape */
      )) {
        this._element.blur();
        eventHandled = true;
      }
      if (eventHandled) {
        EventHelper.stop(event, true);
      }
    }));
    this._register(addDisposableListener(this._element, EventType$1.MOUSE_OVER, (e) => {
      if (!this._element.classList.contains("disabled")) {
        this.updateBackground(true);
      }
    }));
    this._register(addDisposableListener(this._element, EventType$1.MOUSE_OUT, (e) => {
      this.updateBackground(false);
    }));
    this.focusTracker = this._register(trackFocus(this._element));
    this._register(this.focusTracker.onDidFocus(() => {
      if (this.enabled) {
        this.updateBackground(true);
      }
    }));
    this._register(this.focusTracker.onDidBlur(() => {
      if (this.enabled) {
        this.updateBackground(false);
      }
    }));
  }
  dispose() {
    super.dispose();
    this._element.remove();
  }
  getContentElements(content) {
    const elements = [];
    for (let segment of renderLabelWithIcons(content)) {
      if (typeof segment === "string") {
        segment = segment.trim();
        if (segment === "") {
          continue;
        }
        const node2 = document.createElement("span");
        node2.textContent = segment;
        elements.push(node2);
      } else {
        elements.push(segment);
      }
    }
    return elements;
  }
  updateBackground(hover2) {
    let background;
    if (this.options.secondary) {
      background = hover2 ? this.options.buttonSecondaryHoverBackground : this.options.buttonSecondaryBackground;
    } else {
      background = hover2 ? this.options.buttonHoverBackground : this.options.buttonBackground;
    }
    if (background) {
      this._element.style.backgroundColor = background;
    }
  }
  get element() {
    return this._element;
  }
  set label(value) {
    var _a2;
    if (this._label === value) {
      return;
    }
    if (isMarkdownString(this._label) && isMarkdownString(value) && markdownStringEqual(this._label, value)) {
      return;
    }
    this._element.classList.add("monaco-text-button");
    const labelElement = this.options.supportShortLabel ? this._labelElement : this._element;
    if (isMarkdownString(value)) {
      const rendered = renderMarkdown(value, { inline: true });
      rendered.dispose();
      const root3 = (_a2 = rendered.element.querySelector("p")) === null || _a2 === void 0 ? void 0 : _a2.innerHTML;
      if (root3) {
        const sanitized = sanitize$1(root3, { ADD_TAGS: ["b", "i", "u", "code", "span"], ALLOWED_ATTR: ["class"], RETURN_TRUSTED_TYPE: true });
        labelElement.innerHTML = sanitized;
      } else {
        reset(labelElement);
      }
    } else {
      if (this.options.supportIcons) {
        reset(labelElement, ...this.getContentElements(value));
      } else {
        labelElement.textContent = value;
      }
    }
    if (typeof this.options.title === "string") {
      this._element.title = this.options.title;
    } else if (this.options.title) {
      this._element.title = renderStringAsPlaintext(value);
    }
    this._label = value;
  }
  get label() {
    return this._label;
  }
  set enabled(value) {
    if (value) {
      this._element.classList.remove("disabled");
      this._element.setAttribute("aria-disabled", String(false));
      this._element.tabIndex = 0;
    } else {
      this._element.classList.add("disabled");
      this._element.setAttribute("aria-disabled", String(true));
    }
  }
  get enabled() {
    return !this._element.classList.contains("disabled");
  }
}
const postEditWidget = "";
var __decorate$1l = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1j = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$V = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
let PostEditWidget = class PostEditWidget2 extends Disposable {
  constructor(typeId, editor2, visibleContext, showCommand, range2, edits, onSelectNewEdit, _contextMenuService, contextKeyService, _keybindingService) {
    super();
    this.typeId = typeId;
    this.editor = editor2;
    this.showCommand = showCommand;
    this.range = range2;
    this.edits = edits;
    this.onSelectNewEdit = onSelectNewEdit;
    this._contextMenuService = _contextMenuService;
    this._keybindingService = _keybindingService;
    this.allowEditorOverflow = true;
    this.suppressMouseDown = true;
    this.create();
    this.visibleContext = visibleContext.bindTo(contextKeyService);
    this.visibleContext.set(true);
    this._register(toDisposable(() => this.visibleContext.reset()));
    this.editor.addContentWidget(this);
    this.editor.layoutContentWidget(this);
    this._register(toDisposable(() => this.editor.removeContentWidget(this)));
    this._register(this.editor.onDidChangeCursorPosition((e) => {
      if (!range2.containsPosition(e.position)) {
        this.dispose();
      }
    }));
    this._register(Event$1.runAndSubscribe(_keybindingService.onDidUpdateKeybindings, () => {
      this._updateButtonTitle();
    }));
  }
  _updateButtonTitle() {
    var _a2;
    const binding2 = (_a2 = this._keybindingService.lookupKeybinding(this.showCommand.id)) === null || _a2 === void 0 ? void 0 : _a2.getLabel();
    this.button.element.title = this.showCommand.label + (binding2 ? ` (${binding2})` : "");
  }
  create() {
    this.domNode = $$d(".post-edit-widget");
    this.button = this._register(new Button(this.domNode, {
      supportIcons: true
    }));
    this.button.label = "$(insert)";
    this._register(addDisposableListener(this.domNode, EventType$1.CLICK, () => this.showSelector()));
  }
  getId() {
    return PostEditWidget2.baseId + "." + this.typeId;
  }
  getDomNode() {
    return this.domNode;
  }
  getPosition() {
    return {
      position: this.range.getEndPosition(),
      preference: [
        2
        /* ContentWidgetPositionPreference.BELOW */
      ]
    };
  }
  showSelector() {
    this._contextMenuService.showContextMenu({
      getAnchor: () => {
        const pos = getDomNodePagePosition(this.button.element);
        return { x: pos.left + pos.width, y: pos.top + pos.height };
      },
      getActions: () => {
        return this.edits.allEdits.map((edit, i) => toAction({
          id: "",
          label: edit.label,
          checked: i === this.edits.activeEditIndex,
          run: () => {
            if (i !== this.edits.activeEditIndex) {
              return this.onSelectNewEdit(i);
            }
          }
        }));
      }
    });
  }
};
PostEditWidget.baseId = "editor.widget.postEditWidget";
PostEditWidget = __decorate$1l([
  __param$1j(7, IContextMenuService),
  __param$1j(8, IContextKeyService),
  __param$1j(9, IKeybindingService)
], PostEditWidget);
let PostEditWidgetManager = class PostEditWidgetManager2 extends Disposable {
  constructor(_id2, _editor, _visibleContext, _showCommand, _instantiationService, _bulkEditService) {
    super();
    this._id = _id2;
    this._editor = _editor;
    this._visibleContext = _visibleContext;
    this._showCommand = _showCommand;
    this._instantiationService = _instantiationService;
    this._bulkEditService = _bulkEditService;
    this._currentWidget = this._register(new MutableDisposable());
    this._register(Event$1.any(_editor.onDidChangeModel, _editor.onDidChangeModelContent)(() => this.clear()));
  }
  applyEditAndShowIfNeeded(ranges, edits, canShowWidget, token) {
    var _a2, _b2;
    return __awaiter$V(this, void 0, void 0, function* () {
      const model = this._editor.getModel();
      if (!model || !ranges.length) {
        return;
      }
      const edit = edits.allEdits[edits.activeEditIndex];
      if (!edit) {
        return;
      }
      let insertTextEdit = [];
      if (typeof edit.insertText === "string" ? edit.insertText === "" : edit.insertText.snippet === "") {
        insertTextEdit = [];
      } else {
        insertTextEdit = ranges.map((range2) => new ResourceTextEdit(model.uri, typeof edit.insertText === "string" ? { range: range2, text: edit.insertText, insertAsSnippet: false } : { range: range2, text: edit.insertText.snippet, insertAsSnippet: true }));
      }
      const allEdits = [
        ...insertTextEdit,
        ...(_b2 = (_a2 = edit.additionalEdit) === null || _a2 === void 0 ? void 0 : _a2.edits) !== null && _b2 !== void 0 ? _b2 : []
      ];
      const combinedWorkspaceEdit = {
        edits: allEdits
      };
      const primaryRange = ranges[0];
      const editTrackingDecoration = model.deltaDecorations([], [{
        range: primaryRange,
        options: {
          description: "paste-line-suffix",
          stickiness: 0
          /* TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */
        }
      }]);
      let editResult;
      let editRange;
      try {
        editResult = yield this._bulkEditService.apply(combinedWorkspaceEdit, { editor: this._editor, token });
        editRange = model.getDecorationRange(editTrackingDecoration[0]);
      } finally {
        model.deltaDecorations(editTrackingDecoration, []);
      }
      if (canShowWidget && editResult.isApplied && edits.allEdits.length > 1) {
        this.show(editRange !== null && editRange !== void 0 ? editRange : primaryRange, edits, (newEditIndex) => __awaiter$V(this, void 0, void 0, function* () {
          const model2 = this._editor.getModel();
          if (!model2) {
            return;
          }
          yield model2.undo();
          this.applyEditAndShowIfNeeded(ranges, { activeEditIndex: newEditIndex, allEdits: edits.allEdits }, canShowWidget, token);
        }));
      }
    });
  }
  show(range2, edits, onDidSelectEdit) {
    this.clear();
    if (this._editor.hasModel()) {
      this._currentWidget.value = this._instantiationService.createInstance(PostEditWidget, this._id, this._editor, this._visibleContext, this._showCommand, range2, edits, onDidSelectEdit);
    }
  }
  clear() {
    this._currentWidget.clear();
  }
  tryShowSelector() {
    var _a2;
    (_a2 = this._currentWidget.value) === null || _a2 === void 0 ? void 0 : _a2.showSelector();
  }
};
PostEditWidgetManager = __decorate$1l([
  __param$1j(4, IInstantiationService),
  __param$1j(5, IBulkEditService)
], PostEditWidgetManager);
var __decorate$1k = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1i = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$U = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
const changePasteTypeCommandId = "editor.changePasteType";
const pasteWidgetVisibleCtx = new RawContextKey("pasteWidgetVisible", false, localize("pasteWidgetVisible", "Whether the paste widget is showing"));
const vscodeClipboardMime = "application/vnd.code.copyMetadata";
let CopyPasteController = class CopyPasteController2 extends Disposable {
  static get(editor2) {
    return editor2.getContribution(CopyPasteController2.ID);
  }
  constructor(editor2, instantiationService, _bulkEditService, _clipboardService, _languageFeaturesService, _quickInputService, _progressService) {
    super();
    this._bulkEditService = _bulkEditService;
    this._clipboardService = _clipboardService;
    this._languageFeaturesService = _languageFeaturesService;
    this._quickInputService = _quickInputService;
    this._progressService = _progressService;
    this._editor = editor2;
    const container2 = editor2.getContainerDomNode();
    this._register(addDisposableListener(container2, "copy", (e) => this.handleCopy(e)));
    this._register(addDisposableListener(container2, "cut", (e) => this.handleCopy(e)));
    this._register(addDisposableListener(container2, "paste", (e) => this.handlePaste(e), true));
    this._pasteProgressManager = this._register(new InlineProgressManager("pasteIntoEditor", editor2, instantiationService));
    this._postPasteWidgetManager = this._register(instantiationService.createInstance(PostEditWidgetManager, "pasteIntoEditor", editor2, pasteWidgetVisibleCtx, { id: changePasteTypeCommandId, label: localize("postPasteWidgetTitle", "Show paste options...") }));
  }
  changePasteType() {
    this._postPasteWidgetManager.tryShowSelector();
  }
  pasteAs(preferredId) {
    this._editor.focus();
    try {
      this._pasteAsActionContext = { preferredId };
      document.execCommand("paste");
    } finally {
      this._pasteAsActionContext = void 0;
    }
  }
  isPasteAsEnabled() {
    return this._editor.getOption(
      83
      /* EditorOption.pasteAs */
    ).enabled && !this._editor.getOption(
      89
      /* EditorOption.readOnly */
    );
  }
  handleCopy(e) {
    var _a2, _b2;
    if (!this._editor.hasTextFocus()) {
      return;
    }
    if (isWeb) {
      this._clipboardService.writeResources([]);
    }
    if (!e.clipboardData || !this.isPasteAsEnabled()) {
      return;
    }
    const model = this._editor.getModel();
    const selections2 = this._editor.getSelections();
    if (!model || !(selections2 === null || selections2 === void 0 ? void 0 : selections2.length)) {
      return;
    }
    const enableEmptySelectionClipboard = this._editor.getOption(
      36
      /* EditorOption.emptySelectionClipboard */
    );
    let ranges = selections2;
    const wasFromEmptySelection = selections2.length === 1 && selections2[0].isEmpty();
    if (wasFromEmptySelection) {
      if (!enableEmptySelectionClipboard) {
        return;
      }
      ranges = [new Range$2(ranges[0].startLineNumber, 1, ranges[0].startLineNumber, 1 + model.getLineLength(ranges[0].startLineNumber))];
    }
    const toCopy = (_a2 = this._editor._getViewModel()) === null || _a2 === void 0 ? void 0 : _a2.getPlainTextToCopy(selections2, enableEmptySelectionClipboard, isWindows);
    const multicursorText = Array.isArray(toCopy) ? toCopy : null;
    const defaultPastePayload = {
      multicursorText,
      pasteOnNewLine: wasFromEmptySelection,
      mode: null
    };
    const providers = this._languageFeaturesService.documentPasteEditProvider.ordered(model).filter((x) => !!x.prepareDocumentPaste);
    if (!providers.length) {
      this.setCopyMetadata(e.clipboardData, { defaultPastePayload });
      return;
    }
    const dataTransfer = toVSDataTransfer(e.clipboardData);
    const providerCopyMimeTypes = providers.flatMap((x) => {
      var _a3;
      return (_a3 = x.copyMimeTypes) !== null && _a3 !== void 0 ? _a3 : [];
    });
    const handle = generateUuid();
    this.setCopyMetadata(e.clipboardData, {
      id: handle,
      providerCopyMimeTypes,
      defaultPastePayload
    });
    const promise = createCancelablePromise((token) => __awaiter$U(this, void 0, void 0, function* () {
      const results = coalesce(yield Promise.all(providers.map((provider) => __awaiter$U(this, void 0, void 0, function* () {
        try {
          return yield provider.prepareDocumentPaste(model, ranges, dataTransfer, token);
        } catch (err) {
          console.error(err);
          return void 0;
        }
      }))));
      results.reverse();
      for (const result2 of results) {
        for (const [mime, value] of result2) {
          dataTransfer.replace(mime, value);
        }
      }
      return dataTransfer;
    }));
    (_b2 = this._currentCopyOperation) === null || _b2 === void 0 ? void 0 : _b2.dataTransferPromise.cancel();
    this._currentCopyOperation = { handle, dataTransferPromise: promise };
  }
  handlePaste(e) {
    var _a2, _b2;
    return __awaiter$U(this, void 0, void 0, function* () {
      if (!e.clipboardData || !this._editor.hasTextFocus()) {
        return;
      }
      (_a2 = this._currentPasteOperation) === null || _a2 === void 0 ? void 0 : _a2.cancel();
      this._currentPasteOperation = void 0;
      const model = this._editor.getModel();
      const selections2 = this._editor.getSelections();
      if (!(selections2 === null || selections2 === void 0 ? void 0 : selections2.length) || !model) {
        return;
      }
      if (!this.isPasteAsEnabled()) {
        return;
      }
      const metadata = this.fetchCopyMetadata(e);
      const dataTransfer = toExternalVSDataTransfer(e.clipboardData);
      dataTransfer.delete(vscodeClipboardMime);
      const allPotentialMimeTypes = [
        ...e.clipboardData.types,
        ...(_b2 = metadata === null || metadata === void 0 ? void 0 : metadata.providerCopyMimeTypes) !== null && _b2 !== void 0 ? _b2 : [],
        // TODO: always adds `uri-list` because this get set if there are resources in the system clipboard.
        // However we can only check the system clipboard async. For this early check, just add it in.
        // We filter providers again once we have the final dataTransfer we will use.
        Mimes.uriList
      ];
      const allProviders = this._languageFeaturesService.documentPasteEditProvider.ordered(model).filter((provider) => {
        var _a3;
        return (_a3 = provider.pasteMimeTypes) === null || _a3 === void 0 ? void 0 : _a3.some((type) => matchesMimeType(type, allPotentialMimeTypes));
      });
      if (!allProviders.length) {
        return;
      }
      e.preventDefault();
      e.stopImmediatePropagation();
      if (this._pasteAsActionContext) {
        this.showPasteAsPick(this._pasteAsActionContext.preferredId, allProviders, selections2, dataTransfer, metadata);
      } else {
        this.doPasteInline(allProviders, selections2, dataTransfer, metadata);
      }
    });
  }
  doPasteInline(allProviders, selections2, dataTransfer, metadata) {
    const p2 = createCancelablePromise((token) => __awaiter$U(this, void 0, void 0, function* () {
      const editor2 = this._editor;
      if (!editor2.hasModel()) {
        return;
      }
      const model = editor2.getModel();
      const tokenSource = new EditorStateCancellationTokenSource(editor2, 1 | 2, void 0, token);
      try {
        yield this.mergeInDataFromCopy(dataTransfer, metadata, tokenSource.token);
        if (tokenSource.token.isCancellationRequested) {
          return;
        }
        const supportedProviders = allProviders.filter((provider) => isSupportedPasteProvider(provider, dataTransfer));
        if (!supportedProviders.length || supportedProviders.length === 1 && supportedProviders[0].id === "text") {
          yield this.applyDefaultPasteHandler(dataTransfer, metadata, tokenSource.token);
          return;
        }
        const providerEdits = yield this.getPasteEdits(supportedProviders, dataTransfer, model, selections2, tokenSource.token);
        if (tokenSource.token.isCancellationRequested) {
          return;
        }
        if (providerEdits.length === 1 && providerEdits[0].id === "text") {
          yield this.applyDefaultPasteHandler(dataTransfer, metadata, tokenSource.token);
          return;
        }
        if (providerEdits.length) {
          const canShowWidget = editor2.getOption(
            83
            /* EditorOption.pasteAs */
          ).showPasteSelector === "afterPaste";
          return this._postPasteWidgetManager.applyEditAndShowIfNeeded(selections2, { activeEditIndex: 0, allEdits: providerEdits }, canShowWidget, tokenSource.token);
        }
        yield this.applyDefaultPasteHandler(dataTransfer, metadata, tokenSource.token);
      } finally {
        tokenSource.dispose();
        if (this._currentPasteOperation === p2) {
          this._currentPasteOperation = void 0;
        }
      }
    }));
    this._pasteProgressManager.showWhile(selections2[0].getEndPosition(), localize("pasteIntoEditorProgress", "Running paste handlers. Click to cancel"), p2);
    this._currentPasteOperation = p2;
  }
  showPasteAsPick(preferredId, allProviders, selections2, dataTransfer, metadata) {
    const p2 = createCancelablePromise((token) => __awaiter$U(this, void 0, void 0, function* () {
      const editor2 = this._editor;
      if (!editor2.hasModel()) {
        return;
      }
      const model = editor2.getModel();
      const tokenSource = new EditorStateCancellationTokenSource(editor2, 1 | 2, void 0, token);
      try {
        yield this.mergeInDataFromCopy(dataTransfer, metadata, tokenSource.token);
        if (tokenSource.token.isCancellationRequested) {
          return;
        }
        const supportedProviders = allProviders.filter((provider) => isSupportedPasteProvider(provider, dataTransfer));
        const providerEdits = yield this.getPasteEdits(supportedProviders, dataTransfer, model, selections2, tokenSource.token);
        if (tokenSource.token.isCancellationRequested) {
          return;
        }
        if (!providerEdits.length) {
          return;
        }
        let pickedEdit;
        if (typeof preferredId === "string") {
          pickedEdit = providerEdits.find((edit) => edit.id === preferredId);
        } else {
          const selected = yield this._quickInputService.pick(providerEdits.map((edit) => ({
            label: edit.label,
            description: edit.id,
            detail: edit.detail,
            edit
          })), {
            placeHolder: localize("pasteAsPickerPlaceholder", "Select Paste Action")
          });
          pickedEdit = selected === null || selected === void 0 ? void 0 : selected.edit;
        }
        if (!pickedEdit) {
          return;
        }
        const combinedWorkspaceEdit = createCombinedWorkspaceEdit(model.uri, selections2, pickedEdit);
        yield this._bulkEditService.apply(combinedWorkspaceEdit, { editor: this._editor });
      } finally {
        tokenSource.dispose();
        if (this._currentPasteOperation === p2) {
          this._currentPasteOperation = void 0;
        }
      }
    }));
    this._progressService.withProgress({
      location: 10,
      title: localize("pasteAsProgress", "Running paste handlers")
    }, () => p2);
  }
  setCopyMetadata(dataTransfer, metadata) {
    dataTransfer.setData(vscodeClipboardMime, JSON.stringify(metadata));
  }
  fetchCopyMetadata(e) {
    if (!e.clipboardData) {
      return;
    }
    const rawMetadata = e.clipboardData.getData(vscodeClipboardMime);
    if (rawMetadata) {
      try {
        return JSON.parse(rawMetadata);
      } catch (_a2) {
        return void 0;
      }
    }
    const [_, metadata] = ClipboardEventUtils.getTextData(e.clipboardData);
    if (metadata) {
      return {
        defaultPastePayload: {
          mode: metadata.mode,
          multicursorText: withUndefinedAsNull(metadata.multicursorText),
          pasteOnNewLine: !!metadata.isFromEmptySelection
        }
      };
    }
    return void 0;
  }
  mergeInDataFromCopy(dataTransfer, metadata, token) {
    var _a2;
    return __awaiter$U(this, void 0, void 0, function* () {
      if ((metadata === null || metadata === void 0 ? void 0 : metadata.id) && ((_a2 = this._currentCopyOperation) === null || _a2 === void 0 ? void 0 : _a2.handle) === metadata.id) {
        const toMergeDataTransfer = yield this._currentCopyOperation.dataTransferPromise;
        if (token.isCancellationRequested) {
          return;
        }
        for (const [key, value] of toMergeDataTransfer) {
          dataTransfer.replace(key, value);
        }
      }
      if (!dataTransfer.has(Mimes.uriList)) {
        const resources = yield this._clipboardService.readResources();
        if (token.isCancellationRequested) {
          return;
        }
        if (resources.length) {
          dataTransfer.append(Mimes.uriList, createStringDataTransferItem(UriList.create(resources)));
        }
      }
    });
  }
  getPasteEdits(providers, dataTransfer, model, selections2, token) {
    return __awaiter$U(this, void 0, void 0, function* () {
      const result2 = yield raceCancellation(Promise.all(providers.map((provider) => {
        var _a2;
        try {
          return (_a2 = provider.provideDocumentPasteEdits) === null || _a2 === void 0 ? void 0 : _a2.call(provider, model, selections2, dataTransfer, token);
        } catch (err) {
          console.error(err);
          return void 0;
        }
      })).then(coalesce), token);
      result2 === null || result2 === void 0 ? void 0 : result2.sort((a, b) => b.priority - a.priority);
      return result2 !== null && result2 !== void 0 ? result2 : [];
    });
  }
  applyDefaultPasteHandler(dataTransfer, metadata, token) {
    var _a2, _b2, _c2;
    return __awaiter$U(this, void 0, void 0, function* () {
      const textDataTransfer = (_a2 = dataTransfer.get(Mimes.text)) !== null && _a2 !== void 0 ? _a2 : dataTransfer.get("text");
      if (!textDataTransfer) {
        return;
      }
      const text2 = yield textDataTransfer.asString();
      if (token.isCancellationRequested) {
        return;
      }
      const payload = {
        text: text2,
        pasteOnNewLine: (_b2 = metadata === null || metadata === void 0 ? void 0 : metadata.defaultPastePayload.pasteOnNewLine) !== null && _b2 !== void 0 ? _b2 : false,
        multicursorText: (_c2 = metadata === null || metadata === void 0 ? void 0 : metadata.defaultPastePayload.multicursorText) !== null && _c2 !== void 0 ? _c2 : null,
        mode: null
      };
      this._editor.trigger("keyboard", "paste", payload);
    });
  }
};
CopyPasteController.ID = "editor.contrib.copyPasteActionController";
CopyPasteController = __decorate$1k([
  __param$1i(1, IInstantiationService),
  __param$1i(2, IBulkEditService),
  __param$1i(3, IClipboardService),
  __param$1i(4, ILanguageFeaturesService),
  __param$1i(5, IQuickInputService),
  __param$1i(6, IProgressService)
], CopyPasteController);
function isSupportedPasteProvider(provider, dataTransfer) {
  var _a2;
  return Boolean((_a2 = provider.pasteMimeTypes) === null || _a2 === void 0 ? void 0 : _a2.some((type) => dataTransfer.matches(type)));
}
var __decorate$1j = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1h = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$T = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
const builtInLabel = localize("builtIn", "Built-in");
class SimplePasteAndDropProvider {
  provideDocumentPasteEdits(_model, _ranges, dataTransfer, token) {
    return __awaiter$T(this, void 0, void 0, function* () {
      const edit = yield this.getEdit(dataTransfer, token);
      return edit ? { id: this.id, insertText: edit.insertText, label: edit.label, detail: edit.detail, priority: edit.priority } : void 0;
    });
  }
  provideDocumentOnDropEdits(_model, _position, dataTransfer, token) {
    return __awaiter$T(this, void 0, void 0, function* () {
      const edit = yield this.getEdit(dataTransfer, token);
      return edit ? { id: this.id, insertText: edit.insertText, label: edit.label, priority: edit.priority } : void 0;
    });
  }
}
class DefaultTextProvider extends SimplePasteAndDropProvider {
  constructor() {
    super(...arguments);
    this.id = "text";
    this.dropMimeTypes = [Mimes.text];
    this.pasteMimeTypes = [Mimes.text];
  }
  getEdit(dataTransfer, _token) {
    return __awaiter$T(this, void 0, void 0, function* () {
      const textEntry = dataTransfer.get(Mimes.text);
      if (!textEntry) {
        return;
      }
      if (dataTransfer.has(Mimes.uriList)) {
        return;
      }
      const insertText = yield textEntry.asString();
      return {
        id: this.id,
        priority: 0,
        label: localize("text.label", "Insert Plain Text"),
        detail: builtInLabel,
        insertText
      };
    });
  }
}
class PathProvider extends SimplePasteAndDropProvider {
  constructor() {
    super(...arguments);
    this.id = "uri";
    this.dropMimeTypes = [Mimes.uriList];
    this.pasteMimeTypes = [Mimes.uriList];
  }
  getEdit(dataTransfer, token) {
    return __awaiter$T(this, void 0, void 0, function* () {
      const entries = yield extractUriList(dataTransfer);
      if (!entries.length || token.isCancellationRequested) {
        return;
      }
      let uriCount = 0;
      const insertText = entries.map(({ uri, originalText }) => {
        if (uri.scheme === Schemas.file) {
          return uri.fsPath;
        } else {
          uriCount++;
          return originalText;
        }
      }).join(" ");
      let label;
      if (uriCount > 0) {
        label = entries.length > 1 ? localize("defaultDropProvider.uriList.uris", "Insert Uris") : localize("defaultDropProvider.uriList.uri", "Insert Uri");
      } else {
        label = entries.length > 1 ? localize("defaultDropProvider.uriList.paths", "Insert Paths") : localize("defaultDropProvider.uriList.path", "Insert Path");
      }
      return {
        id: this.id,
        priority: 0,
        insertText,
        label,
        detail: builtInLabel
      };
    });
  }
}
let RelativePathProvider = class RelativePathProvider2 extends SimplePasteAndDropProvider {
  constructor(_workspaceContextService) {
    super();
    this._workspaceContextService = _workspaceContextService;
    this.id = "relativePath";
    this.dropMimeTypes = [Mimes.uriList];
    this.pasteMimeTypes = [Mimes.uriList];
  }
  getEdit(dataTransfer, token) {
    return __awaiter$T(this, void 0, void 0, function* () {
      const entries = yield extractUriList(dataTransfer);
      if (!entries.length || token.isCancellationRequested) {
        return;
      }
      const relativeUris = coalesce(entries.map(({ uri }) => {
        const root3 = this._workspaceContextService.getWorkspaceFolder(uri);
        return root3 ? relativePath(root3.uri, uri) : void 0;
      }));
      if (!relativeUris.length) {
        return;
      }
      return {
        id: this.id,
        priority: 0,
        insertText: relativeUris.join(" "),
        label: entries.length > 1 ? localize("defaultDropProvider.uriList.relativePaths", "Insert Relative Paths") : localize("defaultDropProvider.uriList.relativePath", "Insert Relative Path"),
        detail: builtInLabel
      };
    });
  }
};
RelativePathProvider = __decorate$1j([
  __param$1h(0, IWorkspaceContextService)
], RelativePathProvider);
function extractUriList(dataTransfer) {
  return __awaiter$T(this, void 0, void 0, function* () {
    const urlListEntry = dataTransfer.get(Mimes.uriList);
    if (!urlListEntry) {
      return [];
    }
    const strUriList = yield urlListEntry.asString();
    const entries = [];
    for (const entry of UriList.parse(strUriList)) {
      try {
        entries.push({ uri: URI.parse(entry), originalText: entry });
      } catch (_a2) {
      }
    }
    return entries;
  });
}
let DefaultDropProvidersFeature = class DefaultDropProvidersFeature2 extends Disposable {
  constructor(languageFeaturesService, workspaceContextService) {
    super();
    this._register(languageFeaturesService.documentOnDropEditProvider.register("*", new DefaultTextProvider()));
    this._register(languageFeaturesService.documentOnDropEditProvider.register("*", new PathProvider()));
    this._register(languageFeaturesService.documentOnDropEditProvider.register("*", new RelativePathProvider(workspaceContextService)));
  }
};
DefaultDropProvidersFeature = __decorate$1j([
  __param$1h(0, ILanguageFeaturesService),
  __param$1h(1, IWorkspaceContextService)
], DefaultDropProvidersFeature);
let DefaultPasteProvidersFeature = class DefaultPasteProvidersFeature2 extends Disposable {
  constructor(languageFeaturesService, workspaceContextService) {
    super();
    this._register(languageFeaturesService.documentPasteEditProvider.register("*", new DefaultTextProvider()));
    this._register(languageFeaturesService.documentPasteEditProvider.register("*", new PathProvider()));
    this._register(languageFeaturesService.documentPasteEditProvider.register("*", new RelativePathProvider(workspaceContextService)));
  }
};
DefaultPasteProvidersFeature = __decorate$1j([
  __param$1h(0, ILanguageFeaturesService),
  __param$1h(1, IWorkspaceContextService)
], DefaultPasteProvidersFeature);
registerEditorContribution(
  CopyPasteController.ID,
  CopyPasteController,
  0
  /* EditorContributionInstantiation.Eager */
);
registerEditorFeature(DefaultPasteProvidersFeature);
registerEditorCommand(new class extends EditorCommand {
  constructor() {
    super({
      id: changePasteTypeCommandId,
      precondition: pasteWidgetVisibleCtx,
      kbOpts: {
        weight: 100,
        primary: 2048 | 89
      }
    });
  }
  runEditorCommand(_accessor, editor2, _args) {
    var _a2;
    return (_a2 = CopyPasteController.get(editor2)) === null || _a2 === void 0 ? void 0 : _a2.changePasteType();
  }
}());
registerEditorAction(class extends EditorAction {
  constructor() {
    super({
      id: "editor.action.pasteAs",
      label: localize("pasteAs", "Paste As..."),
      alias: "Paste As...",
      precondition: void 0,
      description: {
        description: "Paste as",
        args: [{
          name: "args",
          schema: {
            type: "object",
            properties: {
              "id": {
                type: "string",
                description: localize("pasteAs.id", "The id of the paste edit to try applying. If not provided, the editor will show a picker.")
              }
            }
          }
        }]
      }
    });
  }
  run(_accessor, editor2, args) {
    var _a2;
    const id3 = typeof (args === null || args === void 0 ? void 0 : args.id) === "string" ? args.id : void 0;
    return (_a2 = CopyPasteController.get(editor2)) === null || _a2 === void 0 ? void 0 : _a2.pasteAs(id3);
  }
});
class TreeViewsDnDService {
  constructor() {
    this._dragOperations = /* @__PURE__ */ new Map();
  }
  removeDragOperationTransfer(uuid) {
    if (uuid && this._dragOperations.has(uuid)) {
      const operation = this._dragOperations.get(uuid);
      this._dragOperations.delete(uuid);
      return operation;
    }
    return void 0;
  }
}
class DraggedTreeItemsIdentifier {
  constructor(identifier) {
    this.identifier = identifier;
  }
}
const ITreeViewsDnDService = createDecorator("treeViewsDndService");
registerSingleton(
  ITreeViewsDnDService,
  TreeViewsDnDService,
  1
  /* InstantiationType.Delayed */
);
var __decorate$1i = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1g = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$S = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
const changeDropTypeCommandId = "editor.changeDropType";
const dropWidgetVisibleCtx = new RawContextKey("dropWidgetVisible", false, localize("dropWidgetVisible", "Whether the drop widget is showing"));
let DropIntoEditorController = class DropIntoEditorController2 extends Disposable {
  static get(editor2) {
    return editor2.getContribution(DropIntoEditorController2.ID);
  }
  constructor(editor2, instantiationService, _languageFeaturesService, _treeViewsDragAndDropService) {
    super();
    this._languageFeaturesService = _languageFeaturesService;
    this._treeViewsDragAndDropService = _treeViewsDragAndDropService;
    this.treeItemsTransfer = LocalSelectionTransfer.getInstance();
    this._dropProgressManager = this._register(instantiationService.createInstance(InlineProgressManager, "dropIntoEditor", editor2));
    this._postDropWidgetManager = this._register(instantiationService.createInstance(PostEditWidgetManager, "dropIntoEditor", editor2, dropWidgetVisibleCtx, { id: changeDropTypeCommandId, label: localize("postDropWidgetTitle", "Show drop options...") }));
    this._register(editor2.onDropIntoEditor((e) => this.onDropIntoEditor(editor2, e.position, e.event)));
  }
  changeDropType() {
    this._postDropWidgetManager.tryShowSelector();
  }
  onDropIntoEditor(editor2, position, dragEvent) {
    var _a2;
    return __awaiter$S(this, void 0, void 0, function* () {
      if (!dragEvent.dataTransfer || !editor2.hasModel()) {
        return;
      }
      (_a2 = this._currentOperation) === null || _a2 === void 0 ? void 0 : _a2.cancel();
      editor2.focus();
      editor2.setPosition(position);
      const p2 = createCancelablePromise((token) => __awaiter$S(this, void 0, void 0, function* () {
        const tokenSource = new EditorStateCancellationTokenSource(editor2, 1, void 0, token);
        try {
          const ourDataTransfer = yield this.extractDataTransferData(dragEvent);
          if (ourDataTransfer.size === 0 || tokenSource.token.isCancellationRequested) {
            return;
          }
          const model = editor2.getModel();
          if (!model) {
            return;
          }
          const providers = this._languageFeaturesService.documentOnDropEditProvider.ordered(model).filter((provider) => {
            if (!provider.dropMimeTypes) {
              return true;
            }
            return provider.dropMimeTypes.some((mime) => ourDataTransfer.matches(mime));
          });
          const edits = yield this.getDropEdits(providers, model, position, ourDataTransfer, tokenSource);
          if (tokenSource.token.isCancellationRequested) {
            return;
          }
          if (edits.length) {
            const canShowWidget = editor2.getOption(
              35
              /* EditorOption.dropIntoEditor */
            ).showDropSelector === "afterDrop";
            yield this._postDropWidgetManager.applyEditAndShowIfNeeded([Range$2.fromPositions(position)], { activeEditIndex: 0, allEdits: edits }, canShowWidget, token);
          }
        } finally {
          tokenSource.dispose();
          if (this._currentOperation === p2) {
            this._currentOperation = void 0;
          }
        }
      }));
      this._dropProgressManager.showWhile(position, localize("dropIntoEditorProgress", "Running drop handlers. Click to cancel"), p2);
      this._currentOperation = p2;
    });
  }
  getDropEdits(providers, model, position, dataTransfer, tokenSource) {
    return __awaiter$S(this, void 0, void 0, function* () {
      const results = yield raceCancellation(Promise.all(providers.map((provider) => {
        return provider.provideDocumentOnDropEdits(model, position, dataTransfer, tokenSource.token);
      })), tokenSource.token);
      const edits = coalesce(results !== null && results !== void 0 ? results : []);
      edits.sort((a, b) => b.priority - a.priority);
      return edits;
    });
  }
  extractDataTransferData(dragEvent) {
    return __awaiter$S(this, void 0, void 0, function* () {
      if (!dragEvent.dataTransfer) {
        return new VSDataTransfer();
      }
      const dataTransfer = toExternalVSDataTransfer(dragEvent.dataTransfer);
      if (this.treeItemsTransfer.hasData(DraggedTreeItemsIdentifier.prototype)) {
        const data = this.treeItemsTransfer.getData(DraggedTreeItemsIdentifier.prototype);
        if (Array.isArray(data)) {
          for (const id3 of data) {
            const treeDataTransfer = yield this._treeViewsDragAndDropService.removeDragOperationTransfer(id3.identifier);
            if (treeDataTransfer) {
              for (const [type, value] of treeDataTransfer) {
                dataTransfer.replace(type, value);
              }
            }
          }
        }
      }
      return dataTransfer;
    });
  }
};
DropIntoEditorController.ID = "editor.contrib.dropIntoEditorController";
DropIntoEditorController = __decorate$1i([
  __param$1g(1, IInstantiationService),
  __param$1g(2, ILanguageFeaturesService),
  __param$1g(3, ITreeViewsDnDService)
], DropIntoEditorController);
registerEditorContribution(
  DropIntoEditorController.ID,
  DropIntoEditorController,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);
registerEditorCommand(new class extends EditorCommand {
  constructor() {
    super({
      id: changeDropTypeCommandId,
      precondition: dropWidgetVisibleCtx,
      kbOpts: {
        weight: 100,
        primary: 2048 | 89
      }
    });
  }
  runEditorCommand(_accessor, editor2, _args) {
    var _a2;
    (_a2 = DropIntoEditorController.get(editor2)) === null || _a2 === void 0 ? void 0 : _a2.changeDropType();
  }
}());
registerEditorFeature(DefaultDropProvidersFeature);
class FindDecorations {
  constructor(editor2) {
    this._editor = editor2;
    this._decorations = [];
    this._overviewRulerApproximateDecorations = [];
    this._findScopeDecorationIds = [];
    this._rangeHighlightDecorationId = null;
    this._highlightedDecorationId = null;
    this._startPosition = this._editor.getPosition();
  }
  dispose() {
    this._editor.removeDecorations(this._allDecorations());
    this._decorations = [];
    this._overviewRulerApproximateDecorations = [];
    this._findScopeDecorationIds = [];
    this._rangeHighlightDecorationId = null;
    this._highlightedDecorationId = null;
  }
  reset() {
    this._decorations = [];
    this._overviewRulerApproximateDecorations = [];
    this._findScopeDecorationIds = [];
    this._rangeHighlightDecorationId = null;
    this._highlightedDecorationId = null;
  }
  getCount() {
    return this._decorations.length;
  }
  /** @deprecated use getFindScopes to support multiple selections */
  getFindScope() {
    if (this._findScopeDecorationIds[0]) {
      return this._editor.getModel().getDecorationRange(this._findScopeDecorationIds[0]);
    }
    return null;
  }
  getFindScopes() {
    if (this._findScopeDecorationIds.length) {
      const scopes = this._findScopeDecorationIds.map((findScopeDecorationId) => this._editor.getModel().getDecorationRange(findScopeDecorationId)).filter((element) => !!element);
      if (scopes.length) {
        return scopes;
      }
    }
    return null;
  }
  getStartPosition() {
    return this._startPosition;
  }
  setStartPosition(newStartPosition) {
    this._startPosition = newStartPosition;
    this.setCurrentFindMatch(null);
  }
  _getDecorationIndex(decorationId) {
    const index = this._decorations.indexOf(decorationId);
    if (index >= 0) {
      return index + 1;
    }
    return 1;
  }
  getDecorationRangeAt(index) {
    const decorationId = index < this._decorations.length ? this._decorations[index] : null;
    if (decorationId) {
      return this._editor.getModel().getDecorationRange(decorationId);
    }
    return null;
  }
  getCurrentMatchesPosition(desiredRange) {
    const candidates = this._editor.getModel().getDecorationsInRange(desiredRange);
    for (const candidate of candidates) {
      const candidateOpts = candidate.options;
      if (candidateOpts === FindDecorations._FIND_MATCH_DECORATION || candidateOpts === FindDecorations._CURRENT_FIND_MATCH_DECORATION) {
        return this._getDecorationIndex(candidate.id);
      }
    }
    return 0;
  }
  setCurrentFindMatch(nextMatch) {
    let newCurrentDecorationId = null;
    let matchPosition = 0;
    if (nextMatch) {
      for (let i = 0, len = this._decorations.length; i < len; i++) {
        const range2 = this._editor.getModel().getDecorationRange(this._decorations[i]);
        if (nextMatch.equalsRange(range2)) {
          newCurrentDecorationId = this._decorations[i];
          matchPosition = i + 1;
          break;
        }
      }
    }
    if (this._highlightedDecorationId !== null || newCurrentDecorationId !== null) {
      this._editor.changeDecorations((changeAccessor) => {
        if (this._highlightedDecorationId !== null) {
          changeAccessor.changeDecorationOptions(this._highlightedDecorationId, FindDecorations._FIND_MATCH_DECORATION);
          this._highlightedDecorationId = null;
        }
        if (newCurrentDecorationId !== null) {
          this._highlightedDecorationId = newCurrentDecorationId;
          changeAccessor.changeDecorationOptions(this._highlightedDecorationId, FindDecorations._CURRENT_FIND_MATCH_DECORATION);
        }
        if (this._rangeHighlightDecorationId !== null) {
          changeAccessor.removeDecoration(this._rangeHighlightDecorationId);
          this._rangeHighlightDecorationId = null;
        }
        if (newCurrentDecorationId !== null) {
          let rng = this._editor.getModel().getDecorationRange(newCurrentDecorationId);
          if (rng.startLineNumber !== rng.endLineNumber && rng.endColumn === 1) {
            const lineBeforeEnd = rng.endLineNumber - 1;
            const lineBeforeEndMaxColumn = this._editor.getModel().getLineMaxColumn(lineBeforeEnd);
            rng = new Range$2(rng.startLineNumber, rng.startColumn, lineBeforeEnd, lineBeforeEndMaxColumn);
          }
          this._rangeHighlightDecorationId = changeAccessor.addDecoration(rng, FindDecorations._RANGE_HIGHLIGHT_DECORATION);
        }
      });
    }
    return matchPosition;
  }
  set(findMatches, findScopes) {
    this._editor.changeDecorations((accessor) => {
      let findMatchesOptions = FindDecorations._FIND_MATCH_DECORATION;
      const newOverviewRulerApproximateDecorations = [];
      if (findMatches.length > 1e3) {
        findMatchesOptions = FindDecorations._FIND_MATCH_NO_OVERVIEW_DECORATION;
        const lineCount = this._editor.getModel().getLineCount();
        const height = this._editor.getLayoutInfo().height;
        const approxPixelsPerLine = height / lineCount;
        const mergeLinesDelta = Math.max(2, Math.ceil(3 / approxPixelsPerLine));
        let prevStartLineNumber = findMatches[0].range.startLineNumber;
        let prevEndLineNumber = findMatches[0].range.endLineNumber;
        for (let i = 1, len = findMatches.length; i < len; i++) {
          const range2 = findMatches[i].range;
          if (prevEndLineNumber + mergeLinesDelta >= range2.startLineNumber) {
            if (range2.endLineNumber > prevEndLineNumber) {
              prevEndLineNumber = range2.endLineNumber;
            }
          } else {
            newOverviewRulerApproximateDecorations.push({
              range: new Range$2(prevStartLineNumber, 1, prevEndLineNumber, 1),
              options: FindDecorations._FIND_MATCH_ONLY_OVERVIEW_DECORATION
            });
            prevStartLineNumber = range2.startLineNumber;
            prevEndLineNumber = range2.endLineNumber;
          }
        }
        newOverviewRulerApproximateDecorations.push({
          range: new Range$2(prevStartLineNumber, 1, prevEndLineNumber, 1),
          options: FindDecorations._FIND_MATCH_ONLY_OVERVIEW_DECORATION
        });
      }
      const newFindMatchesDecorations = new Array(findMatches.length);
      for (let i = 0, len = findMatches.length; i < len; i++) {
        newFindMatchesDecorations[i] = {
          range: findMatches[i].range,
          options: findMatchesOptions
        };
      }
      this._decorations = accessor.deltaDecorations(this._decorations, newFindMatchesDecorations);
      this._overviewRulerApproximateDecorations = accessor.deltaDecorations(this._overviewRulerApproximateDecorations, newOverviewRulerApproximateDecorations);
      if (this._rangeHighlightDecorationId) {
        accessor.removeDecoration(this._rangeHighlightDecorationId);
        this._rangeHighlightDecorationId = null;
      }
      if (this._findScopeDecorationIds.length) {
        this._findScopeDecorationIds.forEach((findScopeDecorationId) => accessor.removeDecoration(findScopeDecorationId));
        this._findScopeDecorationIds = [];
      }
      if (findScopes === null || findScopes === void 0 ? void 0 : findScopes.length) {
        this._findScopeDecorationIds = findScopes.map((findScope) => accessor.addDecoration(findScope, FindDecorations._FIND_SCOPE_DECORATION));
      }
    });
  }
  matchBeforePosition(position) {
    if (this._decorations.length === 0) {
      return null;
    }
    for (let i = this._decorations.length - 1; i >= 0; i--) {
      const decorationId = this._decorations[i];
      const r = this._editor.getModel().getDecorationRange(decorationId);
      if (!r || r.endLineNumber > position.lineNumber) {
        continue;
      }
      if (r.endLineNumber < position.lineNumber) {
        return r;
      }
      if (r.endColumn > position.column) {
        continue;
      }
      return r;
    }
    return this._editor.getModel().getDecorationRange(this._decorations[this._decorations.length - 1]);
  }
  matchAfterPosition(position) {
    if (this._decorations.length === 0) {
      return null;
    }
    for (let i = 0, len = this._decorations.length; i < len; i++) {
      const decorationId = this._decorations[i];
      const r = this._editor.getModel().getDecorationRange(decorationId);
      if (!r || r.startLineNumber < position.lineNumber) {
        continue;
      }
      if (r.startLineNumber > position.lineNumber) {
        return r;
      }
      if (r.startColumn < position.column) {
        continue;
      }
      return r;
    }
    return this._editor.getModel().getDecorationRange(this._decorations[0]);
  }
  _allDecorations() {
    let result2 = [];
    result2 = result2.concat(this._decorations);
    result2 = result2.concat(this._overviewRulerApproximateDecorations);
    if (this._findScopeDecorationIds.length) {
      result2.push(...this._findScopeDecorationIds);
    }
    if (this._rangeHighlightDecorationId) {
      result2.push(this._rangeHighlightDecorationId);
    }
    return result2;
  }
}
FindDecorations._CURRENT_FIND_MATCH_DECORATION = ModelDecorationOptions.register({
  description: "current-find-match",
  stickiness: 1,
  zIndex: 13,
  className: "currentFindMatch",
  showIfCollapsed: true,
  overviewRuler: {
    color: themeColorFromId(overviewRulerFindMatchForeground),
    position: OverviewRulerLane$1.Center
  },
  minimap: {
    color: themeColorFromId(minimapFindMatch),
    position: MinimapPosition$1.Inline
  }
});
FindDecorations._FIND_MATCH_DECORATION = ModelDecorationOptions.register({
  description: "find-match",
  stickiness: 1,
  zIndex: 10,
  className: "findMatch",
  showIfCollapsed: true,
  overviewRuler: {
    color: themeColorFromId(overviewRulerFindMatchForeground),
    position: OverviewRulerLane$1.Center
  },
  minimap: {
    color: themeColorFromId(minimapFindMatch),
    position: MinimapPosition$1.Inline
  }
});
FindDecorations._FIND_MATCH_NO_OVERVIEW_DECORATION = ModelDecorationOptions.register({
  description: "find-match-no-overview",
  stickiness: 1,
  className: "findMatch",
  showIfCollapsed: true
});
FindDecorations._FIND_MATCH_ONLY_OVERVIEW_DECORATION = ModelDecorationOptions.register({
  description: "find-match-only-overview",
  stickiness: 1,
  overviewRuler: {
    color: themeColorFromId(overviewRulerFindMatchForeground),
    position: OverviewRulerLane$1.Center
  }
});
FindDecorations._RANGE_HIGHLIGHT_DECORATION = ModelDecorationOptions.register({
  description: "find-range-highlight",
  stickiness: 1,
  className: "rangeHighlight",
  isWholeLine: true
});
FindDecorations._FIND_SCOPE_DECORATION = ModelDecorationOptions.register({
  description: "find-scope",
  className: "findScope",
  isWholeLine: true
});
class ReplaceAllCommand {
  constructor(editorSelection, ranges, replaceStrings) {
    this._editorSelection = editorSelection;
    this._ranges = ranges;
    this._replaceStrings = replaceStrings;
    this._trackedEditorSelectionId = null;
  }
  getEditOperations(model, builder) {
    if (this._ranges.length > 0) {
      const ops = [];
      for (let i = 0; i < this._ranges.length; i++) {
        ops.push({
          range: this._ranges[i],
          text: this._replaceStrings[i]
        });
      }
      ops.sort((o1, o2) => {
        return Range$2.compareRangesUsingStarts(o1.range, o2.range);
      });
      const resultOps = [];
      let previousOp = ops[0];
      for (let i = 1; i < ops.length; i++) {
        if (previousOp.range.endLineNumber === ops[i].range.startLineNumber && previousOp.range.endColumn === ops[i].range.startColumn) {
          previousOp.range = previousOp.range.plusRange(ops[i].range);
          previousOp.text = previousOp.text + ops[i].text;
        } else {
          resultOps.push(previousOp);
          previousOp = ops[i];
        }
      }
      resultOps.push(previousOp);
      for (const op of resultOps) {
        builder.addEditOperation(op.range, op.text);
      }
    }
    this._trackedEditorSelectionId = builder.trackSelection(this._editorSelection);
  }
  computeCursorState(model, helper) {
    return helper.getTrackedSelection(this._trackedEditorSelectionId);
  }
}
function buildReplaceStringWithCasePreserved(matches, pattern) {
  if (matches && matches[0] !== "") {
    const containsHyphens = validateSpecificSpecialCharacter(matches, pattern, "-");
    const containsUnderscores = validateSpecificSpecialCharacter(matches, pattern, "_");
    if (containsHyphens && !containsUnderscores) {
      return buildReplaceStringForSpecificSpecialCharacter(matches, pattern, "-");
    } else if (!containsHyphens && containsUnderscores) {
      return buildReplaceStringForSpecificSpecialCharacter(matches, pattern, "_");
    }
    if (matches[0].toUpperCase() === matches[0]) {
      return pattern.toUpperCase();
    } else if (matches[0].toLowerCase() === matches[0]) {
      return pattern.toLowerCase();
    } else if (containsUppercaseCharacter(matches[0][0]) && pattern.length > 0) {
      return pattern[0].toUpperCase() + pattern.substr(1);
    } else if (matches[0][0].toUpperCase() !== matches[0][0] && pattern.length > 0) {
      return pattern[0].toLowerCase() + pattern.substr(1);
    } else {
      return pattern;
    }
  } else {
    return pattern;
  }
}
function validateSpecificSpecialCharacter(matches, pattern, specialCharacter) {
  const doesContainSpecialCharacter = matches[0].indexOf(specialCharacter) !== -1 && pattern.indexOf(specialCharacter) !== -1;
  return doesContainSpecialCharacter && matches[0].split(specialCharacter).length === pattern.split(specialCharacter).length;
}
function buildReplaceStringForSpecificSpecialCharacter(matches, pattern, specialCharacter) {
  const splitPatternAtSpecialCharacter = pattern.split(specialCharacter);
  const splitMatchAtSpecialCharacter = matches[0].split(specialCharacter);
  let replaceString = "";
  splitPatternAtSpecialCharacter.forEach((splitValue, index) => {
    replaceString += buildReplaceStringWithCasePreserved([splitMatchAtSpecialCharacter[index]], splitValue) + specialCharacter;
  });
  return replaceString.slice(0, -1);
}
class StaticValueReplacePattern {
  constructor(staticValue) {
    this.staticValue = staticValue;
    this.kind = 0;
  }
}
class DynamicPiecesReplacePattern {
  constructor(pieces) {
    this.pieces = pieces;
    this.kind = 1;
  }
}
class ReplacePattern {
  static fromStaticValue(value) {
    return new ReplacePattern([ReplacePiece.staticValue(value)]);
  }
  get hasReplacementPatterns() {
    return this._state.kind === 1;
  }
  constructor(pieces) {
    if (!pieces || pieces.length === 0) {
      this._state = new StaticValueReplacePattern("");
    } else if (pieces.length === 1 && pieces[0].staticValue !== null) {
      this._state = new StaticValueReplacePattern(pieces[0].staticValue);
    } else {
      this._state = new DynamicPiecesReplacePattern(pieces);
    }
  }
  buildReplaceString(matches, preserveCase) {
    if (this._state.kind === 0) {
      if (preserveCase) {
        return buildReplaceStringWithCasePreserved(matches, this._state.staticValue);
      } else {
        return this._state.staticValue;
      }
    }
    let result2 = "";
    for (let i = 0, len = this._state.pieces.length; i < len; i++) {
      const piece = this._state.pieces[i];
      if (piece.staticValue !== null) {
        result2 += piece.staticValue;
        continue;
      }
      let match2 = ReplacePattern._substitute(piece.matchIndex, matches);
      if (piece.caseOps !== null && piece.caseOps.length > 0) {
        const repl = [];
        const lenOps = piece.caseOps.length;
        let opIdx = 0;
        for (let idx = 0, len2 = match2.length; idx < len2; idx++) {
          if (opIdx >= lenOps) {
            repl.push(match2.slice(idx));
            break;
          }
          switch (piece.caseOps[opIdx]) {
            case "U":
              repl.push(match2[idx].toUpperCase());
              break;
            case "u":
              repl.push(match2[idx].toUpperCase());
              opIdx++;
              break;
            case "L":
              repl.push(match2[idx].toLowerCase());
              break;
            case "l":
              repl.push(match2[idx].toLowerCase());
              opIdx++;
              break;
            default:
              repl.push(match2[idx]);
          }
        }
        match2 = repl.join("");
      }
      result2 += match2;
    }
    return result2;
  }
  static _substitute(matchIndex, matches) {
    if (matches === null) {
      return "";
    }
    if (matchIndex === 0) {
      return matches[0];
    }
    let remainder = "";
    while (matchIndex > 0) {
      if (matchIndex < matches.length) {
        const match2 = matches[matchIndex] || "";
        return match2 + remainder;
      }
      remainder = String(matchIndex % 10) + remainder;
      matchIndex = Math.floor(matchIndex / 10);
    }
    return "$" + remainder;
  }
}
class ReplacePiece {
  static staticValue(value) {
    return new ReplacePiece(value, -1, null);
  }
  static caseOps(index, caseOps) {
    return new ReplacePiece(null, index, caseOps);
  }
  constructor(staticValue, matchIndex, caseOps) {
    this.staticValue = staticValue;
    this.matchIndex = matchIndex;
    if (!caseOps || caseOps.length === 0) {
      this.caseOps = null;
    } else {
      this.caseOps = caseOps.slice(0);
    }
  }
}
class ReplacePieceBuilder {
  constructor(source) {
    this._source = source;
    this._lastCharIndex = 0;
    this._result = [];
    this._resultLen = 0;
    this._currentStaticPiece = "";
  }
  emitUnchanged(toCharIndex) {
    this._emitStatic(this._source.substring(this._lastCharIndex, toCharIndex));
    this._lastCharIndex = toCharIndex;
  }
  emitStatic(value, toCharIndex) {
    this._emitStatic(value);
    this._lastCharIndex = toCharIndex;
  }
  _emitStatic(value) {
    if (value.length === 0) {
      return;
    }
    this._currentStaticPiece += value;
  }
  emitMatchIndex(index, toCharIndex, caseOps) {
    if (this._currentStaticPiece.length !== 0) {
      this._result[this._resultLen++] = ReplacePiece.staticValue(this._currentStaticPiece);
      this._currentStaticPiece = "";
    }
    this._result[this._resultLen++] = ReplacePiece.caseOps(index, caseOps);
    this._lastCharIndex = toCharIndex;
  }
  finalize() {
    this.emitUnchanged(this._source.length);
    if (this._currentStaticPiece.length !== 0) {
      this._result[this._resultLen++] = ReplacePiece.staticValue(this._currentStaticPiece);
      this._currentStaticPiece = "";
    }
    return new ReplacePattern(this._result);
  }
}
function parseReplaceString(replaceString) {
  if (!replaceString || replaceString.length === 0) {
    return new ReplacePattern(null);
  }
  const caseOps = [];
  const result2 = new ReplacePieceBuilder(replaceString);
  for (let i = 0, len = replaceString.length; i < len; i++) {
    const chCode = replaceString.charCodeAt(i);
    if (chCode === 92) {
      i++;
      if (i >= len) {
        break;
      }
      const nextChCode = replaceString.charCodeAt(i);
      switch (nextChCode) {
        case 92:
          result2.emitUnchanged(i - 1);
          result2.emitStatic("\\", i + 1);
          break;
        case 110:
          result2.emitUnchanged(i - 1);
          result2.emitStatic("\n", i + 1);
          break;
        case 116:
          result2.emitUnchanged(i - 1);
          result2.emitStatic("	", i + 1);
          break;
        case 117:
        case 85:
        case 108:
        case 76:
          result2.emitUnchanged(i - 1);
          result2.emitStatic("", i + 1);
          caseOps.push(String.fromCharCode(nextChCode));
          break;
      }
      continue;
    }
    if (chCode === 36) {
      i++;
      if (i >= len) {
        break;
      }
      const nextChCode = replaceString.charCodeAt(i);
      if (nextChCode === 36) {
        result2.emitUnchanged(i - 1);
        result2.emitStatic("$", i + 1);
        continue;
      }
      if (nextChCode === 48 || nextChCode === 38) {
        result2.emitUnchanged(i - 1);
        result2.emitMatchIndex(0, i + 1, caseOps);
        caseOps.length = 0;
        continue;
      }
      if (49 <= nextChCode && nextChCode <= 57) {
        let matchIndex = nextChCode - 48;
        if (i + 1 < len) {
          const nextNextChCode = replaceString.charCodeAt(i + 1);
          if (48 <= nextNextChCode && nextNextChCode <= 57) {
            i++;
            matchIndex = matchIndex * 10 + (nextNextChCode - 48);
            result2.emitUnchanged(i - 2);
            result2.emitMatchIndex(matchIndex, i + 1, caseOps);
            caseOps.length = 0;
            continue;
          }
        }
        result2.emitUnchanged(i - 1);
        result2.emitMatchIndex(matchIndex, i + 1, caseOps);
        caseOps.length = 0;
        continue;
      }
    }
  }
  return result2.finalize();
}
const CONTEXT_FIND_WIDGET_VISIBLE = new RawContextKey("findWidgetVisible", false);
CONTEXT_FIND_WIDGET_VISIBLE.toNegated();
const CONTEXT_FIND_INPUT_FOCUSED = new RawContextKey("findInputFocussed", false);
const CONTEXT_REPLACE_INPUT_FOCUSED = new RawContextKey("replaceInputFocussed", false);
const ToggleCaseSensitiveKeybinding = {
  primary: 512 | 33,
  mac: {
    primary: 2048 | 512 | 33
    /* KeyCode.KeyC */
  }
};
const ToggleWholeWordKeybinding = {
  primary: 512 | 53,
  mac: {
    primary: 2048 | 512 | 53
    /* KeyCode.KeyW */
  }
};
const ToggleRegexKeybinding = {
  primary: 512 | 48,
  mac: {
    primary: 2048 | 512 | 48
    /* KeyCode.KeyR */
  }
};
const ToggleSearchScopeKeybinding = {
  primary: 512 | 42,
  mac: {
    primary: 2048 | 512 | 42
    /* KeyCode.KeyL */
  }
};
const TogglePreserveCaseKeybinding = {
  primary: 512 | 46,
  mac: {
    primary: 2048 | 512 | 46
    /* KeyCode.KeyP */
  }
};
const FIND_IDS = {
  StartFindAction: "actions.find",
  StartFindWithSelection: "actions.findWithSelection",
  StartFindWithArgs: "editor.actions.findWithArgs",
  NextMatchFindAction: "editor.action.nextMatchFindAction",
  PreviousMatchFindAction: "editor.action.previousMatchFindAction",
  GoToMatchFindAction: "editor.action.goToMatchFindAction",
  NextSelectionMatchFindAction: "editor.action.nextSelectionMatchFindAction",
  PreviousSelectionMatchFindAction: "editor.action.previousSelectionMatchFindAction",
  StartFindReplaceAction: "editor.action.startFindReplaceAction",
  CloseFindWidgetCommand: "closeFindWidget",
  ToggleCaseSensitiveCommand: "toggleFindCaseSensitive",
  ToggleWholeWordCommand: "toggleFindWholeWord",
  ToggleRegexCommand: "toggleFindRegex",
  ToggleSearchScopeCommand: "toggleFindInSelection",
  TogglePreserveCaseCommand: "togglePreserveCase",
  ReplaceOneAction: "editor.action.replaceOne",
  ReplaceAllAction: "editor.action.replaceAll",
  SelectAllMatchesAction: "editor.action.selectAllMatches"
};
const MATCHES_LIMIT = 19999;
const RESEARCH_DELAY = 240;
class FindModelBoundToEditorModel {
  constructor(editor2, state) {
    this._toDispose = new DisposableStore();
    this._editor = editor2;
    this._state = state;
    this._isDisposed = false;
    this._startSearchingTimer = new TimeoutTimer();
    this._decorations = new FindDecorations(editor2);
    this._toDispose.add(this._decorations);
    this._updateDecorationsScheduler = new RunOnceScheduler(() => this.research(false), 100);
    this._toDispose.add(this._updateDecorationsScheduler);
    this._toDispose.add(this._editor.onDidChangeCursorPosition((e) => {
      if (e.reason === 3 || e.reason === 5 || e.reason === 6) {
        this._decorations.setStartPosition(this._editor.getPosition());
      }
    }));
    this._ignoreModelContentChanged = false;
    this._toDispose.add(this._editor.onDidChangeModelContent((e) => {
      if (this._ignoreModelContentChanged) {
        return;
      }
      if (e.isFlush) {
        this._decorations.reset();
      }
      this._decorations.setStartPosition(this._editor.getPosition());
      this._updateDecorationsScheduler.schedule();
    }));
    this._toDispose.add(this._state.onFindReplaceStateChange((e) => this._onStateChanged(e)));
    this.research(false, this._state.searchScope);
  }
  dispose() {
    this._isDisposed = true;
    dispose(this._startSearchingTimer);
    this._toDispose.dispose();
  }
  _onStateChanged(e) {
    if (this._isDisposed) {
      return;
    }
    if (!this._editor.hasModel()) {
      return;
    }
    if (e.searchString || e.isReplaceRevealed || e.isRegex || e.wholeWord || e.matchCase || e.searchScope) {
      const model = this._editor.getModel();
      if (model.isTooLargeForSyncing()) {
        this._startSearchingTimer.cancel();
        this._startSearchingTimer.setIfNotSet(() => {
          if (e.searchScope) {
            this.research(e.moveCursor, this._state.searchScope);
          } else {
            this.research(e.moveCursor);
          }
        }, RESEARCH_DELAY);
      } else {
        if (e.searchScope) {
          this.research(e.moveCursor, this._state.searchScope);
        } else {
          this.research(e.moveCursor);
        }
      }
    }
  }
  static _getSearchRange(model, findScope) {
    if (findScope) {
      return findScope;
    }
    return model.getFullModelRange();
  }
  research(moveCursor, newFindScope) {
    let findScopes = null;
    if (typeof newFindScope !== "undefined") {
      if (newFindScope !== null) {
        if (!Array.isArray(newFindScope)) {
          findScopes = [newFindScope];
        } else {
          findScopes = newFindScope;
        }
      }
    } else {
      findScopes = this._decorations.getFindScopes();
    }
    if (findScopes !== null) {
      findScopes = findScopes.map((findScope) => {
        if (findScope.startLineNumber !== findScope.endLineNumber) {
          let endLineNumber = findScope.endLineNumber;
          if (findScope.endColumn === 1) {
            endLineNumber = endLineNumber - 1;
          }
          return new Range$2(findScope.startLineNumber, 1, endLineNumber, this._editor.getModel().getLineMaxColumn(endLineNumber));
        }
        return findScope;
      });
    }
    const findMatches = this._findMatches(findScopes, false, MATCHES_LIMIT);
    this._decorations.set(findMatches, findScopes);
    const editorSelection = this._editor.getSelection();
    let currentMatchesPosition = this._decorations.getCurrentMatchesPosition(editorSelection);
    if (currentMatchesPosition === 0 && findMatches.length > 0) {
      const matchAfterSelection = findFirstInSorted$1(findMatches.map((match2) => match2.range), (range2) => Range$2.compareRangesUsingStarts(range2, editorSelection) >= 0);
      currentMatchesPosition = matchAfterSelection > 0 ? matchAfterSelection - 1 + 1 : currentMatchesPosition;
    }
    this._state.changeMatchInfo(currentMatchesPosition, this._decorations.getCount(), void 0);
    if (moveCursor && this._editor.getOption(
      40
      /* EditorOption.find */
    ).cursorMoveOnType) {
      this._moveToNextMatch(this._decorations.getStartPosition());
    }
  }
  _hasMatches() {
    return this._state.matchesCount > 0;
  }
  _cannotFind() {
    if (!this._hasMatches()) {
      const findScope = this._decorations.getFindScope();
      if (findScope) {
        this._editor.revealRangeInCenterIfOutsideViewport(
          findScope,
          0
          /* ScrollType.Smooth */
        );
      }
      return true;
    }
    return false;
  }
  _setCurrentFindMatch(match2) {
    const matchesPosition = this._decorations.setCurrentFindMatch(match2);
    this._state.changeMatchInfo(matchesPosition, this._decorations.getCount(), match2);
    this._editor.setSelection(match2);
    this._editor.revealRangeInCenterIfOutsideViewport(
      match2,
      0
      /* ScrollType.Smooth */
    );
  }
  _prevSearchPosition(before) {
    const isUsingLineStops = this._state.isRegex && (this._state.searchString.indexOf("^") >= 0 || this._state.searchString.indexOf("$") >= 0);
    let { lineNumber, column } = before;
    const model = this._editor.getModel();
    if (isUsingLineStops || column === 1) {
      if (lineNumber === 1) {
        lineNumber = model.getLineCount();
      } else {
        lineNumber--;
      }
      column = model.getLineMaxColumn(lineNumber);
    } else {
      column--;
    }
    return new Position$2(lineNumber, column);
  }
  _moveToPrevMatch(before, isRecursed = false) {
    if (!this._state.canNavigateBack()) {
      const nextMatchRange = this._decorations.matchAfterPosition(before);
      if (nextMatchRange) {
        this._setCurrentFindMatch(nextMatchRange);
      }
      return;
    }
    if (this._decorations.getCount() < MATCHES_LIMIT) {
      let prevMatchRange = this._decorations.matchBeforePosition(before);
      if (prevMatchRange && prevMatchRange.isEmpty() && prevMatchRange.getStartPosition().equals(before)) {
        before = this._prevSearchPosition(before);
        prevMatchRange = this._decorations.matchBeforePosition(before);
      }
      if (prevMatchRange) {
        this._setCurrentFindMatch(prevMatchRange);
      }
      return;
    }
    if (this._cannotFind()) {
      return;
    }
    const findScope = this._decorations.getFindScope();
    const searchRange = FindModelBoundToEditorModel._getSearchRange(this._editor.getModel(), findScope);
    if (searchRange.getEndPosition().isBefore(before)) {
      before = searchRange.getEndPosition();
    }
    if (before.isBefore(searchRange.getStartPosition())) {
      before = searchRange.getEndPosition();
    }
    const { lineNumber, column } = before;
    const model = this._editor.getModel();
    let position = new Position$2(lineNumber, column);
    let prevMatch = model.findPreviousMatch(this._state.searchString, position, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(
      128
      /* EditorOption.wordSeparators */
    ) : null, false);
    if (prevMatch && prevMatch.range.isEmpty() && prevMatch.range.getStartPosition().equals(position)) {
      position = this._prevSearchPosition(position);
      prevMatch = model.findPreviousMatch(this._state.searchString, position, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(
        128
        /* EditorOption.wordSeparators */
      ) : null, false);
    }
    if (!prevMatch) {
      return;
    }
    if (!isRecursed && !searchRange.containsRange(prevMatch.range)) {
      return this._moveToPrevMatch(prevMatch.range.getStartPosition(), true);
    }
    this._setCurrentFindMatch(prevMatch.range);
  }
  moveToPrevMatch() {
    this._moveToPrevMatch(this._editor.getSelection().getStartPosition());
  }
  _nextSearchPosition(after) {
    const isUsingLineStops = this._state.isRegex && (this._state.searchString.indexOf("^") >= 0 || this._state.searchString.indexOf("$") >= 0);
    let { lineNumber, column } = after;
    const model = this._editor.getModel();
    if (isUsingLineStops || column === model.getLineMaxColumn(lineNumber)) {
      if (lineNumber === model.getLineCount()) {
        lineNumber = 1;
      } else {
        lineNumber++;
      }
      column = 1;
    } else {
      column++;
    }
    return new Position$2(lineNumber, column);
  }
  _moveToNextMatch(after) {
    if (!this._state.canNavigateForward()) {
      const prevMatchRange = this._decorations.matchBeforePosition(after);
      if (prevMatchRange) {
        this._setCurrentFindMatch(prevMatchRange);
      }
      return;
    }
    if (this._decorations.getCount() < MATCHES_LIMIT) {
      let nextMatchRange = this._decorations.matchAfterPosition(after);
      if (nextMatchRange && nextMatchRange.isEmpty() && nextMatchRange.getStartPosition().equals(after)) {
        after = this._nextSearchPosition(after);
        nextMatchRange = this._decorations.matchAfterPosition(after);
      }
      if (nextMatchRange) {
        this._setCurrentFindMatch(nextMatchRange);
      }
      return;
    }
    const nextMatch = this._getNextMatch(after, false, true);
    if (nextMatch) {
      this._setCurrentFindMatch(nextMatch.range);
    }
  }
  _getNextMatch(after, captureMatches, forceMove, isRecursed = false) {
    if (this._cannotFind()) {
      return null;
    }
    const findScope = this._decorations.getFindScope();
    const searchRange = FindModelBoundToEditorModel._getSearchRange(this._editor.getModel(), findScope);
    if (searchRange.getEndPosition().isBefore(after)) {
      after = searchRange.getStartPosition();
    }
    if (after.isBefore(searchRange.getStartPosition())) {
      after = searchRange.getStartPosition();
    }
    const { lineNumber, column } = after;
    const model = this._editor.getModel();
    let position = new Position$2(lineNumber, column);
    let nextMatch = model.findNextMatch(this._state.searchString, position, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(
      128
      /* EditorOption.wordSeparators */
    ) : null, captureMatches);
    if (forceMove && nextMatch && nextMatch.range.isEmpty() && nextMatch.range.getStartPosition().equals(position)) {
      position = this._nextSearchPosition(position);
      nextMatch = model.findNextMatch(this._state.searchString, position, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(
        128
        /* EditorOption.wordSeparators */
      ) : null, captureMatches);
    }
    if (!nextMatch) {
      return null;
    }
    if (!isRecursed && !searchRange.containsRange(nextMatch.range)) {
      return this._getNextMatch(nextMatch.range.getEndPosition(), captureMatches, forceMove, true);
    }
    return nextMatch;
  }
  moveToNextMatch() {
    this._moveToNextMatch(this._editor.getSelection().getEndPosition());
  }
  _moveToMatch(index) {
    const decorationRange = this._decorations.getDecorationRangeAt(index);
    if (decorationRange) {
      this._setCurrentFindMatch(decorationRange);
    }
  }
  moveToMatch(index) {
    this._moveToMatch(index);
  }
  _getReplacePattern() {
    if (this._state.isRegex) {
      return parseReplaceString(this._state.replaceString);
    }
    return ReplacePattern.fromStaticValue(this._state.replaceString);
  }
  replace() {
    if (!this._hasMatches()) {
      return;
    }
    const replacePattern = this._getReplacePattern();
    const selection = this._editor.getSelection();
    const nextMatch = this._getNextMatch(selection.getStartPosition(), true, false);
    if (nextMatch) {
      if (selection.equalsRange(nextMatch.range)) {
        const replaceString = replacePattern.buildReplaceString(nextMatch.matches, this._state.preserveCase);
        const command = new ReplaceCommand(selection, replaceString);
        this._executeEditorCommand("replace", command);
        this._decorations.setStartPosition(new Position$2(selection.startLineNumber, selection.startColumn + replaceString.length));
        this.research(true);
      } else {
        this._decorations.setStartPosition(this._editor.getPosition());
        this._setCurrentFindMatch(nextMatch.range);
      }
    }
  }
  _findMatches(findScopes, captureMatches, limitResultCount) {
    const searchRanges = (findScopes || [null]).map((scope) => FindModelBoundToEditorModel._getSearchRange(this._editor.getModel(), scope));
    return this._editor.getModel().findMatches(this._state.searchString, searchRanges, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(
      128
      /* EditorOption.wordSeparators */
    ) : null, captureMatches, limitResultCount);
  }
  replaceAll() {
    if (!this._hasMatches()) {
      return;
    }
    const findScopes = this._decorations.getFindScopes();
    if (findScopes === null && this._state.matchesCount >= MATCHES_LIMIT) {
      this._largeReplaceAll();
    } else {
      this._regularReplaceAll(findScopes);
    }
    this.research(false);
  }
  _largeReplaceAll() {
    const searchParams = new SearchParams(this._state.searchString, this._state.isRegex, this._state.matchCase, this._state.wholeWord ? this._editor.getOption(
      128
      /* EditorOption.wordSeparators */
    ) : null);
    const searchData = searchParams.parseSearchRequest();
    if (!searchData) {
      return;
    }
    let searchRegex = searchData.regex;
    if (!searchRegex.multiline) {
      let mod = "mu";
      if (searchRegex.ignoreCase) {
        mod += "i";
      }
      if (searchRegex.global) {
        mod += "g";
      }
      searchRegex = new RegExp(searchRegex.source, mod);
    }
    const model = this._editor.getModel();
    const modelText = model.getValue(
      1
      /* EndOfLinePreference.LF */
    );
    const fullModelRange = model.getFullModelRange();
    const replacePattern = this._getReplacePattern();
    let resultText;
    const preserveCase = this._state.preserveCase;
    if (replacePattern.hasReplacementPatterns || preserveCase) {
      resultText = modelText.replace(searchRegex, function() {
        return replacePattern.buildReplaceString(arguments, preserveCase);
      });
    } else {
      resultText = modelText.replace(searchRegex, replacePattern.buildReplaceString(null, preserveCase));
    }
    const command = new ReplaceCommandThatPreservesSelection(fullModelRange, resultText, this._editor.getSelection());
    this._executeEditorCommand("replaceAll", command);
  }
  _regularReplaceAll(findScopes) {
    const replacePattern = this._getReplacePattern();
    const matches = this._findMatches(
      findScopes,
      replacePattern.hasReplacementPatterns || this._state.preserveCase,
      1073741824
      /* Constants.MAX_SAFE_SMALL_INTEGER */
    );
    const replaceStrings = [];
    for (let i = 0, len = matches.length; i < len; i++) {
      replaceStrings[i] = replacePattern.buildReplaceString(matches[i].matches, this._state.preserveCase);
    }
    const command = new ReplaceAllCommand(this._editor.getSelection(), matches.map((m) => m.range), replaceStrings);
    this._executeEditorCommand("replaceAll", command);
  }
  selectAllMatches() {
    if (!this._hasMatches()) {
      return;
    }
    const findScopes = this._decorations.getFindScopes();
    const matches = this._findMatches(
      findScopes,
      false,
      1073741824
      /* Constants.MAX_SAFE_SMALL_INTEGER */
    );
    let selections2 = matches.map((m) => new Selection$1(m.range.startLineNumber, m.range.startColumn, m.range.endLineNumber, m.range.endColumn));
    const editorSelection = this._editor.getSelection();
    for (let i = 0, len = selections2.length; i < len; i++) {
      const sel = selections2[i];
      if (sel.equalsRange(editorSelection)) {
        selections2 = [editorSelection].concat(selections2.slice(0, i)).concat(selections2.slice(i + 1));
        break;
      }
    }
    this._editor.setSelections(selections2);
  }
  _executeEditorCommand(source, command) {
    try {
      this._ignoreModelContentChanged = true;
      this._editor.pushUndoStop();
      this._editor.executeCommand(source, command);
      this._editor.pushUndoStop();
    } finally {
      this._ignoreModelContentChanged = false;
    }
  }
}
const findOptionsWidget = "";
class FindOptionsWidget extends Widget$1 {
  constructor(editor2, state, keybindingService) {
    super();
    this._hideSoon = this._register(new RunOnceScheduler(() => this._hide(), 2e3));
    this._isVisible = false;
    this._editor = editor2;
    this._state = state;
    this._keybindingService = keybindingService;
    this._domNode = document.createElement("div");
    this._domNode.className = "findOptionsWidget";
    this._domNode.style.display = "none";
    this._domNode.style.top = "10px";
    this._domNode.style.zIndex = "12";
    this._domNode.setAttribute("role", "presentation");
    this._domNode.setAttribute("aria-hidden", "true");
    const toggleStyles = {
      inputActiveOptionBorder: asCssVariable(inputActiveOptionBorder),
      inputActiveOptionForeground: asCssVariable(inputActiveOptionForeground),
      inputActiveOptionBackground: asCssVariable(inputActiveOptionBackground)
    };
    this.caseSensitive = this._register(new CaseSensitiveToggle(Object.assign({ appendTitle: this._keybindingLabelFor(FIND_IDS.ToggleCaseSensitiveCommand), isChecked: this._state.matchCase }, toggleStyles)));
    this._domNode.appendChild(this.caseSensitive.domNode);
    this._register(this.caseSensitive.onChange(() => {
      this._state.change({
        matchCase: this.caseSensitive.checked
      }, false);
    }));
    this.wholeWords = this._register(new WholeWordsToggle(Object.assign({ appendTitle: this._keybindingLabelFor(FIND_IDS.ToggleWholeWordCommand), isChecked: this._state.wholeWord }, toggleStyles)));
    this._domNode.appendChild(this.wholeWords.domNode);
    this._register(this.wholeWords.onChange(() => {
      this._state.change({
        wholeWord: this.wholeWords.checked
      }, false);
    }));
    this.regex = this._register(new RegexToggle(Object.assign({ appendTitle: this._keybindingLabelFor(FIND_IDS.ToggleRegexCommand), isChecked: this._state.isRegex }, toggleStyles)));
    this._domNode.appendChild(this.regex.domNode);
    this._register(this.regex.onChange(() => {
      this._state.change({
        isRegex: this.regex.checked
      }, false);
    }));
    this._editor.addOverlayWidget(this);
    this._register(this._state.onFindReplaceStateChange((e) => {
      let somethingChanged = false;
      if (e.isRegex) {
        this.regex.checked = this._state.isRegex;
        somethingChanged = true;
      }
      if (e.wholeWord) {
        this.wholeWords.checked = this._state.wholeWord;
        somethingChanged = true;
      }
      if (e.matchCase) {
        this.caseSensitive.checked = this._state.matchCase;
        somethingChanged = true;
      }
      if (!this._state.isRevealed && somethingChanged) {
        this._revealTemporarily();
      }
    }));
    this._register(addDisposableListener(this._domNode, EventType$1.MOUSE_LEAVE, (e) => this._onMouseLeave()));
    this._register(addDisposableListener(this._domNode, "mouseover", (e) => this._onMouseOver()));
  }
  _keybindingLabelFor(actionId) {
    const kb = this._keybindingService.lookupKeybinding(actionId);
    if (!kb) {
      return "";
    }
    return ` (${kb.getLabel()})`;
  }
  dispose() {
    this._editor.removeOverlayWidget(this);
    super.dispose();
  }
  // ----- IOverlayWidget API
  getId() {
    return FindOptionsWidget.ID;
  }
  getDomNode() {
    return this._domNode;
  }
  getPosition() {
    return {
      preference: 0
      /* OverlayWidgetPositionPreference.TOP_RIGHT_CORNER */
    };
  }
  highlightFindOptions() {
    this._revealTemporarily();
  }
  _revealTemporarily() {
    this._show();
    this._hideSoon.schedule();
  }
  _onMouseLeave() {
    this._hideSoon.schedule();
  }
  _onMouseOver() {
    this._hideSoon.cancel();
  }
  _show() {
    if (this._isVisible) {
      return;
    }
    this._isVisible = true;
    this._domNode.style.display = "block";
  }
  _hide() {
    if (!this._isVisible) {
      return;
    }
    this._isVisible = false;
    this._domNode.style.display = "none";
  }
}
FindOptionsWidget.ID = "editor.contrib.findOptionsWidget";
function effectiveOptionValue(override, value) {
  if (override === 1) {
    return true;
  }
  if (override === 2) {
    return false;
  }
  return value;
}
class FindReplaceState extends Disposable {
  get searchString() {
    return this._searchString;
  }
  get replaceString() {
    return this._replaceString;
  }
  get isRevealed() {
    return this._isRevealed;
  }
  get isReplaceRevealed() {
    return this._isReplaceRevealed;
  }
  get isRegex() {
    return effectiveOptionValue(this._isRegexOverride, this._isRegex);
  }
  get wholeWord() {
    return effectiveOptionValue(this._wholeWordOverride, this._wholeWord);
  }
  get matchCase() {
    return effectiveOptionValue(this._matchCaseOverride, this._matchCase);
  }
  get preserveCase() {
    return effectiveOptionValue(this._preserveCaseOverride, this._preserveCase);
  }
  get actualIsRegex() {
    return this._isRegex;
  }
  get actualWholeWord() {
    return this._wholeWord;
  }
  get actualMatchCase() {
    return this._matchCase;
  }
  get actualPreserveCase() {
    return this._preserveCase;
  }
  get searchScope() {
    return this._searchScope;
  }
  get matchesPosition() {
    return this._matchesPosition;
  }
  get matchesCount() {
    return this._matchesCount;
  }
  get currentMatch() {
    return this._currentMatch;
  }
  constructor() {
    super();
    this._onFindReplaceStateChange = this._register(new Emitter$1());
    this.onFindReplaceStateChange = this._onFindReplaceStateChange.event;
    this._searchString = "";
    this._replaceString = "";
    this._isRevealed = false;
    this._isReplaceRevealed = false;
    this._isRegex = false;
    this._isRegexOverride = 0;
    this._wholeWord = false;
    this._wholeWordOverride = 0;
    this._matchCase = false;
    this._matchCaseOverride = 0;
    this._preserveCase = false;
    this._preserveCaseOverride = 0;
    this._searchScope = null;
    this._matchesPosition = 0;
    this._matchesCount = 0;
    this._currentMatch = null;
    this._loop = true;
    this._isSearching = false;
    this._filters = null;
  }
  changeMatchInfo(matchesPosition, matchesCount, currentMatch) {
    const changeEvent = {
      moveCursor: false,
      updateHistory: false,
      searchString: false,
      replaceString: false,
      isRevealed: false,
      isReplaceRevealed: false,
      isRegex: false,
      wholeWord: false,
      matchCase: false,
      preserveCase: false,
      searchScope: false,
      matchesPosition: false,
      matchesCount: false,
      currentMatch: false,
      loop: false,
      isSearching: false,
      filters: false
    };
    let somethingChanged = false;
    if (matchesCount === 0) {
      matchesPosition = 0;
    }
    if (matchesPosition > matchesCount) {
      matchesPosition = matchesCount;
    }
    if (this._matchesPosition !== matchesPosition) {
      this._matchesPosition = matchesPosition;
      changeEvent.matchesPosition = true;
      somethingChanged = true;
    }
    if (this._matchesCount !== matchesCount) {
      this._matchesCount = matchesCount;
      changeEvent.matchesCount = true;
      somethingChanged = true;
    }
    if (typeof currentMatch !== "undefined") {
      if (!Range$2.equalsRange(this._currentMatch, currentMatch)) {
        this._currentMatch = currentMatch;
        changeEvent.currentMatch = true;
        somethingChanged = true;
      }
    }
    if (somethingChanged) {
      this._onFindReplaceStateChange.fire(changeEvent);
    }
  }
  change(newState, moveCursor, updateHistory = true) {
    var _a2;
    const changeEvent = {
      moveCursor,
      updateHistory,
      searchString: false,
      replaceString: false,
      isRevealed: false,
      isReplaceRevealed: false,
      isRegex: false,
      wholeWord: false,
      matchCase: false,
      preserveCase: false,
      searchScope: false,
      matchesPosition: false,
      matchesCount: false,
      currentMatch: false,
      loop: false,
      isSearching: false,
      filters: false
    };
    let somethingChanged = false;
    const oldEffectiveIsRegex = this.isRegex;
    const oldEffectiveWholeWords = this.wholeWord;
    const oldEffectiveMatchCase = this.matchCase;
    const oldEffectivePreserveCase = this.preserveCase;
    if (typeof newState.searchString !== "undefined") {
      if (this._searchString !== newState.searchString) {
        this._searchString = newState.searchString;
        changeEvent.searchString = true;
        somethingChanged = true;
      }
    }
    if (typeof newState.replaceString !== "undefined") {
      if (this._replaceString !== newState.replaceString) {
        this._replaceString = newState.replaceString;
        changeEvent.replaceString = true;
        somethingChanged = true;
      }
    }
    if (typeof newState.isRevealed !== "undefined") {
      if (this._isRevealed !== newState.isRevealed) {
        this._isRevealed = newState.isRevealed;
        changeEvent.isRevealed = true;
        somethingChanged = true;
      }
    }
    if (typeof newState.isReplaceRevealed !== "undefined") {
      if (this._isReplaceRevealed !== newState.isReplaceRevealed) {
        this._isReplaceRevealed = newState.isReplaceRevealed;
        changeEvent.isReplaceRevealed = true;
        somethingChanged = true;
      }
    }
    if (typeof newState.isRegex !== "undefined") {
      this._isRegex = newState.isRegex;
    }
    if (typeof newState.wholeWord !== "undefined") {
      this._wholeWord = newState.wholeWord;
    }
    if (typeof newState.matchCase !== "undefined") {
      this._matchCase = newState.matchCase;
    }
    if (typeof newState.preserveCase !== "undefined") {
      this._preserveCase = newState.preserveCase;
    }
    if (typeof newState.searchScope !== "undefined") {
      if (!((_a2 = newState.searchScope) === null || _a2 === void 0 ? void 0 : _a2.every((newSearchScope) => {
        var _a3;
        return (_a3 = this._searchScope) === null || _a3 === void 0 ? void 0 : _a3.some((existingSearchScope) => {
          return !Range$2.equalsRange(existingSearchScope, newSearchScope);
        });
      }))) {
        this._searchScope = newState.searchScope;
        changeEvent.searchScope = true;
        somethingChanged = true;
      }
    }
    if (typeof newState.loop !== "undefined") {
      if (this._loop !== newState.loop) {
        this._loop = newState.loop;
        changeEvent.loop = true;
        somethingChanged = true;
      }
    }
    if (typeof newState.isSearching !== "undefined") {
      if (this._isSearching !== newState.isSearching) {
        this._isSearching = newState.isSearching;
        changeEvent.isSearching = true;
        somethingChanged = true;
      }
    }
    if (typeof newState.filters !== "undefined") {
      if (this._filters) {
        this._filters.update(newState.filters);
      } else {
        this._filters = newState.filters;
      }
      changeEvent.filters = true;
      somethingChanged = true;
    }
    this._isRegexOverride = typeof newState.isRegexOverride !== "undefined" ? newState.isRegexOverride : 0;
    this._wholeWordOverride = typeof newState.wholeWordOverride !== "undefined" ? newState.wholeWordOverride : 0;
    this._matchCaseOverride = typeof newState.matchCaseOverride !== "undefined" ? newState.matchCaseOverride : 0;
    this._preserveCaseOverride = typeof newState.preserveCaseOverride !== "undefined" ? newState.preserveCaseOverride : 0;
    if (oldEffectiveIsRegex !== this.isRegex) {
      somethingChanged = true;
      changeEvent.isRegex = true;
    }
    if (oldEffectiveWholeWords !== this.wholeWord) {
      somethingChanged = true;
      changeEvent.wholeWord = true;
    }
    if (oldEffectiveMatchCase !== this.matchCase) {
      somethingChanged = true;
      changeEvent.matchCase = true;
    }
    if (oldEffectivePreserveCase !== this.preserveCase) {
      somethingChanged = true;
      changeEvent.preserveCase = true;
    }
    if (somethingChanged) {
      this._onFindReplaceStateChange.fire(changeEvent);
    }
  }
  canNavigateBack() {
    return this.canNavigateInLoop() || this.matchesPosition !== 1;
  }
  canNavigateForward() {
    return this.canNavigateInLoop() || this.matchesPosition < this.matchesCount;
  }
  canNavigateInLoop() {
    return this._loop || this.matchesCount >= MATCHES_LIMIT;
  }
}
const findWidget = "";
const NLS_DEFAULT_LABEL = localize("defaultLabel", "input");
const NLS_PRESERVE_CASE_LABEL = localize("label.preserveCaseToggle", "Preserve Case");
class PreserveCaseToggle extends Toggle {
  constructor(opts) {
    super({
      // TODO: does this need its own icon?
      icon: Codicon.preserveCase,
      title: NLS_PRESERVE_CASE_LABEL + opts.appendTitle,
      isChecked: opts.isChecked,
      inputActiveOptionBorder: opts.inputActiveOptionBorder,
      inputActiveOptionForeground: opts.inputActiveOptionForeground,
      inputActiveOptionBackground: opts.inputActiveOptionBackground
    });
  }
}
class ReplaceInput extends Widget$1 {
  constructor(parent, contextViewProvider, _showOptionButtons, options) {
    super();
    this._showOptionButtons = _showOptionButtons;
    this.fixFocusOnOptionClickEnabled = true;
    this.cachedOptionsWidth = 0;
    this._onDidOptionChange = this._register(new Emitter$1());
    this.onDidOptionChange = this._onDidOptionChange.event;
    this._onKeyDown = this._register(new Emitter$1());
    this.onKeyDown = this._onKeyDown.event;
    this._onMouseDown = this._register(new Emitter$1());
    this._onInput = this._register(new Emitter$1());
    this._onKeyUp = this._register(new Emitter$1());
    this._onPreserveCaseKeyDown = this._register(new Emitter$1());
    this.onPreserveCaseKeyDown = this._onPreserveCaseKeyDown.event;
    this.contextViewProvider = contextViewProvider;
    this.placeholder = options.placeholder || "";
    this.validation = options.validation;
    this.label = options.label || NLS_DEFAULT_LABEL;
    const appendPreserveCaseLabel = options.appendPreserveCaseLabel || "";
    const history = options.history || [];
    const flexibleHeight = !!options.flexibleHeight;
    const flexibleWidth = !!options.flexibleWidth;
    const flexibleMaxHeight = options.flexibleMaxHeight;
    this.domNode = document.createElement("div");
    this.domNode.classList.add("monaco-findInput");
    this.inputBox = this._register(new HistoryInputBox(this.domNode, this.contextViewProvider, {
      ariaLabel: this.label || "",
      placeholder: this.placeholder || "",
      validationOptions: {
        validation: this.validation
      },
      history,
      showHistoryHint: options.showHistoryHint,
      flexibleHeight,
      flexibleWidth,
      flexibleMaxHeight,
      inputBoxStyles: options.inputBoxStyles
    }));
    this.preserveCase = this._register(new PreserveCaseToggle(Object.assign({ appendTitle: appendPreserveCaseLabel, isChecked: false }, options.toggleStyles)));
    this._register(this.preserveCase.onChange((viaKeyboard) => {
      this._onDidOptionChange.fire(viaKeyboard);
      if (!viaKeyboard && this.fixFocusOnOptionClickEnabled) {
        this.inputBox.focus();
      }
      this.validate();
    }));
    this._register(this.preserveCase.onKeyDown((e) => {
      this._onPreserveCaseKeyDown.fire(e);
    }));
    if (this._showOptionButtons) {
      this.cachedOptionsWidth = this.preserveCase.width();
    } else {
      this.cachedOptionsWidth = 0;
    }
    const indexes = [this.preserveCase.domNode];
    this.onkeydown(this.domNode, (event) => {
      if (event.equals(
        15
        /* KeyCode.LeftArrow */
      ) || event.equals(
        17
        /* KeyCode.RightArrow */
      ) || event.equals(
        9
        /* KeyCode.Escape */
      )) {
        const index = indexes.indexOf(document.activeElement);
        if (index >= 0) {
          let newIndex = -1;
          if (event.equals(
            17
            /* KeyCode.RightArrow */
          )) {
            newIndex = (index + 1) % indexes.length;
          } else if (event.equals(
            15
            /* KeyCode.LeftArrow */
          )) {
            if (index === 0) {
              newIndex = indexes.length - 1;
            } else {
              newIndex = index - 1;
            }
          }
          if (event.equals(
            9
            /* KeyCode.Escape */
          )) {
            indexes[index].blur();
            this.inputBox.focus();
          } else if (newIndex >= 0) {
            indexes[newIndex].focus();
          }
          EventHelper.stop(event, true);
        }
      }
    });
    const controls = document.createElement("div");
    controls.className = "controls";
    controls.style.display = this._showOptionButtons ? "block" : "none";
    controls.appendChild(this.preserveCase.domNode);
    this.domNode.appendChild(controls);
    parent === null || parent === void 0 ? void 0 : parent.appendChild(this.domNode);
    this.onkeydown(this.inputBox.inputElement, (e) => this._onKeyDown.fire(e));
    this.onkeyup(this.inputBox.inputElement, (e) => this._onKeyUp.fire(e));
    this.oninput(this.inputBox.inputElement, (e) => this._onInput.fire());
    this.onmousedown(this.inputBox.inputElement, (e) => this._onMouseDown.fire(e));
  }
  enable() {
    this.domNode.classList.remove("disabled");
    this.inputBox.enable();
    this.preserveCase.enable();
  }
  disable() {
    this.domNode.classList.add("disabled");
    this.inputBox.disable();
    this.preserveCase.disable();
  }
  setEnabled(enabled) {
    if (enabled) {
      this.enable();
    } else {
      this.disable();
    }
  }
  select() {
    this.inputBox.select();
  }
  focus() {
    this.inputBox.focus();
  }
  getPreserveCase() {
    return this.preserveCase.checked;
  }
  setPreserveCase(value) {
    this.preserveCase.checked = value;
  }
  focusOnPreserve() {
    this.preserveCase.focus();
  }
  validate() {
    var _a2;
    (_a2 = this.inputBox) === null || _a2 === void 0 ? void 0 : _a2.validate();
  }
  set width(newWidth) {
    this.inputBox.paddingRight = this.cachedOptionsWidth;
    this.domNode.style.width = newWidth + "px";
  }
  dispose() {
    super.dispose();
  }
}
var __decorate$1h = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1f = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
const historyNavigationVisible = new RawContextKey("suggestWidgetVisible", false, localize("suggestWidgetVisible", "Whether suggestion are visible"));
const HistoryNavigationWidgetFocusContext = "historyNavigationWidgetFocus";
const HistoryNavigationForwardsEnablementContext = "historyNavigationForwardsEnabled";
const HistoryNavigationBackwardsEnablementContext = "historyNavigationBackwardsEnabled";
let lastFocusedWidget = void 0;
const widgets = [];
function registerAndCreateHistoryNavigationContext(scopedContextKeyService, widget) {
  if (widgets.includes(widget)) {
    throw new Error("Cannot register the same widget multiple times");
  }
  widgets.push(widget);
  const disposableStore = new DisposableStore();
  const historyNavigationWidgetFocus = new RawContextKey(HistoryNavigationWidgetFocusContext, false).bindTo(scopedContextKeyService);
  const historyNavigationForwardsEnablement = new RawContextKey(HistoryNavigationForwardsEnablementContext, true).bindTo(scopedContextKeyService);
  const historyNavigationBackwardsEnablement = new RawContextKey(HistoryNavigationBackwardsEnablementContext, true).bindTo(scopedContextKeyService);
  const onDidFocus = () => {
    historyNavigationWidgetFocus.set(true);
    lastFocusedWidget = widget;
  };
  const onDidBlur = () => {
    historyNavigationWidgetFocus.set(false);
    if (lastFocusedWidget === widget) {
      lastFocusedWidget = void 0;
    }
  };
  if (widget.element === document.activeElement) {
    onDidFocus();
  }
  disposableStore.add(widget.onDidFocus(() => onDidFocus()));
  disposableStore.add(widget.onDidBlur(() => onDidBlur()));
  disposableStore.add(toDisposable(() => {
    widgets.splice(widgets.indexOf(widget), 1);
    onDidBlur();
  }));
  return {
    historyNavigationForwardsEnablement,
    historyNavigationBackwardsEnablement,
    dispose() {
      disposableStore.dispose();
    }
  };
}
let ContextScopedFindInput = class ContextScopedFindInput2 extends FindInput {
  constructor(container2, contextViewProvider, options, contextKeyService) {
    super(container2, contextViewProvider, options);
    const scopedContextKeyService = this._register(contextKeyService.createScoped(this.inputBox.element));
    this._register(registerAndCreateHistoryNavigationContext(scopedContextKeyService, this.inputBox));
  }
};
ContextScopedFindInput = __decorate$1h([
  __param$1f(3, IContextKeyService)
], ContextScopedFindInput);
let ContextScopedReplaceInput = class ContextScopedReplaceInput2 extends ReplaceInput {
  constructor(container2, contextViewProvider, options, contextKeyService, showReplaceOptions = false) {
    super(container2, contextViewProvider, showReplaceOptions, options);
    const scopedContextKeyService = this._register(contextKeyService.createScoped(this.inputBox.element));
    this._register(registerAndCreateHistoryNavigationContext(scopedContextKeyService, this.inputBox));
  }
};
ContextScopedReplaceInput = __decorate$1h([
  __param$1f(3, IContextKeyService)
], ContextScopedReplaceInput);
KeybindingsRegistry.registerCommandAndKeybindingRule({
  id: "history.showPrevious",
  weight: 200,
  when: ContextKeyExpr.and(ContextKeyExpr.has(HistoryNavigationWidgetFocusContext), ContextKeyExpr.equals(HistoryNavigationBackwardsEnablementContext, true), historyNavigationVisible.isEqualTo(false)),
  primary: 16,
  secondary: [
    512 | 16
    /* KeyCode.UpArrow */
  ],
  handler: (accessor) => {
    lastFocusedWidget === null || lastFocusedWidget === void 0 ? void 0 : lastFocusedWidget.showPreviousValue();
  }
});
KeybindingsRegistry.registerCommandAndKeybindingRule({
  id: "history.showNext",
  weight: 200,
  when: ContextKeyExpr.and(ContextKeyExpr.has(HistoryNavigationWidgetFocusContext), ContextKeyExpr.equals(HistoryNavigationForwardsEnablementContext, true), historyNavigationVisible.isEqualTo(false)),
  primary: 18,
  secondary: [
    512 | 18
    /* KeyCode.DownArrow */
  ],
  handler: (accessor) => {
    lastFocusedWidget === null || lastFocusedWidget === void 0 ? void 0 : lastFocusedWidget.showNextValue();
  }
});
function showHistoryKeybindingHint(keybindingService) {
  var _a2, _b2;
  return ((_a2 = keybindingService.lookupKeybinding("history.showPrevious")) === null || _a2 === void 0 ? void 0 : _a2.getElectronAccelerator()) === "Up" && ((_b2 = keybindingService.lookupKeybinding("history.showNext")) === null || _b2 === void 0 ? void 0 : _b2.getElectronAccelerator()) === "Down";
}
var __awaiter$R = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
const findSelectionIcon = registerIcon("find-selection", Codicon.selection, localize("findSelectionIcon", "Icon for 'Find in Selection' in the editor find widget."));
const findCollapsedIcon = registerIcon("find-collapsed", Codicon.chevronRight, localize("findCollapsedIcon", "Icon to indicate that the editor find widget is collapsed."));
const findExpandedIcon = registerIcon("find-expanded", Codicon.chevronDown, localize("findExpandedIcon", "Icon to indicate that the editor find widget is expanded."));
const findReplaceIcon = registerIcon("find-replace", Codicon.replace, localize("findReplaceIcon", "Icon for 'Replace' in the editor find widget."));
const findReplaceAllIcon = registerIcon("find-replace-all", Codicon.replaceAll, localize("findReplaceAllIcon", "Icon for 'Replace All' in the editor find widget."));
const findPreviousMatchIcon = registerIcon("find-previous-match", Codicon.arrowUp, localize("findPreviousMatchIcon", "Icon for 'Find Previous' in the editor find widget."));
const findNextMatchIcon = registerIcon("find-next-match", Codicon.arrowDown, localize("findNextMatchIcon", "Icon for 'Find Next' in the editor find widget."));
const NLS_FIND_DIALOG_LABEL = localize("label.findDialog", "Find / Replace");
const NLS_FIND_INPUT_LABEL = localize("label.find", "Find");
const NLS_FIND_INPUT_PLACEHOLDER = localize("placeholder.find", "Find");
const NLS_PREVIOUS_MATCH_BTN_LABEL = localize("label.previousMatchButton", "Previous Match");
const NLS_NEXT_MATCH_BTN_LABEL = localize("label.nextMatchButton", "Next Match");
const NLS_TOGGLE_SELECTION_FIND_TITLE = localize("label.toggleSelectionFind", "Find in Selection");
const NLS_CLOSE_BTN_LABEL = localize("label.closeButton", "Close");
const NLS_REPLACE_INPUT_LABEL = localize("label.replace", "Replace");
const NLS_REPLACE_INPUT_PLACEHOLDER = localize("placeholder.replace", "Replace");
const NLS_REPLACE_BTN_LABEL = localize("label.replaceButton", "Replace");
const NLS_REPLACE_ALL_BTN_LABEL = localize("label.replaceAllButton", "Replace All");
const NLS_TOGGLE_REPLACE_MODE_BTN_LABEL = localize("label.toggleReplaceButton", "Toggle Replace");
const NLS_MATCHES_COUNT_LIMIT_TITLE = localize("title.matchesCountLimit", "Only the first {0} results are highlighted, but all find operations work on the entire text.", MATCHES_LIMIT);
const NLS_MATCHES_LOCATION = localize("label.matchesLocation", "{0} of {1}");
const NLS_NO_RESULTS = localize("label.noResults", "No results");
const FIND_WIDGET_INITIAL_WIDTH = 419;
const PART_WIDTH = 275;
const FIND_INPUT_AREA_WIDTH = PART_WIDTH - 54;
let MAX_MATCHES_COUNT_WIDTH = 69;
const FIND_INPUT_AREA_HEIGHT = 33;
const ctrlEnterReplaceAllWarningPromptedKey = "ctrlEnterReplaceAll.windows.donotask";
const ctrlKeyMod = isMacintosh ? 256 : 2048;
class FindWidgetViewZone {
  constructor(afterLineNumber) {
    this.afterLineNumber = afterLineNumber;
    this.heightInPx = FIND_INPUT_AREA_HEIGHT;
    this.suppressMouseDown = false;
    this.domNode = document.createElement("div");
    this.domNode.className = "dock-find-viewzone";
  }
}
function stopPropagationForMultiLineUpwards(event, value, textarea) {
  const isMultiline = !!value.match(/\n/);
  if (textarea && isMultiline && textarea.selectionStart > 0) {
    event.stopPropagation();
    return;
  }
}
function stopPropagationForMultiLineDownwards(event, value, textarea) {
  const isMultiline = !!value.match(/\n/);
  if (textarea && isMultiline && textarea.selectionEnd < textarea.value.length) {
    event.stopPropagation();
    return;
  }
}
class FindWidget extends Widget$1 {
  constructor(codeEditor, controller, state, contextViewProvider, keybindingService, contextKeyService, themeService, storageService, notificationService) {
    super();
    this._cachedHeight = null;
    this._revealTimeouts = [];
    this._codeEditor = codeEditor;
    this._controller = controller;
    this._state = state;
    this._contextViewProvider = contextViewProvider;
    this._keybindingService = keybindingService;
    this._contextKeyService = contextKeyService;
    this._storageService = storageService;
    this._notificationService = notificationService;
    this._ctrlEnterReplaceAllWarningPrompted = !!storageService.getBoolean(
      ctrlEnterReplaceAllWarningPromptedKey,
      0
      /* StorageScope.PROFILE */
    );
    this._isVisible = false;
    this._isReplaceVisible = false;
    this._ignoreChangeEvent = false;
    this._updateHistoryDelayer = new Delayer(500);
    this._register(toDisposable(() => this._updateHistoryDelayer.cancel()));
    this._register(this._state.onFindReplaceStateChange((e) => this._onStateChanged(e)));
    this._buildDomNode();
    this._updateButtons();
    this._tryUpdateWidgetWidth();
    this._findInput.inputBox.layout();
    this._register(this._codeEditor.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        89
        /* EditorOption.readOnly */
      )) {
        if (this._codeEditor.getOption(
          89
          /* EditorOption.readOnly */
        )) {
          this._state.change({ isReplaceRevealed: false }, false);
        }
        this._updateButtons();
      }
      if (e.hasChanged(
        142
        /* EditorOption.layoutInfo */
      )) {
        this._tryUpdateWidgetWidth();
      }
      if (e.hasChanged(
        2
        /* EditorOption.accessibilitySupport */
      )) {
        this.updateAccessibilitySupport();
      }
      if (e.hasChanged(
        40
        /* EditorOption.find */
      )) {
        const supportLoop = this._codeEditor.getOption(
          40
          /* EditorOption.find */
        ).loop;
        this._state.change({ loop: supportLoop }, false);
        const addExtraSpaceOnTop = this._codeEditor.getOption(
          40
          /* EditorOption.find */
        ).addExtraSpaceOnTop;
        if (addExtraSpaceOnTop && !this._viewZone) {
          this._viewZone = new FindWidgetViewZone(0);
          this._showViewZone();
        }
        if (!addExtraSpaceOnTop && this._viewZone) {
          this._removeViewZone();
        }
      }
    }));
    this.updateAccessibilitySupport();
    this._register(this._codeEditor.onDidChangeCursorSelection(() => {
      if (this._isVisible) {
        this._updateToggleSelectionFindButton();
      }
    }));
    this._register(this._codeEditor.onDidFocusEditorWidget(() => __awaiter$R(this, void 0, void 0, function* () {
      if (this._isVisible) {
        const globalBufferTerm = yield this._controller.getGlobalBufferTerm();
        if (globalBufferTerm && globalBufferTerm !== this._state.searchString) {
          this._state.change({ searchString: globalBufferTerm }, false);
          this._findInput.select();
        }
      }
    })));
    this._findInputFocused = CONTEXT_FIND_INPUT_FOCUSED.bindTo(contextKeyService);
    this._findFocusTracker = this._register(trackFocus(this._findInput.inputBox.inputElement));
    this._register(this._findFocusTracker.onDidFocus(() => {
      this._findInputFocused.set(true);
      this._updateSearchScope();
    }));
    this._register(this._findFocusTracker.onDidBlur(() => {
      this._findInputFocused.set(false);
    }));
    this._replaceInputFocused = CONTEXT_REPLACE_INPUT_FOCUSED.bindTo(contextKeyService);
    this._replaceFocusTracker = this._register(trackFocus(this._replaceInput.inputBox.inputElement));
    this._register(this._replaceFocusTracker.onDidFocus(() => {
      this._replaceInputFocused.set(true);
      this._updateSearchScope();
    }));
    this._register(this._replaceFocusTracker.onDidBlur(() => {
      this._replaceInputFocused.set(false);
    }));
    this._codeEditor.addOverlayWidget(this);
    if (this._codeEditor.getOption(
      40
      /* EditorOption.find */
    ).addExtraSpaceOnTop) {
      this._viewZone = new FindWidgetViewZone(0);
    }
    this._register(this._codeEditor.onDidChangeModel(() => {
      if (!this._isVisible) {
        return;
      }
      this._viewZoneId = void 0;
    }));
    this._register(this._codeEditor.onDidScrollChange((e) => {
      if (e.scrollTopChanged) {
        this._layoutViewZone();
        return;
      }
      setTimeout(() => {
        this._layoutViewZone();
      }, 0);
    }));
  }
  // ----- IOverlayWidget API
  getId() {
    return FindWidget.ID;
  }
  getDomNode() {
    return this._domNode;
  }
  getPosition() {
    if (this._isVisible) {
      return {
        preference: 0
        /* OverlayWidgetPositionPreference.TOP_RIGHT_CORNER */
      };
    }
    return null;
  }
  // ----- React to state changes
  _onStateChanged(e) {
    if (e.searchString) {
      try {
        this._ignoreChangeEvent = true;
        this._findInput.setValue(this._state.searchString);
      } finally {
        this._ignoreChangeEvent = false;
      }
      this._updateButtons();
    }
    if (e.replaceString) {
      this._replaceInput.inputBox.value = this._state.replaceString;
    }
    if (e.isRevealed) {
      if (this._state.isRevealed) {
        this._reveal();
      } else {
        this._hide(true);
      }
    }
    if (e.isReplaceRevealed) {
      if (this._state.isReplaceRevealed) {
        if (!this._codeEditor.getOption(
          89
          /* EditorOption.readOnly */
        ) && !this._isReplaceVisible) {
          this._isReplaceVisible = true;
          this._replaceInput.width = getTotalWidth(this._findInput.domNode);
          this._updateButtons();
          this._replaceInput.inputBox.layout();
        }
      } else {
        if (this._isReplaceVisible) {
          this._isReplaceVisible = false;
          this._updateButtons();
        }
      }
    }
    if ((e.isRevealed || e.isReplaceRevealed) && (this._state.isRevealed || this._state.isReplaceRevealed)) {
      if (this._tryUpdateHeight()) {
        this._showViewZone();
      }
    }
    if (e.isRegex) {
      this._findInput.setRegex(this._state.isRegex);
    }
    if (e.wholeWord) {
      this._findInput.setWholeWords(this._state.wholeWord);
    }
    if (e.matchCase) {
      this._findInput.setCaseSensitive(this._state.matchCase);
    }
    if (e.preserveCase) {
      this._replaceInput.setPreserveCase(this._state.preserveCase);
    }
    if (e.searchScope) {
      if (this._state.searchScope) {
        this._toggleSelectionFind.checked = true;
      } else {
        this._toggleSelectionFind.checked = false;
      }
      this._updateToggleSelectionFindButton();
    }
    if (e.searchString || e.matchesCount || e.matchesPosition) {
      const showRedOutline = this._state.searchString.length > 0 && this._state.matchesCount === 0;
      this._domNode.classList.toggle("no-results", showRedOutline);
      this._updateMatchesCount();
      this._updateButtons();
    }
    if (e.searchString || e.currentMatch) {
      this._layoutViewZone();
    }
    if (e.updateHistory) {
      this._delayedUpdateHistory();
    }
    if (e.loop) {
      this._updateButtons();
    }
  }
  _delayedUpdateHistory() {
    this._updateHistoryDelayer.trigger(this._updateHistory.bind(this)).then(void 0, onUnexpectedError);
  }
  _updateHistory() {
    if (this._state.searchString) {
      this._findInput.inputBox.addToHistory();
    }
    if (this._state.replaceString) {
      this._replaceInput.inputBox.addToHistory();
    }
  }
  _updateMatchesCount() {
    this._matchesCount.style.minWidth = MAX_MATCHES_COUNT_WIDTH + "px";
    if (this._state.matchesCount >= MATCHES_LIMIT) {
      this._matchesCount.title = NLS_MATCHES_COUNT_LIMIT_TITLE;
    } else {
      this._matchesCount.title = "";
    }
    if (this._matchesCount.firstChild) {
      this._matchesCount.removeChild(this._matchesCount.firstChild);
    }
    let label;
    if (this._state.matchesCount > 0) {
      let matchesCount = String(this._state.matchesCount);
      if (this._state.matchesCount >= MATCHES_LIMIT) {
        matchesCount += "+";
      }
      let matchesPosition = String(this._state.matchesPosition);
      if (matchesPosition === "0") {
        matchesPosition = "?";
      }
      label = format$2(NLS_MATCHES_LOCATION, matchesPosition, matchesCount);
    } else {
      label = NLS_NO_RESULTS;
    }
    this._matchesCount.appendChild(document.createTextNode(label));
    alert(this._getAriaLabel(label, this._state.currentMatch, this._state.searchString));
    MAX_MATCHES_COUNT_WIDTH = Math.max(MAX_MATCHES_COUNT_WIDTH, this._matchesCount.clientWidth);
  }
  // ----- actions
  _getAriaLabel(label, currentMatch, searchString) {
    if (label === NLS_NO_RESULTS) {
      return searchString === "" ? localize("ariaSearchNoResultEmpty", "{0} found", label) : localize("ariaSearchNoResult", "{0} found for '{1}'", label, searchString);
    }
    if (currentMatch) {
      const ariaLabel = localize("ariaSearchNoResultWithLineNum", "{0} found for '{1}', at {2}", label, searchString, currentMatch.startLineNumber + ":" + currentMatch.startColumn);
      const model = this._codeEditor.getModel();
      if (model && currentMatch.startLineNumber <= model.getLineCount() && currentMatch.startLineNumber >= 1) {
        const lineContent = model.getLineContent(currentMatch.startLineNumber);
        return `${lineContent}, ${ariaLabel}`;
      }
      return ariaLabel;
    }
    return localize("ariaSearchNoResultWithLineNumNoCurrentMatch", "{0} found for '{1}'", label, searchString);
  }
  /**
   * If 'selection find' is ON we should not disable the button (its function is to cancel 'selection find').
   * If 'selection find' is OFF we enable the button only if there is a selection.
   */
  _updateToggleSelectionFindButton() {
    const selection = this._codeEditor.getSelection();
    const isSelection = selection ? selection.startLineNumber !== selection.endLineNumber || selection.startColumn !== selection.endColumn : false;
    const isChecked = this._toggleSelectionFind.checked;
    if (this._isVisible && (isChecked || isSelection)) {
      this._toggleSelectionFind.enable();
    } else {
      this._toggleSelectionFind.disable();
    }
  }
  _updateButtons() {
    this._findInput.setEnabled(this._isVisible);
    this._replaceInput.setEnabled(this._isVisible && this._isReplaceVisible);
    this._updateToggleSelectionFindButton();
    this._closeBtn.setEnabled(this._isVisible);
    const findInputIsNonEmpty = this._state.searchString.length > 0;
    const matchesCount = this._state.matchesCount ? true : false;
    this._prevBtn.setEnabled(this._isVisible && findInputIsNonEmpty && matchesCount && this._state.canNavigateBack());
    this._nextBtn.setEnabled(this._isVisible && findInputIsNonEmpty && matchesCount && this._state.canNavigateForward());
    this._replaceBtn.setEnabled(this._isVisible && this._isReplaceVisible && findInputIsNonEmpty);
    this._replaceAllBtn.setEnabled(this._isVisible && this._isReplaceVisible && findInputIsNonEmpty);
    this._domNode.classList.toggle("replaceToggled", this._isReplaceVisible);
    this._toggleReplaceBtn.setExpanded(this._isReplaceVisible);
    const canReplace = !this._codeEditor.getOption(
      89
      /* EditorOption.readOnly */
    );
    this._toggleReplaceBtn.setEnabled(this._isVisible && canReplace);
  }
  _reveal() {
    this._revealTimeouts.forEach((e) => {
      clearTimeout(e);
    });
    this._revealTimeouts = [];
    if (!this._isVisible) {
      this._isVisible = true;
      const selection = this._codeEditor.getSelection();
      switch (this._codeEditor.getOption(
        40
        /* EditorOption.find */
      ).autoFindInSelection) {
        case "always":
          this._toggleSelectionFind.checked = true;
          break;
        case "never":
          this._toggleSelectionFind.checked = false;
          break;
        case "multiline": {
          const isSelectionMultipleLine = !!selection && selection.startLineNumber !== selection.endLineNumber;
          this._toggleSelectionFind.checked = isSelectionMultipleLine;
          break;
        }
      }
      this._tryUpdateWidgetWidth();
      this._updateButtons();
      this._revealTimeouts.push(setTimeout(() => {
        this._domNode.classList.add("visible");
        this._domNode.setAttribute("aria-hidden", "false");
      }, 0));
      this._revealTimeouts.push(setTimeout(() => {
        this._findInput.validate();
      }, 200));
      this._codeEditor.layoutOverlayWidget(this);
      let adjustEditorScrollTop = true;
      if (this._codeEditor.getOption(
        40
        /* EditorOption.find */
      ).seedSearchStringFromSelection && selection) {
        const domNode = this._codeEditor.getDomNode();
        if (domNode) {
          const editorCoords = getDomNodePagePosition(domNode);
          const startCoords = this._codeEditor.getScrolledVisiblePosition(selection.getStartPosition());
          const startLeft = editorCoords.left + (startCoords ? startCoords.left : 0);
          const startTop = startCoords ? startCoords.top : 0;
          if (this._viewZone && startTop < this._viewZone.heightInPx) {
            if (selection.endLineNumber > selection.startLineNumber) {
              adjustEditorScrollTop = false;
            }
            const leftOfFindWidget = getTopLeftOffset(this._domNode).left;
            if (startLeft > leftOfFindWidget) {
              adjustEditorScrollTop = false;
            }
            const endCoords = this._codeEditor.getScrolledVisiblePosition(selection.getEndPosition());
            const endLeft = editorCoords.left + (endCoords ? endCoords.left : 0);
            if (endLeft > leftOfFindWidget) {
              adjustEditorScrollTop = false;
            }
          }
        }
      }
      this._showViewZone(adjustEditorScrollTop);
    }
  }
  _hide(focusTheEditor) {
    this._revealTimeouts.forEach((e) => {
      clearTimeout(e);
    });
    this._revealTimeouts = [];
    if (this._isVisible) {
      this._isVisible = false;
      this._updateButtons();
      this._domNode.classList.remove("visible");
      this._domNode.setAttribute("aria-hidden", "true");
      this._findInput.clearMessage();
      if (focusTheEditor) {
        this._codeEditor.focus();
      }
      this._codeEditor.layoutOverlayWidget(this);
      this._removeViewZone();
    }
  }
  _layoutViewZone(targetScrollTop) {
    const addExtraSpaceOnTop = this._codeEditor.getOption(
      40
      /* EditorOption.find */
    ).addExtraSpaceOnTop;
    if (!addExtraSpaceOnTop) {
      this._removeViewZone();
      return;
    }
    if (!this._isVisible) {
      return;
    }
    const viewZone = this._viewZone;
    if (this._viewZoneId !== void 0 || !viewZone) {
      return;
    }
    this._codeEditor.changeViewZones((accessor) => {
      viewZone.heightInPx = this._getHeight();
      this._viewZoneId = accessor.addZone(viewZone);
      this._codeEditor.setScrollTop(targetScrollTop || this._codeEditor.getScrollTop() + viewZone.heightInPx);
    });
  }
  _showViewZone(adjustScroll = true) {
    if (!this._isVisible) {
      return;
    }
    const addExtraSpaceOnTop = this._codeEditor.getOption(
      40
      /* EditorOption.find */
    ).addExtraSpaceOnTop;
    if (!addExtraSpaceOnTop) {
      return;
    }
    if (this._viewZone === void 0) {
      this._viewZone = new FindWidgetViewZone(0);
    }
    const viewZone = this._viewZone;
    this._codeEditor.changeViewZones((accessor) => {
      if (this._viewZoneId !== void 0) {
        const newHeight = this._getHeight();
        if (newHeight === viewZone.heightInPx) {
          return;
        }
        const scrollAdjustment = newHeight - viewZone.heightInPx;
        viewZone.heightInPx = newHeight;
        accessor.layoutZone(this._viewZoneId);
        if (adjustScroll) {
          this._codeEditor.setScrollTop(this._codeEditor.getScrollTop() + scrollAdjustment);
        }
        return;
      } else {
        let scrollAdjustment = this._getHeight();
        scrollAdjustment -= this._codeEditor.getOption(
          82
          /* EditorOption.padding */
        ).top;
        if (scrollAdjustment <= 0) {
          return;
        }
        viewZone.heightInPx = scrollAdjustment;
        this._viewZoneId = accessor.addZone(viewZone);
        if (adjustScroll) {
          this._codeEditor.setScrollTop(this._codeEditor.getScrollTop() + scrollAdjustment);
        }
      }
    });
  }
  _removeViewZone() {
    this._codeEditor.changeViewZones((accessor) => {
      if (this._viewZoneId !== void 0) {
        accessor.removeZone(this._viewZoneId);
        this._viewZoneId = void 0;
        if (this._viewZone) {
          this._codeEditor.setScrollTop(this._codeEditor.getScrollTop() - this._viewZone.heightInPx);
          this._viewZone = void 0;
        }
      }
    });
  }
  _tryUpdateWidgetWidth() {
    if (!this._isVisible) {
      return;
    }
    if (!isInDOM(this._domNode)) {
      return;
    }
    const layoutInfo = this._codeEditor.getLayoutInfo();
    const editorContentWidth = layoutInfo.contentWidth;
    if (editorContentWidth <= 0) {
      this._domNode.classList.add("hiddenEditor");
      return;
    } else if (this._domNode.classList.contains("hiddenEditor")) {
      this._domNode.classList.remove("hiddenEditor");
    }
    const editorWidth = layoutInfo.width;
    const minimapWidth = layoutInfo.minimap.minimapWidth;
    let collapsedFindWidget = false;
    let reducedFindWidget = false;
    let narrowFindWidget = false;
    if (this._resized) {
      const widgetWidth = getTotalWidth(this._domNode);
      if (widgetWidth > FIND_WIDGET_INITIAL_WIDTH) {
        this._domNode.style.maxWidth = `${editorWidth - 28 - minimapWidth - 15}px`;
        this._replaceInput.width = getTotalWidth(this._findInput.domNode);
        return;
      }
    }
    if (FIND_WIDGET_INITIAL_WIDTH + 28 + minimapWidth >= editorWidth) {
      reducedFindWidget = true;
    }
    if (FIND_WIDGET_INITIAL_WIDTH + 28 + minimapWidth - MAX_MATCHES_COUNT_WIDTH >= editorWidth) {
      narrowFindWidget = true;
    }
    if (FIND_WIDGET_INITIAL_WIDTH + 28 + minimapWidth - MAX_MATCHES_COUNT_WIDTH >= editorWidth + 50) {
      collapsedFindWidget = true;
    }
    this._domNode.classList.toggle("collapsed-find-widget", collapsedFindWidget);
    this._domNode.classList.toggle("narrow-find-widget", narrowFindWidget);
    this._domNode.classList.toggle("reduced-find-widget", reducedFindWidget);
    if (!narrowFindWidget && !collapsedFindWidget) {
      this._domNode.style.maxWidth = `${editorWidth - 28 - minimapWidth - 15}px`;
    }
    this._findInput.layout({ collapsedFindWidget, narrowFindWidget, reducedFindWidget });
    if (this._resized) {
      const findInputWidth = this._findInput.inputBox.element.clientWidth;
      if (findInputWidth > 0) {
        this._replaceInput.width = findInputWidth;
      }
    } else if (this._isReplaceVisible) {
      this._replaceInput.width = getTotalWidth(this._findInput.domNode);
    }
  }
  _getHeight() {
    let totalheight = 0;
    totalheight += 4;
    totalheight += this._findInput.inputBox.height + 2;
    if (this._isReplaceVisible) {
      totalheight += 4;
      totalheight += this._replaceInput.inputBox.height + 2;
    }
    totalheight += 4;
    return totalheight;
  }
  _tryUpdateHeight() {
    const totalHeight = this._getHeight();
    if (this._cachedHeight !== null && this._cachedHeight === totalHeight) {
      return false;
    }
    this._cachedHeight = totalHeight;
    this._domNode.style.height = `${totalHeight}px`;
    return true;
  }
  // ----- Public
  focusFindInput() {
    this._findInput.select();
    this._findInput.focus();
  }
  focusReplaceInput() {
    this._replaceInput.select();
    this._replaceInput.focus();
  }
  highlightFindOptions() {
    this._findInput.highlightFindOptions();
  }
  _updateSearchScope() {
    if (!this._codeEditor.hasModel()) {
      return;
    }
    if (this._toggleSelectionFind.checked) {
      const selections2 = this._codeEditor.getSelections();
      selections2.map((selection) => {
        if (selection.endColumn === 1 && selection.endLineNumber > selection.startLineNumber) {
          selection = selection.setEndPosition(selection.endLineNumber - 1, this._codeEditor.getModel().getLineMaxColumn(selection.endLineNumber - 1));
        }
        const currentMatch = this._state.currentMatch;
        if (selection.startLineNumber !== selection.endLineNumber) {
          if (!Range$2.equalsRange(selection, currentMatch)) {
            return selection;
          }
        }
        return null;
      }).filter((element) => !!element);
      if (selections2.length) {
        this._state.change({ searchScope: selections2 }, true);
      }
    }
  }
  _onFindInputMouseDown(e) {
    if (e.middleButton) {
      e.stopPropagation();
    }
  }
  _onFindInputKeyDown(e) {
    if (e.equals(
      ctrlKeyMod | 3
      /* KeyCode.Enter */
    )) {
      if (this._keybindingService.dispatchEvent(e, e.target)) {
        e.preventDefault();
        return;
      } else {
        this._findInput.inputBox.insertAtCursor("\n");
        e.preventDefault();
        return;
      }
    }
    if (e.equals(
      2
      /* KeyCode.Tab */
    )) {
      if (this._isReplaceVisible) {
        this._replaceInput.focus();
      } else {
        this._findInput.focusOnCaseSensitive();
      }
      e.preventDefault();
      return;
    }
    if (e.equals(
      2048 | 18
      /* KeyCode.DownArrow */
    )) {
      this._codeEditor.focus();
      e.preventDefault();
      return;
    }
    if (e.equals(
      16
      /* KeyCode.UpArrow */
    )) {
      return stopPropagationForMultiLineUpwards(e, this._findInput.getValue(), this._findInput.domNode.querySelector("textarea"));
    }
    if (e.equals(
      18
      /* KeyCode.DownArrow */
    )) {
      return stopPropagationForMultiLineDownwards(e, this._findInput.getValue(), this._findInput.domNode.querySelector("textarea"));
    }
  }
  _onReplaceInputKeyDown(e) {
    if (e.equals(
      ctrlKeyMod | 3
      /* KeyCode.Enter */
    )) {
      if (this._keybindingService.dispatchEvent(e, e.target)) {
        e.preventDefault();
        return;
      } else {
        if (isWindows && isNative && !this._ctrlEnterReplaceAllWarningPrompted) {
          this._notificationService.info(localize("ctrlEnter.keybindingChanged", "Ctrl+Enter now inserts line break instead of replacing all. You can modify the keybinding for editor.action.replaceAll to override this behavior."));
          this._ctrlEnterReplaceAllWarningPrompted = true;
          this._storageService.store(
            ctrlEnterReplaceAllWarningPromptedKey,
            true,
            0,
            0
            /* StorageTarget.USER */
          );
        }
        this._replaceInput.inputBox.insertAtCursor("\n");
        e.preventDefault();
        return;
      }
    }
    if (e.equals(
      2
      /* KeyCode.Tab */
    )) {
      this._findInput.focusOnCaseSensitive();
      e.preventDefault();
      return;
    }
    if (e.equals(
      1024 | 2
      /* KeyCode.Tab */
    )) {
      this._findInput.focus();
      e.preventDefault();
      return;
    }
    if (e.equals(
      2048 | 18
      /* KeyCode.DownArrow */
    )) {
      this._codeEditor.focus();
      e.preventDefault();
      return;
    }
    if (e.equals(
      16
      /* KeyCode.UpArrow */
    )) {
      return stopPropagationForMultiLineUpwards(e, this._replaceInput.inputBox.value, this._replaceInput.inputBox.element.querySelector("textarea"));
    }
    if (e.equals(
      18
      /* KeyCode.DownArrow */
    )) {
      return stopPropagationForMultiLineDownwards(e, this._replaceInput.inputBox.value, this._replaceInput.inputBox.element.querySelector("textarea"));
    }
  }
  // ----- sash
  getVerticalSashLeft(_sash) {
    return 0;
  }
  // ----- initialization
  _keybindingLabelFor(actionId) {
    const kb = this._keybindingService.lookupKeybinding(actionId);
    if (!kb) {
      return "";
    }
    return ` (${kb.getLabel()})`;
  }
  _buildDomNode() {
    const flexibleHeight = true;
    const flexibleWidth = true;
    this._findInput = this._register(new ContextScopedFindInput(null, this._contextViewProvider, {
      width: FIND_INPUT_AREA_WIDTH,
      label: NLS_FIND_INPUT_LABEL,
      placeholder: NLS_FIND_INPUT_PLACEHOLDER,
      appendCaseSensitiveLabel: this._keybindingLabelFor(FIND_IDS.ToggleCaseSensitiveCommand),
      appendWholeWordsLabel: this._keybindingLabelFor(FIND_IDS.ToggleWholeWordCommand),
      appendRegexLabel: this._keybindingLabelFor(FIND_IDS.ToggleRegexCommand),
      validation: (value) => {
        if (value.length === 0 || !this._findInput.getRegex()) {
          return null;
        }
        try {
          new RegExp(value, "gu");
          return null;
        } catch (e) {
          return { content: e.message };
        }
      },
      flexibleHeight,
      flexibleWidth,
      flexibleMaxHeight: 118,
      showCommonFindToggles: true,
      showHistoryHint: () => showHistoryKeybindingHint(this._keybindingService),
      inputBoxStyles: defaultInputBoxStyles,
      toggleStyles: defaultToggleStyles
    }, this._contextKeyService));
    this._findInput.setRegex(!!this._state.isRegex);
    this._findInput.setCaseSensitive(!!this._state.matchCase);
    this._findInput.setWholeWords(!!this._state.wholeWord);
    this._register(this._findInput.onKeyDown((e) => this._onFindInputKeyDown(e)));
    this._register(this._findInput.inputBox.onDidChange(() => {
      if (this._ignoreChangeEvent) {
        return;
      }
      this._state.change({ searchString: this._findInput.getValue() }, true);
    }));
    this._register(this._findInput.onDidOptionChange(() => {
      this._state.change({
        isRegex: this._findInput.getRegex(),
        wholeWord: this._findInput.getWholeWords(),
        matchCase: this._findInput.getCaseSensitive()
      }, true);
    }));
    this._register(this._findInput.onCaseSensitiveKeyDown((e) => {
      if (e.equals(
        1024 | 2
        /* KeyCode.Tab */
      )) {
        if (this._isReplaceVisible) {
          this._replaceInput.focus();
          e.preventDefault();
        }
      }
    }));
    this._register(this._findInput.onRegexKeyDown((e) => {
      if (e.equals(
        2
        /* KeyCode.Tab */
      )) {
        if (this._isReplaceVisible) {
          this._replaceInput.focusOnPreserve();
          e.preventDefault();
        }
      }
    }));
    this._register(this._findInput.inputBox.onDidHeightChange((e) => {
      if (this._tryUpdateHeight()) {
        this._showViewZone();
      }
    }));
    if (isLinux) {
      this._register(this._findInput.onMouseDown((e) => this._onFindInputMouseDown(e)));
    }
    this._matchesCount = document.createElement("div");
    this._matchesCount.className = "matchesCount";
    this._updateMatchesCount();
    this._prevBtn = this._register(new SimpleButton({
      label: NLS_PREVIOUS_MATCH_BTN_LABEL + this._keybindingLabelFor(FIND_IDS.PreviousMatchFindAction),
      icon: findPreviousMatchIcon,
      onTrigger: () => {
        assertIsDefined(this._codeEditor.getAction(FIND_IDS.PreviousMatchFindAction)).run().then(void 0, onUnexpectedError);
      }
    }));
    this._nextBtn = this._register(new SimpleButton({
      label: NLS_NEXT_MATCH_BTN_LABEL + this._keybindingLabelFor(FIND_IDS.NextMatchFindAction),
      icon: findNextMatchIcon,
      onTrigger: () => {
        assertIsDefined(this._codeEditor.getAction(FIND_IDS.NextMatchFindAction)).run().then(void 0, onUnexpectedError);
      }
    }));
    const findPart = document.createElement("div");
    findPart.className = "find-part";
    findPart.appendChild(this._findInput.domNode);
    const actionsContainer = document.createElement("div");
    actionsContainer.className = "find-actions";
    findPart.appendChild(actionsContainer);
    actionsContainer.appendChild(this._matchesCount);
    actionsContainer.appendChild(this._prevBtn.domNode);
    actionsContainer.appendChild(this._nextBtn.domNode);
    this._toggleSelectionFind = this._register(new Toggle({
      icon: findSelectionIcon,
      title: NLS_TOGGLE_SELECTION_FIND_TITLE + this._keybindingLabelFor(FIND_IDS.ToggleSearchScopeCommand),
      isChecked: false,
      inputActiveOptionBackground: asCssVariable(inputActiveOptionBackground),
      inputActiveOptionBorder: asCssVariable(inputActiveOptionBorder),
      inputActiveOptionForeground: asCssVariable(inputActiveOptionForeground)
    }));
    this._register(this._toggleSelectionFind.onChange(() => {
      if (this._toggleSelectionFind.checked) {
        if (this._codeEditor.hasModel()) {
          const selections2 = this._codeEditor.getSelections();
          selections2.map((selection) => {
            if (selection.endColumn === 1 && selection.endLineNumber > selection.startLineNumber) {
              selection = selection.setEndPosition(selection.endLineNumber - 1, this._codeEditor.getModel().getLineMaxColumn(selection.endLineNumber - 1));
            }
            if (!selection.isEmpty()) {
              return selection;
            }
            return null;
          }).filter((element) => !!element);
          if (selections2.length) {
            this._state.change({ searchScope: selections2 }, true);
          }
        }
      } else {
        this._state.change({ searchScope: null }, true);
      }
    }));
    actionsContainer.appendChild(this._toggleSelectionFind.domNode);
    this._closeBtn = this._register(new SimpleButton({
      label: NLS_CLOSE_BTN_LABEL + this._keybindingLabelFor(FIND_IDS.CloseFindWidgetCommand),
      icon: widgetClose,
      onTrigger: () => {
        this._state.change({ isRevealed: false, searchScope: null }, false);
      },
      onKeyDown: (e) => {
        if (e.equals(
          2
          /* KeyCode.Tab */
        )) {
          if (this._isReplaceVisible) {
            if (this._replaceBtn.isEnabled()) {
              this._replaceBtn.focus();
            } else {
              this._codeEditor.focus();
            }
            e.preventDefault();
          }
        }
      }
    }));
    this._replaceInput = this._register(new ContextScopedReplaceInput(null, void 0, {
      label: NLS_REPLACE_INPUT_LABEL,
      placeholder: NLS_REPLACE_INPUT_PLACEHOLDER,
      appendPreserveCaseLabel: this._keybindingLabelFor(FIND_IDS.TogglePreserveCaseCommand),
      history: [],
      flexibleHeight,
      flexibleWidth,
      flexibleMaxHeight: 118,
      showHistoryHint: () => showHistoryKeybindingHint(this._keybindingService),
      inputBoxStyles: defaultInputBoxStyles,
      toggleStyles: defaultToggleStyles
    }, this._contextKeyService, true));
    this._replaceInput.setPreserveCase(!!this._state.preserveCase);
    this._register(this._replaceInput.onKeyDown((e) => this._onReplaceInputKeyDown(e)));
    this._register(this._replaceInput.inputBox.onDidChange(() => {
      this._state.change({ replaceString: this._replaceInput.inputBox.value }, false);
    }));
    this._register(this._replaceInput.inputBox.onDidHeightChange((e) => {
      if (this._isReplaceVisible && this._tryUpdateHeight()) {
        this._showViewZone();
      }
    }));
    this._register(this._replaceInput.onDidOptionChange(() => {
      this._state.change({
        preserveCase: this._replaceInput.getPreserveCase()
      }, true);
    }));
    this._register(this._replaceInput.onPreserveCaseKeyDown((e) => {
      if (e.equals(
        2
        /* KeyCode.Tab */
      )) {
        if (this._prevBtn.isEnabled()) {
          this._prevBtn.focus();
        } else if (this._nextBtn.isEnabled()) {
          this._nextBtn.focus();
        } else if (this._toggleSelectionFind.enabled) {
          this._toggleSelectionFind.focus();
        } else if (this._closeBtn.isEnabled()) {
          this._closeBtn.focus();
        }
        e.preventDefault();
      }
    }));
    this._replaceBtn = this._register(new SimpleButton({
      label: NLS_REPLACE_BTN_LABEL + this._keybindingLabelFor(FIND_IDS.ReplaceOneAction),
      icon: findReplaceIcon,
      onTrigger: () => {
        this._controller.replace();
      },
      onKeyDown: (e) => {
        if (e.equals(
          1024 | 2
          /* KeyCode.Tab */
        )) {
          this._closeBtn.focus();
          e.preventDefault();
        }
      }
    }));
    this._replaceAllBtn = this._register(new SimpleButton({
      label: NLS_REPLACE_ALL_BTN_LABEL + this._keybindingLabelFor(FIND_IDS.ReplaceAllAction),
      icon: findReplaceAllIcon,
      onTrigger: () => {
        this._controller.replaceAll();
      }
    }));
    const replacePart = document.createElement("div");
    replacePart.className = "replace-part";
    replacePart.appendChild(this._replaceInput.domNode);
    const replaceActionsContainer = document.createElement("div");
    replaceActionsContainer.className = "replace-actions";
    replacePart.appendChild(replaceActionsContainer);
    replaceActionsContainer.appendChild(this._replaceBtn.domNode);
    replaceActionsContainer.appendChild(this._replaceAllBtn.domNode);
    this._toggleReplaceBtn = this._register(new SimpleButton({
      label: NLS_TOGGLE_REPLACE_MODE_BTN_LABEL,
      className: "codicon toggle left",
      onTrigger: () => {
        this._state.change({ isReplaceRevealed: !this._isReplaceVisible }, false);
        if (this._isReplaceVisible) {
          this._replaceInput.width = getTotalWidth(this._findInput.domNode);
          this._replaceInput.inputBox.layout();
        }
        this._showViewZone();
      }
    }));
    this._toggleReplaceBtn.setExpanded(this._isReplaceVisible);
    this._domNode = document.createElement("div");
    this._domNode.className = "editor-widget find-widget";
    this._domNode.setAttribute("aria-hidden", "true");
    this._domNode.ariaLabel = NLS_FIND_DIALOG_LABEL;
    this._domNode.role = "dialog";
    this._domNode.style.width = `${FIND_WIDGET_INITIAL_WIDTH}px`;
    this._domNode.appendChild(this._toggleReplaceBtn.domNode);
    this._domNode.appendChild(findPart);
    this._domNode.appendChild(this._closeBtn.domNode);
    this._domNode.appendChild(replacePart);
    this._resizeSash = new Sash(this._domNode, this, { orientation: 0, size: 2 });
    this._resized = false;
    let originalWidth = FIND_WIDGET_INITIAL_WIDTH;
    this._register(this._resizeSash.onDidStart(() => {
      originalWidth = getTotalWidth(this._domNode);
    }));
    this._register(this._resizeSash.onDidChange((evt) => {
      this._resized = true;
      const width = originalWidth + evt.startX - evt.currentX;
      if (width < FIND_WIDGET_INITIAL_WIDTH) {
        return;
      }
      const maxWidth = parseFloat(getComputedStyle$1(this._domNode).maxWidth) || 0;
      if (width > maxWidth) {
        return;
      }
      this._domNode.style.width = `${width}px`;
      if (this._isReplaceVisible) {
        this._replaceInput.width = getTotalWidth(this._findInput.domNode);
      }
      this._findInput.inputBox.layout();
      this._tryUpdateHeight();
    }));
    this._register(this._resizeSash.onDidReset(() => {
      const currentWidth = getTotalWidth(this._domNode);
      if (currentWidth < FIND_WIDGET_INITIAL_WIDTH) {
        return;
      }
      let width = FIND_WIDGET_INITIAL_WIDTH;
      if (!this._resized || currentWidth === FIND_WIDGET_INITIAL_WIDTH) {
        const layoutInfo = this._codeEditor.getLayoutInfo();
        width = layoutInfo.width - 28 - layoutInfo.minimap.minimapWidth - 15;
        this._resized = true;
      }
      this._domNode.style.width = `${width}px`;
      if (this._isReplaceVisible) {
        this._replaceInput.width = getTotalWidth(this._findInput.domNode);
      }
      this._findInput.inputBox.layout();
    }));
  }
  updateAccessibilitySupport() {
    const value = this._codeEditor.getOption(
      2
      /* EditorOption.accessibilitySupport */
    );
    this._findInput.setFocusInputOnOptionClick(
      value !== 2
      /* AccessibilitySupport.Enabled */
    );
  }
}
FindWidget.ID = "editor.contrib.findWidget";
class SimpleButton extends Widget$1 {
  constructor(opts) {
    super();
    this._opts = opts;
    let className3 = "button";
    if (this._opts.className) {
      className3 = className3 + " " + this._opts.className;
    }
    if (this._opts.icon) {
      className3 = className3 + " " + ThemeIcon.asClassName(this._opts.icon);
    }
    this._domNode = document.createElement("div");
    this._domNode.title = this._opts.label;
    this._domNode.tabIndex = 0;
    this._domNode.className = className3;
    this._domNode.setAttribute("role", "button");
    this._domNode.setAttribute("aria-label", this._opts.label);
    this.onclick(this._domNode, (e) => {
      this._opts.onTrigger();
      e.preventDefault();
    });
    this.onkeydown(this._domNode, (e) => {
      var _a2, _b2;
      if (e.equals(
        10
        /* KeyCode.Space */
      ) || e.equals(
        3
        /* KeyCode.Enter */
      )) {
        this._opts.onTrigger();
        e.preventDefault();
        return;
      }
      (_b2 = (_a2 = this._opts).onKeyDown) === null || _b2 === void 0 ? void 0 : _b2.call(_a2, e);
    });
  }
  get domNode() {
    return this._domNode;
  }
  isEnabled() {
    return this._domNode.tabIndex >= 0;
  }
  focus() {
    this._domNode.focus();
  }
  setEnabled(enabled) {
    this._domNode.classList.toggle("disabled", !enabled);
    this._domNode.setAttribute("aria-disabled", String(!enabled));
    this._domNode.tabIndex = enabled ? 0 : -1;
  }
  setExpanded(expanded) {
    this._domNode.setAttribute("aria-expanded", String(!!expanded));
    if (expanded) {
      this._domNode.classList.remove(...ThemeIcon.asClassNameArray(findCollapsedIcon));
      this._domNode.classList.add(...ThemeIcon.asClassNameArray(findExpandedIcon));
    } else {
      this._domNode.classList.remove(...ThemeIcon.asClassNameArray(findExpandedIcon));
      this._domNode.classList.add(...ThemeIcon.asClassNameArray(findCollapsedIcon));
    }
  }
}
registerThemingParticipant((theme, collector) => {
  const addBackgroundColorRule = (selector3, color) => {
    if (color) {
      collector.addRule(`.monaco-editor ${selector3} { background-color: ${color}; }`);
    }
  };
  addBackgroundColorRule(".findMatch", theme.getColor(editorFindMatchHighlight));
  addBackgroundColorRule(".currentFindMatch", theme.getColor(editorFindMatch));
  addBackgroundColorRule(".findScope", theme.getColor(editorFindRangeHighlight));
  const widgetBackground = theme.getColor(editorWidgetBackground);
  addBackgroundColorRule(".find-widget", widgetBackground);
  const widgetShadowColor = theme.getColor(widgetShadow);
  if (widgetShadowColor) {
    collector.addRule(`.monaco-editor .find-widget { box-shadow: 0 0 8px 2px ${widgetShadowColor}; }`);
  }
  const widgetBorderColor = theme.getColor(widgetBorder);
  if (widgetBorderColor) {
    collector.addRule(`.monaco-editor .find-widget { border-left: 1px solid ${widgetBorderColor}; border-right: 1px solid ${widgetBorderColor}; border-bottom: 1px solid ${widgetBorderColor}; }`);
  }
  const findMatchHighlightBorder = theme.getColor(editorFindMatchHighlightBorder);
  if (findMatchHighlightBorder) {
    collector.addRule(`.monaco-editor .findMatch { border: 1px ${isHighContrast(theme.type) ? "dotted" : "solid"} ${findMatchHighlightBorder}; box-sizing: border-box; }`);
  }
  const findMatchBorder = theme.getColor(editorFindMatchBorder);
  if (findMatchBorder) {
    collector.addRule(`.monaco-editor .currentFindMatch { border: 2px solid ${findMatchBorder}; padding: 1px; box-sizing: border-box; }`);
  }
  const findRangeHighlightBorder = theme.getColor(editorFindRangeHighlightBorder);
  if (findRangeHighlightBorder) {
    collector.addRule(`.monaco-editor .findScope { border: 1px ${isHighContrast(theme.type) ? "dashed" : "solid"} ${findRangeHighlightBorder}; }`);
  }
  const hcBorder = theme.getColor(contrastBorder);
  if (hcBorder) {
    collector.addRule(`.monaco-editor .find-widget { border: 1px solid ${hcBorder}; }`);
  }
  const foreground2 = theme.getColor(editorWidgetForeground);
  if (foreground2) {
    collector.addRule(`.monaco-editor .find-widget { color: ${foreground2}; }`);
  }
  const error2 = theme.getColor(errorForeground);
  if (error2) {
    collector.addRule(`.monaco-editor .find-widget.no-results .matchesCount { color: ${error2}; }`);
  }
  const resizeBorderBackground = theme.getColor(editorWidgetResizeBorder);
  if (resizeBorderBackground) {
    collector.addRule(`.monaco-editor .find-widget .monaco-sash { background-color: ${resizeBorderBackground}; }`);
  } else {
    const border = theme.getColor(editorWidgetBorder);
    if (border) {
      collector.addRule(`.monaco-editor .find-widget .monaco-sash { background-color: ${border}; }`);
    }
  }
  const toolbarHoverBackgroundColor = theme.getColor(toolbarHoverBackground);
  if (toolbarHoverBackgroundColor) {
    collector.addRule(`
		.monaco-editor .find-widget .button:not(.disabled):hover,
		.monaco-editor .find-widget .codicon-find-selection:hover {
			background-color: ${toolbarHoverBackgroundColor} !important;
		}
	`);
  }
  const focusOutline = theme.getColor(focusBorder);
  if (focusOutline) {
    collector.addRule(`.monaco-editor .find-widget .monaco-inputbox.synthetic-focus { outline-color: ${focusOutline}; }`);
  }
});
var __decorate$1g = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1e = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$Q = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
const SEARCH_STRING_MAX_LENGTH = 524288;
function getSelectionSearchString(editor2, seedSearchStringFromSelection = "single", seedSearchStringFromNonEmptySelection = false) {
  if (!editor2.hasModel()) {
    return null;
  }
  const selection = editor2.getSelection();
  if (seedSearchStringFromSelection === "single" && selection.startLineNumber === selection.endLineNumber || seedSearchStringFromSelection === "multiple") {
    if (selection.isEmpty()) {
      const wordAtPosition = editor2.getConfiguredWordAtPosition(selection.getStartPosition());
      if (wordAtPosition && false === seedSearchStringFromNonEmptySelection) {
        return wordAtPosition.word;
      }
    } else {
      if (editor2.getModel().getValueLengthInRange(selection) < SEARCH_STRING_MAX_LENGTH) {
        return editor2.getModel().getValueInRange(selection);
      }
    }
  }
  return null;
}
let CommonFindController = class CommonFindController2 extends Disposable {
  get editor() {
    return this._editor;
  }
  static get(editor2) {
    return editor2.getContribution(CommonFindController2.ID);
  }
  constructor(editor2, contextKeyService, storageService, clipboardService) {
    super();
    this._editor = editor2;
    this._findWidgetVisible = CONTEXT_FIND_WIDGET_VISIBLE.bindTo(contextKeyService);
    this._contextKeyService = contextKeyService;
    this._storageService = storageService;
    this._clipboardService = clipboardService;
    this._updateHistoryDelayer = new Delayer(500);
    this._state = this._register(new FindReplaceState());
    this.loadQueryState();
    this._register(this._state.onFindReplaceStateChange((e) => this._onStateChanged(e)));
    this._model = null;
    this._register(this._editor.onDidChangeModel(() => {
      const shouldRestartFind = this._editor.getModel() && this._state.isRevealed;
      this.disposeModel();
      this._state.change({
        searchScope: null,
        matchCase: this._storageService.getBoolean("editor.matchCase", 1, false),
        wholeWord: this._storageService.getBoolean("editor.wholeWord", 1, false),
        isRegex: this._storageService.getBoolean("editor.isRegex", 1, false),
        preserveCase: this._storageService.getBoolean("editor.preserveCase", 1, false)
      }, false);
      if (shouldRestartFind) {
        this._start({
          forceRevealReplace: false,
          seedSearchStringFromSelection: "none",
          seedSearchStringFromNonEmptySelection: false,
          seedSearchStringFromGlobalClipboard: false,
          shouldFocus: 0,
          shouldAnimate: false,
          updateSearchScope: false,
          loop: this._editor.getOption(
            40
            /* EditorOption.find */
          ).loop
        });
      }
    }));
  }
  dispose() {
    this.disposeModel();
    super.dispose();
  }
  disposeModel() {
    if (this._model) {
      this._model.dispose();
      this._model = null;
    }
  }
  _onStateChanged(e) {
    this.saveQueryState(e);
    if (e.isRevealed) {
      if (this._state.isRevealed) {
        this._findWidgetVisible.set(true);
      } else {
        this._findWidgetVisible.reset();
        this.disposeModel();
      }
    }
    if (e.searchString) {
      this.setGlobalBufferTerm(this._state.searchString);
    }
  }
  saveQueryState(e) {
    if (e.isRegex) {
      this._storageService.store(
        "editor.isRegex",
        this._state.actualIsRegex,
        1,
        1
        /* StorageTarget.MACHINE */
      );
    }
    if (e.wholeWord) {
      this._storageService.store(
        "editor.wholeWord",
        this._state.actualWholeWord,
        1,
        1
        /* StorageTarget.MACHINE */
      );
    }
    if (e.matchCase) {
      this._storageService.store(
        "editor.matchCase",
        this._state.actualMatchCase,
        1,
        1
        /* StorageTarget.MACHINE */
      );
    }
    if (e.preserveCase) {
      this._storageService.store(
        "editor.preserveCase",
        this._state.actualPreserveCase,
        1,
        1
        /* StorageTarget.MACHINE */
      );
    }
  }
  loadQueryState() {
    this._state.change({
      matchCase: this._storageService.getBoolean("editor.matchCase", 1, this._state.matchCase),
      wholeWord: this._storageService.getBoolean("editor.wholeWord", 1, this._state.wholeWord),
      isRegex: this._storageService.getBoolean("editor.isRegex", 1, this._state.isRegex),
      preserveCase: this._storageService.getBoolean("editor.preserveCase", 1, this._state.preserveCase)
    }, false);
  }
  isFindInputFocused() {
    return !!CONTEXT_FIND_INPUT_FOCUSED.getValue(this._contextKeyService);
  }
  getState() {
    return this._state;
  }
  closeFindWidget() {
    this._state.change({
      isRevealed: false,
      searchScope: null
    }, false);
    this._editor.focus();
  }
  toggleCaseSensitive() {
    this._state.change({ matchCase: !this._state.matchCase }, false);
    if (!this._state.isRevealed) {
      this.highlightFindOptions();
    }
  }
  toggleWholeWords() {
    this._state.change({ wholeWord: !this._state.wholeWord }, false);
    if (!this._state.isRevealed) {
      this.highlightFindOptions();
    }
  }
  toggleRegex() {
    this._state.change({ isRegex: !this._state.isRegex }, false);
    if (!this._state.isRevealed) {
      this.highlightFindOptions();
    }
  }
  togglePreserveCase() {
    this._state.change({ preserveCase: !this._state.preserveCase }, false);
    if (!this._state.isRevealed) {
      this.highlightFindOptions();
    }
  }
  toggleSearchScope() {
    if (this._state.searchScope) {
      this._state.change({ searchScope: null }, true);
    } else {
      if (this._editor.hasModel()) {
        const selections2 = this._editor.getSelections();
        selections2.map((selection) => {
          if (selection.endColumn === 1 && selection.endLineNumber > selection.startLineNumber) {
            selection = selection.setEndPosition(selection.endLineNumber - 1, this._editor.getModel().getLineMaxColumn(selection.endLineNumber - 1));
          }
          if (!selection.isEmpty()) {
            return selection;
          }
          return null;
        }).filter((element) => !!element);
        if (selections2.length) {
          this._state.change({ searchScope: selections2 }, true);
        }
      }
    }
  }
  setSearchString(searchString) {
    if (this._state.isRegex) {
      searchString = escapeRegExpCharacters(searchString);
    }
    this._state.change({ searchString }, false);
  }
  highlightFindOptions(ignoreWhenVisible = false) {
  }
  _start(opts, newState) {
    return __awaiter$Q(this, void 0, void 0, function* () {
      this.disposeModel();
      if (!this._editor.hasModel()) {
        return;
      }
      const stateChanges = Object.assign(Object.assign({}, newState), { isRevealed: true });
      if (opts.seedSearchStringFromSelection === "single") {
        const selectionSearchString = getSelectionSearchString(this._editor, opts.seedSearchStringFromSelection, opts.seedSearchStringFromNonEmptySelection);
        if (selectionSearchString) {
          if (this._state.isRegex) {
            stateChanges.searchString = escapeRegExpCharacters(selectionSearchString);
          } else {
            stateChanges.searchString = selectionSearchString;
          }
        }
      } else if (opts.seedSearchStringFromSelection === "multiple" && !opts.updateSearchScope) {
        const selectionSearchString = getSelectionSearchString(this._editor, opts.seedSearchStringFromSelection);
        if (selectionSearchString) {
          stateChanges.searchString = selectionSearchString;
        }
      }
      if (!stateChanges.searchString && opts.seedSearchStringFromGlobalClipboard) {
        const selectionSearchString = yield this.getGlobalBufferTerm();
        if (!this._editor.hasModel()) {
          return;
        }
        if (selectionSearchString) {
          stateChanges.searchString = selectionSearchString;
        }
      }
      if (opts.forceRevealReplace || stateChanges.isReplaceRevealed) {
        stateChanges.isReplaceRevealed = true;
      } else if (!this._findWidgetVisible.get()) {
        stateChanges.isReplaceRevealed = false;
      }
      if (opts.updateSearchScope) {
        const currentSelections = this._editor.getSelections();
        if (currentSelections.some((selection) => !selection.isEmpty())) {
          stateChanges.searchScope = currentSelections;
        }
      }
      stateChanges.loop = opts.loop;
      this._state.change(stateChanges, false);
      if (!this._model) {
        this._model = new FindModelBoundToEditorModel(this._editor, this._state);
      }
    });
  }
  start(opts, newState) {
    return this._start(opts, newState);
  }
  moveToNextMatch() {
    if (this._model) {
      this._model.moveToNextMatch();
      return true;
    }
    return false;
  }
  moveToPrevMatch() {
    if (this._model) {
      this._model.moveToPrevMatch();
      return true;
    }
    return false;
  }
  goToMatch(index) {
    if (this._model) {
      this._model.moveToMatch(index);
      return true;
    }
    return false;
  }
  replace() {
    if (this._model) {
      this._model.replace();
      return true;
    }
    return false;
  }
  replaceAll() {
    if (this._model) {
      this._model.replaceAll();
      return true;
    }
    return false;
  }
  selectAllMatches() {
    if (this._model) {
      this._model.selectAllMatches();
      this._editor.focus();
      return true;
    }
    return false;
  }
  getGlobalBufferTerm() {
    return __awaiter$Q(this, void 0, void 0, function* () {
      if (this._editor.getOption(
        40
        /* EditorOption.find */
      ).globalFindClipboard && this._editor.hasModel() && !this._editor.getModel().isTooLargeForSyncing()) {
        return this._clipboardService.readFindText();
      }
      return "";
    });
  }
  setGlobalBufferTerm(text2) {
    if (this._editor.getOption(
      40
      /* EditorOption.find */
    ).globalFindClipboard && this._editor.hasModel() && !this._editor.getModel().isTooLargeForSyncing()) {
      this._clipboardService.writeFindText(text2);
    }
  }
};
CommonFindController.ID = "editor.contrib.findController";
CommonFindController = __decorate$1g([
  __param$1e(1, IContextKeyService),
  __param$1e(2, IStorageService),
  __param$1e(3, IClipboardService)
], CommonFindController);
let FindController2 = class FindController3 extends CommonFindController {
  constructor(editor2, _contextViewService, _contextKeyService, _keybindingService, _themeService, _notificationService, _storageService, clipboardService) {
    super(editor2, _contextKeyService, _storageService, clipboardService);
    this._contextViewService = _contextViewService;
    this._keybindingService = _keybindingService;
    this._themeService = _themeService;
    this._notificationService = _notificationService;
    this._widget = null;
    this._findOptionsWidget = null;
  }
  _start(opts, newState) {
    const _super = Object.create(null, {
      _start: { get: () => super._start }
    });
    return __awaiter$Q(this, void 0, void 0, function* () {
      if (!this._widget) {
        this._createFindWidget();
      }
      const selection = this._editor.getSelection();
      let updateSearchScope = false;
      switch (this._editor.getOption(
        40
        /* EditorOption.find */
      ).autoFindInSelection) {
        case "always":
          updateSearchScope = true;
          break;
        case "never":
          updateSearchScope = false;
          break;
        case "multiline": {
          const isSelectionMultipleLine = !!selection && selection.startLineNumber !== selection.endLineNumber;
          updateSearchScope = isSelectionMultipleLine;
          break;
        }
      }
      opts.updateSearchScope = opts.updateSearchScope || updateSearchScope;
      yield _super._start.call(this, opts, newState);
      if (this._widget) {
        if (opts.shouldFocus === 2) {
          this._widget.focusReplaceInput();
        } else if (opts.shouldFocus === 1) {
          this._widget.focusFindInput();
        }
      }
    });
  }
  highlightFindOptions(ignoreWhenVisible = false) {
    if (!this._widget) {
      this._createFindWidget();
    }
    if (this._state.isRevealed && !ignoreWhenVisible) {
      this._widget.highlightFindOptions();
    } else {
      this._findOptionsWidget.highlightFindOptions();
    }
  }
  _createFindWidget() {
    this._widget = this._register(new FindWidget(this._editor, this, this._state, this._contextViewService, this._keybindingService, this._contextKeyService, this._themeService, this._storageService, this._notificationService));
    this._findOptionsWidget = this._register(new FindOptionsWidget(this._editor, this._state, this._keybindingService));
  }
};
FindController2 = __decorate$1g([
  __param$1e(1, IContextViewService),
  __param$1e(2, IContextKeyService),
  __param$1e(3, IKeybindingService),
  __param$1e(4, IThemeService),
  __param$1e(5, INotificationService),
  __param$1e(6, IStorageService),
  __param$1e(7, IClipboardService)
], FindController2);
const StartFindAction = registerMultiEditorAction(new MultiEditorAction({
  id: FIND_IDS.StartFindAction,
  label: localize("startFindAction", "Find"),
  alias: "Find",
  precondition: ContextKeyExpr.or(EditorContextKeys.focus, ContextKeyExpr.has("editorIsOpen")),
  kbOpts: {
    kbExpr: null,
    primary: 2048 | 36,
    weight: 100
    /* KeybindingWeight.EditorContrib */
  },
  menuOpts: {
    menuId: MenuId.MenubarEditMenu,
    group: "3_find",
    title: localize({ key: "miFind", comment: ["&& denotes a mnemonic"] }, "&&Find"),
    order: 1
  }
}));
StartFindAction.addImplementation(0, (accessor, editor2, args) => {
  const controller = CommonFindController.get(editor2);
  if (!controller) {
    return false;
  }
  return controller.start({
    forceRevealReplace: false,
    seedSearchStringFromSelection: editor2.getOption(
      40
      /* EditorOption.find */
    ).seedSearchStringFromSelection !== "never" ? "single" : "none",
    seedSearchStringFromNonEmptySelection: editor2.getOption(
      40
      /* EditorOption.find */
    ).seedSearchStringFromSelection === "selection",
    seedSearchStringFromGlobalClipboard: editor2.getOption(
      40
      /* EditorOption.find */
    ).globalFindClipboard,
    shouldFocus: 1,
    shouldAnimate: true,
    updateSearchScope: false,
    loop: editor2.getOption(
      40
      /* EditorOption.find */
    ).loop
  });
});
const findArgDescription = {
  description: "Open a new In-Editor Find Widget.",
  args: [{
    name: "Open a new In-Editor Find Widget args",
    schema: {
      properties: {
        searchString: { type: "string" },
        replaceString: { type: "string" },
        regex: { type: "boolean" },
        regexOverride: {
          type: "number",
          description: localize("actions.find.isRegexOverride", 'Overrides "Use Regular Expression" flag.\nThe flag will not be saved for the future.\n0: Do Nothing\n1: True\n2: False')
        },
        wholeWord: { type: "boolean" },
        wholeWordOverride: {
          type: "number",
          description: localize("actions.find.wholeWordOverride", 'Overrides "Match Whole Word" flag.\nThe flag will not be saved for the future.\n0: Do Nothing\n1: True\n2: False')
        },
        matchCase: { type: "boolean" },
        matchCaseOverride: {
          type: "number",
          description: localize("actions.find.matchCaseOverride", 'Overrides "Math Case" flag.\nThe flag will not be saved for the future.\n0: Do Nothing\n1: True\n2: False')
        },
        preserveCase: { type: "boolean" },
        preserveCaseOverride: {
          type: "number",
          description: localize("actions.find.preserveCaseOverride", 'Overrides "Preserve Case" flag.\nThe flag will not be saved for the future.\n0: Do Nothing\n1: True\n2: False')
        },
        findInSelection: { type: "boolean" }
      }
    }
  }]
};
class StartFindWithArgsAction extends EditorAction {
  constructor() {
    super({
      id: FIND_IDS.StartFindWithArgs,
      label: localize("startFindWithArgsAction", "Find With Arguments"),
      alias: "Find With Arguments",
      precondition: void 0,
      kbOpts: {
        kbExpr: null,
        primary: 0,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      description: findArgDescription
    });
  }
  run(accessor, editor2, args) {
    return __awaiter$Q(this, void 0, void 0, function* () {
      const controller = CommonFindController.get(editor2);
      if (controller) {
        const newState = args ? {
          searchString: args.searchString,
          replaceString: args.replaceString,
          isReplaceRevealed: args.replaceString !== void 0,
          isRegex: args.isRegex,
          // isRegexOverride: args.regexOverride,
          wholeWord: args.matchWholeWord,
          // wholeWordOverride: args.wholeWordOverride,
          matchCase: args.isCaseSensitive,
          // matchCaseOverride: args.matchCaseOverride,
          preserveCase: args.preserveCase
          // preserveCaseOverride: args.preserveCaseOverride,
        } : {};
        yield controller.start({
          forceRevealReplace: false,
          seedSearchStringFromSelection: controller.getState().searchString.length === 0 && editor2.getOption(
            40
            /* EditorOption.find */
          ).seedSearchStringFromSelection !== "never" ? "single" : "none",
          seedSearchStringFromNonEmptySelection: editor2.getOption(
            40
            /* EditorOption.find */
          ).seedSearchStringFromSelection === "selection",
          seedSearchStringFromGlobalClipboard: true,
          shouldFocus: 1,
          shouldAnimate: true,
          updateSearchScope: (args === null || args === void 0 ? void 0 : args.findInSelection) || false,
          loop: editor2.getOption(
            40
            /* EditorOption.find */
          ).loop
        }, newState);
        controller.setGlobalBufferTerm(controller.getState().searchString);
      }
    });
  }
}
class StartFindWithSelectionAction extends EditorAction {
  constructor() {
    super({
      id: FIND_IDS.StartFindWithSelection,
      label: localize("startFindWithSelectionAction", "Find With Selection"),
      alias: "Find With Selection",
      precondition: void 0,
      kbOpts: {
        kbExpr: null,
        primary: 0,
        mac: {
          primary: 2048 | 35
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor2) {
    return __awaiter$Q(this, void 0, void 0, function* () {
      const controller = CommonFindController.get(editor2);
      if (controller) {
        yield controller.start({
          forceRevealReplace: false,
          seedSearchStringFromSelection: "multiple",
          seedSearchStringFromNonEmptySelection: false,
          seedSearchStringFromGlobalClipboard: false,
          shouldFocus: 0,
          shouldAnimate: true,
          updateSearchScope: false,
          loop: editor2.getOption(
            40
            /* EditorOption.find */
          ).loop
        });
        controller.setGlobalBufferTerm(controller.getState().searchString);
      }
    });
  }
}
class MatchFindAction extends EditorAction {
  run(accessor, editor2) {
    return __awaiter$Q(this, void 0, void 0, function* () {
      const controller = CommonFindController.get(editor2);
      if (controller && !this._run(controller)) {
        yield controller.start({
          forceRevealReplace: false,
          seedSearchStringFromSelection: controller.getState().searchString.length === 0 && editor2.getOption(
            40
            /* EditorOption.find */
          ).seedSearchStringFromSelection !== "never" ? "single" : "none",
          seedSearchStringFromNonEmptySelection: editor2.getOption(
            40
            /* EditorOption.find */
          ).seedSearchStringFromSelection === "selection",
          seedSearchStringFromGlobalClipboard: true,
          shouldFocus: 0,
          shouldAnimate: true,
          updateSearchScope: false,
          loop: editor2.getOption(
            40
            /* EditorOption.find */
          ).loop
        });
        this._run(controller);
      }
    });
  }
}
class NextMatchFindAction extends MatchFindAction {
  constructor() {
    super({
      id: FIND_IDS.NextMatchFindAction,
      label: localize("findNextMatchAction", "Find Next"),
      alias: "Find Next",
      precondition: void 0,
      kbOpts: [{
        kbExpr: EditorContextKeys.focus,
        primary: 61,
        mac: { primary: 2048 | 37, secondary: [
          61
          /* KeyCode.F3 */
        ] },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }, {
        kbExpr: ContextKeyExpr.and(EditorContextKeys.focus, CONTEXT_FIND_INPUT_FOCUSED),
        primary: 3,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }]
    });
  }
  _run(controller) {
    const result2 = controller.moveToNextMatch();
    if (result2) {
      controller.editor.pushUndoStop();
      return true;
    }
    return false;
  }
}
class PreviousMatchFindAction extends MatchFindAction {
  constructor() {
    super({
      id: FIND_IDS.PreviousMatchFindAction,
      label: localize("findPreviousMatchAction", "Find Previous"),
      alias: "Find Previous",
      precondition: void 0,
      kbOpts: [
        {
          kbExpr: EditorContextKeys.focus,
          primary: 1024 | 61,
          mac: { primary: 2048 | 1024 | 37, secondary: [
            1024 | 61
            /* KeyCode.F3 */
          ] },
          weight: 100
          /* KeybindingWeight.EditorContrib */
        },
        {
          kbExpr: ContextKeyExpr.and(EditorContextKeys.focus, CONTEXT_FIND_INPUT_FOCUSED),
          primary: 1024 | 3,
          weight: 100
          /* KeybindingWeight.EditorContrib */
        }
      ]
    });
  }
  _run(controller) {
    return controller.moveToPrevMatch();
  }
}
class MoveToMatchFindAction extends EditorAction {
  constructor() {
    super({
      id: FIND_IDS.GoToMatchFindAction,
      label: localize("findMatchAction.goToMatch", "Go to Match..."),
      alias: "Go to Match...",
      precondition: CONTEXT_FIND_WIDGET_VISIBLE
    });
    this._highlightDecorations = [];
  }
  run(accessor, editor2, args) {
    const controller = CommonFindController.get(editor2);
    if (!controller) {
      return;
    }
    const matchesCount = controller.getState().matchesCount;
    if (matchesCount < 1) {
      const notificationService = accessor.get(INotificationService);
      notificationService.notify({
        severity: Severity.Warning,
        message: localize("findMatchAction.noResults", "No matches. Try searching for something else.")
      });
      return;
    }
    const quickInputService = accessor.get(IQuickInputService);
    const inputBox2 = quickInputService.createInputBox();
    inputBox2.placeholder = localize("findMatchAction.inputPlaceHolder", "Type a number to go to a specific match (between 1 and {0})", matchesCount);
    const toFindMatchIndex = (value) => {
      const index = parseInt(value);
      if (isNaN(index)) {
        return void 0;
      }
      const matchCount = controller.getState().matchesCount;
      if (index > 0 && index <= matchCount) {
        return index - 1;
      } else if (index < 0 && index >= -matchCount) {
        return matchCount + index;
      }
      return void 0;
    };
    const updatePickerAndEditor = (value) => {
      const index = toFindMatchIndex(value);
      if (typeof index === "number") {
        inputBox2.validationMessage = void 0;
        controller.goToMatch(index);
        const currentMatch = controller.getState().currentMatch;
        if (currentMatch) {
          this.addDecorations(editor2, currentMatch);
        }
      } else {
        inputBox2.validationMessage = localize("findMatchAction.inputValidationMessage", "Please type a number between 1 and {0}", controller.getState().matchesCount);
        this.clearDecorations(editor2);
      }
    };
    inputBox2.onDidChangeValue((value) => {
      updatePickerAndEditor(value);
    });
    inputBox2.onDidAccept(() => {
      const index = toFindMatchIndex(inputBox2.value);
      if (typeof index === "number") {
        controller.goToMatch(index);
        inputBox2.hide();
      } else {
        inputBox2.validationMessage = localize("findMatchAction.inputValidationMessage", "Please type a number between 1 and {0}", controller.getState().matchesCount);
      }
    });
    inputBox2.onDidHide(() => {
      this.clearDecorations(editor2);
      inputBox2.dispose();
    });
    inputBox2.show();
  }
  clearDecorations(editor2) {
    editor2.changeDecorations((changeAccessor) => {
      this._highlightDecorations = changeAccessor.deltaDecorations(this._highlightDecorations, []);
    });
  }
  addDecorations(editor2, range2) {
    editor2.changeDecorations((changeAccessor) => {
      this._highlightDecorations = changeAccessor.deltaDecorations(this._highlightDecorations, [
        {
          range: range2,
          options: {
            description: "find-match-quick-access-range-highlight",
            className: "rangeHighlight",
            isWholeLine: true
          }
        },
        {
          range: range2,
          options: {
            description: "find-match-quick-access-range-highlight-overview",
            overviewRuler: {
              color: themeColorFromId(overviewRulerRangeHighlight),
              position: OverviewRulerLane$1.Full
            }
          }
        }
      ]);
    });
  }
}
class SelectionMatchFindAction extends EditorAction {
  run(accessor, editor2) {
    return __awaiter$Q(this, void 0, void 0, function* () {
      const controller = CommonFindController.get(editor2);
      if (!controller) {
        return;
      }
      const selectionSearchString = getSelectionSearchString(editor2, "single", false);
      if (selectionSearchString) {
        controller.setSearchString(selectionSearchString);
      }
      if (!this._run(controller)) {
        yield controller.start({
          forceRevealReplace: false,
          seedSearchStringFromSelection: "none",
          seedSearchStringFromNonEmptySelection: false,
          seedSearchStringFromGlobalClipboard: false,
          shouldFocus: 0,
          shouldAnimate: true,
          updateSearchScope: false,
          loop: editor2.getOption(
            40
            /* EditorOption.find */
          ).loop
        });
        this._run(controller);
      }
    });
  }
}
class NextSelectionMatchFindAction extends SelectionMatchFindAction {
  constructor() {
    super({
      id: FIND_IDS.NextSelectionMatchFindAction,
      label: localize("nextSelectionMatchFindAction", "Find Next Selection"),
      alias: "Find Next Selection",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.focus,
        primary: 2048 | 61,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  _run(controller) {
    return controller.moveToNextMatch();
  }
}
class PreviousSelectionMatchFindAction extends SelectionMatchFindAction {
  constructor() {
    super({
      id: FIND_IDS.PreviousSelectionMatchFindAction,
      label: localize("previousSelectionMatchFindAction", "Find Previous Selection"),
      alias: "Find Previous Selection",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.focus,
        primary: 2048 | 1024 | 61,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  _run(controller) {
    return controller.moveToPrevMatch();
  }
}
const StartFindReplaceAction = registerMultiEditorAction(new MultiEditorAction({
  id: FIND_IDS.StartFindReplaceAction,
  label: localize("startReplace", "Replace"),
  alias: "Replace",
  precondition: ContextKeyExpr.or(EditorContextKeys.focus, ContextKeyExpr.has("editorIsOpen")),
  kbOpts: {
    kbExpr: null,
    primary: 2048 | 38,
    mac: {
      primary: 2048 | 512 | 36
      /* KeyCode.KeyF */
    },
    weight: 100
    /* KeybindingWeight.EditorContrib */
  },
  menuOpts: {
    menuId: MenuId.MenubarEditMenu,
    group: "3_find",
    title: localize({ key: "miReplace", comment: ["&& denotes a mnemonic"] }, "&&Replace"),
    order: 2
  }
}));
StartFindReplaceAction.addImplementation(0, (accessor, editor2, args) => {
  if (!editor2.hasModel() || editor2.getOption(
    89
    /* EditorOption.readOnly */
  )) {
    return false;
  }
  const controller = CommonFindController.get(editor2);
  if (!controller) {
    return false;
  }
  const currentSelection = editor2.getSelection();
  const findInputFocused = controller.isFindInputFocused();
  const seedSearchStringFromSelection = !currentSelection.isEmpty() && currentSelection.startLineNumber === currentSelection.endLineNumber && editor2.getOption(
    40
    /* EditorOption.find */
  ).seedSearchStringFromSelection !== "never" && !findInputFocused;
  const shouldFocus = findInputFocused || seedSearchStringFromSelection ? 2 : 1;
  return controller.start({
    forceRevealReplace: true,
    seedSearchStringFromSelection: seedSearchStringFromSelection ? "single" : "none",
    seedSearchStringFromNonEmptySelection: editor2.getOption(
      40
      /* EditorOption.find */
    ).seedSearchStringFromSelection === "selection",
    seedSearchStringFromGlobalClipboard: editor2.getOption(
      40
      /* EditorOption.find */
    ).seedSearchStringFromSelection !== "never",
    shouldFocus,
    shouldAnimate: true,
    updateSearchScope: false,
    loop: editor2.getOption(
      40
      /* EditorOption.find */
    ).loop
  });
});
registerEditorContribution(
  CommonFindController.ID,
  FindController2,
  0
  /* EditorContributionInstantiation.Eager */
);
registerEditorAction(StartFindWithArgsAction);
registerEditorAction(StartFindWithSelectionAction);
registerEditorAction(NextMatchFindAction);
registerEditorAction(PreviousMatchFindAction);
registerEditorAction(MoveToMatchFindAction);
registerEditorAction(NextSelectionMatchFindAction);
registerEditorAction(PreviousSelectionMatchFindAction);
const FindCommand = EditorCommand.bindToContribution(CommonFindController.get);
registerEditorCommand(new FindCommand({
  id: FIND_IDS.CloseFindWidgetCommand,
  precondition: CONTEXT_FIND_WIDGET_VISIBLE,
  handler: (x) => x.closeFindWidget(),
  kbOpts: {
    weight: 100 + 5,
    kbExpr: ContextKeyExpr.and(EditorContextKeys.focus, ContextKeyExpr.not("isComposing")),
    primary: 9,
    secondary: [
      1024 | 9
      /* KeyCode.Escape */
    ]
  }
}));
registerEditorCommand(new FindCommand({
  id: FIND_IDS.ToggleCaseSensitiveCommand,
  precondition: void 0,
  handler: (x) => x.toggleCaseSensitive(),
  kbOpts: {
    weight: 100 + 5,
    kbExpr: EditorContextKeys.focus,
    primary: ToggleCaseSensitiveKeybinding.primary,
    mac: ToggleCaseSensitiveKeybinding.mac,
    win: ToggleCaseSensitiveKeybinding.win,
    linux: ToggleCaseSensitiveKeybinding.linux
  }
}));
registerEditorCommand(new FindCommand({
  id: FIND_IDS.ToggleWholeWordCommand,
  precondition: void 0,
  handler: (x) => x.toggleWholeWords(),
  kbOpts: {
    weight: 100 + 5,
    kbExpr: EditorContextKeys.focus,
    primary: ToggleWholeWordKeybinding.primary,
    mac: ToggleWholeWordKeybinding.mac,
    win: ToggleWholeWordKeybinding.win,
    linux: ToggleWholeWordKeybinding.linux
  }
}));
registerEditorCommand(new FindCommand({
  id: FIND_IDS.ToggleRegexCommand,
  precondition: void 0,
  handler: (x) => x.toggleRegex(),
  kbOpts: {
    weight: 100 + 5,
    kbExpr: EditorContextKeys.focus,
    primary: ToggleRegexKeybinding.primary,
    mac: ToggleRegexKeybinding.mac,
    win: ToggleRegexKeybinding.win,
    linux: ToggleRegexKeybinding.linux
  }
}));
registerEditorCommand(new FindCommand({
  id: FIND_IDS.ToggleSearchScopeCommand,
  precondition: void 0,
  handler: (x) => x.toggleSearchScope(),
  kbOpts: {
    weight: 100 + 5,
    kbExpr: EditorContextKeys.focus,
    primary: ToggleSearchScopeKeybinding.primary,
    mac: ToggleSearchScopeKeybinding.mac,
    win: ToggleSearchScopeKeybinding.win,
    linux: ToggleSearchScopeKeybinding.linux
  }
}));
registerEditorCommand(new FindCommand({
  id: FIND_IDS.TogglePreserveCaseCommand,
  precondition: void 0,
  handler: (x) => x.togglePreserveCase(),
  kbOpts: {
    weight: 100 + 5,
    kbExpr: EditorContextKeys.focus,
    primary: TogglePreserveCaseKeybinding.primary,
    mac: TogglePreserveCaseKeybinding.mac,
    win: TogglePreserveCaseKeybinding.win,
    linux: TogglePreserveCaseKeybinding.linux
  }
}));
registerEditorCommand(new FindCommand({
  id: FIND_IDS.ReplaceOneAction,
  precondition: CONTEXT_FIND_WIDGET_VISIBLE,
  handler: (x) => x.replace(),
  kbOpts: {
    weight: 100 + 5,
    kbExpr: EditorContextKeys.focus,
    primary: 2048 | 1024 | 22
    /* KeyCode.Digit1 */
  }
}));
registerEditorCommand(new FindCommand({
  id: FIND_IDS.ReplaceOneAction,
  precondition: CONTEXT_FIND_WIDGET_VISIBLE,
  handler: (x) => x.replace(),
  kbOpts: {
    weight: 100 + 5,
    kbExpr: ContextKeyExpr.and(EditorContextKeys.focus, CONTEXT_REPLACE_INPUT_FOCUSED),
    primary: 3
    /* KeyCode.Enter */
  }
}));
registerEditorCommand(new FindCommand({
  id: FIND_IDS.ReplaceAllAction,
  precondition: CONTEXT_FIND_WIDGET_VISIBLE,
  handler: (x) => x.replaceAll(),
  kbOpts: {
    weight: 100 + 5,
    kbExpr: EditorContextKeys.focus,
    primary: 2048 | 512 | 3
    /* KeyCode.Enter */
  }
}));
registerEditorCommand(new FindCommand({
  id: FIND_IDS.ReplaceAllAction,
  precondition: CONTEXT_FIND_WIDGET_VISIBLE,
  handler: (x) => x.replaceAll(),
  kbOpts: {
    weight: 100 + 5,
    kbExpr: ContextKeyExpr.and(EditorContextKeys.focus, CONTEXT_REPLACE_INPUT_FOCUSED),
    primary: void 0,
    mac: {
      primary: 2048 | 3
    }
  }
}));
registerEditorCommand(new FindCommand({
  id: FIND_IDS.SelectAllMatchesAction,
  precondition: CONTEXT_FIND_WIDGET_VISIBLE,
  handler: (x) => x.selectAllMatches(),
  kbOpts: {
    weight: 100 + 5,
    kbExpr: EditorContextKeys.focus,
    primary: 512 | 3
    /* KeyCode.Enter */
  }
}));
const folding = "";
const foldSourceAbbr = {
  [
    0
    /* FoldSource.provider */
  ]: " ",
  [
    1
    /* FoldSource.userDefined */
  ]: "u",
  [
    2
    /* FoldSource.recovered */
  ]: "r"
};
const MAX_FOLDING_REGIONS = 65535;
const MAX_LINE_NUMBER = 16777215;
const MASK_INDENT = 4278190080;
class BitField {
  constructor(size2) {
    const numWords = Math.ceil(size2 / 32);
    this._states = new Uint32Array(numWords);
  }
  get(index) {
    const arrayIndex = index / 32 | 0;
    const bit = index % 32;
    return (this._states[arrayIndex] & 1 << bit) !== 0;
  }
  set(index, newState) {
    const arrayIndex = index / 32 | 0;
    const bit = index % 32;
    const value = this._states[arrayIndex];
    if (newState) {
      this._states[arrayIndex] = value | 1 << bit;
    } else {
      this._states[arrayIndex] = value & ~(1 << bit);
    }
  }
}
class FoldingRegions {
  constructor(startIndexes, endIndexes, types2) {
    if (startIndexes.length !== endIndexes.length || startIndexes.length > MAX_FOLDING_REGIONS) {
      throw new Error("invalid startIndexes or endIndexes size");
    }
    this._startIndexes = startIndexes;
    this._endIndexes = endIndexes;
    this._collapseStates = new BitField(startIndexes.length);
    this._userDefinedStates = new BitField(startIndexes.length);
    this._recoveredStates = new BitField(startIndexes.length);
    this._types = types2;
    this._parentsComputed = false;
  }
  ensureParentIndices() {
    if (!this._parentsComputed) {
      this._parentsComputed = true;
      const parentIndexes = [];
      const isInsideLast = (startLineNumber, endLineNumber) => {
        const index = parentIndexes[parentIndexes.length - 1];
        return this.getStartLineNumber(index) <= startLineNumber && this.getEndLineNumber(index) >= endLineNumber;
      };
      for (let i = 0, len = this._startIndexes.length; i < len; i++) {
        const startLineNumber = this._startIndexes[i];
        const endLineNumber = this._endIndexes[i];
        if (startLineNumber > MAX_LINE_NUMBER || endLineNumber > MAX_LINE_NUMBER) {
          throw new Error("startLineNumber or endLineNumber must not exceed " + MAX_LINE_NUMBER);
        }
        while (parentIndexes.length > 0 && !isInsideLast(startLineNumber, endLineNumber)) {
          parentIndexes.pop();
        }
        const parentIndex = parentIndexes.length > 0 ? parentIndexes[parentIndexes.length - 1] : -1;
        parentIndexes.push(i);
        this._startIndexes[i] = startLineNumber + ((parentIndex & 255) << 24);
        this._endIndexes[i] = endLineNumber + ((parentIndex & 65280) << 16);
      }
    }
  }
  get length() {
    return this._startIndexes.length;
  }
  getStartLineNumber(index) {
    return this._startIndexes[index] & MAX_LINE_NUMBER;
  }
  getEndLineNumber(index) {
    return this._endIndexes[index] & MAX_LINE_NUMBER;
  }
  getType(index) {
    return this._types ? this._types[index] : void 0;
  }
  hasTypes() {
    return !!this._types;
  }
  isCollapsed(index) {
    return this._collapseStates.get(index);
  }
  setCollapsed(index, newState) {
    this._collapseStates.set(index, newState);
  }
  isUserDefined(index) {
    return this._userDefinedStates.get(index);
  }
  setUserDefined(index, newState) {
    return this._userDefinedStates.set(index, newState);
  }
  isRecovered(index) {
    return this._recoveredStates.get(index);
  }
  setRecovered(index, newState) {
    return this._recoveredStates.set(index, newState);
  }
  getSource(index) {
    if (this.isUserDefined(index)) {
      return 1;
    } else if (this.isRecovered(index)) {
      return 2;
    }
    return 0;
  }
  setSource(index, source) {
    if (source === 1) {
      this.setUserDefined(index, true);
      this.setRecovered(index, false);
    } else if (source === 2) {
      this.setUserDefined(index, false);
      this.setRecovered(index, true);
    } else {
      this.setUserDefined(index, false);
      this.setRecovered(index, false);
    }
  }
  setCollapsedAllOfType(type, newState) {
    let hasChanged2 = false;
    if (this._types) {
      for (let i = 0; i < this._types.length; i++) {
        if (this._types[i] === type) {
          this.setCollapsed(i, newState);
          hasChanged2 = true;
        }
      }
    }
    return hasChanged2;
  }
  toRegion(index) {
    return new FoldingRegion(this, index);
  }
  getParentIndex(index) {
    this.ensureParentIndices();
    const parent = ((this._startIndexes[index] & MASK_INDENT) >>> 24) + ((this._endIndexes[index] & MASK_INDENT) >>> 16);
    if (parent === MAX_FOLDING_REGIONS) {
      return -1;
    }
    return parent;
  }
  contains(index, line) {
    return this.getStartLineNumber(index) <= line && this.getEndLineNumber(index) >= line;
  }
  findIndex(line) {
    let low = 0, high = this._startIndexes.length;
    if (high === 0) {
      return -1;
    }
    while (low < high) {
      const mid = Math.floor((low + high) / 2);
      if (line < this.getStartLineNumber(mid)) {
        high = mid;
      } else {
        low = mid + 1;
      }
    }
    return low - 1;
  }
  findRange(line) {
    let index = this.findIndex(line);
    if (index >= 0) {
      const endLineNumber = this.getEndLineNumber(index);
      if (endLineNumber >= line) {
        return index;
      }
      index = this.getParentIndex(index);
      while (index !== -1) {
        if (this.contains(index, line)) {
          return index;
        }
        index = this.getParentIndex(index);
      }
    }
    return -1;
  }
  toString() {
    const res = [];
    for (let i = 0; i < this.length; i++) {
      res[i] = `[${foldSourceAbbr[this.getSource(i)]}${this.isCollapsed(i) ? "+" : "-"}] ${this.getStartLineNumber(i)}/${this.getEndLineNumber(i)}`;
    }
    return res.join(", ");
  }
  toFoldRange(index) {
    return {
      startLineNumber: this._startIndexes[index] & MAX_LINE_NUMBER,
      endLineNumber: this._endIndexes[index] & MAX_LINE_NUMBER,
      type: this._types ? this._types[index] : void 0,
      isCollapsed: this.isCollapsed(index),
      source: this.getSource(index)
    };
  }
  static fromFoldRanges(ranges) {
    const rangesLength = ranges.length;
    const startIndexes = new Uint32Array(rangesLength);
    const endIndexes = new Uint32Array(rangesLength);
    let types2 = [];
    let gotTypes = false;
    for (let i = 0; i < rangesLength; i++) {
      const range2 = ranges[i];
      startIndexes[i] = range2.startLineNumber;
      endIndexes[i] = range2.endLineNumber;
      types2.push(range2.type);
      if (range2.type) {
        gotTypes = true;
      }
    }
    if (!gotTypes) {
      types2 = void 0;
    }
    const regions = new FoldingRegions(startIndexes, endIndexes, types2);
    for (let i = 0; i < rangesLength; i++) {
      if (ranges[i].isCollapsed) {
        regions.setCollapsed(i, true);
      }
      regions.setSource(i, ranges[i].source);
    }
    return regions;
  }
  /**
   * Two inputs, each a FoldingRegions or a FoldRange[], are merged.
   * Each input must be pre-sorted on startLineNumber.
   * The first list is assumed to always include all regions currently defined by range providers.
   * The second list only contains the previously collapsed and all manual ranges.
   * If the line position matches, the range of the new range is taken, and the range is no longer manual
   * When an entry in one list overlaps an entry in the other, the second list's entry "wins" and
   * overlapping entries in the first list are discarded.
   * Invalid entries are discarded. An entry is invalid if:
   * 		the start and end line numbers aren't a valid range of line numbers,
   * 		it is out of sequence or has the same start line as a preceding entry,
   * 		it overlaps a preceding entry and is not fully contained by that entry.
   */
  static sanitizeAndMerge(rangesA, rangesB, maxLineNumber) {
    maxLineNumber = maxLineNumber !== null && maxLineNumber !== void 0 ? maxLineNumber : Number.MAX_VALUE;
    const getIndexedFunction = (r, limit) => {
      return Array.isArray(r) ? (i) => {
        return i < limit ? r[i] : void 0;
      } : (i) => {
        return i < limit ? r.toFoldRange(i) : void 0;
      };
    };
    const getA = getIndexedFunction(rangesA, rangesA.length);
    const getB = getIndexedFunction(rangesB, rangesB.length);
    let indexA = 0;
    let indexB = 0;
    let nextA = getA(0);
    let nextB = getB(0);
    const stackedRanges = [];
    let topStackedRange;
    let prevLineNumber = 0;
    const resultRanges = [];
    while (nextA || nextB) {
      let useRange = void 0;
      if (nextB && (!nextA || nextA.startLineNumber >= nextB.startLineNumber)) {
        if (nextA && nextA.startLineNumber === nextB.startLineNumber) {
          if (nextB.source === 1) {
            useRange = nextB;
          } else {
            useRange = nextA;
            useRange.isCollapsed = nextB.isCollapsed && nextA.endLineNumber === nextB.endLineNumber;
            useRange.source = 0;
          }
          nextA = getA(++indexA);
        } else {
          useRange = nextB;
          if (nextB.isCollapsed && nextB.source === 0) {
            useRange.source = 2;
          }
        }
        nextB = getB(++indexB);
      } else {
        let scanIndex = indexB;
        let prescanB = nextB;
        while (true) {
          if (!prescanB || prescanB.startLineNumber > nextA.endLineNumber) {
            useRange = nextA;
            break;
          }
          if (prescanB.source === 1 && prescanB.endLineNumber > nextA.endLineNumber) {
            break;
          }
          prescanB = getB(++scanIndex);
        }
        nextA = getA(++indexA);
      }
      if (useRange) {
        while (topStackedRange && topStackedRange.endLineNumber < useRange.startLineNumber) {
          topStackedRange = stackedRanges.pop();
        }
        if (useRange.endLineNumber > useRange.startLineNumber && useRange.startLineNumber > prevLineNumber && useRange.endLineNumber <= maxLineNumber && (!topStackedRange || topStackedRange.endLineNumber >= useRange.endLineNumber)) {
          resultRanges.push(useRange);
          prevLineNumber = useRange.startLineNumber;
          if (topStackedRange) {
            stackedRanges.push(topStackedRange);
          }
          topStackedRange = useRange;
        }
      }
    }
    return resultRanges;
  }
}
class FoldingRegion {
  constructor(ranges, index) {
    this.ranges = ranges;
    this.index = index;
  }
  get startLineNumber() {
    return this.ranges.getStartLineNumber(this.index);
  }
  get endLineNumber() {
    return this.ranges.getEndLineNumber(this.index);
  }
  get regionIndex() {
    return this.index;
  }
  get parentIndex() {
    return this.ranges.getParentIndex(this.index);
  }
  get isCollapsed() {
    return this.ranges.isCollapsed(this.index);
  }
  containedBy(range2) {
    return range2.startLineNumber <= this.startLineNumber && range2.endLineNumber >= this.endLineNumber;
  }
  containsLine(lineNumber) {
    return this.startLineNumber <= lineNumber && lineNumber <= this.endLineNumber;
  }
}
class FoldingModel {
  get regions() {
    return this._regions;
  }
  get textModel() {
    return this._textModel;
  }
  constructor(textModel, decorationProvider) {
    this._updateEventEmitter = new Emitter$1();
    this.onDidChange = this._updateEventEmitter.event;
    this._textModel = textModel;
    this._decorationProvider = decorationProvider;
    this._regions = new FoldingRegions(new Uint32Array(0), new Uint32Array(0));
    this._editorDecorationIds = [];
  }
  toggleCollapseState(toggledRegions) {
    if (!toggledRegions.length) {
      return;
    }
    toggledRegions = toggledRegions.sort((r1, r2) => r1.regionIndex - r2.regionIndex);
    const processed = {};
    this._decorationProvider.changeDecorations((accessor) => {
      let k = 0;
      let dirtyRegionEndLine = -1;
      let lastHiddenLine = -1;
      const updateDecorationsUntil = (index) => {
        while (k < index) {
          const endLineNumber = this._regions.getEndLineNumber(k);
          const isCollapsed = this._regions.isCollapsed(k);
          if (endLineNumber <= dirtyRegionEndLine) {
            const isManual = this.regions.getSource(k) !== 0;
            accessor.changeDecorationOptions(this._editorDecorationIds[k], this._decorationProvider.getDecorationOption(isCollapsed, endLineNumber <= lastHiddenLine, isManual));
          }
          if (isCollapsed && endLineNumber > lastHiddenLine) {
            lastHiddenLine = endLineNumber;
          }
          k++;
        }
      };
      for (const region of toggledRegions) {
        const index = region.regionIndex;
        const editorDecorationId = this._editorDecorationIds[index];
        if (editorDecorationId && !processed[editorDecorationId]) {
          processed[editorDecorationId] = true;
          updateDecorationsUntil(index);
          const newCollapseState = !this._regions.isCollapsed(index);
          this._regions.setCollapsed(index, newCollapseState);
          dirtyRegionEndLine = Math.max(dirtyRegionEndLine, this._regions.getEndLineNumber(index));
        }
      }
      updateDecorationsUntil(this._regions.length);
    });
    this._updateEventEmitter.fire({ model: this, collapseStateChanged: toggledRegions });
  }
  removeManualRanges(ranges) {
    const newFoldingRanges = new Array();
    const intersects2 = (foldRange) => {
      for (const range2 of ranges) {
        if (!(range2.startLineNumber > foldRange.endLineNumber || foldRange.startLineNumber > range2.endLineNumber)) {
          return true;
        }
      }
      return false;
    };
    for (let i = 0; i < this._regions.length; i++) {
      const foldRange = this._regions.toFoldRange(i);
      if (foldRange.source === 0 || !intersects2(foldRange)) {
        newFoldingRanges.push(foldRange);
      }
    }
    this.updatePost(FoldingRegions.fromFoldRanges(newFoldingRanges));
  }
  update(newRegions, blockedLineNumers = []) {
    const foldedOrManualRanges = this._currentFoldedOrManualRanges(blockedLineNumers);
    const newRanges = FoldingRegions.sanitizeAndMerge(newRegions, foldedOrManualRanges, this._textModel.getLineCount());
    this.updatePost(FoldingRegions.fromFoldRanges(newRanges));
  }
  updatePost(newRegions) {
    const newEditorDecorations = [];
    let lastHiddenLine = -1;
    for (let index = 0, limit = newRegions.length; index < limit; index++) {
      const startLineNumber = newRegions.getStartLineNumber(index);
      const endLineNumber = newRegions.getEndLineNumber(index);
      const isCollapsed = newRegions.isCollapsed(index);
      const isManual = newRegions.getSource(index) !== 0;
      const decorationRange = {
        startLineNumber,
        startColumn: this._textModel.getLineMaxColumn(startLineNumber),
        endLineNumber,
        endColumn: this._textModel.getLineMaxColumn(endLineNumber) + 1
      };
      newEditorDecorations.push({ range: decorationRange, options: this._decorationProvider.getDecorationOption(isCollapsed, endLineNumber <= lastHiddenLine, isManual) });
      if (isCollapsed && endLineNumber > lastHiddenLine) {
        lastHiddenLine = endLineNumber;
      }
    }
    this._decorationProvider.changeDecorations((accessor) => this._editorDecorationIds = accessor.deltaDecorations(this._editorDecorationIds, newEditorDecorations));
    this._regions = newRegions;
    this._updateEventEmitter.fire({ model: this });
  }
  _currentFoldedOrManualRanges(blockedLineNumers = []) {
    const isBlocked = (startLineNumber, endLineNumber) => {
      for (const blockedLineNumber of blockedLineNumers) {
        if (startLineNumber < blockedLineNumber && blockedLineNumber <= endLineNumber) {
          return true;
        }
      }
      return false;
    };
    const foldedRanges = [];
    for (let i = 0, limit = this._regions.length; i < limit; i++) {
      let isCollapsed = this.regions.isCollapsed(i);
      const source = this.regions.getSource(i);
      if (isCollapsed || source !== 0) {
        const foldRange = this._regions.toFoldRange(i);
        const decRange = this._textModel.getDecorationRange(this._editorDecorationIds[i]);
        if (decRange) {
          if (isCollapsed && isBlocked(decRange.startLineNumber, decRange.endLineNumber)) {
            isCollapsed = false;
          }
          foldedRanges.push({
            startLineNumber: decRange.startLineNumber,
            endLineNumber: decRange.endLineNumber,
            type: foldRange.type,
            isCollapsed,
            source
          });
        }
      }
    }
    return foldedRanges;
  }
  /**
   * Collapse state memento, for persistence only
   */
  getMemento() {
    const foldedOrManualRanges = this._currentFoldedOrManualRanges();
    const result2 = [];
    const maxLineNumber = this._textModel.getLineCount();
    for (let i = 0, limit = foldedOrManualRanges.length; i < limit; i++) {
      const range2 = foldedOrManualRanges[i];
      if (range2.startLineNumber >= range2.endLineNumber || range2.startLineNumber < 1 || range2.endLineNumber > maxLineNumber) {
        continue;
      }
      const checksum = this._getLinesChecksum(range2.startLineNumber + 1, range2.endLineNumber);
      result2.push({
        startLineNumber: range2.startLineNumber,
        endLineNumber: range2.endLineNumber,
        isCollapsed: range2.isCollapsed,
        source: range2.source,
        checksum
      });
    }
    return result2.length > 0 ? result2 : void 0;
  }
  /**
   * Apply persisted state, for persistence only
   */
  applyMemento(state) {
    var _a2, _b2;
    if (!Array.isArray(state)) {
      return;
    }
    const rangesToRestore = [];
    const maxLineNumber = this._textModel.getLineCount();
    for (const range2 of state) {
      if (range2.startLineNumber >= range2.endLineNumber || range2.startLineNumber < 1 || range2.endLineNumber > maxLineNumber) {
        continue;
      }
      const checksum = this._getLinesChecksum(range2.startLineNumber + 1, range2.endLineNumber);
      if (!range2.checksum || checksum === range2.checksum) {
        rangesToRestore.push({
          startLineNumber: range2.startLineNumber,
          endLineNumber: range2.endLineNumber,
          type: void 0,
          isCollapsed: (_a2 = range2.isCollapsed) !== null && _a2 !== void 0 ? _a2 : true,
          source: (_b2 = range2.source) !== null && _b2 !== void 0 ? _b2 : 0
          /* FoldSource.provider */
        });
      }
    }
    const newRanges = FoldingRegions.sanitizeAndMerge(this._regions, rangesToRestore, maxLineNumber);
    this.updatePost(FoldingRegions.fromFoldRanges(newRanges));
  }
  _getLinesChecksum(lineNumber1, lineNumber2) {
    const h2 = hash(this._textModel.getLineContent(lineNumber1) + this._textModel.getLineContent(lineNumber2));
    return h2 % 1e6;
  }
  dispose() {
    this._decorationProvider.removeDecorations(this._editorDecorationIds);
  }
  getAllRegionsAtLine(lineNumber, filter2) {
    const result2 = [];
    if (this._regions) {
      let index = this._regions.findRange(lineNumber);
      let level = 1;
      while (index >= 0) {
        const current = this._regions.toRegion(index);
        if (!filter2 || filter2(current, level)) {
          result2.push(current);
        }
        level++;
        index = current.parentIndex;
      }
    }
    return result2;
  }
  getRegionAtLine(lineNumber) {
    if (this._regions) {
      const index = this._regions.findRange(lineNumber);
      if (index >= 0) {
        return this._regions.toRegion(index);
      }
    }
    return null;
  }
  getRegionsInside(region, filter2) {
    const result2 = [];
    const index = region ? region.regionIndex + 1 : 0;
    const endLineNumber = region ? region.endLineNumber : Number.MAX_VALUE;
    if (filter2 && filter2.length === 2) {
      const levelStack = [];
      for (let i = index, len = this._regions.length; i < len; i++) {
        const current = this._regions.toRegion(i);
        if (this._regions.getStartLineNumber(i) < endLineNumber) {
          while (levelStack.length > 0 && !current.containedBy(levelStack[levelStack.length - 1])) {
            levelStack.pop();
          }
          levelStack.push(current);
          if (filter2(current, levelStack.length)) {
            result2.push(current);
          }
        } else {
          break;
        }
      }
    } else {
      for (let i = index, len = this._regions.length; i < len; i++) {
        const current = this._regions.toRegion(i);
        if (this._regions.getStartLineNumber(i) < endLineNumber) {
          if (!filter2 || filter2(current)) {
            result2.push(current);
          }
        } else {
          break;
        }
      }
    }
    return result2;
  }
}
function toggleCollapseState(foldingModel, levels, lineNumbers2) {
  const toToggle = [];
  for (const lineNumber of lineNumbers2) {
    const region = foldingModel.getRegionAtLine(lineNumber);
    if (region) {
      const doCollapse = !region.isCollapsed;
      toToggle.push(region);
      if (levels > 1) {
        const regionsInside = foldingModel.getRegionsInside(region, (r, level) => r.isCollapsed !== doCollapse && level < levels);
        toToggle.push(...regionsInside);
      }
    }
  }
  foldingModel.toggleCollapseState(toToggle);
}
function setCollapseStateLevelsDown(foldingModel, doCollapse, levels = Number.MAX_VALUE, lineNumbers2) {
  const toToggle = [];
  if (lineNumbers2 && lineNumbers2.length > 0) {
    for (const lineNumber of lineNumbers2) {
      const region = foldingModel.getRegionAtLine(lineNumber);
      if (region) {
        if (region.isCollapsed !== doCollapse) {
          toToggle.push(region);
        }
        if (levels > 1) {
          const regionsInside = foldingModel.getRegionsInside(region, (r, level) => r.isCollapsed !== doCollapse && level < levels);
          toToggle.push(...regionsInside);
        }
      }
    }
  } else {
    const regionsInside = foldingModel.getRegionsInside(null, (r, level) => r.isCollapsed !== doCollapse && level < levels);
    toToggle.push(...regionsInside);
  }
  foldingModel.toggleCollapseState(toToggle);
}
function setCollapseStateLevelsUp(foldingModel, doCollapse, levels, lineNumbers2) {
  const toToggle = [];
  for (const lineNumber of lineNumbers2) {
    const regions = foldingModel.getAllRegionsAtLine(lineNumber, (region, level) => region.isCollapsed !== doCollapse && level <= levels);
    toToggle.push(...regions);
  }
  foldingModel.toggleCollapseState(toToggle);
}
function setCollapseStateUp(foldingModel, doCollapse, lineNumbers2) {
  const toToggle = [];
  for (const lineNumber of lineNumbers2) {
    const regions = foldingModel.getAllRegionsAtLine(lineNumber, (region) => region.isCollapsed !== doCollapse);
    if (regions.length > 0) {
      toToggle.push(regions[0]);
    }
  }
  foldingModel.toggleCollapseState(toToggle);
}
function setCollapseStateAtLevel(foldingModel, foldLevel, doCollapse, blockedLineNumbers) {
  const filter2 = (region, level) => level === foldLevel && region.isCollapsed !== doCollapse && !blockedLineNumbers.some((line) => region.containsLine(line));
  const toToggle = foldingModel.getRegionsInside(null, filter2);
  foldingModel.toggleCollapseState(toToggle);
}
function setCollapseStateForRest(foldingModel, doCollapse, blockedLineNumbers) {
  const filteredRegions = [];
  for (const lineNumber of blockedLineNumbers) {
    const regions = foldingModel.getAllRegionsAtLine(lineNumber, void 0);
    if (regions.length > 0) {
      filteredRegions.push(regions[0]);
    }
  }
  const filter2 = (region) => filteredRegions.every((filteredRegion) => !filteredRegion.containedBy(region) && !region.containedBy(filteredRegion)) && region.isCollapsed !== doCollapse;
  const toToggle = foldingModel.getRegionsInside(null, filter2);
  foldingModel.toggleCollapseState(toToggle);
}
function setCollapseStateForMatchingLines(foldingModel, regExp, doCollapse) {
  const editorModel = foldingModel.textModel;
  const regions = foldingModel.regions;
  const toToggle = [];
  for (let i = regions.length - 1; i >= 0; i--) {
    if (doCollapse !== regions.isCollapsed(i)) {
      const startLineNumber = regions.getStartLineNumber(i);
      if (regExp.test(editorModel.getLineContent(startLineNumber))) {
        toToggle.push(regions.toRegion(i));
      }
    }
  }
  foldingModel.toggleCollapseState(toToggle);
}
function setCollapseStateForType(foldingModel, type, doCollapse) {
  const regions = foldingModel.regions;
  const toToggle = [];
  for (let i = regions.length - 1; i >= 0; i--) {
    if (doCollapse !== regions.isCollapsed(i) && type === regions.getType(i)) {
      toToggle.push(regions.toRegion(i));
    }
  }
  foldingModel.toggleCollapseState(toToggle);
}
function getParentFoldLine(lineNumber, foldingModel) {
  let startLineNumber = null;
  const foldingRegion = foldingModel.getRegionAtLine(lineNumber);
  if (foldingRegion !== null) {
    startLineNumber = foldingRegion.startLineNumber;
    if (lineNumber === startLineNumber) {
      const parentFoldingIdx = foldingRegion.parentIndex;
      if (parentFoldingIdx !== -1) {
        startLineNumber = foldingModel.regions.getStartLineNumber(parentFoldingIdx);
      } else {
        startLineNumber = null;
      }
    }
  }
  return startLineNumber;
}
function getPreviousFoldLine(lineNumber, foldingModel) {
  let foldingRegion = foldingModel.getRegionAtLine(lineNumber);
  if (foldingRegion !== null && foldingRegion.startLineNumber === lineNumber) {
    if (lineNumber !== foldingRegion.startLineNumber) {
      return foldingRegion.startLineNumber;
    } else {
      const expectedParentIndex = foldingRegion.parentIndex;
      let minLineNumber = 0;
      if (expectedParentIndex !== -1) {
        minLineNumber = foldingModel.regions.getStartLineNumber(foldingRegion.parentIndex);
      }
      while (foldingRegion !== null) {
        if (foldingRegion.regionIndex > 0) {
          foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex - 1);
          if (foldingRegion.startLineNumber <= minLineNumber) {
            return null;
          } else if (foldingRegion.parentIndex === expectedParentIndex) {
            return foldingRegion.startLineNumber;
          }
        } else {
          return null;
        }
      }
    }
  } else {
    if (foldingModel.regions.length > 0) {
      foldingRegion = foldingModel.regions.toRegion(foldingModel.regions.length - 1);
      while (foldingRegion !== null) {
        if (foldingRegion.startLineNumber < lineNumber) {
          return foldingRegion.startLineNumber;
        }
        if (foldingRegion.regionIndex > 0) {
          foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex - 1);
        } else {
          foldingRegion = null;
        }
      }
    }
  }
  return null;
}
function getNextFoldLine(lineNumber, foldingModel) {
  let foldingRegion = foldingModel.getRegionAtLine(lineNumber);
  if (foldingRegion !== null && foldingRegion.startLineNumber === lineNumber) {
    const expectedParentIndex = foldingRegion.parentIndex;
    let maxLineNumber = 0;
    if (expectedParentIndex !== -1) {
      maxLineNumber = foldingModel.regions.getEndLineNumber(foldingRegion.parentIndex);
    } else if (foldingModel.regions.length === 0) {
      return null;
    } else {
      maxLineNumber = foldingModel.regions.getEndLineNumber(foldingModel.regions.length - 1);
    }
    while (foldingRegion !== null) {
      if (foldingRegion.regionIndex < foldingModel.regions.length) {
        foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex + 1);
        if (foldingRegion.startLineNumber >= maxLineNumber) {
          return null;
        } else if (foldingRegion.parentIndex === expectedParentIndex) {
          return foldingRegion.startLineNumber;
        }
      } else {
        return null;
      }
    }
  } else {
    if (foldingModel.regions.length > 0) {
      foldingRegion = foldingModel.regions.toRegion(0);
      while (foldingRegion !== null) {
        if (foldingRegion.startLineNumber > lineNumber) {
          return foldingRegion.startLineNumber;
        }
        if (foldingRegion.regionIndex < foldingModel.regions.length) {
          foldingRegion = foldingModel.regions.toRegion(foldingRegion.regionIndex + 1);
        } else {
          foldingRegion = null;
        }
      }
    }
  }
  return null;
}
class HiddenRangeModel {
  get onDidChange() {
    return this._updateEventEmitter.event;
  }
  get hiddenRanges() {
    return this._hiddenRanges;
  }
  constructor(model) {
    this._updateEventEmitter = new Emitter$1();
    this._hasLineChanges = false;
    this._foldingModel = model;
    this._foldingModelListener = model.onDidChange((_) => this.updateHiddenRanges());
    this._hiddenRanges = [];
    if (model.regions.length) {
      this.updateHiddenRanges();
    }
  }
  notifyChangeModelContent(e) {
    if (this._hiddenRanges.length && !this._hasLineChanges) {
      this._hasLineChanges = e.changes.some((change) => {
        return change.range.endLineNumber !== change.range.startLineNumber || countEOL(change.text)[0] !== 0;
      });
    }
  }
  updateHiddenRanges() {
    let updateHiddenAreas = false;
    const newHiddenAreas = [];
    let i = 0;
    let k = 0;
    let lastCollapsedStart = Number.MAX_VALUE;
    let lastCollapsedEnd = -1;
    const ranges = this._foldingModel.regions;
    for (; i < ranges.length; i++) {
      if (!ranges.isCollapsed(i)) {
        continue;
      }
      const startLineNumber = ranges.getStartLineNumber(i) + 1;
      const endLineNumber = ranges.getEndLineNumber(i);
      if (lastCollapsedStart <= startLineNumber && endLineNumber <= lastCollapsedEnd) {
        continue;
      }
      if (!updateHiddenAreas && k < this._hiddenRanges.length && this._hiddenRanges[k].startLineNumber === startLineNumber && this._hiddenRanges[k].endLineNumber === endLineNumber) {
        newHiddenAreas.push(this._hiddenRanges[k]);
        k++;
      } else {
        updateHiddenAreas = true;
        newHiddenAreas.push(new Range$2(startLineNumber, 1, endLineNumber, 1));
      }
      lastCollapsedStart = startLineNumber;
      lastCollapsedEnd = endLineNumber;
    }
    if (this._hasLineChanges || updateHiddenAreas || k < this._hiddenRanges.length) {
      this.applyHiddenRanges(newHiddenAreas);
    }
  }
  applyHiddenRanges(newHiddenAreas) {
    this._hiddenRanges = newHiddenAreas;
    this._hasLineChanges = false;
    this._updateEventEmitter.fire(newHiddenAreas);
  }
  hasRanges() {
    return this._hiddenRanges.length > 0;
  }
  isHidden(line) {
    return findRange(this._hiddenRanges, line) !== null;
  }
  adjustSelections(selections2) {
    let hasChanges = false;
    const editorModel = this._foldingModel.textModel;
    let lastRange = null;
    const adjustLine = (line) => {
      if (!lastRange || !isInside(line, lastRange)) {
        lastRange = findRange(this._hiddenRanges, line);
      }
      if (lastRange) {
        return lastRange.startLineNumber - 1;
      }
      return null;
    };
    for (let i = 0, len = selections2.length; i < len; i++) {
      let selection = selections2[i];
      const adjustedStartLine = adjustLine(selection.startLineNumber);
      if (adjustedStartLine) {
        selection = selection.setStartPosition(adjustedStartLine, editorModel.getLineMaxColumn(adjustedStartLine));
        hasChanges = true;
      }
      const adjustedEndLine = adjustLine(selection.endLineNumber);
      if (adjustedEndLine) {
        selection = selection.setEndPosition(adjustedEndLine, editorModel.getLineMaxColumn(adjustedEndLine));
        hasChanges = true;
      }
      selections2[i] = selection;
    }
    return hasChanges;
  }
  dispose() {
    if (this.hiddenRanges.length > 0) {
      this._hiddenRanges = [];
      this._updateEventEmitter.fire(this._hiddenRanges);
    }
    if (this._foldingModelListener) {
      this._foldingModelListener.dispose();
      this._foldingModelListener = null;
    }
  }
}
function isInside(line, range2) {
  return line >= range2.startLineNumber && line <= range2.endLineNumber;
}
function findRange(ranges, line) {
  const i = findFirstInSorted$1(ranges, (r) => line < r.startLineNumber) - 1;
  if (i >= 0 && ranges[i].endLineNumber >= line) {
    return ranges[i];
  }
  return null;
}
const MAX_FOLDING_REGIONS_FOR_INDENT_DEFAULT = 5e3;
const ID_INDENT_PROVIDER = "indent";
class IndentRangeProvider {
  constructor(editorModel, languageConfigurationService, foldingRangesLimit) {
    this.editorModel = editorModel;
    this.languageConfigurationService = languageConfigurationService;
    this.foldingRangesLimit = foldingRangesLimit;
    this.id = ID_INDENT_PROVIDER;
  }
  dispose() {
  }
  compute(cancelationToken) {
    const foldingRules = this.languageConfigurationService.getLanguageConfiguration(this.editorModel.getLanguageId()).foldingRules;
    const offSide = foldingRules && !!foldingRules.offSide;
    const markers = foldingRules && foldingRules.markers;
    return Promise.resolve(computeRanges(this.editorModel, offSide, markers, this.foldingRangesLimit));
  }
}
let RangesCollector$1 = class RangesCollector {
  constructor(foldingRangesLimit) {
    this._startIndexes = [];
    this._endIndexes = [];
    this._indentOccurrences = [];
    this._length = 0;
    this._foldingRangesLimit = foldingRangesLimit;
  }
  insertFirst(startLineNumber, endLineNumber, indent) {
    if (startLineNumber > MAX_LINE_NUMBER || endLineNumber > MAX_LINE_NUMBER) {
      return;
    }
    const index = this._length;
    this._startIndexes[index] = startLineNumber;
    this._endIndexes[index] = endLineNumber;
    this._length++;
    if (indent < 1e3) {
      this._indentOccurrences[indent] = (this._indentOccurrences[indent] || 0) + 1;
    }
  }
  toIndentRanges(model) {
    const limit = this._foldingRangesLimit.limit;
    if (this._length <= limit) {
      this._foldingRangesLimit.update(this._length, false);
      const startIndexes = new Uint32Array(this._length);
      const endIndexes = new Uint32Array(this._length);
      for (let i = this._length - 1, k = 0; i >= 0; i--, k++) {
        startIndexes[k] = this._startIndexes[i];
        endIndexes[k] = this._endIndexes[i];
      }
      return new FoldingRegions(startIndexes, endIndexes);
    } else {
      this._foldingRangesLimit.update(this._length, limit);
      let entries = 0;
      let maxIndent = this._indentOccurrences.length;
      for (let i = 0; i < this._indentOccurrences.length; i++) {
        const n2 = this._indentOccurrences[i];
        if (n2) {
          if (n2 + entries > limit) {
            maxIndent = i;
            break;
          }
          entries += n2;
        }
      }
      const tabSize = model.getOptions().tabSize;
      const startIndexes = new Uint32Array(limit);
      const endIndexes = new Uint32Array(limit);
      for (let i = this._length - 1, k = 0; i >= 0; i--) {
        const startIndex = this._startIndexes[i];
        const lineContent = model.getLineContent(startIndex);
        const indent = computeIndentLevel(lineContent, tabSize);
        if (indent < maxIndent || indent === maxIndent && entries++ < limit) {
          startIndexes[k] = startIndex;
          endIndexes[k] = this._endIndexes[i];
          k++;
        }
      }
      return new FoldingRegions(startIndexes, endIndexes);
    }
  }
};
const foldingRangesLimitDefault = {
  limit: MAX_FOLDING_REGIONS_FOR_INDENT_DEFAULT,
  update: () => {
  }
};
function computeRanges(model, offSide, markers, foldingRangesLimit = foldingRangesLimitDefault) {
  const tabSize = model.getOptions().tabSize;
  const result2 = new RangesCollector$1(foldingRangesLimit);
  let pattern = void 0;
  if (markers) {
    pattern = new RegExp(`(${markers.start.source})|(?:${markers.end.source})`);
  }
  const previousRegions = [];
  const line = model.getLineCount() + 1;
  previousRegions.push({ indent: -1, endAbove: line, line });
  for (let line2 = model.getLineCount(); line2 > 0; line2--) {
    const lineContent = model.getLineContent(line2);
    const indent = computeIndentLevel(lineContent, tabSize);
    let previous = previousRegions[previousRegions.length - 1];
    if (indent === -1) {
      if (offSide) {
        previous.endAbove = line2;
      }
      continue;
    }
    let m;
    if (pattern && (m = lineContent.match(pattern))) {
      if (m[1]) {
        let i = previousRegions.length - 1;
        while (i > 0 && previousRegions[i].indent !== -2) {
          i--;
        }
        if (i > 0) {
          previousRegions.length = i + 1;
          previous = previousRegions[i];
          result2.insertFirst(line2, previous.line, indent);
          previous.line = line2;
          previous.indent = indent;
          previous.endAbove = line2;
          continue;
        }
      } else {
        previousRegions.push({ indent: -2, endAbove: line2, line: line2 });
        continue;
      }
    }
    if (previous.indent > indent) {
      do {
        previousRegions.pop();
        previous = previousRegions[previousRegions.length - 1];
      } while (previous.indent > indent);
      const endLineNumber = previous.endAbove - 1;
      if (endLineNumber - line2 >= 1) {
        result2.insertFirst(line2, endLineNumber, indent);
      }
    }
    if (previous.indent === indent) {
      previous.endAbove = line2;
    } else {
      previousRegions.push({ indent, endAbove: line2, line: line2 });
    }
  }
  return result2.toIndentRanges(model);
}
const foldBackground = registerColor("editor.foldBackground", { light: transparent(editorSelectionBackground, 0.3), dark: transparent(editorSelectionBackground, 0.3), hcDark: null, hcLight: null }, localize("foldBackgroundBackground", "Background color behind folded ranges. The color must not be opaque so as not to hide underlying decorations."), true);
registerColor("editorGutter.foldingControlForeground", { dark: iconForeground, light: iconForeground, hcDark: iconForeground, hcLight: iconForeground }, localize("editorGutter.foldingControlForeground", "Color of the folding control in the editor gutter."));
const foldingExpandedIcon = registerIcon("folding-expanded", Codicon.chevronDown, localize("foldingExpandedIcon", "Icon for expanded ranges in the editor glyph margin."));
const foldingCollapsedIcon = registerIcon("folding-collapsed", Codicon.chevronRight, localize("foldingCollapsedIcon", "Icon for collapsed ranges in the editor glyph margin."));
const foldingManualCollapsedIcon = registerIcon("folding-manual-collapsed", foldingCollapsedIcon, localize("foldingManualCollapedIcon", "Icon for manually collapsed ranges in the editor glyph margin."));
const foldingManualExpandedIcon = registerIcon("folding-manual-expanded", foldingExpandedIcon, localize("foldingManualExpandedIcon", "Icon for manually expanded ranges in the editor glyph margin."));
const foldedBackgroundMinimap = { color: themeColorFromId(foldBackground), position: MinimapPosition$1.Inline };
class FoldingDecorationProvider {
  constructor(editor2) {
    this.editor = editor2;
    this.showFoldingControls = "mouseover";
    this.showFoldingHighlights = true;
  }
  getDecorationOption(isCollapsed, isHidden, isManual) {
    if (isHidden) {
      return FoldingDecorationProvider.HIDDEN_RANGE_DECORATION;
    }
    if (this.showFoldingControls === "never") {
      if (isCollapsed) {
        return this.showFoldingHighlights ? FoldingDecorationProvider.NO_CONTROLS_COLLAPSED_HIGHLIGHTED_RANGE_DECORATION : FoldingDecorationProvider.NO_CONTROLS_COLLAPSED_RANGE_DECORATION;
      }
      return FoldingDecorationProvider.NO_CONTROLS_EXPANDED_RANGE_DECORATION;
    }
    if (isCollapsed) {
      return isManual ? this.showFoldingHighlights ? FoldingDecorationProvider.MANUALLY_COLLAPSED_HIGHLIGHTED_VISUAL_DECORATION : FoldingDecorationProvider.MANUALLY_COLLAPSED_VISUAL_DECORATION : this.showFoldingHighlights ? FoldingDecorationProvider.COLLAPSED_HIGHLIGHTED_VISUAL_DECORATION : FoldingDecorationProvider.COLLAPSED_VISUAL_DECORATION;
    } else if (this.showFoldingControls === "mouseover") {
      return isManual ? FoldingDecorationProvider.MANUALLY_EXPANDED_AUTO_HIDE_VISUAL_DECORATION : FoldingDecorationProvider.EXPANDED_AUTO_HIDE_VISUAL_DECORATION;
    } else {
      return isManual ? FoldingDecorationProvider.MANUALLY_EXPANDED_VISUAL_DECORATION : FoldingDecorationProvider.EXPANDED_VISUAL_DECORATION;
    }
  }
  changeDecorations(callback) {
    return this.editor.changeDecorations(callback);
  }
  removeDecorations(decorationIds) {
    this.editor.removeDecorations(decorationIds);
  }
}
FoldingDecorationProvider.COLLAPSED_VISUAL_DECORATION = ModelDecorationOptions.register({
  description: "folding-collapsed-visual-decoration",
  stickiness: 0,
  afterContentClassName: "inline-folded",
  isWholeLine: true,
  firstLineDecorationClassName: ThemeIcon.asClassName(foldingCollapsedIcon)
});
FoldingDecorationProvider.COLLAPSED_HIGHLIGHTED_VISUAL_DECORATION = ModelDecorationOptions.register({
  description: "folding-collapsed-highlighted-visual-decoration",
  stickiness: 0,
  afterContentClassName: "inline-folded",
  className: "folded-background",
  minimap: foldedBackgroundMinimap,
  isWholeLine: true,
  firstLineDecorationClassName: ThemeIcon.asClassName(foldingCollapsedIcon)
});
FoldingDecorationProvider.MANUALLY_COLLAPSED_VISUAL_DECORATION = ModelDecorationOptions.register({
  description: "folding-manually-collapsed-visual-decoration",
  stickiness: 0,
  afterContentClassName: "inline-folded",
  isWholeLine: true,
  firstLineDecorationClassName: ThemeIcon.asClassName(foldingManualCollapsedIcon)
});
FoldingDecorationProvider.MANUALLY_COLLAPSED_HIGHLIGHTED_VISUAL_DECORATION = ModelDecorationOptions.register({
  description: "folding-manually-collapsed-highlighted-visual-decoration",
  stickiness: 0,
  afterContentClassName: "inline-folded",
  className: "folded-background",
  minimap: foldedBackgroundMinimap,
  isWholeLine: true,
  firstLineDecorationClassName: ThemeIcon.asClassName(foldingManualCollapsedIcon)
});
FoldingDecorationProvider.NO_CONTROLS_COLLAPSED_RANGE_DECORATION = ModelDecorationOptions.register({
  description: "folding-no-controls-range-decoration",
  stickiness: 0,
  afterContentClassName: "inline-folded",
  isWholeLine: true
});
FoldingDecorationProvider.NO_CONTROLS_COLLAPSED_HIGHLIGHTED_RANGE_DECORATION = ModelDecorationOptions.register({
  description: "folding-no-controls-range-decoration",
  stickiness: 0,
  afterContentClassName: "inline-folded",
  className: "folded-background",
  minimap: foldedBackgroundMinimap,
  isWholeLine: true
});
FoldingDecorationProvider.EXPANDED_VISUAL_DECORATION = ModelDecorationOptions.register({
  description: "folding-expanded-visual-decoration",
  stickiness: 1,
  isWholeLine: true,
  firstLineDecorationClassName: "alwaysShowFoldIcons " + ThemeIcon.asClassName(foldingExpandedIcon)
});
FoldingDecorationProvider.EXPANDED_AUTO_HIDE_VISUAL_DECORATION = ModelDecorationOptions.register({
  description: "folding-expanded-auto-hide-visual-decoration",
  stickiness: 1,
  isWholeLine: true,
  firstLineDecorationClassName: ThemeIcon.asClassName(foldingExpandedIcon)
});
FoldingDecorationProvider.MANUALLY_EXPANDED_VISUAL_DECORATION = ModelDecorationOptions.register({
  description: "folding-manually-expanded-visual-decoration",
  stickiness: 0,
  isWholeLine: true,
  firstLineDecorationClassName: "alwaysShowFoldIcons " + ThemeIcon.asClassName(foldingManualExpandedIcon)
});
FoldingDecorationProvider.MANUALLY_EXPANDED_AUTO_HIDE_VISUAL_DECORATION = ModelDecorationOptions.register({
  description: "folding-manually-expanded-auto-hide-visual-decoration",
  stickiness: 0,
  isWholeLine: true,
  firstLineDecorationClassName: ThemeIcon.asClassName(foldingManualExpandedIcon)
});
FoldingDecorationProvider.NO_CONTROLS_EXPANDED_RANGE_DECORATION = ModelDecorationOptions.register({
  description: "folding-no-controls-range-decoration",
  stickiness: 0,
  isWholeLine: true
});
FoldingDecorationProvider.HIDDEN_RANGE_DECORATION = ModelDecorationOptions.register({
  description: "folding-hidden-range-decoration",
  stickiness: 1
  /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
});
const foldingContext = {};
const ID_SYNTAX_PROVIDER = "syntax";
class SyntaxRangeProvider {
  constructor(editorModel, providers, handleFoldingRangesChange, foldingRangesLimit, fallbackRangeProvider) {
    this.editorModel = editorModel;
    this.providers = providers;
    this.handleFoldingRangesChange = handleFoldingRangesChange;
    this.foldingRangesLimit = foldingRangesLimit;
    this.fallbackRangeProvider = fallbackRangeProvider;
    this.id = ID_SYNTAX_PROVIDER;
    this.disposables = new DisposableStore();
    if (fallbackRangeProvider) {
      this.disposables.add(fallbackRangeProvider);
    }
    for (const provider of providers) {
      if (typeof provider.onDidChange === "function") {
        this.disposables.add(provider.onDidChange(handleFoldingRangesChange));
      }
    }
  }
  compute(cancellationToken) {
    return collectSyntaxRanges(this.providers, this.editorModel, cancellationToken).then((ranges) => {
      var _a2, _b2;
      if (ranges) {
        const res = sanitizeRanges(ranges, this.foldingRangesLimit);
        return res;
      }
      return (_b2 = (_a2 = this.fallbackRangeProvider) === null || _a2 === void 0 ? void 0 : _a2.compute(cancellationToken)) !== null && _b2 !== void 0 ? _b2 : null;
    });
  }
  dispose() {
    this.disposables.dispose();
  }
}
function collectSyntaxRanges(providers, model, cancellationToken) {
  let rangeData = null;
  const promises = providers.map((provider, i) => {
    return Promise.resolve(provider.provideFoldingRanges(model, foldingContext, cancellationToken)).then((ranges) => {
      if (cancellationToken.isCancellationRequested) {
        return;
      }
      if (Array.isArray(ranges)) {
        if (!Array.isArray(rangeData)) {
          rangeData = [];
        }
        const nLines = model.getLineCount();
        for (const r of ranges) {
          if (r.start > 0 && r.end > r.start && r.end <= nLines) {
            rangeData.push({ start: r.start, end: r.end, rank: i, kind: r.kind });
          }
        }
      }
    }, onUnexpectedExternalError);
  });
  return Promise.all(promises).then((_) => {
    return rangeData;
  });
}
class RangesCollector2 {
  constructor(foldingRangesLimit) {
    this._startIndexes = [];
    this._endIndexes = [];
    this._nestingLevels = [];
    this._nestingLevelCounts = [];
    this._types = [];
    this._length = 0;
    this._foldingRangesLimit = foldingRangesLimit;
  }
  add(startLineNumber, endLineNumber, type, nestingLevel) {
    if (startLineNumber > MAX_LINE_NUMBER || endLineNumber > MAX_LINE_NUMBER) {
      return;
    }
    const index = this._length;
    this._startIndexes[index] = startLineNumber;
    this._endIndexes[index] = endLineNumber;
    this._nestingLevels[index] = nestingLevel;
    this._types[index] = type;
    this._length++;
    if (nestingLevel < 30) {
      this._nestingLevelCounts[nestingLevel] = (this._nestingLevelCounts[nestingLevel] || 0) + 1;
    }
  }
  toIndentRanges() {
    const limit = this._foldingRangesLimit.limit;
    if (this._length <= limit) {
      this._foldingRangesLimit.update(this._length, false);
      const startIndexes = new Uint32Array(this._length);
      const endIndexes = new Uint32Array(this._length);
      for (let i = 0; i < this._length; i++) {
        startIndexes[i] = this._startIndexes[i];
        endIndexes[i] = this._endIndexes[i];
      }
      return new FoldingRegions(startIndexes, endIndexes, this._types);
    } else {
      this._foldingRangesLimit.update(this._length, limit);
      let entries = 0;
      let maxLevel = this._nestingLevelCounts.length;
      for (let i = 0; i < this._nestingLevelCounts.length; i++) {
        const n2 = this._nestingLevelCounts[i];
        if (n2) {
          if (n2 + entries > limit) {
            maxLevel = i;
            break;
          }
          entries += n2;
        }
      }
      const startIndexes = new Uint32Array(limit);
      const endIndexes = new Uint32Array(limit);
      const types2 = [];
      for (let i = 0, k = 0; i < this._length; i++) {
        const level = this._nestingLevels[i];
        if (level < maxLevel || level === maxLevel && entries++ < limit) {
          startIndexes[k] = this._startIndexes[i];
          endIndexes[k] = this._endIndexes[i];
          types2[k] = this._types[i];
          k++;
        }
      }
      return new FoldingRegions(startIndexes, endIndexes, types2);
    }
  }
}
function sanitizeRanges(rangeData, foldingRangesLimit) {
  const sorted = rangeData.sort((d1, d2) => {
    let diff = d1.start - d2.start;
    if (diff === 0) {
      diff = d1.rank - d2.rank;
    }
    return diff;
  });
  const collector = new RangesCollector2(foldingRangesLimit);
  let top = void 0;
  const previous = [];
  for (const entry of sorted) {
    if (!top) {
      top = entry;
      collector.add(entry.start, entry.end, entry.kind && entry.kind.value, previous.length);
    } else {
      if (entry.start > top.start) {
        if (entry.end <= top.end) {
          previous.push(top);
          top = entry;
          collector.add(entry.start, entry.end, entry.kind && entry.kind.value, previous.length);
        } else {
          if (entry.start > top.end) {
            do {
              top = previous.pop();
            } while (top && entry.start > top.end);
            if (top) {
              previous.push(top);
            }
            top = entry;
          }
          collector.add(entry.start, entry.end, entry.kind && entry.kind.value, previous.length);
        }
      }
    }
  }
  return collector.toIndentRanges();
}
var __decorate$1f = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1d = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$P = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
const CONTEXT_FOLDING_ENABLED = new RawContextKey("foldingEnabled", false);
let FoldingController = class FoldingController2 extends Disposable {
  static get(editor2) {
    return editor2.getContribution(FoldingController2.ID);
  }
  static getFoldingRangeProviders(languageFeaturesService, model) {
    var _a2, _b2;
    const foldingRangeProviders = languageFeaturesService.foldingRangeProvider.ordered(model);
    return (_b2 = (_a2 = FoldingController2._foldingRangeSelector) === null || _a2 === void 0 ? void 0 : _a2.call(FoldingController2, foldingRangeProviders, model)) !== null && _b2 !== void 0 ? _b2 : foldingRangeProviders;
  }
  constructor(editor2, contextKeyService, languageConfigurationService, notificationService, languageFeatureDebounceService, languageFeaturesService) {
    super();
    this.contextKeyService = contextKeyService;
    this.languageConfigurationService = languageConfigurationService;
    this.languageFeaturesService = languageFeaturesService;
    this.localToDispose = this._register(new DisposableStore());
    this.editor = editor2;
    this._foldingLimitReporter = new RangesLimitReporter(editor2);
    const options = this.editor.getOptions();
    this._isEnabled = options.get(
      42
      /* EditorOption.folding */
    );
    this._useFoldingProviders = options.get(
      43
      /* EditorOption.foldingStrategy */
    ) !== "indentation";
    this._unfoldOnClickAfterEndOfLine = options.get(
      47
      /* EditorOption.unfoldOnClickAfterEndOfLine */
    );
    this._restoringViewState = false;
    this._currentModelHasFoldedImports = false;
    this._foldingImportsByDefault = options.get(
      45
      /* EditorOption.foldingImportsByDefault */
    );
    this.updateDebounceInfo = languageFeatureDebounceService.for(languageFeaturesService.foldingRangeProvider, "Folding", { min: 200 });
    this.foldingModel = null;
    this.hiddenRangeModel = null;
    this.rangeProvider = null;
    this.foldingRegionPromise = null;
    this.foldingModelPromise = null;
    this.updateScheduler = null;
    this.cursorChangedScheduler = null;
    this.mouseDownInfo = null;
    this.foldingDecorationProvider = new FoldingDecorationProvider(editor2);
    this.foldingDecorationProvider.showFoldingControls = options.get(
      108
      /* EditorOption.showFoldingControls */
    );
    this.foldingDecorationProvider.showFoldingHighlights = options.get(
      44
      /* EditorOption.foldingHighlight */
    );
    this.foldingEnabled = CONTEXT_FOLDING_ENABLED.bindTo(this.contextKeyService);
    this.foldingEnabled.set(this._isEnabled);
    this._register(this.editor.onDidChangeModel(() => this.onModelChanged()));
    this._register(this.editor.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        42
        /* EditorOption.folding */
      )) {
        this._isEnabled = this.editor.getOptions().get(
          42
          /* EditorOption.folding */
        );
        this.foldingEnabled.set(this._isEnabled);
        this.onModelChanged();
      }
      if (e.hasChanged(
        46
        /* EditorOption.foldingMaximumRegions */
      )) {
        this.onModelChanged();
      }
      if (e.hasChanged(
        108
        /* EditorOption.showFoldingControls */
      ) || e.hasChanged(
        44
        /* EditorOption.foldingHighlight */
      )) {
        const options2 = this.editor.getOptions();
        this.foldingDecorationProvider.showFoldingControls = options2.get(
          108
          /* EditorOption.showFoldingControls */
        );
        this.foldingDecorationProvider.showFoldingHighlights = options2.get(
          44
          /* EditorOption.foldingHighlight */
        );
        this.triggerFoldingModelChanged();
      }
      if (e.hasChanged(
        43
        /* EditorOption.foldingStrategy */
      )) {
        this._useFoldingProviders = this.editor.getOptions().get(
          43
          /* EditorOption.foldingStrategy */
        ) !== "indentation";
        this.onFoldingStrategyChanged();
      }
      if (e.hasChanged(
        47
        /* EditorOption.unfoldOnClickAfterEndOfLine */
      )) {
        this._unfoldOnClickAfterEndOfLine = this.editor.getOptions().get(
          47
          /* EditorOption.unfoldOnClickAfterEndOfLine */
        );
      }
      if (e.hasChanged(
        45
        /* EditorOption.foldingImportsByDefault */
      )) {
        this._foldingImportsByDefault = this.editor.getOptions().get(
          45
          /* EditorOption.foldingImportsByDefault */
        );
      }
    }));
    this.onModelChanged();
  }
  /**
   * Store view state.
   */
  saveViewState() {
    const model = this.editor.getModel();
    if (!model || !this._isEnabled || model.isTooLargeForTokenization()) {
      return {};
    }
    if (this.foldingModel) {
      const collapsedRegions = this.foldingModel.getMemento();
      const provider = this.rangeProvider ? this.rangeProvider.id : void 0;
      return { collapsedRegions, lineCount: model.getLineCount(), provider, foldedImports: this._currentModelHasFoldedImports };
    }
    return void 0;
  }
  /**
   * Restore view state.
   */
  restoreViewState(state) {
    const model = this.editor.getModel();
    if (!model || !this._isEnabled || model.isTooLargeForTokenization() || !this.hiddenRangeModel) {
      return;
    }
    if (!state) {
      return;
    }
    this._currentModelHasFoldedImports = !!state.foldedImports;
    if (state.collapsedRegions && state.collapsedRegions.length > 0 && this.foldingModel) {
      this._restoringViewState = true;
      try {
        this.foldingModel.applyMemento(state.collapsedRegions);
      } finally {
        this._restoringViewState = false;
      }
    }
  }
  onModelChanged() {
    this.localToDispose.clear();
    const model = this.editor.getModel();
    if (!this._isEnabled || !model || model.isTooLargeForTokenization()) {
      return;
    }
    this._currentModelHasFoldedImports = false;
    this.foldingModel = new FoldingModel(model, this.foldingDecorationProvider);
    this.localToDispose.add(this.foldingModel);
    this.hiddenRangeModel = new HiddenRangeModel(this.foldingModel);
    this.localToDispose.add(this.hiddenRangeModel);
    this.localToDispose.add(this.hiddenRangeModel.onDidChange((hr) => this.onHiddenRangesChanges(hr)));
    this.updateScheduler = new Delayer(this.updateDebounceInfo.get(model));
    this.cursorChangedScheduler = new RunOnceScheduler(() => this.revealCursor(), 200);
    this.localToDispose.add(this.cursorChangedScheduler);
    this.localToDispose.add(this.languageFeaturesService.foldingRangeProvider.onDidChange(() => this.onFoldingStrategyChanged()));
    this.localToDispose.add(this.editor.onDidChangeModelLanguageConfiguration(() => this.onFoldingStrategyChanged()));
    this.localToDispose.add(this.editor.onDidChangeModelContent((e) => this.onDidChangeModelContent(e)));
    this.localToDispose.add(this.editor.onDidChangeCursorPosition(() => this.onCursorPositionChanged()));
    this.localToDispose.add(this.editor.onMouseDown((e) => this.onEditorMouseDown(e)));
    this.localToDispose.add(this.editor.onMouseUp((e) => this.onEditorMouseUp(e)));
    this.localToDispose.add({
      dispose: () => {
        var _a2, _b2;
        if (this.foldingRegionPromise) {
          this.foldingRegionPromise.cancel();
          this.foldingRegionPromise = null;
        }
        (_a2 = this.updateScheduler) === null || _a2 === void 0 ? void 0 : _a2.cancel();
        this.updateScheduler = null;
        this.foldingModel = null;
        this.foldingModelPromise = null;
        this.hiddenRangeModel = null;
        this.cursorChangedScheduler = null;
        (_b2 = this.rangeProvider) === null || _b2 === void 0 ? void 0 : _b2.dispose();
        this.rangeProvider = null;
      }
    });
    this.triggerFoldingModelChanged();
  }
  onFoldingStrategyChanged() {
    var _a2;
    (_a2 = this.rangeProvider) === null || _a2 === void 0 ? void 0 : _a2.dispose();
    this.rangeProvider = null;
    this.triggerFoldingModelChanged();
  }
  getRangeProvider(editorModel) {
    if (this.rangeProvider) {
      return this.rangeProvider;
    }
    const indentRangeProvider = new IndentRangeProvider(editorModel, this.languageConfigurationService, this._foldingLimitReporter);
    this.rangeProvider = indentRangeProvider;
    if (this._useFoldingProviders && this.foldingModel) {
      const selectedProviders = FoldingController2.getFoldingRangeProviders(this.languageFeaturesService, editorModel);
      if (selectedProviders.length > 0) {
        this.rangeProvider = new SyntaxRangeProvider(editorModel, selectedProviders, () => this.triggerFoldingModelChanged(), this._foldingLimitReporter, indentRangeProvider);
      }
    }
    return this.rangeProvider;
  }
  getFoldingModel() {
    return this.foldingModelPromise;
  }
  onDidChangeModelContent(e) {
    var _a2;
    (_a2 = this.hiddenRangeModel) === null || _a2 === void 0 ? void 0 : _a2.notifyChangeModelContent(e);
    this.triggerFoldingModelChanged();
  }
  triggerFoldingModelChanged() {
    if (this.updateScheduler) {
      if (this.foldingRegionPromise) {
        this.foldingRegionPromise.cancel();
        this.foldingRegionPromise = null;
      }
      this.foldingModelPromise = this.updateScheduler.trigger(() => {
        const foldingModel = this.foldingModel;
        if (!foldingModel) {
          return null;
        }
        const sw = new StopWatch();
        const provider = this.getRangeProvider(foldingModel.textModel);
        const foldingRegionPromise = this.foldingRegionPromise = createCancelablePromise((token) => provider.compute(token));
        return foldingRegionPromise.then((foldingRanges) => {
          if (foldingRanges && foldingRegionPromise === this.foldingRegionPromise) {
            let scrollState;
            if (this._foldingImportsByDefault && !this._currentModelHasFoldedImports) {
              const hasChanges = foldingRanges.setCollapsedAllOfType(FoldingRangeKind.Imports.value, true);
              if (hasChanges) {
                scrollState = StableEditorScrollState.capture(this.editor);
                this._currentModelHasFoldedImports = hasChanges;
              }
            }
            const selections2 = this.editor.getSelections();
            const selectionLineNumbers = selections2 ? selections2.map((s) => s.startLineNumber) : [];
            foldingModel.update(foldingRanges, selectionLineNumbers);
            scrollState === null || scrollState === void 0 ? void 0 : scrollState.restore(this.editor);
            const newValue = this.updateDebounceInfo.update(foldingModel.textModel, sw.elapsed());
            if (this.updateScheduler) {
              this.updateScheduler.defaultDelay = newValue;
            }
          }
          return foldingModel;
        });
      }).then(void 0, (err) => {
        onUnexpectedError(err);
        return null;
      });
    }
  }
  onHiddenRangesChanges(hiddenRanges) {
    if (this.hiddenRangeModel && hiddenRanges.length && !this._restoringViewState) {
      const selections2 = this.editor.getSelections();
      if (selections2) {
        if (this.hiddenRangeModel.adjustSelections(selections2)) {
          this.editor.setSelections(selections2);
        }
      }
    }
    this.editor.setHiddenAreas(hiddenRanges, this);
  }
  onCursorPositionChanged() {
    if (this.hiddenRangeModel && this.hiddenRangeModel.hasRanges()) {
      this.cursorChangedScheduler.schedule();
    }
  }
  revealCursor() {
    const foldingModel = this.getFoldingModel();
    if (!foldingModel) {
      return;
    }
    foldingModel.then((foldingModel2) => {
      if (foldingModel2) {
        const selections2 = this.editor.getSelections();
        if (selections2 && selections2.length > 0) {
          const toToggle = [];
          for (const selection of selections2) {
            const lineNumber = selection.selectionStartLineNumber;
            if (this.hiddenRangeModel && this.hiddenRangeModel.isHidden(lineNumber)) {
              toToggle.push(...foldingModel2.getAllRegionsAtLine(lineNumber, (r) => r.isCollapsed && lineNumber > r.startLineNumber));
            }
          }
          if (toToggle.length) {
            foldingModel2.toggleCollapseState(toToggle);
            this.reveal(selections2[0].getPosition());
          }
        }
      }
    }).then(void 0, onUnexpectedError);
  }
  onEditorMouseDown(e) {
    this.mouseDownInfo = null;
    if (!this.hiddenRangeModel || !e.target || !e.target.range) {
      return;
    }
    if (!e.event.leftButton && !e.event.middleButton) {
      return;
    }
    const range2 = e.target.range;
    let iconClicked = false;
    switch (e.target.type) {
      case 4: {
        const data = e.target.detail;
        const offsetLeftInGutter = e.target.element.offsetLeft;
        const gutterOffsetX = data.offsetX - offsetLeftInGutter;
        if (gutterOffsetX < 4) {
          return;
        }
        iconClicked = true;
        break;
      }
      case 7: {
        if (this._unfoldOnClickAfterEndOfLine && this.hiddenRangeModel.hasRanges()) {
          const data = e.target.detail;
          if (!data.isAfterLines) {
            break;
          }
        }
        return;
      }
      case 6: {
        if (this.hiddenRangeModel.hasRanges()) {
          const model = this.editor.getModel();
          if (model && range2.startColumn === model.getLineMaxColumn(range2.startLineNumber)) {
            break;
          }
        }
        return;
      }
      default:
        return;
    }
    this.mouseDownInfo = { lineNumber: range2.startLineNumber, iconClicked };
  }
  onEditorMouseUp(e) {
    const foldingModel = this.foldingModel;
    if (!foldingModel || !this.mouseDownInfo || !e.target) {
      return;
    }
    const lineNumber = this.mouseDownInfo.lineNumber;
    const iconClicked = this.mouseDownInfo.iconClicked;
    const range2 = e.target.range;
    if (!range2 || range2.startLineNumber !== lineNumber) {
      return;
    }
    if (iconClicked) {
      if (e.target.type !== 4) {
        return;
      }
    } else {
      const model = this.editor.getModel();
      if (!model || range2.startColumn !== model.getLineMaxColumn(lineNumber)) {
        return;
      }
    }
    const region = foldingModel.getRegionAtLine(lineNumber);
    if (region && region.startLineNumber === lineNumber) {
      const isCollapsed = region.isCollapsed;
      if (iconClicked || isCollapsed) {
        const surrounding = e.event.altKey;
        let toToggle = [];
        if (surrounding) {
          const filter2 = (otherRegion) => !otherRegion.containedBy(region) && !region.containedBy(otherRegion);
          const toMaybeToggle = foldingModel.getRegionsInside(null, filter2);
          for (const r of toMaybeToggle) {
            if (r.isCollapsed) {
              toToggle.push(r);
            }
          }
          if (toToggle.length === 0) {
            toToggle = toMaybeToggle;
          }
        } else {
          const recursive = e.event.middleButton || e.event.shiftKey;
          if (recursive) {
            for (const r of foldingModel.getRegionsInside(region)) {
              if (r.isCollapsed === isCollapsed) {
                toToggle.push(r);
              }
            }
          }
          if (isCollapsed || !recursive || toToggle.length === 0) {
            toToggle.push(region);
          }
        }
        foldingModel.toggleCollapseState(toToggle);
        this.reveal({ lineNumber, column: 1 });
      }
    }
  }
  reveal(position) {
    this.editor.revealPositionInCenterIfOutsideViewport(
      position,
      0
      /* ScrollType.Smooth */
    );
  }
};
FoldingController.ID = "editor.contrib.folding";
FoldingController = __decorate$1f([
  __param$1d(1, IContextKeyService),
  __param$1d(2, ILanguageConfigurationService),
  __param$1d(3, INotificationService),
  __param$1d(4, ILanguageFeatureDebounceService),
  __param$1d(5, ILanguageFeaturesService)
], FoldingController);
class RangesLimitReporter {
  constructor(editor2) {
    this.editor = editor2;
    this._onDidChange = new Emitter$1();
    this._computed = 0;
    this._limited = false;
  }
  get limit() {
    return this.editor.getOptions().get(
      46
      /* EditorOption.foldingMaximumRegions */
    );
  }
  update(computed2, limited) {
    if (computed2 !== this._computed || limited !== this._limited) {
      this._computed = computed2;
      this._limited = limited;
      this._onDidChange.fire();
    }
  }
}
class FoldingAction extends EditorAction {
  runEditorCommand(accessor, editor2, args) {
    const languageConfigurationService = accessor.get(ILanguageConfigurationService);
    const foldingController = FoldingController.get(editor2);
    if (!foldingController) {
      return;
    }
    const foldingModelPromise = foldingController.getFoldingModel();
    if (foldingModelPromise) {
      this.reportTelemetry(accessor, editor2);
      return foldingModelPromise.then((foldingModel) => {
        if (foldingModel) {
          this.invoke(foldingController, foldingModel, editor2, args, languageConfigurationService);
          const selection = editor2.getSelection();
          if (selection) {
            foldingController.reveal(selection.getStartPosition());
          }
        }
      });
    }
  }
  getSelectedLines(editor2) {
    const selections2 = editor2.getSelections();
    return selections2 ? selections2.map((s) => s.startLineNumber) : [];
  }
  getLineNumbers(args, editor2) {
    if (args && args.selectionLines) {
      return args.selectionLines.map((l) => l + 1);
    }
    return this.getSelectedLines(editor2);
  }
  run(_accessor, _editor) {
  }
}
function foldingArgumentsConstraint(args) {
  if (!isUndefined$1(args)) {
    if (!isObject$4(args)) {
      return false;
    }
    const foldingArgs = args;
    if (!isUndefined$1(foldingArgs.levels) && !isNumber$3(foldingArgs.levels)) {
      return false;
    }
    if (!isUndefined$1(foldingArgs.direction) && !isString$4(foldingArgs.direction)) {
      return false;
    }
    if (!isUndefined$1(foldingArgs.selectionLines) && (!Array.isArray(foldingArgs.selectionLines) || !foldingArgs.selectionLines.every(isNumber$3))) {
      return false;
    }
  }
  return true;
}
class UnfoldAction extends FoldingAction {
  constructor() {
    super({
      id: "editor.unfold",
      label: localize("unfoldAction.label", "Unfold"),
      alias: "Unfold",
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 1024 | 94,
        mac: {
          primary: 2048 | 512 | 94
          /* KeyCode.BracketRight */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      description: {
        description: "Unfold the content in the editor",
        args: [
          {
            name: "Unfold editor argument",
            description: `Property-value pairs that can be passed through this argument:
						* 'levels': Number of levels to unfold. If not set, defaults to 1.
						* 'direction': If 'up', unfold given number of levels up otherwise unfolds down.
						* 'selectionLines': Array of the start lines (0-based) of the editor selections to apply the unfold action to. If not set, the active selection(s) will be used.
						`,
            constraint: foldingArgumentsConstraint,
            schema: {
              "type": "object",
              "properties": {
                "levels": {
                  "type": "number",
                  "default": 1
                },
                "direction": {
                  "type": "string",
                  "enum": ["up", "down"],
                  "default": "down"
                },
                "selectionLines": {
                  "type": "array",
                  "items": {
                    "type": "number"
                  }
                }
              }
            }
          }
        ]
      }
    });
  }
  invoke(_foldingController, foldingModel, editor2, args) {
    const levels = args && args.levels || 1;
    const lineNumbers2 = this.getLineNumbers(args, editor2);
    if (args && args.direction === "up") {
      setCollapseStateLevelsUp(foldingModel, false, levels, lineNumbers2);
    } else {
      setCollapseStateLevelsDown(foldingModel, false, levels, lineNumbers2);
    }
  }
}
class UnFoldRecursivelyAction extends FoldingAction {
  constructor() {
    super({
      id: "editor.unfoldRecursively",
      label: localize("unFoldRecursivelyAction.label", "Unfold Recursively"),
      alias: "Unfold Recursively",
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: KeyChord(
          2048 | 41,
          2048 | 94
          /* KeyCode.BracketRight */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, editor2, _args) {
    setCollapseStateLevelsDown(foldingModel, false, Number.MAX_VALUE, this.getSelectedLines(editor2));
  }
}
class FoldAction extends FoldingAction {
  constructor() {
    super({
      id: "editor.fold",
      label: localize("foldAction.label", "Fold"),
      alias: "Fold",
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 1024 | 92,
        mac: {
          primary: 2048 | 512 | 92
          /* KeyCode.BracketLeft */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      description: {
        description: "Fold the content in the editor",
        args: [
          {
            name: "Fold editor argument",
            description: `Property-value pairs that can be passed through this argument:
							* 'levels': Number of levels to fold.
							* 'direction': If 'up', folds given number of levels up otherwise folds down.
							* 'selectionLines': Array of the start lines (0-based) of the editor selections to apply the fold action to. If not set, the active selection(s) will be used.
							If no levels or direction is set, folds the region at the locations or if already collapsed, the first uncollapsed parent instead.
						`,
            constraint: foldingArgumentsConstraint,
            schema: {
              "type": "object",
              "properties": {
                "levels": {
                  "type": "number"
                },
                "direction": {
                  "type": "string",
                  "enum": ["up", "down"]
                },
                "selectionLines": {
                  "type": "array",
                  "items": {
                    "type": "number"
                  }
                }
              }
            }
          }
        ]
      }
    });
  }
  invoke(_foldingController, foldingModel, editor2, args) {
    const lineNumbers2 = this.getLineNumbers(args, editor2);
    const levels = args && args.levels;
    const direction = args && args.direction;
    if (typeof levels !== "number" && typeof direction !== "string") {
      setCollapseStateUp(foldingModel, true, lineNumbers2);
    } else {
      if (direction === "up") {
        setCollapseStateLevelsUp(foldingModel, true, levels || 1, lineNumbers2);
      } else {
        setCollapseStateLevelsDown(foldingModel, true, levels || 1, lineNumbers2);
      }
    }
  }
}
class ToggleFoldAction extends FoldingAction {
  constructor() {
    super({
      id: "editor.toggleFold",
      label: localize("toggleFoldAction.label", "Toggle Fold"),
      alias: "Toggle Fold",
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: KeyChord(
          2048 | 41,
          2048 | 42
          /* KeyCode.KeyL */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, editor2) {
    const selectedLines = this.getSelectedLines(editor2);
    toggleCollapseState(foldingModel, 1, selectedLines);
  }
}
class FoldRecursivelyAction extends FoldingAction {
  constructor() {
    super({
      id: "editor.foldRecursively",
      label: localize("foldRecursivelyAction.label", "Fold Recursively"),
      alias: "Fold Recursively",
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: KeyChord(
          2048 | 41,
          2048 | 92
          /* KeyCode.BracketLeft */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, editor2) {
    const selectedLines = this.getSelectedLines(editor2);
    setCollapseStateLevelsDown(foldingModel, true, Number.MAX_VALUE, selectedLines);
  }
}
class FoldAllBlockCommentsAction extends FoldingAction {
  constructor() {
    super({
      id: "editor.foldAllBlockComments",
      label: localize("foldAllBlockComments.label", "Fold All Block Comments"),
      alias: "Fold All Block Comments",
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: KeyChord(
          2048 | 41,
          2048 | 90
          /* KeyCode.Slash */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, editor2, args, languageConfigurationService) {
    if (foldingModel.regions.hasTypes()) {
      setCollapseStateForType(foldingModel, FoldingRangeKind.Comment.value, true);
    } else {
      const editorModel = editor2.getModel();
      if (!editorModel) {
        return;
      }
      const comments = languageConfigurationService.getLanguageConfiguration(editorModel.getLanguageId()).comments;
      if (comments && comments.blockCommentStartToken) {
        const regExp = new RegExp("^\\s*" + escapeRegExpCharacters(comments.blockCommentStartToken));
        setCollapseStateForMatchingLines(foldingModel, regExp, true);
      }
    }
  }
}
class FoldAllRegionsAction extends FoldingAction {
  constructor() {
    super({
      id: "editor.foldAllMarkerRegions",
      label: localize("foldAllMarkerRegions.label", "Fold All Regions"),
      alias: "Fold All Regions",
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: KeyChord(
          2048 | 41,
          2048 | 29
          /* KeyCode.Digit8 */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, editor2, args, languageConfigurationService) {
    if (foldingModel.regions.hasTypes()) {
      setCollapseStateForType(foldingModel, FoldingRangeKind.Region.value, true);
    } else {
      const editorModel = editor2.getModel();
      if (!editorModel) {
        return;
      }
      const foldingRules = languageConfigurationService.getLanguageConfiguration(editorModel.getLanguageId()).foldingRules;
      if (foldingRules && foldingRules.markers && foldingRules.markers.start) {
        const regExp = new RegExp(foldingRules.markers.start);
        setCollapseStateForMatchingLines(foldingModel, regExp, true);
      }
    }
  }
}
class UnfoldAllRegionsAction extends FoldingAction {
  constructor() {
    super({
      id: "editor.unfoldAllMarkerRegions",
      label: localize("unfoldAllMarkerRegions.label", "Unfold All Regions"),
      alias: "Unfold All Regions",
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: KeyChord(
          2048 | 41,
          2048 | 30
          /* KeyCode.Digit9 */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, editor2, args, languageConfigurationService) {
    if (foldingModel.regions.hasTypes()) {
      setCollapseStateForType(foldingModel, FoldingRangeKind.Region.value, false);
    } else {
      const editorModel = editor2.getModel();
      if (!editorModel) {
        return;
      }
      const foldingRules = languageConfigurationService.getLanguageConfiguration(editorModel.getLanguageId()).foldingRules;
      if (foldingRules && foldingRules.markers && foldingRules.markers.start) {
        const regExp = new RegExp(foldingRules.markers.start);
        setCollapseStateForMatchingLines(foldingModel, regExp, false);
      }
    }
  }
}
class FoldAllRegionsExceptAction extends FoldingAction {
  constructor() {
    super({
      id: "editor.foldAllExcept",
      label: localize("foldAllExcept.label", "Fold All Regions Except Selected"),
      alias: "Fold All Regions Except Selected",
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: KeyChord(
          2048 | 41,
          2048 | 88
          /* KeyCode.Minus */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, editor2) {
    const selectedLines = this.getSelectedLines(editor2);
    setCollapseStateForRest(foldingModel, true, selectedLines);
  }
}
class UnfoldAllRegionsExceptAction extends FoldingAction {
  constructor() {
    super({
      id: "editor.unfoldAllExcept",
      label: localize("unfoldAllExcept.label", "Unfold All Regions Except Selected"),
      alias: "Unfold All Regions Except Selected",
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: KeyChord(
          2048 | 41,
          2048 | 86
          /* KeyCode.Equal */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, editor2) {
    const selectedLines = this.getSelectedLines(editor2);
    setCollapseStateForRest(foldingModel, false, selectedLines);
  }
}
class FoldAllAction extends FoldingAction {
  constructor() {
    super({
      id: "editor.foldAll",
      label: localize("foldAllAction.label", "Fold All"),
      alias: "Fold All",
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: KeyChord(
          2048 | 41,
          2048 | 21
          /* KeyCode.Digit0 */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, _editor) {
    setCollapseStateLevelsDown(foldingModel, true);
  }
}
class UnfoldAllAction extends FoldingAction {
  constructor() {
    super({
      id: "editor.unfoldAll",
      label: localize("unfoldAllAction.label", "Unfold All"),
      alias: "Unfold All",
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: KeyChord(
          2048 | 41,
          2048 | 40
          /* KeyCode.KeyJ */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, _editor) {
    setCollapseStateLevelsDown(foldingModel, false);
  }
}
class FoldLevelAction extends FoldingAction {
  getFoldingLevel() {
    return parseInt(this.id.substr(FoldLevelAction.ID_PREFIX.length));
  }
  invoke(_foldingController, foldingModel, editor2) {
    setCollapseStateAtLevel(foldingModel, this.getFoldingLevel(), true, this.getSelectedLines(editor2));
  }
}
FoldLevelAction.ID_PREFIX = "editor.foldLevel";
FoldLevelAction.ID = (level) => FoldLevelAction.ID_PREFIX + level;
class GotoParentFoldAction extends FoldingAction {
  constructor() {
    super({
      id: "editor.gotoParentFold",
      label: localize("gotoParentFold.label", "Go to Parent Fold"),
      alias: "Go to Parent Fold",
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, editor2) {
    const selectedLines = this.getSelectedLines(editor2);
    if (selectedLines.length > 0) {
      const startLineNumber = getParentFoldLine(selectedLines[0], foldingModel);
      if (startLineNumber !== null) {
        editor2.setSelection({
          startLineNumber,
          startColumn: 1,
          endLineNumber: startLineNumber,
          endColumn: 1
        });
      }
    }
  }
}
class GotoPreviousFoldAction extends FoldingAction {
  constructor() {
    super({
      id: "editor.gotoPreviousFold",
      label: localize("gotoPreviousFold.label", "Go to Previous Folding Range"),
      alias: "Go to Previous Folding Range",
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, editor2) {
    const selectedLines = this.getSelectedLines(editor2);
    if (selectedLines.length > 0) {
      const startLineNumber = getPreviousFoldLine(selectedLines[0], foldingModel);
      if (startLineNumber !== null) {
        editor2.setSelection({
          startLineNumber,
          startColumn: 1,
          endLineNumber: startLineNumber,
          endColumn: 1
        });
      }
    }
  }
}
class GotoNextFoldAction extends FoldingAction {
  constructor() {
    super({
      id: "editor.gotoNextFold",
      label: localize("gotoNextFold.label", "Go to Next Folding Range"),
      alias: "Go to Next Folding Range",
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, editor2) {
    const selectedLines = this.getSelectedLines(editor2);
    if (selectedLines.length > 0) {
      const startLineNumber = getNextFoldLine(selectedLines[0], foldingModel);
      if (startLineNumber !== null) {
        editor2.setSelection({
          startLineNumber,
          startColumn: 1,
          endLineNumber: startLineNumber,
          endColumn: 1
        });
      }
    }
  }
}
class FoldRangeFromSelectionAction extends FoldingAction {
  constructor() {
    super({
      id: "editor.createFoldingRangeFromSelection",
      label: localize("createManualFoldRange.label", "Create Folding Range from Selection"),
      alias: "Create Folding Range from Selection",
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: KeyChord(
          2048 | 41,
          2048 | 87
          /* KeyCode.Comma */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(_foldingController, foldingModel, editor2) {
    var _a2;
    const collapseRanges = [];
    const selections2 = editor2.getSelections();
    if (selections2) {
      for (const selection of selections2) {
        let endLineNumber = selection.endLineNumber;
        if (selection.endColumn === 1) {
          --endLineNumber;
        }
        if (endLineNumber > selection.startLineNumber) {
          collapseRanges.push({
            startLineNumber: selection.startLineNumber,
            endLineNumber,
            type: void 0,
            isCollapsed: true,
            source: 1
            /* FoldSource.userDefined */
          });
          editor2.setSelection({
            startLineNumber: selection.startLineNumber,
            startColumn: 1,
            endLineNumber: selection.startLineNumber,
            endColumn: 1
          });
        }
      }
      if (collapseRanges.length > 0) {
        collapseRanges.sort((a, b) => {
          return a.startLineNumber - b.startLineNumber;
        });
        const newRanges = FoldingRegions.sanitizeAndMerge(foldingModel.regions, collapseRanges, (_a2 = editor2.getModel()) === null || _a2 === void 0 ? void 0 : _a2.getLineCount());
        foldingModel.updatePost(FoldingRegions.fromFoldRanges(newRanges));
      }
    }
  }
}
class RemoveFoldRangeFromSelectionAction extends FoldingAction {
  constructor() {
    super({
      id: "editor.removeManualFoldingRanges",
      label: localize("removeManualFoldingRanges.label", "Remove Manual Folding Ranges"),
      alias: "Remove Manual Folding Ranges",
      precondition: CONTEXT_FOLDING_ENABLED,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: KeyChord(
          2048 | 41,
          2048 | 89
          /* KeyCode.Period */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  invoke(foldingController, foldingModel, editor2) {
    const selections2 = editor2.getSelections();
    if (selections2) {
      const ranges = [];
      for (const selection of selections2) {
        const { startLineNumber, endLineNumber } = selection;
        ranges.push(endLineNumber >= startLineNumber ? { startLineNumber, endLineNumber } : { endLineNumber, startLineNumber });
      }
      foldingModel.removeManualRanges(ranges);
      foldingController.triggerFoldingModelChanged();
    }
  }
}
registerEditorContribution(
  FoldingController.ID,
  FoldingController,
  0
  /* EditorContributionInstantiation.Eager */
);
registerEditorAction(UnfoldAction);
registerEditorAction(UnFoldRecursivelyAction);
registerEditorAction(FoldAction);
registerEditorAction(FoldRecursivelyAction);
registerEditorAction(FoldAllAction);
registerEditorAction(UnfoldAllAction);
registerEditorAction(FoldAllBlockCommentsAction);
registerEditorAction(FoldAllRegionsAction);
registerEditorAction(UnfoldAllRegionsAction);
registerEditorAction(FoldAllRegionsExceptAction);
registerEditorAction(UnfoldAllRegionsExceptAction);
registerEditorAction(ToggleFoldAction);
registerEditorAction(GotoParentFoldAction);
registerEditorAction(GotoPreviousFoldAction);
registerEditorAction(GotoNextFoldAction);
registerEditorAction(FoldRangeFromSelectionAction);
registerEditorAction(RemoveFoldRangeFromSelectionAction);
for (let i = 1; i <= 7; i++) {
  registerInstantiatedEditorAction(new FoldLevelAction({
    id: FoldLevelAction.ID(i),
    label: localize("foldLevelAction.label", "Fold Level {0}", i),
    alias: `Fold Level ${i}`,
    precondition: CONTEXT_FOLDING_ENABLED,
    kbOpts: {
      kbExpr: EditorContextKeys.editorTextFocus,
      primary: KeyChord(2048 | 41, 2048 | 21 + i),
      weight: 100
      /* KeybindingWeight.EditorContrib */
    }
  }));
}
CommandsRegistry.registerCommand("_executeFoldingRangeProvider", function(accessor, ...args) {
  return __awaiter$P(this, void 0, void 0, function* () {
    const [resource] = args;
    if (!(resource instanceof URI)) {
      throw illegalArgument();
    }
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const model = accessor.get(IModelService).getModel(resource);
    if (!model) {
      throw illegalArgument();
    }
    const configurationService = accessor.get(IConfigurationService);
    if (!configurationService.getValue("editor.folding", { resource })) {
      return [];
    }
    const languageConfigurationService = accessor.get(ILanguageConfigurationService);
    const strategy = configurationService.getValue("editor.foldingStrategy", { resource });
    const foldingLimitReporter = {
      get limit() {
        return configurationService.getValue("editor.foldingMaximumRegions", { resource });
      },
      update: (computed2, limited) => {
      }
    };
    const indentRangeProvider = new IndentRangeProvider(model, languageConfigurationService, foldingLimitReporter);
    let rangeProvider = indentRangeProvider;
    if (strategy !== "indentation") {
      const providers = FoldingController.getFoldingRangeProviders(languageFeaturesService, model);
      if (providers.length) {
        rangeProvider = new SyntaxRangeProvider(model, providers, () => {
        }, foldingLimitReporter, indentRangeProvider);
      }
    }
    const ranges = yield rangeProvider.compute(CancellationToken.None);
    const result2 = [];
    try {
      if (ranges) {
        for (let i = 0; i < ranges.length; i++) {
          const type = ranges.getType(i);
          result2.push({ start: ranges.getStartLineNumber(i), end: ranges.getEndLineNumber(i), kind: type ? FoldingRangeKind.fromValue(type) : void 0 });
        }
      }
      return result2;
    } finally {
      rangeProvider.dispose();
    }
  });
});
class EditorFontZoomIn extends EditorAction {
  constructor() {
    super({
      id: "editor.action.fontZoomIn",
      label: localize("EditorFontZoomIn.label", "Editor Font Zoom In"),
      alias: "Editor Font Zoom In",
      precondition: void 0
    });
  }
  run(accessor, editor2) {
    EditorZoom.setZoomLevel(EditorZoom.getZoomLevel() + 1);
  }
}
class EditorFontZoomOut extends EditorAction {
  constructor() {
    super({
      id: "editor.action.fontZoomOut",
      label: localize("EditorFontZoomOut.label", "Editor Font Zoom Out"),
      alias: "Editor Font Zoom Out",
      precondition: void 0
    });
  }
  run(accessor, editor2) {
    EditorZoom.setZoomLevel(EditorZoom.getZoomLevel() - 1);
  }
}
class EditorFontZoomReset extends EditorAction {
  constructor() {
    super({
      id: "editor.action.fontZoomReset",
      label: localize("EditorFontZoomReset.label", "Editor Font Zoom Reset"),
      alias: "Editor Font Zoom Reset",
      precondition: void 0
    });
  }
  run(accessor, editor2) {
    EditorZoom.setZoomLevel(0);
  }
}
registerEditorAction(EditorFontZoomIn);
registerEditorAction(EditorFontZoomOut);
registerEditorAction(EditorFontZoomReset);
class FormattingEdit {
  static _handleEolEdits(editor2, edits) {
    let newEol = void 0;
    const singleEdits = [];
    for (const edit of edits) {
      if (typeof edit.eol === "number") {
        newEol = edit.eol;
      }
      if (edit.range && typeof edit.text === "string") {
        singleEdits.push(edit);
      }
    }
    if (typeof newEol === "number") {
      if (editor2.hasModel()) {
        editor2.getModel().pushEOL(newEol);
      }
    }
    return singleEdits;
  }
  static _isFullModelReplaceEdit(editor2, edit) {
    if (!editor2.hasModel()) {
      return false;
    }
    const model = editor2.getModel();
    const editRange = model.validateRange(edit.range);
    const fullModelRange = model.getFullModelRange();
    return fullModelRange.equalsRange(editRange);
  }
  static execute(editor2, _edits, addUndoStops) {
    if (addUndoStops) {
      editor2.pushUndoStop();
    }
    const scrollState = StableEditorScrollState.capture(editor2);
    const edits = FormattingEdit._handleEolEdits(editor2, _edits);
    if (edits.length === 1 && FormattingEdit._isFullModelReplaceEdit(editor2, edits[0])) {
      editor2.executeEdits("formatEditsCommand", edits.map((edit) => EditOperation.replace(Range$2.lift(edit.range), edit.text)));
    } else {
      editor2.executeEdits("formatEditsCommand", edits.map((edit) => EditOperation.replaceMove(Range$2.lift(edit.range), edit.text)));
    }
    if (addUndoStops) {
      editor2.pushUndoStop();
    }
    scrollState.restoreRelativeVerticalPositionOfCursor(editor2);
  }
}
class ExtensionIdentifier {
  constructor(value) {
    this.value = value;
    this._lower = value.toLowerCase();
  }
  /**
   * Gives the value by which to index (for equality).
   */
  static toKey(id3) {
    if (typeof id3 === "string") {
      return id3.toLowerCase();
    }
    return id3._lower;
  }
}
class ExtensionIdentifierSet {
  constructor(iterable) {
    this._set = /* @__PURE__ */ new Set();
    if (iterable) {
      for (const value of iterable) {
        this.add(value);
      }
    }
  }
  add(id3) {
    this._set.add(ExtensionIdentifier.toKey(id3));
  }
  has(id3) {
    return this._set.has(ExtensionIdentifier.toKey(id3));
  }
}
var __awaiter$O = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
function alertFormattingEdits(edits) {
  edits = edits.filter((edit) => edit.range);
  if (!edits.length) {
    return;
  }
  let { range: range2 } = edits[0];
  for (let i = 1; i < edits.length; i++) {
    range2 = Range$2.plusRange(range2, edits[i].range);
  }
  const { startLineNumber, endLineNumber } = range2;
  if (startLineNumber === endLineNumber) {
    if (edits.length === 1) {
      alert(localize("hint11", "Made 1 formatting edit on line {0}", startLineNumber));
    } else {
      alert(localize("hintn1", "Made {0} formatting edits on line {1}", edits.length, startLineNumber));
    }
  } else {
    if (edits.length === 1) {
      alert(localize("hint1n", "Made 1 formatting edit between lines {0} and {1}", startLineNumber, endLineNumber));
    } else {
      alert(localize("hintnn", "Made {0} formatting edits between lines {1} and {2}", edits.length, startLineNumber, endLineNumber));
    }
  }
}
function getRealAndSyntheticDocumentFormattersOrdered(documentFormattingEditProvider, documentRangeFormattingEditProvider, model) {
  const result2 = [];
  const seen2 = new ExtensionIdentifierSet();
  const docFormatter = documentFormattingEditProvider.ordered(model);
  for (const formatter2 of docFormatter) {
    result2.push(formatter2);
    if (formatter2.extensionId) {
      seen2.add(formatter2.extensionId);
    }
  }
  const rangeFormatter = documentRangeFormattingEditProvider.ordered(model);
  for (const formatter2 of rangeFormatter) {
    if (formatter2.extensionId) {
      if (seen2.has(formatter2.extensionId)) {
        continue;
      }
      seen2.add(formatter2.extensionId);
    }
    result2.push({
      displayName: formatter2.displayName,
      extensionId: formatter2.extensionId,
      provideDocumentFormattingEdits(model2, options, token) {
        return formatter2.provideDocumentRangeFormattingEdits(model2, model2.getFullModelRange(), options, token);
      }
    });
  }
  return result2;
}
class FormattingConflicts {
  static setFormatterSelector(selector3) {
    const remove2 = FormattingConflicts._selectors.unshift(selector3);
    return { dispose: remove2 };
  }
  static select(formatter2, document2, mode) {
    return __awaiter$O(this, void 0, void 0, function* () {
      if (formatter2.length === 0) {
        return void 0;
      }
      const selector3 = Iterable.first(FormattingConflicts._selectors);
      if (selector3) {
        return yield selector3(formatter2, document2, mode);
      }
      return void 0;
    });
  }
}
FormattingConflicts._selectors = new LinkedList();
function formatDocumentRangesWithSelectedProvider(accessor, editorOrModel, rangeOrRanges, mode, progress, token) {
  return __awaiter$O(this, void 0, void 0, function* () {
    const instaService = accessor.get(IInstantiationService);
    const { documentRangeFormattingEditProvider: documentRangeFormattingEditProviderRegistry } = accessor.get(ILanguageFeaturesService);
    const model = isCodeEditor(editorOrModel) ? editorOrModel.getModel() : editorOrModel;
    const provider = documentRangeFormattingEditProviderRegistry.ordered(model);
    const selected = yield FormattingConflicts.select(provider, model, mode);
    if (selected) {
      progress.report(selected);
      yield instaService.invokeFunction(formatDocumentRangesWithProvider, selected, editorOrModel, rangeOrRanges, token);
    }
  });
}
function formatDocumentRangesWithProvider(accessor, provider, editorOrModel, rangeOrRanges, token) {
  var _a2, _b2;
  return __awaiter$O(this, void 0, void 0, function* () {
    const workerService = accessor.get(IEditorWorkerService);
    const logService = accessor.get(ILogService);
    let model;
    let cts;
    if (isCodeEditor(editorOrModel)) {
      model = editorOrModel.getModel();
      cts = new EditorStateCancellationTokenSource(editorOrModel, 1 | 4, void 0, token);
    } else {
      model = editorOrModel;
      cts = new TextModelCancellationTokenSource(editorOrModel, token);
    }
    const ranges = [];
    let len = 0;
    for (const range2 of asArray(rangeOrRanges).sort(Range$2.compareRangesUsingStarts)) {
      if (len > 0 && Range$2.areIntersectingOrTouching(ranges[len - 1], range2)) {
        ranges[len - 1] = Range$2.fromPositions(ranges[len - 1].getStartPosition(), range2.getEndPosition());
      } else {
        len = ranges.push(range2);
      }
    }
    const computeEdits = (range2) => __awaiter$O(this, void 0, void 0, function* () {
      var _c2, _d2;
      logService.trace(`[format][provideDocumentRangeFormattingEdits] (request)`, (_c2 = provider.extensionId) === null || _c2 === void 0 ? void 0 : _c2.value, range2);
      const result2 = (yield provider.provideDocumentRangeFormattingEdits(model, range2, model.getFormattingOptions(), cts.token)) || [];
      logService.trace(`[format][provideDocumentRangeFormattingEdits] (response)`, (_d2 = provider.extensionId) === null || _d2 === void 0 ? void 0 : _d2.value, result2);
      return result2;
    });
    const hasIntersectingEdit = (a, b) => {
      if (!a.length || !b.length) {
        return false;
      }
      const mergedA = a.reduce((acc, val) => {
        return Range$2.plusRange(acc, val.range);
      }, a[0].range);
      if (!b.some((x) => {
        return Range$2.intersectRanges(mergedA, x.range);
      })) {
        return false;
      }
      for (const edit of a) {
        for (const otherEdit of b) {
          if (Range$2.intersectRanges(edit.range, otherEdit.range)) {
            return true;
          }
        }
      }
      return false;
    };
    const allEdits = [];
    const rawEditsList = [];
    try {
      if (typeof provider.provideDocumentRangesFormattingEdits === "function") {
        logService.trace(`[format][provideDocumentRangeFormattingEdits] (request)`, (_a2 = provider.extensionId) === null || _a2 === void 0 ? void 0 : _a2.value, ranges);
        const result2 = (yield provider.provideDocumentRangesFormattingEdits(model, ranges, model.getFormattingOptions(), cts.token)) || [];
        logService.trace(`[format][provideDocumentRangeFormattingEdits] (response)`, (_b2 = provider.extensionId) === null || _b2 === void 0 ? void 0 : _b2.value, result2);
        rawEditsList.push(result2);
      } else {
        for (const range2 of ranges) {
          if (cts.token.isCancellationRequested) {
            return true;
          }
          rawEditsList.push(yield computeEdits(range2));
        }
        for (let i = 0; i < ranges.length; ++i) {
          for (let j = i + 1; j < ranges.length; ++j) {
            if (cts.token.isCancellationRequested) {
              return true;
            }
            if (hasIntersectingEdit(rawEditsList[i], rawEditsList[j])) {
              const mergedRange = Range$2.plusRange(ranges[i], ranges[j]);
              const edits = yield computeEdits(mergedRange);
              ranges.splice(j, 1);
              ranges.splice(i, 1);
              ranges.push(mergedRange);
              rawEditsList.splice(j, 1);
              rawEditsList.splice(i, 1);
              rawEditsList.push(edits);
              i = 0;
              j = 0;
            }
          }
        }
      }
      for (const rawEdits of rawEditsList) {
        if (cts.token.isCancellationRequested) {
          return true;
        }
        const minimalEdits = yield workerService.computeMoreMinimalEdits(model.uri, rawEdits);
        if (minimalEdits) {
          allEdits.push(...minimalEdits);
        }
      }
    } finally {
      cts.dispose();
    }
    if (allEdits.length === 0) {
      return false;
    }
    if (isCodeEditor(editorOrModel)) {
      FormattingEdit.execute(editorOrModel, allEdits, true);
      alertFormattingEdits(allEdits);
      editorOrModel.revealPositionInCenterIfOutsideViewport(
        editorOrModel.getPosition(),
        1
        /* ScrollType.Immediate */
      );
    } else {
      const [{ range: range2 }] = allEdits;
      const initialSelection = new Selection$1(range2.startLineNumber, range2.startColumn, range2.endLineNumber, range2.endColumn);
      model.pushEditOperations([initialSelection], allEdits.map((edit) => {
        return {
          text: edit.text,
          range: Range$2.lift(edit.range),
          forceMoveMarkers: true
        };
      }), (undoEdits) => {
        for (const { range: range3 } of undoEdits) {
          if (Range$2.areIntersectingOrTouching(range3, initialSelection)) {
            return [new Selection$1(range3.startLineNumber, range3.startColumn, range3.endLineNumber, range3.endColumn)];
          }
        }
        return null;
      });
    }
    return true;
  });
}
function formatDocumentWithSelectedProvider(accessor, editorOrModel, mode, progress, token) {
  return __awaiter$O(this, void 0, void 0, function* () {
    const instaService = accessor.get(IInstantiationService);
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const model = isCodeEditor(editorOrModel) ? editorOrModel.getModel() : editorOrModel;
    const provider = getRealAndSyntheticDocumentFormattersOrdered(languageFeaturesService.documentFormattingEditProvider, languageFeaturesService.documentRangeFormattingEditProvider, model);
    const selected = yield FormattingConflicts.select(provider, model, mode);
    if (selected) {
      progress.report(selected);
      yield instaService.invokeFunction(formatDocumentWithProvider, selected, editorOrModel, mode, token);
    }
  });
}
function formatDocumentWithProvider(accessor, provider, editorOrModel, mode, token) {
  return __awaiter$O(this, void 0, void 0, function* () {
    const workerService = accessor.get(IEditorWorkerService);
    let model;
    let cts;
    if (isCodeEditor(editorOrModel)) {
      model = editorOrModel.getModel();
      cts = new EditorStateCancellationTokenSource(editorOrModel, 1 | 4, void 0, token);
    } else {
      model = editorOrModel;
      cts = new TextModelCancellationTokenSource(editorOrModel, token);
    }
    let edits;
    try {
      const rawEdits = yield provider.provideDocumentFormattingEdits(model, model.getFormattingOptions(), cts.token);
      edits = yield workerService.computeMoreMinimalEdits(model.uri, rawEdits);
      if (cts.token.isCancellationRequested) {
        return true;
      }
    } finally {
      cts.dispose();
    }
    if (!edits || edits.length === 0) {
      return false;
    }
    if (isCodeEditor(editorOrModel)) {
      FormattingEdit.execute(
        editorOrModel,
        edits,
        mode !== 2
        /* FormattingMode.Silent */
      );
      if (mode !== 2) {
        alertFormattingEdits(edits);
        editorOrModel.revealPositionInCenterIfOutsideViewport(
          editorOrModel.getPosition(),
          1
          /* ScrollType.Immediate */
        );
      }
    } else {
      const [{ range: range2 }] = edits;
      const initialSelection = new Selection$1(range2.startLineNumber, range2.startColumn, range2.endLineNumber, range2.endColumn);
      model.pushEditOperations([initialSelection], edits.map((edit) => {
        return {
          text: edit.text,
          range: Range$2.lift(edit.range),
          forceMoveMarkers: true
        };
      }), (undoEdits) => {
        for (const { range: range3 } of undoEdits) {
          if (Range$2.areIntersectingOrTouching(range3, initialSelection)) {
            return [new Selection$1(range3.startLineNumber, range3.startColumn, range3.endLineNumber, range3.endColumn)];
          }
        }
        return null;
      });
    }
    return true;
  });
}
function getDocumentRangeFormattingEditsUntilResult(workerService, languageFeaturesService, model, range2, options, token) {
  return __awaiter$O(this, void 0, void 0, function* () {
    const providers = languageFeaturesService.documentRangeFormattingEditProvider.ordered(model);
    for (const provider of providers) {
      const rawEdits = yield Promise.resolve(provider.provideDocumentRangeFormattingEdits(model, range2, options, token)).catch(onUnexpectedExternalError);
      if (isNonEmptyArray(rawEdits)) {
        return yield workerService.computeMoreMinimalEdits(model.uri, rawEdits);
      }
    }
    return void 0;
  });
}
function getDocumentFormattingEditsUntilResult(workerService, languageFeaturesService, model, options, token) {
  return __awaiter$O(this, void 0, void 0, function* () {
    const providers = getRealAndSyntheticDocumentFormattersOrdered(languageFeaturesService.documentFormattingEditProvider, languageFeaturesService.documentRangeFormattingEditProvider, model);
    for (const provider of providers) {
      const rawEdits = yield Promise.resolve(provider.provideDocumentFormattingEdits(model, options, token)).catch(onUnexpectedExternalError);
      if (isNonEmptyArray(rawEdits)) {
        return yield workerService.computeMoreMinimalEdits(model.uri, rawEdits);
      }
    }
    return void 0;
  });
}
function getOnTypeFormattingEdits(workerService, languageFeaturesService, model, position, ch, options, token) {
  const providers = languageFeaturesService.onTypeFormattingEditProvider.ordered(model);
  if (providers.length === 0) {
    return Promise.resolve(void 0);
  }
  if (providers[0].autoFormatTriggerCharacters.indexOf(ch) < 0) {
    return Promise.resolve(void 0);
  }
  return Promise.resolve(providers[0].provideOnTypeFormattingEdits(model, position, ch, options, token)).catch(onUnexpectedExternalError).then((edits) => {
    return workerService.computeMoreMinimalEdits(model.uri, edits);
  });
}
CommandsRegistry.registerCommand("_executeFormatRangeProvider", function(accessor, ...args) {
  return __awaiter$O(this, void 0, void 0, function* () {
    const [resource, range2, options] = args;
    assertType(URI.isUri(resource));
    assertType(Range$2.isIRange(range2));
    const resolverService = accessor.get(ITextModelService);
    const workerService = accessor.get(IEditorWorkerService);
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const reference = yield resolverService.createModelReference(resource);
    try {
      return getDocumentRangeFormattingEditsUntilResult(workerService, languageFeaturesService, reference.object.textEditorModel, Range$2.lift(range2), options, CancellationToken.None);
    } finally {
      reference.dispose();
    }
  });
});
CommandsRegistry.registerCommand("_executeFormatDocumentProvider", function(accessor, ...args) {
  return __awaiter$O(this, void 0, void 0, function* () {
    const [resource, options] = args;
    assertType(URI.isUri(resource));
    const resolverService = accessor.get(ITextModelService);
    const workerService = accessor.get(IEditorWorkerService);
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const reference = yield resolverService.createModelReference(resource);
    try {
      return getDocumentFormattingEditsUntilResult(workerService, languageFeaturesService, reference.object.textEditorModel, options, CancellationToken.None);
    } finally {
      reference.dispose();
    }
  });
});
CommandsRegistry.registerCommand("_executeFormatOnTypeProvider", function(accessor, ...args) {
  return __awaiter$O(this, void 0, void 0, function* () {
    const [resource, position, ch, options] = args;
    assertType(URI.isUri(resource));
    assertType(Position$2.isIPosition(position));
    assertType(typeof ch === "string");
    const resolverService = accessor.get(ITextModelService);
    const workerService = accessor.get(IEditorWorkerService);
    const languageFeaturesService = accessor.get(ILanguageFeaturesService);
    const reference = yield resolverService.createModelReference(resource);
    try {
      return getOnTypeFormattingEdits(workerService, languageFeaturesService, reference.object.textEditorModel, Position$2.lift(position), ch, options, CancellationToken.None);
    } finally {
      reference.dispose();
    }
  });
});
var __decorate$1e = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1c = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$N = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
let FormatOnType = class FormatOnType2 {
  constructor(_editor, _languageFeaturesService, _workerService) {
    this._editor = _editor;
    this._languageFeaturesService = _languageFeaturesService;
    this._workerService = _workerService;
    this._disposables = new DisposableStore();
    this._sessionDisposables = new DisposableStore();
    this._disposables.add(_languageFeaturesService.onTypeFormattingEditProvider.onDidChange(this._update, this));
    this._disposables.add(_editor.onDidChangeModel(() => this._update()));
    this._disposables.add(_editor.onDidChangeModelLanguage(() => this._update()));
    this._disposables.add(_editor.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        55
        /* EditorOption.formatOnType */
      )) {
        this._update();
      }
    }));
    this._update();
  }
  dispose() {
    this._disposables.dispose();
    this._sessionDisposables.dispose();
  }
  _update() {
    this._sessionDisposables.clear();
    if (!this._editor.getOption(
      55
      /* EditorOption.formatOnType */
    )) {
      return;
    }
    if (!this._editor.hasModel()) {
      return;
    }
    const model = this._editor.getModel();
    const [support] = this._languageFeaturesService.onTypeFormattingEditProvider.ordered(model);
    if (!support || !support.autoFormatTriggerCharacters) {
      return;
    }
    const triggerChars = new CharacterSet();
    for (const ch of support.autoFormatTriggerCharacters) {
      triggerChars.add(ch.charCodeAt(0));
    }
    this._sessionDisposables.add(this._editor.onDidType((text2) => {
      const lastCharCode = text2.charCodeAt(text2.length - 1);
      if (triggerChars.has(lastCharCode)) {
        this._trigger(String.fromCharCode(lastCharCode));
      }
    }));
  }
  _trigger(ch) {
    if (!this._editor.hasModel()) {
      return;
    }
    if (this._editor.getSelections().length > 1 || !this._editor.getSelection().isEmpty()) {
      return;
    }
    const model = this._editor.getModel();
    const position = this._editor.getPosition();
    const cts = new CancellationTokenSource$1();
    const unbind = this._editor.onDidChangeModelContent((e) => {
      if (e.isFlush) {
        cts.cancel();
        unbind.dispose();
        return;
      }
      for (let i = 0, len = e.changes.length; i < len; i++) {
        const change = e.changes[i];
        if (change.range.endLineNumber <= position.lineNumber) {
          cts.cancel();
          unbind.dispose();
          return;
        }
      }
    });
    getOnTypeFormattingEdits(this._workerService, this._languageFeaturesService, model, position, ch, model.getFormattingOptions(), cts.token).then((edits) => {
      if (cts.token.isCancellationRequested) {
        return;
      }
      if (isNonEmptyArray(edits)) {
        FormattingEdit.execute(this._editor, edits, true);
        alertFormattingEdits(edits);
      }
    }).finally(() => {
      unbind.dispose();
    });
  }
};
FormatOnType.ID = "editor.contrib.autoFormat";
FormatOnType = __decorate$1e([
  __param$1c(1, ILanguageFeaturesService),
  __param$1c(2, IEditorWorkerService)
], FormatOnType);
let FormatOnPaste = class FormatOnPaste2 {
  constructor(editor2, _languageFeaturesService, _instantiationService) {
    this.editor = editor2;
    this._languageFeaturesService = _languageFeaturesService;
    this._instantiationService = _instantiationService;
    this._callOnDispose = new DisposableStore();
    this._callOnModel = new DisposableStore();
    this._callOnDispose.add(editor2.onDidChangeConfiguration(() => this._update()));
    this._callOnDispose.add(editor2.onDidChangeModel(() => this._update()));
    this._callOnDispose.add(editor2.onDidChangeModelLanguage(() => this._update()));
    this._callOnDispose.add(_languageFeaturesService.documentRangeFormattingEditProvider.onDidChange(this._update, this));
  }
  dispose() {
    this._callOnDispose.dispose();
    this._callOnModel.dispose();
  }
  _update() {
    this._callOnModel.clear();
    if (!this.editor.getOption(
      54
      /* EditorOption.formatOnPaste */
    )) {
      return;
    }
    if (!this.editor.hasModel()) {
      return;
    }
    if (!this._languageFeaturesService.documentRangeFormattingEditProvider.has(this.editor.getModel())) {
      return;
    }
    this._callOnModel.add(this.editor.onDidPaste(({ range: range2 }) => this._trigger(range2)));
  }
  _trigger(range2) {
    if (!this.editor.hasModel()) {
      return;
    }
    if (this.editor.getSelections().length > 1) {
      return;
    }
    this._instantiationService.invokeFunction(formatDocumentRangesWithSelectedProvider, this.editor, range2, 2, Progress.None, CancellationToken.None).catch(onUnexpectedError);
  }
};
FormatOnPaste.ID = "editor.contrib.formatOnPaste";
FormatOnPaste = __decorate$1e([
  __param$1c(1, ILanguageFeaturesService),
  __param$1c(2, IInstantiationService)
], FormatOnPaste);
class FormatDocumentAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.formatDocument",
      label: localize("formatDocument.label", "Format Document"),
      alias: "Format Document",
      precondition: ContextKeyExpr.and(EditorContextKeys.notInCompositeEditor, EditorContextKeys.writable, EditorContextKeys.hasDocumentFormattingProvider),
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 1024 | 512 | 36,
        linux: {
          primary: 2048 | 1024 | 39
          /* KeyCode.KeyI */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      contextMenuOpts: {
        group: "1_modification",
        order: 1.3
      }
    });
  }
  run(accessor, editor2) {
    return __awaiter$N(this, void 0, void 0, function* () {
      if (editor2.hasModel()) {
        const instaService = accessor.get(IInstantiationService);
        const progressService = accessor.get(IEditorProgressService);
        yield progressService.showWhile(instaService.invokeFunction(formatDocumentWithSelectedProvider, editor2, 1, Progress.None, CancellationToken.None), 250);
      }
    });
  }
}
class FormatSelectionAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.formatSelection",
      label: localize("formatSelection.label", "Format Selection"),
      alias: "Format Selection",
      precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasDocumentSelectionFormattingProvider),
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: KeyChord(
          2048 | 41,
          2048 | 36
          /* KeyCode.KeyF */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      contextMenuOpts: {
        when: EditorContextKeys.hasNonEmptySelection,
        group: "1_modification",
        order: 1.31
      }
    });
  }
  run(accessor, editor2) {
    return __awaiter$N(this, void 0, void 0, function* () {
      if (!editor2.hasModel()) {
        return;
      }
      const instaService = accessor.get(IInstantiationService);
      const model = editor2.getModel();
      const ranges = editor2.getSelections().map((range2) => {
        return range2.isEmpty() ? new Range$2(range2.startLineNumber, 1, range2.startLineNumber, model.getLineMaxColumn(range2.startLineNumber)) : range2;
      });
      const progressService = accessor.get(IEditorProgressService);
      yield progressService.showWhile(instaService.invokeFunction(formatDocumentRangesWithSelectedProvider, editor2, ranges, 1, Progress.None, CancellationToken.None), 250);
    });
  }
}
registerEditorContribution(
  FormatOnType.ID,
  FormatOnType,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);
registerEditorContribution(
  FormatOnPaste.ID,
  FormatOnPaste,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);
registerEditorAction(FormatDocumentAction);
registerEditorAction(FormatSelectionAction);
CommandsRegistry.registerCommand("editor.action.format", (accessor) => __awaiter$N(void 0, void 0, void 0, function* () {
  const editor2 = accessor.get(ICodeEditorService).getFocusedCodeEditor();
  if (!editor2 || !editor2.hasModel()) {
    return;
  }
  const commandService = accessor.get(ICommandService);
  if (editor2.getSelection().isEmpty()) {
    yield commandService.executeCommand("editor.action.formatDocument");
  } else {
    yield commandService.executeCommand("editor.action.formatSelection");
  }
}));
var __decorate$1d = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1b = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$M = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class TreeElement {
  remove() {
    var _a2;
    (_a2 = this.parent) === null || _a2 === void 0 ? void 0 : _a2.children.delete(this.id);
  }
  static findId(candidate, container2) {
    let candidateId;
    if (typeof candidate === "string") {
      candidateId = `${container2.id}/${candidate}`;
    } else {
      candidateId = `${container2.id}/${candidate.name}`;
      if (container2.children.get(candidateId) !== void 0) {
        candidateId = `${container2.id}/${candidate.name}_${candidate.range.startLineNumber}_${candidate.range.startColumn}`;
      }
    }
    let id3 = candidateId;
    for (let i = 0; container2.children.get(id3) !== void 0; i++) {
      id3 = `${candidateId}_${i}`;
    }
    return id3;
  }
  static empty(element) {
    return element.children.size === 0;
  }
}
class OutlineElement extends TreeElement {
  constructor(id3, parent, symbol) {
    super();
    this.id = id3;
    this.parent = parent;
    this.symbol = symbol;
    this.children = /* @__PURE__ */ new Map();
  }
}
class OutlineGroup extends TreeElement {
  constructor(id3, parent, label, order) {
    super();
    this.id = id3;
    this.parent = parent;
    this.label = label;
    this.order = order;
    this.children = /* @__PURE__ */ new Map();
  }
}
class OutlineModel extends TreeElement {
  static create(registry, textModel, token) {
    const cts = new CancellationTokenSource$1(token);
    const result2 = new OutlineModel(textModel.uri);
    const provider = registry.ordered(textModel);
    const promises = provider.map((provider2, index) => {
      var _a2;
      const id3 = TreeElement.findId(`provider_${index}`, result2);
      const group2 = new OutlineGroup(id3, result2, (_a2 = provider2.displayName) !== null && _a2 !== void 0 ? _a2 : "Unknown Outline Provider", index);
      return Promise.resolve(provider2.provideDocumentSymbols(textModel, cts.token)).then((result3) => {
        for (const info of result3 || []) {
          OutlineModel._makeOutlineElement(info, group2);
        }
        return group2;
      }, (err) => {
        onUnexpectedExternalError(err);
        return group2;
      }).then((group3) => {
        if (!TreeElement.empty(group3)) {
          result2._groups.set(id3, group3);
        } else {
          group3.remove();
        }
      });
    });
    const listener = registry.onDidChange(() => {
      const newProvider = registry.ordered(textModel);
      if (!equals$3(newProvider, provider)) {
        cts.cancel();
      }
    });
    return Promise.all(promises).then(() => {
      if (cts.token.isCancellationRequested && !token.isCancellationRequested) {
        return OutlineModel.create(registry, textModel, token);
      } else {
        return result2._compact();
      }
    }).finally(() => {
      listener.dispose();
    });
  }
  static _makeOutlineElement(info, container2) {
    const id3 = TreeElement.findId(info, container2);
    const res = new OutlineElement(id3, container2, info);
    if (info.children) {
      for (const childInfo of info.children) {
        OutlineModel._makeOutlineElement(childInfo, res);
      }
    }
    container2.children.set(res.id, res);
  }
  constructor(uri) {
    super();
    this.uri = uri;
    this.id = "root";
    this.parent = void 0;
    this._groups = /* @__PURE__ */ new Map();
    this.children = /* @__PURE__ */ new Map();
    this.id = "root";
    this.parent = void 0;
  }
  _compact() {
    let count = 0;
    for (const [key, group2] of this._groups) {
      if (group2.children.size === 0) {
        this._groups.delete(key);
      } else {
        count += 1;
      }
    }
    if (count !== 1) {
      this.children = this._groups;
    } else {
      const group2 = Iterable.first(this._groups.values());
      for (const [, child] of group2.children) {
        child.parent = this;
        this.children.set(child.id, child);
      }
    }
    return this;
  }
  getTopLevelSymbols() {
    const roots = [];
    for (const child of this.children.values()) {
      if (child instanceof OutlineElement) {
        roots.push(child.symbol);
      } else {
        roots.push(...Iterable.map(child.children.values(), (child2) => child2.symbol));
      }
    }
    return roots.sort((a, b) => Range$2.compareRangesUsingStarts(a.range, b.range));
  }
  asListOfDocumentSymbols() {
    const roots = this.getTopLevelSymbols();
    const bucket = [];
    OutlineModel._flattenDocumentSymbols(bucket, roots, "");
    return bucket.sort((a, b) => Position$2.compare(Range$2.getStartPosition(a.range), Range$2.getStartPosition(b.range)) || Position$2.compare(Range$2.getEndPosition(b.range), Range$2.getEndPosition(a.range)));
  }
  static _flattenDocumentSymbols(bucket, entries, overrideContainerLabel) {
    for (const entry of entries) {
      bucket.push({
        kind: entry.kind,
        tags: entry.tags,
        name: entry.name,
        detail: entry.detail,
        containerName: entry.containerName || overrideContainerLabel,
        range: entry.range,
        selectionRange: entry.selectionRange,
        children: void 0
        // we flatten it...
      });
      if (entry.children) {
        OutlineModel._flattenDocumentSymbols(bucket, entry.children, entry.name);
      }
    }
  }
}
const IOutlineModelService = createDecorator("IOutlineModelService");
let OutlineModelService = class OutlineModelService2 {
  constructor(_languageFeaturesService, debounces, modelService) {
    this._languageFeaturesService = _languageFeaturesService;
    this._disposables = new DisposableStore();
    this._cache = new LRUCache$2(10, 0.7);
    this._debounceInformation = debounces.for(_languageFeaturesService.documentSymbolProvider, "DocumentSymbols", { min: 350 });
    this._disposables.add(modelService.onModelRemoved((textModel) => {
      this._cache.delete(textModel.id);
    }));
  }
  dispose() {
    this._disposables.dispose();
  }
  getOrCreate(textModel, token) {
    return __awaiter$M(this, void 0, void 0, function* () {
      const registry = this._languageFeaturesService.documentSymbolProvider;
      const provider = registry.ordered(textModel);
      let data = this._cache.get(textModel.id);
      if (!data || data.versionId !== textModel.getVersionId() || !equals$3(data.provider, provider)) {
        const source = new CancellationTokenSource$1();
        data = {
          versionId: textModel.getVersionId(),
          provider,
          promiseCnt: 0,
          source,
          promise: OutlineModel.create(registry, textModel, source.token),
          model: void 0
        };
        this._cache.set(textModel.id, data);
        const now = Date.now();
        data.promise.then((outlineModel) => {
          data.model = outlineModel;
          this._debounceInformation.update(textModel, Date.now() - now);
        }).catch((_err) => {
          this._cache.delete(textModel.id);
        });
      }
      if (data.model) {
        return data.model;
      }
      data.promiseCnt += 1;
      const listener = token.onCancellationRequested(() => {
        if (--data.promiseCnt === 0) {
          data.source.cancel();
          this._cache.delete(textModel.id);
        }
      });
      try {
        return yield data.promise;
      } finally {
        listener.dispose();
      }
    });
  }
};
OutlineModelService = __decorate$1d([
  __param$1b(0, ILanguageFeaturesService),
  __param$1b(1, ILanguageFeatureDebounceService),
  __param$1b(2, IModelService)
], OutlineModelService);
registerSingleton(
  IOutlineModelService,
  OutlineModelService,
  1
  /* InstantiationType.Delayed */
);
var __awaiter$L = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
CommandsRegistry.registerCommand("_executeDocumentSymbolProvider", function(accessor, ...args) {
  return __awaiter$L(this, void 0, void 0, function* () {
    const [resource] = args;
    assertType(URI.isUri(resource));
    const outlineService = accessor.get(IOutlineModelService);
    const modelService = accessor.get(ITextModelService);
    const reference = yield modelService.createModelReference(resource);
    try {
      return (yield outlineService.getOrCreate(reference.object.textEditorModel, CancellationToken.None)).getTopLevelSymbols();
    } finally {
      reference.dispose();
    }
  });
});
class InlineCompletionContextKeys extends Disposable {
  constructor(contextKeyService, model) {
    super();
    this.contextKeyService = contextKeyService;
    this.model = model;
    this.inlineCompletionVisible = InlineCompletionContextKeys.inlineSuggestionVisible.bindTo(this.contextKeyService);
    this.inlineCompletionSuggestsIndentation = InlineCompletionContextKeys.inlineSuggestionHasIndentation.bindTo(this.contextKeyService);
    this.inlineCompletionSuggestsIndentationLessThanTabSize = InlineCompletionContextKeys.inlineSuggestionHasIndentationLessThanTabSize.bindTo(this.contextKeyService);
    this.suppressSuggestions = InlineCompletionContextKeys.suppressSuggestions.bindTo(this.contextKeyService);
    this._register(autorun("update context key: inlineCompletionVisible, suppressSuggestions", (reader) => {
      const model2 = this.model.read(reader);
      const state = model2 === null || model2 === void 0 ? void 0 : model2.state.read(reader);
      const isInlineCompletionVisible = !!(state === null || state === void 0 ? void 0 : state.inlineCompletion) && (state === null || state === void 0 ? void 0 : state.ghostText) !== void 0 && !(state === null || state === void 0 ? void 0 : state.ghostText.isEmpty());
      this.inlineCompletionVisible.set(isInlineCompletionVisible);
      if ((state === null || state === void 0 ? void 0 : state.ghostText) && (state === null || state === void 0 ? void 0 : state.inlineCompletion)) {
        this.suppressSuggestions.set(state.inlineCompletion.inlineCompletion.source.inlineCompletions.suppressSuggestions);
      }
    }));
    this._register(autorun("update context key: inlineCompletionSuggestsIndentation, inlineCompletionSuggestsIndentationLessThanTabSize", (reader) => {
      const model2 = this.model.read(reader);
      let startsWithIndentation = false;
      let startsWithIndentationLessThanTabSize = true;
      const ghostText2 = model2 === null || model2 === void 0 ? void 0 : model2.ghostText.read(reader);
      if (!!(model2 === null || model2 === void 0 ? void 0 : model2.selectedSuggestItem) && ghostText2 && ghostText2.parts.length > 0) {
        const { column, lines } = ghostText2.parts[0];
        const firstLine = lines[0];
        const indentationEndColumn = model2.textModel.getLineIndentColumn(ghostText2.lineNumber);
        const inIndentation = column <= indentationEndColumn;
        if (inIndentation) {
          let firstNonWsIdx = firstNonWhitespaceIndex(firstLine);
          if (firstNonWsIdx === -1) {
            firstNonWsIdx = firstLine.length - 1;
          }
          startsWithIndentation = firstNonWsIdx > 0;
          const tabSize = model2.textModel.getOptions().tabSize;
          const visibleColumnIndentation = CursorColumns.visibleColumnFromColumn(firstLine, firstNonWsIdx + 1, tabSize);
          startsWithIndentationLessThanTabSize = visibleColumnIndentation < tabSize;
        }
      }
      this.inlineCompletionSuggestsIndentation.set(startsWithIndentation);
      this.inlineCompletionSuggestsIndentationLessThanTabSize.set(startsWithIndentationLessThanTabSize);
    }));
  }
}
InlineCompletionContextKeys.inlineSuggestionVisible = new RawContextKey("inlineSuggestionVisible", false, localize("inlineSuggestionVisible", "Whether an inline suggestion is visible"));
InlineCompletionContextKeys.inlineSuggestionHasIndentation = new RawContextKey("inlineSuggestionHasIndentation", false, localize("inlineSuggestionHasIndentation", "Whether the inline suggestion starts with whitespace"));
InlineCompletionContextKeys.inlineSuggestionHasIndentationLessThanTabSize = new RawContextKey("inlineSuggestionHasIndentationLessThanTabSize", true, localize("inlineSuggestionHasIndentationLessThanTabSize", "Whether the inline suggestion starts with whitespace that is less than what would be inserted by tab"));
InlineCompletionContextKeys.suppressSuggestions = new RawContextKey("inlineSuggestionSuppressSuggestions", void 0, localize("suppressSuggestions", "Whether suggestions should be suppressed for the current suggestion"));
const ghostText = "";
function applyEdits(text2, edits) {
  const transformer = new PositionOffsetTransformer(text2);
  const offsetEdits = edits.map((e) => {
    const range2 = Range$2.lift(e.range);
    return {
      startOffset: transformer.getOffset(range2.getStartPosition()),
      endOffset: transformer.getOffset(range2.getEndPosition()),
      text: e.text
    };
  });
  offsetEdits.sort((a, b) => b.startOffset - a.startOffset);
  for (const edit of offsetEdits) {
    text2 = text2.substring(0, edit.startOffset) + edit.text + text2.substring(edit.endOffset);
  }
  return text2;
}
class PositionOffsetTransformer {
  constructor(text2) {
    this.lineStartOffsetByLineIdx = [];
    this.lineStartOffsetByLineIdx.push(0);
    for (let i = 0; i < text2.length; i++) {
      if (text2.charAt(i) === "\n") {
        this.lineStartOffsetByLineIdx.push(i + 1);
      }
    }
  }
  getOffset(position) {
    return this.lineStartOffsetByLineIdx[position.lineNumber - 1] + position.column - 1;
  }
}
const array = [];
function getReadonlyEmptyArray() {
  return array;
}
class ColumnRange {
  constructor(startColumn, endColumnExclusive) {
    this.startColumn = startColumn;
    this.endColumnExclusive = endColumnExclusive;
    if (startColumn > endColumnExclusive) {
      throw new BugIndicatingError(`startColumn ${startColumn} cannot be after endColumnExclusive ${endColumnExclusive}`);
    }
  }
  toRange(lineNumber) {
    return new Range$2(lineNumber, this.startColumn, lineNumber, this.endColumnExclusive);
  }
}
function applyObservableDecorations$1(editor2, decorations2) {
  const d = new DisposableStore();
  const decorationsCollection = editor2.createDecorationsCollection();
  d.add(autorun(`Apply decorations from ${decorations2.debugName}`, (reader) => {
    const d2 = decorations2.read(reader);
    decorationsCollection.set(d2);
  }));
  d.add({
    dispose: () => {
      decorationsCollection.clear();
    }
  });
  return d;
}
function addPositions(pos1, pos2) {
  return new Position$2(pos1.lineNumber + pos2.lineNumber - 1, pos2.lineNumber === 1 ? pos1.column + pos2.column - 1 : pos2.column);
}
function lengthOfText(text2) {
  let line = 1;
  let column = 1;
  for (const c of text2) {
    if (c === "\n") {
      line++;
      column = 1;
    } else {
      column++;
    }
  }
  return new Position$2(line, column);
}
class GhostText {
  constructor(lineNumber, parts) {
    this.lineNumber = lineNumber;
    this.parts = parts;
  }
  renderForScreenReader(lineText) {
    if (this.parts.length === 0) {
      return "";
    }
    const lastPart = this.parts[this.parts.length - 1];
    const cappedLineText = lineText.substr(0, lastPart.column - 1);
    const text2 = applyEdits(cappedLineText, this.parts.map((p2) => ({
      range: { startLineNumber: 1, endLineNumber: 1, startColumn: p2.column, endColumn: p2.column },
      text: p2.lines.join("\n")
    })));
    return text2.substring(this.parts[0].column - 1);
  }
  isEmpty() {
    return this.parts.every((p2) => p2.lines.length === 0);
  }
  get lineCount() {
    return 1 + this.parts.reduce((r, p2) => r + p2.lines.length - 1, 0);
  }
}
class GhostTextPart {
  constructor(column, lines, preview) {
    this.column = column;
    this.lines = lines;
    this.preview = preview;
  }
}
class GhostTextReplacement {
  constructor(lineNumber, columnRange, newLines, additionalReservedLineCount = 0) {
    this.lineNumber = lineNumber;
    this.columnRange = columnRange;
    this.newLines = newLines;
    this.additionalReservedLineCount = additionalReservedLineCount;
    this.parts = [
      new GhostTextPart(this.columnRange.endColumnExclusive, this.newLines, false)
    ];
  }
  renderForScreenReader(_lineText) {
    return this.newLines.join("\n");
  }
  get lineCount() {
    return this.newLines.length;
  }
  isEmpty() {
    return this.parts.every((p2) => p2.lines.length === 0);
  }
}
var __decorate$1c = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1a = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let GhostTextWidget = class GhostTextWidget2 extends Disposable {
  constructor(editor2, model, languageService) {
    super();
    this.editor = editor2;
    this.model = model;
    this.languageService = languageService;
    this.isDisposed = observableValue("isDisposed", false);
    this.currentTextModel = observableFromEvent(this.editor.onDidChangeModel, () => this.editor.getModel());
    this.uiState = derived("uiState", (reader) => {
      if (this.isDisposed.read(reader)) {
        return void 0;
      }
      const textModel = this.currentTextModel.read(reader);
      if (textModel !== this.model.targetTextModel.read(reader)) {
        return void 0;
      }
      const ghostText2 = this.model.ghostText.read(reader);
      if (!ghostText2) {
        return void 0;
      }
      const replacedRange = ghostText2 instanceof GhostTextReplacement ? ghostText2.columnRange : void 0;
      const inlineTexts = [];
      const additionalLines = [];
      function addToAdditionalLines(lines, className3) {
        if (additionalLines.length > 0) {
          const lastLine = additionalLines[additionalLines.length - 1];
          if (className3) {
            lastLine.decorations.push(new LineDecoration(
              lastLine.content.length + 1,
              lastLine.content.length + 1 + lines[0].length,
              className3,
              0
              /* InlineDecorationType.Regular */
            ));
          }
          lastLine.content += lines[0];
          lines = lines.slice(1);
        }
        for (const line of lines) {
          additionalLines.push({
            content: line,
            decorations: className3 ? [new LineDecoration(
              1,
              line.length + 1,
              className3,
              0
              /* InlineDecorationType.Regular */
            )] : []
          });
        }
      }
      const textBufferLine = textModel.getLineContent(ghostText2.lineNumber);
      let hiddenTextStartColumn = void 0;
      let lastIdx = 0;
      for (const part of ghostText2.parts) {
        let lines = part.lines;
        if (hiddenTextStartColumn === void 0) {
          inlineTexts.push({
            column: part.column,
            text: lines[0],
            preview: part.preview
          });
          lines = lines.slice(1);
        } else {
          addToAdditionalLines([textBufferLine.substring(lastIdx, part.column - 1)], void 0);
        }
        if (lines.length > 0) {
          addToAdditionalLines(lines, "ghost-text");
          if (hiddenTextStartColumn === void 0 && part.column <= textBufferLine.length) {
            hiddenTextStartColumn = part.column;
          }
        }
        lastIdx = part.column - 1;
      }
      if (hiddenTextStartColumn !== void 0) {
        addToAdditionalLines([textBufferLine.substring(lastIdx)], void 0);
      }
      const hiddenRange = hiddenTextStartColumn !== void 0 ? new ColumnRange(hiddenTextStartColumn, textBufferLine.length + 1) : void 0;
      return {
        replacedRange,
        inlineTexts,
        additionalLines,
        hiddenRange,
        lineNumber: ghostText2.lineNumber,
        additionalReservedLineCount: this.model.minReservedLineCount.read(reader),
        targetTextModel: textModel
      };
    });
    this.decorations = derived("decorations", (reader) => {
      const uiState = this.uiState.read(reader);
      if (!uiState) {
        return [];
      }
      const decorations2 = [];
      if (uiState.replacedRange) {
        decorations2.push({
          range: uiState.replacedRange.toRange(uiState.lineNumber),
          options: { inlineClassName: "inline-completion-text-to-replace", description: "GhostTextReplacement" }
        });
      }
      if (uiState.hiddenRange) {
        decorations2.push({
          range: uiState.hiddenRange.toRange(uiState.lineNumber),
          options: { inlineClassName: "ghost-text-hidden", description: "ghost-text-hidden" }
        });
      }
      for (const p2 of uiState.inlineTexts) {
        decorations2.push({
          range: Range$2.fromPositions(new Position$2(uiState.lineNumber, p2.column)),
          options: {
            description: "ghost-text",
            after: { content: p2.text, inlineClassName: p2.preview ? "ghost-text-decoration-preview" : "ghost-text-decoration", cursorStops: InjectedTextCursorStops$1.Left },
            showIfCollapsed: true
          }
        });
      }
      return decorations2;
    });
    this.additionalLinesWidget = this._register(new AdditionalLinesWidget(this.editor, this.languageService.languageIdCodec, derived("lines", (reader) => {
      const uiState = this.uiState.read(reader);
      return uiState ? {
        lineNumber: uiState.lineNumber,
        additionalLines: uiState.additionalLines,
        minReservedLineCount: uiState.additionalReservedLineCount,
        targetTextModel: uiState.targetTextModel
      } : void 0;
    })));
    this._register(toDisposable(() => {
      this.isDisposed.set(true, void 0);
    }));
    this._register(applyObservableDecorations$1(this.editor, this.decorations));
  }
  ownsViewZone(viewZoneId) {
    return this.additionalLinesWidget.viewZoneId === viewZoneId;
  }
};
GhostTextWidget = __decorate$1c([
  __param$1a(2, ILanguageService)
], GhostTextWidget);
class AdditionalLinesWidget extends Disposable {
  get viewZoneId() {
    return this._viewZoneId;
  }
  constructor(editor2, languageIdCodec, lines) {
    super();
    this.editor = editor2;
    this.languageIdCodec = languageIdCodec;
    this.lines = lines;
    this._viewZoneId = void 0;
    this.editorOptionsChanged = observableSignalFromEvent("editorOptionChanged", Event$1.filter(this.editor.onDidChangeConfiguration, (e) => e.hasChanged(
      32
      /* EditorOption.disableMonospaceOptimizations */
    ) || e.hasChanged(
      115
      /* EditorOption.stopRenderingLineAfter */
    ) || e.hasChanged(
      97
      /* EditorOption.renderWhitespace */
    ) || e.hasChanged(
      92
      /* EditorOption.renderControlCharacters */
    ) || e.hasChanged(
      50
      /* EditorOption.fontLigatures */
    ) || e.hasChanged(
      49
      /* EditorOption.fontInfo */
    ) || e.hasChanged(
      65
      /* EditorOption.lineHeight */
    )));
    this._register(autorun("update view zone", (reader) => {
      const lines2 = this.lines.read(reader);
      this.editorOptionsChanged.read(reader);
      if (lines2) {
        this.updateLines(lines2.lineNumber, lines2.additionalLines, lines2.minReservedLineCount);
      } else {
        this.clear();
      }
    }));
  }
  dispose() {
    super.dispose();
    this.clear();
  }
  clear() {
    this.editor.changeViewZones((changeAccessor) => {
      if (this._viewZoneId) {
        changeAccessor.removeZone(this._viewZoneId);
        this._viewZoneId = void 0;
      }
    });
  }
  updateLines(lineNumber, additionalLines, minReservedLineCount) {
    const textModel = this.editor.getModel();
    if (!textModel) {
      return;
    }
    const { tabSize } = textModel.getOptions();
    this.editor.changeViewZones((changeAccessor) => {
      if (this._viewZoneId) {
        changeAccessor.removeZone(this._viewZoneId);
        this._viewZoneId = void 0;
      }
      const heightInLines = Math.max(additionalLines.length, minReservedLineCount);
      if (heightInLines > 0) {
        const domNode = document.createElement("div");
        renderLines$1(domNode, tabSize, additionalLines, this.editor.getOptions(), this.languageIdCodec);
        this._viewZoneId = changeAccessor.addZone({
          afterLineNumber: lineNumber,
          heightInLines,
          domNode,
          afterColumnAffinity: 1
          /* PositionAffinity.Right */
        });
      }
    });
  }
}
function renderLines$1(domNode, tabSize, lines, opts, languageIdCodec) {
  const disableMonospaceOptimizations = opts.get(
    32
    /* EditorOption.disableMonospaceOptimizations */
  );
  const stopRenderingLineAfter = opts.get(
    115
    /* EditorOption.stopRenderingLineAfter */
  );
  const renderWhitespace = "none";
  const renderControlCharacters = opts.get(
    92
    /* EditorOption.renderControlCharacters */
  );
  const fontLigatures = opts.get(
    50
    /* EditorOption.fontLigatures */
  );
  const fontInfo = opts.get(
    49
    /* EditorOption.fontInfo */
  );
  const lineHeight = opts.get(
    65
    /* EditorOption.lineHeight */
  );
  const sb = new StringBuilder(1e4);
  sb.appendString('<div class="suggest-preview-text">');
  for (let i = 0, len = lines.length; i < len; i++) {
    const lineData = lines[i];
    const line = lineData.content;
    sb.appendString('<div class="view-line');
    sb.appendString('" style="top:');
    sb.appendString(String(i * lineHeight));
    sb.appendString('px;width:1000000px;">');
    const isBasicASCII$1 = isBasicASCII(line);
    const containsRTL$1 = containsRTL(line);
    const lineTokens = LineTokens.createEmpty(line, languageIdCodec);
    renderViewLine(new RenderLineInput(fontInfo.isMonospace && !disableMonospaceOptimizations, fontInfo.canUseHalfwidthRightwardsArrow, line, false, isBasicASCII$1, containsRTL$1, 0, lineTokens, lineData.decorations, tabSize, 0, fontInfo.spaceWidth, fontInfo.middotWidth, fontInfo.wsmiddotWidth, stopRenderingLineAfter, renderWhitespace, renderControlCharacters, fontLigatures !== EditorFontLigatures.OFF, null), sb);
    sb.appendString("</div>");
  }
  sb.appendString("</div>");
  applyFontInfo(domNode, fontInfo);
  const html2 = sb.build();
  const trustedhtml = ttPolicy$2 ? ttPolicy$2.createHTML(html2) : html2;
  domNode.innerHTML = trustedhtml;
}
const ttPolicy$2 = createTrustedTypesPolicy("editorGhostText", { createHTML: (value) => value });
class SingleTextEdit {
  constructor(range2, text2) {
    this.range = range2;
    this.text = text2;
  }
  removeCommonPrefix(model, validModelRange) {
    const modelRange = validModelRange ? this.range.intersectRanges(validModelRange) : this.range;
    if (!modelRange) {
      return this;
    }
    const valueToReplace = model.getValueInRange(
      modelRange,
      1
      /* EndOfLinePreference.LF */
    );
    const commonPrefixLen = commonPrefixLength(valueToReplace, this.text);
    const start = addPositions(this.range.getStartPosition(), lengthOfText(valueToReplace.substring(0, commonPrefixLen)));
    const text2 = this.text.substring(commonPrefixLen);
    const range2 = Range$2.fromPositions(start, this.range.getEndPosition());
    return new SingleTextEdit(range2, text2);
  }
  augments(base2) {
    return this.text.startsWith(base2.text) && rangeExtends(this.range, base2.range);
  }
  /**
   * @param previewSuffixLength Sets where to split `inlineCompletion.text`.
   * 	If the text is `hello` and the suffix length is 2, the non-preview part is `hel` and the preview-part is `lo`.
  */
  computeGhostText(model, mode, cursorPosition, previewSuffixLength = 0) {
    let edit = this.removeCommonPrefix(model);
    if (edit.range.endLineNumber !== edit.range.startLineNumber) {
      return void 0;
    }
    const sourceLine = model.getLineContent(edit.range.startLineNumber);
    const sourceIndentationLength = getLeadingWhitespace(sourceLine).length;
    const suggestionTouchesIndentation = edit.range.startColumn - 1 <= sourceIndentationLength;
    if (suggestionTouchesIndentation) {
      const suggestionAddedIndentationLength = getLeadingWhitespace(edit.text).length;
      const replacedIndentation = sourceLine.substring(edit.range.startColumn - 1, sourceIndentationLength);
      const [startPosition, endPosition] = [edit.range.getStartPosition(), edit.range.getEndPosition()];
      const newStartPosition = startPosition.column + replacedIndentation.length <= endPosition.column ? startPosition.delta(0, replacedIndentation.length) : endPosition;
      const rangeThatDoesNotReplaceIndentation = Range$2.fromPositions(newStartPosition, endPosition);
      const suggestionWithoutIndentationChange = edit.text.startsWith(replacedIndentation) ? edit.text.substring(replacedIndentation.length) : edit.text.substring(suggestionAddedIndentationLength);
      edit = new SingleTextEdit(rangeThatDoesNotReplaceIndentation, suggestionWithoutIndentationChange);
    }
    const valueToBeReplaced = model.getValueInRange(edit.range);
    const changes = cachingDiff(valueToBeReplaced, edit.text);
    if (!changes) {
      return void 0;
    }
    const lineNumber = edit.range.startLineNumber;
    const parts = new Array();
    if (mode === "prefix") {
      const filteredChanges = changes.filter((c) => c.originalLength === 0);
      if (filteredChanges.length > 1 || filteredChanges.length === 1 && filteredChanges[0].originalStart !== valueToBeReplaced.length) {
        return void 0;
      }
    }
    const previewStartInCompletionText = edit.text.length - previewSuffixLength;
    for (const c of changes) {
      const insertColumn = edit.range.startColumn + c.originalStart + c.originalLength;
      if (mode === "subwordSmart" && cursorPosition && cursorPosition.lineNumber === edit.range.startLineNumber && insertColumn < cursorPosition.column) {
        return void 0;
      }
      if (c.originalLength > 0) {
        return void 0;
      }
      if (c.modifiedLength === 0) {
        continue;
      }
      const modifiedEnd = c.modifiedStart + c.modifiedLength;
      const nonPreviewTextEnd = Math.max(c.modifiedStart, Math.min(modifiedEnd, previewStartInCompletionText));
      const nonPreviewText = edit.text.substring(c.modifiedStart, nonPreviewTextEnd);
      const italicText = edit.text.substring(nonPreviewTextEnd, Math.max(c.modifiedStart, modifiedEnd));
      if (nonPreviewText.length > 0) {
        const lines = splitLines(nonPreviewText);
        parts.push(new GhostTextPart(insertColumn, lines, false));
      }
      if (italicText.length > 0) {
        const lines = splitLines(italicText);
        parts.push(new GhostTextPart(insertColumn, lines, true));
      }
    }
    return new GhostText(lineNumber, parts);
  }
}
function rangeExtends(extendingRange, rangeToExtend) {
  return rangeToExtend.getStartPosition().equals(extendingRange.getStartPosition()) && rangeToExtend.getEndPosition().isBeforeOrEqual(extendingRange.getEndPosition());
}
let lastRequest = void 0;
function cachingDiff(originalValue, newValue) {
  if ((lastRequest === null || lastRequest === void 0 ? void 0 : lastRequest.originalValue) === originalValue && (lastRequest === null || lastRequest === void 0 ? void 0 : lastRequest.newValue) === newValue) {
    return lastRequest === null || lastRequest === void 0 ? void 0 : lastRequest.changes;
  } else {
    let changes = smartDiff(originalValue, newValue, true);
    if (changes) {
      const deletedChars = deletedCharacters(changes);
      if (deletedChars > 0) {
        const newChanges = smartDiff(originalValue, newValue, false);
        if (newChanges && deletedCharacters(newChanges) < deletedChars) {
          changes = newChanges;
        }
      }
    }
    lastRequest = {
      originalValue,
      newValue,
      changes
    };
    return changes;
  }
}
function deletedCharacters(changes) {
  let sum = 0;
  for (const c of changes) {
    sum += c.originalLength;
  }
  return sum;
}
function smartDiff(originalValue, newValue, smartBracketMatching) {
  if (originalValue.length > 5e3 || newValue.length > 5e3) {
    return void 0;
  }
  function getMaxCharCode(val) {
    let maxCharCode2 = 0;
    for (let i = 0, len = val.length; i < len; i++) {
      const charCode = val.charCodeAt(i);
      if (charCode > maxCharCode2) {
        maxCharCode2 = charCode;
      }
    }
    return maxCharCode2;
  }
  const maxCharCode = Math.max(getMaxCharCode(originalValue), getMaxCharCode(newValue));
  function getUniqueCharCode(id3) {
    if (id3 < 0) {
      throw new Error("unexpected");
    }
    return maxCharCode + id3 + 1;
  }
  function getElements(source) {
    let level = 0;
    let group2 = 0;
    const characters = new Int32Array(source.length);
    for (let i = 0, len = source.length; i < len; i++) {
      if (smartBracketMatching && source[i] === "(") {
        const id3 = group2 * 100 + level;
        characters[i] = getUniqueCharCode(2 * id3);
        level++;
      } else if (smartBracketMatching && source[i] === ")") {
        level = Math.max(level - 1, 0);
        const id3 = group2 * 100 + level;
        characters[i] = getUniqueCharCode(2 * id3 + 1);
        if (level === 0) {
          group2++;
        }
      } else {
        characters[i] = source.charCodeAt(i);
      }
    }
    return characters;
  }
  const elements1 = getElements(originalValue);
  const elements2 = getElements(newValue);
  return new LcsDiff({ getElements: () => elements1 }, { getElements: () => elements2 }).ComputeDiff(false).changes;
}
function fixBracketsInLine(tokens, languageConfigurationService) {
  const denseKeyProvider = new DenseKeyProvider();
  const bracketTokens = new LanguageAgnosticBracketTokens(denseKeyProvider, (languageId) => languageConfigurationService.getLanguageConfiguration(languageId));
  const tokenizer3 = new TextBufferTokenizer(new StaticTokenizerSource([tokens]), bracketTokens);
  const node2 = parseDocument(tokenizer3, [], void 0, true);
  let str2 = "";
  const line = tokens.getLineContent();
  function processNode(node3, offset) {
    if (node3.kind === 2) {
      processNode(node3.openingBracket, offset);
      offset = lengthAdd(offset, node3.openingBracket.length);
      if (node3.child) {
        processNode(node3.child, offset);
        offset = lengthAdd(offset, node3.child.length);
      }
      if (node3.closingBracket) {
        processNode(node3.closingBracket, offset);
        offset = lengthAdd(offset, node3.closingBracket.length);
      } else {
        const singleLangBracketTokens = bracketTokens.getSingleLanguageBracketTokens(node3.openingBracket.languageId);
        const closingTokenText = singleLangBracketTokens.findClosingTokenText(node3.openingBracket.bracketIds);
        str2 += closingTokenText;
      }
    } else if (node3.kind === 3)
      ;
    else if (node3.kind === 0 || node3.kind === 1) {
      str2 += line.substring(lengthGetColumnCountIfZeroLineCount(offset), lengthGetColumnCountIfZeroLineCount(lengthAdd(offset, node3.length)));
    } else if (node3.kind === 4) {
      for (const child of node3.children) {
        processNode(child, offset);
        offset = lengthAdd(offset, child.length);
      }
    }
  }
  processNode(node2, lengthZero);
  return str2;
}
class StaticTokenizerSource {
  constructor(lines) {
    this.lines = lines;
    this.tokenization = {
      getLineTokens: (lineNumber) => {
        return this.lines[lineNumber - 1];
      }
    };
  }
  getLineCount() {
    return this.lines.length;
  }
  getLineLength(lineNumber) {
    return this.lines[lineNumber - 1].getLineContent().length;
  }
}
class Scanner2 {
  constructor() {
    this.value = "";
    this.pos = 0;
  }
  static isDigitCharacter(ch) {
    return ch >= 48 && ch <= 57;
  }
  static isVariableCharacter(ch) {
    return ch === 95 || ch >= 97 && ch <= 122 || ch >= 65 && ch <= 90;
  }
  text(value) {
    this.value = value;
    this.pos = 0;
  }
  tokenText(token) {
    return this.value.substr(token.pos, token.len);
  }
  next() {
    if (this.pos >= this.value.length) {
      return { type: 14, pos: this.pos, len: 0 };
    }
    const pos = this.pos;
    let len = 0;
    let ch = this.value.charCodeAt(pos);
    let type;
    type = Scanner2._table[ch];
    if (typeof type === "number") {
      this.pos += 1;
      return { type, pos, len: 1 };
    }
    if (Scanner2.isDigitCharacter(ch)) {
      type = 8;
      do {
        len += 1;
        ch = this.value.charCodeAt(pos + len);
      } while (Scanner2.isDigitCharacter(ch));
      this.pos += len;
      return { type, pos, len };
    }
    if (Scanner2.isVariableCharacter(ch)) {
      type = 9;
      do {
        ch = this.value.charCodeAt(pos + ++len);
      } while (Scanner2.isVariableCharacter(ch) || Scanner2.isDigitCharacter(ch));
      this.pos += len;
      return { type, pos, len };
    }
    type = 10;
    do {
      len += 1;
      ch = this.value.charCodeAt(pos + len);
    } while (!isNaN(ch) && typeof Scanner2._table[ch] === "undefined" && !Scanner2.isDigitCharacter(ch) && !Scanner2.isVariableCharacter(ch));
    this.pos += len;
    return { type, pos, len };
  }
}
Scanner2._table = {
  [
    36
    /* CharCode.DollarSign */
  ]: 0,
  [
    58
    /* CharCode.Colon */
  ]: 1,
  [
    44
    /* CharCode.Comma */
  ]: 2,
  [
    123
    /* CharCode.OpenCurlyBrace */
  ]: 3,
  [
    125
    /* CharCode.CloseCurlyBrace */
  ]: 4,
  [
    92
    /* CharCode.Backslash */
  ]: 5,
  [
    47
    /* CharCode.Slash */
  ]: 6,
  [
    124
    /* CharCode.Pipe */
  ]: 7,
  [
    43
    /* CharCode.Plus */
  ]: 11,
  [
    45
    /* CharCode.Dash */
  ]: 12,
  [
    63
    /* CharCode.QuestionMark */
  ]: 13
};
class Marker {
  constructor() {
    this._children = [];
  }
  appendChild(child) {
    if (child instanceof Text && this._children[this._children.length - 1] instanceof Text) {
      this._children[this._children.length - 1].value += child.value;
    } else {
      child.parent = this;
      this._children.push(child);
    }
    return this;
  }
  replace(child, others) {
    const { parent } = child;
    const idx = parent.children.indexOf(child);
    const newChildren = parent.children.slice(0);
    newChildren.splice(idx, 1, ...others);
    parent._children = newChildren;
    (function _fixParent(children, parent2) {
      for (const child2 of children) {
        child2.parent = parent2;
        _fixParent(child2.children, child2);
      }
    })(others, parent);
  }
  get children() {
    return this._children;
  }
  get rightMostDescendant() {
    if (this._children.length > 0) {
      return this._children[this._children.length - 1].rightMostDescendant;
    }
    return this;
  }
  get snippet() {
    let candidate = this;
    while (true) {
      if (!candidate) {
        return void 0;
      }
      if (candidate instanceof TextmateSnippet) {
        return candidate;
      }
      candidate = candidate.parent;
    }
  }
  toString() {
    return this.children.reduce((prev, cur) => prev + cur.toString(), "");
  }
  len() {
    return 0;
  }
}
class Text extends Marker {
  constructor(value) {
    super();
    this.value = value;
  }
  toString() {
    return this.value;
  }
  len() {
    return this.value.length;
  }
  clone() {
    return new Text(this.value);
  }
}
class TransformableMarker extends Marker {
}
class Placeholder extends TransformableMarker {
  static compareByIndex(a, b) {
    if (a.index === b.index) {
      return 0;
    } else if (a.isFinalTabstop) {
      return 1;
    } else if (b.isFinalTabstop) {
      return -1;
    } else if (a.index < b.index) {
      return -1;
    } else if (a.index > b.index) {
      return 1;
    } else {
      return 0;
    }
  }
  constructor(index) {
    super();
    this.index = index;
  }
  get isFinalTabstop() {
    return this.index === 0;
  }
  get choice() {
    return this._children.length === 1 && this._children[0] instanceof Choice ? this._children[0] : void 0;
  }
  clone() {
    const ret = new Placeholder(this.index);
    if (this.transform) {
      ret.transform = this.transform.clone();
    }
    ret._children = this.children.map((child) => child.clone());
    return ret;
  }
}
class Choice extends Marker {
  constructor() {
    super(...arguments);
    this.options = [];
  }
  appendChild(marker) {
    if (marker instanceof Text) {
      marker.parent = this;
      this.options.push(marker);
    }
    return this;
  }
  toString() {
    return this.options[0].value;
  }
  len() {
    return this.options[0].len();
  }
  clone() {
    const ret = new Choice();
    this.options.forEach(ret.appendChild, ret);
    return ret;
  }
}
class Transform extends Marker {
  constructor() {
    super(...arguments);
    this.regexp = new RegExp("");
  }
  resolve(value) {
    const _this = this;
    let didMatch = false;
    let ret = value.replace(this.regexp, function() {
      didMatch = true;
      return _this._replace(Array.prototype.slice.call(arguments, 0, -2));
    });
    if (!didMatch && this._children.some((child) => child instanceof FormatString && Boolean(child.elseValue))) {
      ret = this._replace([]);
    }
    return ret;
  }
  _replace(groups) {
    let ret = "";
    for (const marker of this._children) {
      if (marker instanceof FormatString) {
        let value = groups[marker.index] || "";
        value = marker.resolve(value);
        ret += value;
      } else {
        ret += marker.toString();
      }
    }
    return ret;
  }
  toString() {
    return "";
  }
  clone() {
    const ret = new Transform();
    ret.regexp = new RegExp(this.regexp.source, (this.regexp.ignoreCase ? "i" : "") + (this.regexp.global ? "g" : ""));
    ret._children = this.children.map((child) => child.clone());
    return ret;
  }
}
class FormatString extends Marker {
  constructor(index, shorthandName, ifValue, elseValue) {
    super();
    this.index = index;
    this.shorthandName = shorthandName;
    this.ifValue = ifValue;
    this.elseValue = elseValue;
  }
  resolve(value) {
    if (this.shorthandName === "upcase") {
      return !value ? "" : value.toLocaleUpperCase();
    } else if (this.shorthandName === "downcase") {
      return !value ? "" : value.toLocaleLowerCase();
    } else if (this.shorthandName === "capitalize") {
      return !value ? "" : value[0].toLocaleUpperCase() + value.substr(1);
    } else if (this.shorthandName === "pascalcase") {
      return !value ? "" : this._toPascalCase(value);
    } else if (this.shorthandName === "camelcase") {
      return !value ? "" : this._toCamelCase(value);
    } else if (Boolean(value) && typeof this.ifValue === "string") {
      return this.ifValue;
    } else if (!Boolean(value) && typeof this.elseValue === "string") {
      return this.elseValue;
    } else {
      return value || "";
    }
  }
  _toPascalCase(value) {
    const match2 = value.match(/[a-z0-9]+/gi);
    if (!match2) {
      return value;
    }
    return match2.map((word2) => {
      return word2.charAt(0).toUpperCase() + word2.substr(1);
    }).join("");
  }
  _toCamelCase(value) {
    const match2 = value.match(/[a-z0-9]+/gi);
    if (!match2) {
      return value;
    }
    return match2.map((word2, index) => {
      if (index === 0) {
        return word2.charAt(0).toLowerCase() + word2.substr(1);
      }
      return word2.charAt(0).toUpperCase() + word2.substr(1);
    }).join("");
  }
  clone() {
    const ret = new FormatString(this.index, this.shorthandName, this.ifValue, this.elseValue);
    return ret;
  }
}
class Variable extends TransformableMarker {
  constructor(name) {
    super();
    this.name = name;
  }
  resolve(resolver) {
    let value = resolver.resolve(this);
    if (this.transform) {
      value = this.transform.resolve(value || "");
    }
    if (value !== void 0) {
      this._children = [new Text(value)];
      return true;
    }
    return false;
  }
  clone() {
    const ret = new Variable(this.name);
    if (this.transform) {
      ret.transform = this.transform.clone();
    }
    ret._children = this.children.map((child) => child.clone());
    return ret;
  }
}
function walk(marker, visitor) {
  const stack = [...marker];
  while (stack.length > 0) {
    const marker2 = stack.shift();
    const recurse = visitor(marker2);
    if (!recurse) {
      break;
    }
    stack.unshift(...marker2.children);
  }
}
class TextmateSnippet extends Marker {
  get placeholderInfo() {
    if (!this._placeholders) {
      const all = [];
      let last2;
      this.walk(function(candidate) {
        if (candidate instanceof Placeholder) {
          all.push(candidate);
          last2 = !last2 || last2.index < candidate.index ? candidate : last2;
        }
        return true;
      });
      this._placeholders = { all, last: last2 };
    }
    return this._placeholders;
  }
  get placeholders() {
    const { all } = this.placeholderInfo;
    return all;
  }
  offset(marker) {
    let pos = 0;
    let found = false;
    this.walk((candidate) => {
      if (candidate === marker) {
        found = true;
        return false;
      }
      pos += candidate.len();
      return true;
    });
    if (!found) {
      return -1;
    }
    return pos;
  }
  fullLen(marker) {
    let ret = 0;
    walk([marker], (marker2) => {
      ret += marker2.len();
      return true;
    });
    return ret;
  }
  enclosingPlaceholders(placeholder) {
    const ret = [];
    let { parent } = placeholder;
    while (parent) {
      if (parent instanceof Placeholder) {
        ret.push(parent);
      }
      parent = parent.parent;
    }
    return ret;
  }
  resolveVariables(resolver) {
    this.walk((candidate) => {
      if (candidate instanceof Variable) {
        if (candidate.resolve(resolver)) {
          this._placeholders = void 0;
        }
      }
      return true;
    });
    return this;
  }
  appendChild(child) {
    this._placeholders = void 0;
    return super.appendChild(child);
  }
  replace(child, others) {
    this._placeholders = void 0;
    return super.replace(child, others);
  }
  clone() {
    const ret = new TextmateSnippet();
    this._children = this.children.map((child) => child.clone());
    return ret;
  }
  walk(visitor) {
    walk(this.children, visitor);
  }
}
class SnippetParser {
  constructor() {
    this._scanner = new Scanner2();
    this._token = { type: 14, pos: 0, len: 0 };
  }
  static escape(value) {
    return value.replace(/\$|}|\\/g, "\\$&");
  }
  static guessNeedsClipboard(template) {
    return /\${?CLIPBOARD/.test(template);
  }
  parse(value, insertFinalTabstop, enforceFinalTabstop) {
    const snippet = new TextmateSnippet();
    this.parseFragment(value, snippet);
    this.ensureFinalTabstop(snippet, enforceFinalTabstop !== null && enforceFinalTabstop !== void 0 ? enforceFinalTabstop : false, insertFinalTabstop !== null && insertFinalTabstop !== void 0 ? insertFinalTabstop : false);
    return snippet;
  }
  parseFragment(value, snippet) {
    const offset = snippet.children.length;
    this._scanner.text(value);
    this._token = this._scanner.next();
    while (this._parse(snippet)) {
    }
    const placeholderDefaultValues = /* @__PURE__ */ new Map();
    const incompletePlaceholders = [];
    snippet.walk((marker) => {
      if (marker instanceof Placeholder) {
        if (marker.isFinalTabstop) {
          placeholderDefaultValues.set(0, void 0);
        } else if (!placeholderDefaultValues.has(marker.index) && marker.children.length > 0) {
          placeholderDefaultValues.set(marker.index, marker.children);
        } else {
          incompletePlaceholders.push(marker);
        }
      }
      return true;
    });
    const fillInIncompletePlaceholder = (placeholder, stack2) => {
      const defaultValues = placeholderDefaultValues.get(placeholder.index);
      if (!defaultValues) {
        return;
      }
      const clone2 = new Placeholder(placeholder.index);
      clone2.transform = placeholder.transform;
      for (const child of defaultValues) {
        const newChild = child.clone();
        clone2.appendChild(newChild);
        if (newChild instanceof Placeholder && placeholderDefaultValues.has(newChild.index) && !stack2.has(newChild.index)) {
          stack2.add(newChild.index);
          fillInIncompletePlaceholder(newChild, stack2);
          stack2.delete(newChild.index);
        }
      }
      snippet.replace(placeholder, [clone2]);
    };
    const stack = /* @__PURE__ */ new Set();
    for (const placeholder of incompletePlaceholders) {
      fillInIncompletePlaceholder(placeholder, stack);
    }
    return snippet.children.slice(offset);
  }
  ensureFinalTabstop(snippet, enforceFinalTabstop, insertFinalTabstop) {
    if (enforceFinalTabstop || insertFinalTabstop && snippet.placeholders.length > 0) {
      const finalTabstop = snippet.placeholders.find((p2) => p2.index === 0);
      if (!finalTabstop) {
        snippet.appendChild(new Placeholder(0));
      }
    }
  }
  _accept(type, value) {
    if (type === void 0 || this._token.type === type) {
      const ret = !value ? true : this._scanner.tokenText(this._token);
      this._token = this._scanner.next();
      return ret;
    }
    return false;
  }
  _backTo(token) {
    this._scanner.pos = token.pos + token.len;
    this._token = token;
    return false;
  }
  _until(type) {
    const start = this._token;
    while (this._token.type !== type) {
      if (this._token.type === 14) {
        return false;
      } else if (this._token.type === 5) {
        const nextToken = this._scanner.next();
        if (nextToken.type !== 0 && nextToken.type !== 4 && nextToken.type !== 5) {
          return false;
        }
      }
      this._token = this._scanner.next();
    }
    const value = this._scanner.value.substring(start.pos, this._token.pos).replace(/\\(\$|}|\\)/g, "$1");
    this._token = this._scanner.next();
    return value;
  }
  _parse(marker) {
    return this._parseEscaped(marker) || this._parseTabstopOrVariableName(marker) || this._parseComplexPlaceholder(marker) || this._parseComplexVariable(marker) || this._parseAnything(marker);
  }
  // \$, \\, \} -> just text
  _parseEscaped(marker) {
    let value;
    if (value = this._accept(5, true)) {
      value = this._accept(0, true) || this._accept(4, true) || this._accept(5, true) || value;
      marker.appendChild(new Text(value));
      return true;
    }
    return false;
  }
  // $foo -> variable, $1 -> tabstop
  _parseTabstopOrVariableName(parent) {
    let value;
    const token = this._token;
    const match2 = this._accept(
      0
      /* TokenType.Dollar */
    ) && (value = this._accept(9, true) || this._accept(8, true));
    if (!match2) {
      return this._backTo(token);
    }
    parent.appendChild(/^\d+$/.test(value) ? new Placeholder(Number(value)) : new Variable(value));
    return true;
  }
  // ${1:<children>}, ${1} -> placeholder
  _parseComplexPlaceholder(parent) {
    let index;
    const token = this._token;
    const match2 = this._accept(
      0
      /* TokenType.Dollar */
    ) && this._accept(
      3
      /* TokenType.CurlyOpen */
    ) && (index = this._accept(8, true));
    if (!match2) {
      return this._backTo(token);
    }
    const placeholder = new Placeholder(Number(index));
    if (this._accept(
      1
      /* TokenType.Colon */
    )) {
      while (true) {
        if (this._accept(
          4
          /* TokenType.CurlyClose */
        )) {
          parent.appendChild(placeholder);
          return true;
        }
        if (this._parse(placeholder)) {
          continue;
        }
        parent.appendChild(new Text("${" + index + ":"));
        placeholder.children.forEach(parent.appendChild, parent);
        return true;
      }
    } else if (placeholder.index > 0 && this._accept(
      7
      /* TokenType.Pipe */
    )) {
      const choice = new Choice();
      while (true) {
        if (this._parseChoiceElement(choice)) {
          if (this._accept(
            2
            /* TokenType.Comma */
          )) {
            continue;
          }
          if (this._accept(
            7
            /* TokenType.Pipe */
          )) {
            placeholder.appendChild(choice);
            if (this._accept(
              4
              /* TokenType.CurlyClose */
            )) {
              parent.appendChild(placeholder);
              return true;
            }
          }
        }
        this._backTo(token);
        return false;
      }
    } else if (this._accept(
      6
      /* TokenType.Forwardslash */
    )) {
      if (this._parseTransform(placeholder)) {
        parent.appendChild(placeholder);
        return true;
      }
      this._backTo(token);
      return false;
    } else if (this._accept(
      4
      /* TokenType.CurlyClose */
    )) {
      parent.appendChild(placeholder);
      return true;
    } else {
      return this._backTo(token);
    }
  }
  _parseChoiceElement(parent) {
    const token = this._token;
    const values = [];
    while (true) {
      if (this._token.type === 2 || this._token.type === 7) {
        break;
      }
      let value;
      if (value = this._accept(5, true)) {
        value = this._accept(2, true) || this._accept(7, true) || this._accept(5, true) || value;
      } else {
        value = this._accept(void 0, true);
      }
      if (!value) {
        this._backTo(token);
        return false;
      }
      values.push(value);
    }
    if (values.length === 0) {
      this._backTo(token);
      return false;
    }
    parent.appendChild(new Text(values.join("")));
    return true;
  }
  // ${foo:<children>}, ${foo} -> variable
  _parseComplexVariable(parent) {
    let name;
    const token = this._token;
    const match2 = this._accept(
      0
      /* TokenType.Dollar */
    ) && this._accept(
      3
      /* TokenType.CurlyOpen */
    ) && (name = this._accept(9, true));
    if (!match2) {
      return this._backTo(token);
    }
    const variable = new Variable(name);
    if (this._accept(
      1
      /* TokenType.Colon */
    )) {
      while (true) {
        if (this._accept(
          4
          /* TokenType.CurlyClose */
        )) {
          parent.appendChild(variable);
          return true;
        }
        if (this._parse(variable)) {
          continue;
        }
        parent.appendChild(new Text("${" + name + ":"));
        variable.children.forEach(parent.appendChild, parent);
        return true;
      }
    } else if (this._accept(
      6
      /* TokenType.Forwardslash */
    )) {
      if (this._parseTransform(variable)) {
        parent.appendChild(variable);
        return true;
      }
      this._backTo(token);
      return false;
    } else if (this._accept(
      4
      /* TokenType.CurlyClose */
    )) {
      parent.appendChild(variable);
      return true;
    } else {
      return this._backTo(token);
    }
  }
  _parseTransform(parent) {
    const transform = new Transform();
    let regexValue = "";
    let regexOptions = "";
    while (true) {
      if (this._accept(
        6
        /* TokenType.Forwardslash */
      )) {
        break;
      }
      let escaped;
      if (escaped = this._accept(5, true)) {
        escaped = this._accept(6, true) || escaped;
        regexValue += escaped;
        continue;
      }
      if (this._token.type !== 14) {
        regexValue += this._accept(void 0, true);
        continue;
      }
      return false;
    }
    while (true) {
      if (this._accept(
        6
        /* TokenType.Forwardslash */
      )) {
        break;
      }
      let escaped;
      if (escaped = this._accept(5, true)) {
        escaped = this._accept(5, true) || this._accept(6, true) || escaped;
        transform.appendChild(new Text(escaped));
        continue;
      }
      if (this._parseFormatString(transform) || this._parseAnything(transform)) {
        continue;
      }
      return false;
    }
    while (true) {
      if (this._accept(
        4
        /* TokenType.CurlyClose */
      )) {
        break;
      }
      if (this._token.type !== 14) {
        regexOptions += this._accept(void 0, true);
        continue;
      }
      return false;
    }
    try {
      transform.regexp = new RegExp(regexValue, regexOptions);
    } catch (e) {
      return false;
    }
    parent.transform = transform;
    return true;
  }
  _parseFormatString(parent) {
    const token = this._token;
    if (!this._accept(
      0
      /* TokenType.Dollar */
    )) {
      return false;
    }
    let complex = false;
    if (this._accept(
      3
      /* TokenType.CurlyOpen */
    )) {
      complex = true;
    }
    const index = this._accept(8, true);
    if (!index) {
      this._backTo(token);
      return false;
    } else if (!complex) {
      parent.appendChild(new FormatString(Number(index)));
      return true;
    } else if (this._accept(
      4
      /* TokenType.CurlyClose */
    )) {
      parent.appendChild(new FormatString(Number(index)));
      return true;
    } else if (!this._accept(
      1
      /* TokenType.Colon */
    )) {
      this._backTo(token);
      return false;
    }
    if (this._accept(
      6
      /* TokenType.Forwardslash */
    )) {
      const shorthand = this._accept(9, true);
      if (!shorthand || !this._accept(
        4
        /* TokenType.CurlyClose */
      )) {
        this._backTo(token);
        return false;
      } else {
        parent.appendChild(new FormatString(Number(index), shorthand));
        return true;
      }
    } else if (this._accept(
      11
      /* TokenType.Plus */
    )) {
      const ifValue = this._until(
        4
        /* TokenType.CurlyClose */
      );
      if (ifValue) {
        parent.appendChild(new FormatString(Number(index), void 0, ifValue, void 0));
        return true;
      }
    } else if (this._accept(
      12
      /* TokenType.Dash */
    )) {
      const elseValue = this._until(
        4
        /* TokenType.CurlyClose */
      );
      if (elseValue) {
        parent.appendChild(new FormatString(Number(index), void 0, void 0, elseValue));
        return true;
      }
    } else if (this._accept(
      13
      /* TokenType.QuestionMark */
    )) {
      const ifValue = this._until(
        1
        /* TokenType.Colon */
      );
      if (ifValue) {
        const elseValue = this._until(
          4
          /* TokenType.CurlyClose */
        );
        if (elseValue) {
          parent.appendChild(new FormatString(Number(index), void 0, ifValue, elseValue));
          return true;
        }
      }
    } else {
      const elseValue = this._until(
        4
        /* TokenType.CurlyClose */
      );
      if (elseValue) {
        parent.appendChild(new FormatString(Number(index), void 0, void 0, elseValue));
        return true;
      }
    }
    this._backTo(token);
    return false;
  }
  _parseAnything(marker) {
    if (this._token.type !== 14) {
      marker.appendChild(new Text(this._scanner.tokenText(this._token)));
      this._accept(void 0);
      return true;
    }
    return false;
  }
}
var __awaiter$K = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
function provideInlineCompletions(registry, position, model, context, token = CancellationToken.None, languageConfigurationService) {
  return __awaiter$K(this, void 0, void 0, function* () {
    const defaultReplaceRange = getDefaultRange(position, model);
    const providers = registry.all(model);
    const multiMap = new SetMap();
    for (const provider of providers) {
      if (provider.groupId) {
        multiMap.add(provider.groupId, provider);
      }
    }
    function getPreferredProviders(provider) {
      if (!provider.yieldsToGroupIds) {
        return [];
      }
      const result2 = [];
      for (const groupId of provider.yieldsToGroupIds || []) {
        const providers2 = multiMap.get(groupId);
        for (const p2 of providers2) {
          result2.push(p2);
        }
      }
      return result2;
    }
    const states = /* @__PURE__ */ new Map();
    const seen2 = /* @__PURE__ */ new Set();
    function findPreferredProviderCircle(provider, stack) {
      stack = [...stack, provider];
      if (seen2.has(provider)) {
        return stack;
      }
      seen2.add(provider);
      try {
        const preferred = getPreferredProviders(provider);
        for (const p2 of preferred) {
          const c = findPreferredProviderCircle(p2, stack);
          if (c) {
            return c;
          }
        }
      } finally {
        seen2.delete(provider);
      }
      return void 0;
    }
    function processProvider(provider) {
      const state = states.get(provider);
      if (state) {
        return state;
      }
      const circle = findPreferredProviderCircle(provider, []);
      if (circle) {
        onUnexpectedExternalError(new Error(`Inline completions: cyclic yield-to dependency detected. Path: ${circle.map((s) => s.toString ? s.toString() : "" + s).join(" -> ")}`));
      }
      const deferredPromise = new DeferredPromise();
      states.set(provider, deferredPromise.p);
      (() => __awaiter$K(this, void 0, void 0, function* () {
        if (!circle) {
          const preferred = getPreferredProviders(provider);
          for (const p2 of preferred) {
            const result2 = yield processProvider(p2);
            if (result2 && result2.items.length > 0) {
              return void 0;
            }
          }
        }
        try {
          const completions = yield provider.provideInlineCompletions(model, position, context, token);
          return completions;
        } catch (e) {
          onUnexpectedExternalError(e);
          return void 0;
        }
      }))().then((c) => deferredPromise.complete(c), (e) => deferredPromise.error(e));
      return deferredPromise.p;
    }
    const providerResults = yield Promise.all(providers.map((provider) => __awaiter$K(this, void 0, void 0, function* () {
      return { provider, completions: yield processProvider(provider) };
    })));
    const itemsByHash = /* @__PURE__ */ new Map();
    const lists = [];
    for (const result2 of providerResults) {
      const completions = result2.completions;
      if (!completions) {
        continue;
      }
      const list2 = new InlineCompletionList(completions, result2.provider);
      lists.push(list2);
      for (const item of completions.items) {
        const inlineCompletionItem = InlineCompletionItem.from(item, list2, defaultReplaceRange, model, languageConfigurationService);
        itemsByHash.set(inlineCompletionItem.hash(), inlineCompletionItem);
      }
    }
    return new InlineCompletionProviderResult(Array.from(itemsByHash.values()), new Set(itemsByHash.keys()), lists);
  });
}
class InlineCompletionProviderResult {
  constructor(completions, hashs, providerResults) {
    this.completions = completions;
    this.hashs = hashs;
    this.providerResults = providerResults;
  }
  has(item) {
    return this.hashs.has(item.hash());
  }
  dispose() {
    for (const result2 of this.providerResults) {
      result2.removeRef();
    }
  }
}
class InlineCompletionList {
  constructor(inlineCompletions, provider) {
    this.inlineCompletions = inlineCompletions;
    this.provider = provider;
    this.refCount = 1;
  }
  addRef() {
    this.refCount++;
  }
  removeRef() {
    this.refCount--;
    if (this.refCount === 0) {
      this.provider.freeInlineCompletions(this.inlineCompletions);
    }
  }
}
class InlineCompletionItem {
  static from(inlineCompletion, source, defaultReplaceRange, textModel, languageConfigurationService) {
    let insertText;
    let snippetInfo;
    let range2 = inlineCompletion.range ? Range$2.lift(inlineCompletion.range) : defaultReplaceRange;
    if (typeof inlineCompletion.insertText === "string") {
      insertText = inlineCompletion.insertText;
      if (languageConfigurationService && inlineCompletion.completeBracketPairs) {
        insertText = closeBrackets(insertText, range2.getStartPosition(), textModel, languageConfigurationService);
        const diff = insertText.length - inlineCompletion.insertText.length;
        if (diff !== 0) {
          range2 = new Range$2(range2.startLineNumber, range2.startColumn, range2.endLineNumber, range2.endColumn + diff);
        }
      }
      snippetInfo = void 0;
    } else if ("snippet" in inlineCompletion.insertText) {
      const preBracketCompletionLength = inlineCompletion.insertText.snippet.length;
      if (languageConfigurationService && inlineCompletion.completeBracketPairs) {
        inlineCompletion.insertText.snippet = closeBrackets(inlineCompletion.insertText.snippet, range2.getStartPosition(), textModel, languageConfigurationService);
        const diff = inlineCompletion.insertText.snippet.length - preBracketCompletionLength;
        if (diff !== 0) {
          range2 = new Range$2(range2.startLineNumber, range2.startColumn, range2.endLineNumber, range2.endColumn + diff);
        }
      }
      const snippet = new SnippetParser().parse(inlineCompletion.insertText.snippet);
      if (snippet.children.length === 1 && snippet.children[0] instanceof Text) {
        insertText = snippet.children[0].value;
        snippetInfo = void 0;
      } else {
        insertText = snippet.toString();
        snippetInfo = {
          snippet: inlineCompletion.insertText.snippet,
          range: range2
        };
      }
    } else {
      assertNever(inlineCompletion.insertText);
    }
    return new InlineCompletionItem(insertText, inlineCompletion.command, range2, insertText, snippetInfo, inlineCompletion.additionalTextEdits || getReadonlyEmptyArray(), inlineCompletion, source);
  }
  constructor(filterText, command, range2, insertText, snippetInfo, additionalTextEdits, sourceInlineCompletion, source) {
    this.filterText = filterText;
    this.command = command;
    this.range = range2;
    this.insertText = insertText;
    this.snippetInfo = snippetInfo;
    this.additionalTextEdits = additionalTextEdits;
    this.sourceInlineCompletion = sourceInlineCompletion;
    this.source = source;
    filterText = filterText.replace(/\r\n|\r/g, "\n");
    insertText = filterText.replace(/\r\n|\r/g, "\n");
  }
  withRange(updatedRange) {
    return new InlineCompletionItem(this.filterText, this.command, updatedRange, this.insertText, this.snippetInfo, this.additionalTextEdits, this.sourceInlineCompletion, this.source);
  }
  hash() {
    return JSON.stringify({ insertText: this.insertText, range: this.range.toString() });
  }
}
function getDefaultRange(position, model) {
  const word2 = model.getWordAtPosition(position);
  const maxColumn = model.getLineMaxColumn(position.lineNumber);
  return word2 ? new Range$2(position.lineNumber, word2.startColumn, position.lineNumber, maxColumn) : Range$2.fromPositions(position, position.with(void 0, maxColumn));
}
function closeBrackets(text2, position, model, languageConfigurationService) {
  const lineStart = model.getLineContent(position.lineNumber).substring(0, position.column - 1);
  const newLine = lineStart + text2;
  const newTokens = model.tokenization.tokenizeLineWithEdit(position, newLine.length - (position.column - 1), text2);
  const slicedTokens = newTokens === null || newTokens === void 0 ? void 0 : newTokens.sliceAndInflate(position.column - 1, newLine.length, 0);
  if (!slicedTokens) {
    return text2;
  }
  const newText = fixBracketsInLine(slicedTokens, languageConfigurationService);
  return newText;
}
var __decorate$1b = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$19 = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$J = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
let InlineCompletionsSource = class InlineCompletionsSource2 extends Disposable {
  constructor(textModel, versionId, _debounceValue, languageFeaturesService, languageConfigurationService) {
    super();
    this.textModel = textModel;
    this.versionId = versionId;
    this._debounceValue = _debounceValue;
    this.languageFeaturesService = languageFeaturesService;
    this.languageConfigurationService = languageConfigurationService;
    this._updateOperation = this._register(new MutableDisposable());
    this.inlineCompletions = disposableObservableValue("inlineCompletions", void 0);
    this.suggestWidgetInlineCompletions = disposableObservableValue("suggestWidgetInlineCompletions", void 0);
    this._register(this.textModel.onDidChangeContent(() => {
      this._updateOperation.clear();
    }));
  }
  fetch(position, context, activeInlineCompletion) {
    var _a2, _b2;
    const request = new UpdateRequest(position, context, this.textModel.getVersionId());
    const target = context.selectedSuggestionInfo ? this.suggestWidgetInlineCompletions : this.inlineCompletions;
    if ((_a2 = this._updateOperation.value) === null || _a2 === void 0 ? void 0 : _a2.request.satisfies(request)) {
      return this._updateOperation.value.promise;
    } else if ((_b2 = target.get()) === null || _b2 === void 0 ? void 0 : _b2.request.satisfies(request)) {
      return Promise.resolve(true);
    }
    const updateOngoing = !!this._updateOperation.value;
    this._updateOperation.clear();
    const source = new CancellationTokenSource$1();
    const promise = (() => __awaiter$J(this, void 0, void 0, function* () {
      const shouldDebounce = updateOngoing || context.triggerKind === InlineCompletionTriggerKind$1.Automatic;
      if (shouldDebounce) {
        yield wait(this._debounceValue.get(this.textModel));
      }
      if (source.token.isCancellationRequested || this.textModel.getVersionId() !== request.versionId) {
        return false;
      }
      const startTime2 = /* @__PURE__ */ new Date();
      const updatedCompletions = yield provideInlineCompletions(this.languageFeaturesService.inlineCompletionsProvider, position, this.textModel, context, source.token, this.languageConfigurationService);
      if (source.token.isCancellationRequested || this.textModel.getVersionId() !== request.versionId) {
        return false;
      }
      const endTime = /* @__PURE__ */ new Date();
      this._debounceValue.update(this.textModel, endTime.getTime() - startTime2.getTime());
      const completions = new UpToDateInlineCompletions(updatedCompletions, request, this.textModel, this.versionId);
      if (activeInlineCompletion) {
        const asInlineCompletion = activeInlineCompletion.toInlineCompletion(void 0);
        if (activeInlineCompletion.canBeReused(this.textModel, position) && !updatedCompletions.has(asInlineCompletion)) {
          completions.prepend(activeInlineCompletion.inlineCompletion, asInlineCompletion.range, true);
        }
      }
      this._updateOperation.clear();
      transaction((tx) => {
        target.set(completions, tx);
      });
      return true;
    }))();
    const updateOperation = new UpdateOperation(request, source, promise);
    this._updateOperation.value = updateOperation;
    return promise;
  }
  clear(tx) {
    this._updateOperation.clear();
    this.inlineCompletions.set(void 0, tx);
    this.suggestWidgetInlineCompletions.set(void 0, tx);
  }
  clearSuggestWidgetInlineCompletions(tx) {
    var _a2;
    if ((_a2 = this._updateOperation.value) === null || _a2 === void 0 ? void 0 : _a2.request.context.selectedSuggestionInfo) {
      this._updateOperation.clear();
    }
    this.suggestWidgetInlineCompletions.set(void 0, tx);
  }
  cancelUpdate() {
    this._updateOperation.clear();
  }
};
InlineCompletionsSource = __decorate$1b([
  __param$19(3, ILanguageFeaturesService),
  __param$19(4, ILanguageConfigurationService)
], InlineCompletionsSource);
function wait(ms, cancellationToken) {
  return new Promise((resolve2) => {
    let d = void 0;
    const handle = setTimeout(() => {
      if (d) {
        d.dispose();
      }
      resolve2();
    }, ms);
    if (cancellationToken) {
      d = cancellationToken.onCancellationRequested(() => {
        clearTimeout(handle);
        if (d) {
          d.dispose();
        }
        resolve2();
      });
    }
  });
}
class UpdateRequest {
  constructor(position, context, versionId) {
    this.position = position;
    this.context = context;
    this.versionId = versionId;
  }
  satisfies(other) {
    return this.position.equals(other.position) && equals$1(this.context.selectedSuggestionInfo, other.context.selectedSuggestionInfo, (v1, v2) => v1.equals(v2)) && (other.context.triggerKind === InlineCompletionTriggerKind$1.Automatic || this.context.triggerKind === InlineCompletionTriggerKind$1.Explicit) && this.versionId === other.versionId;
  }
}
function equals$1(v1, v2, equals3) {
  if (!v1 || !v2) {
    return v1 === v2;
  }
  return equals3(v1, v2);
}
class UpdateOperation {
  constructor(request, cancellationTokenSource, promise) {
    this.request = request;
    this.cancellationTokenSource = cancellationTokenSource;
    this.promise = promise;
  }
  dispose() {
    this.cancellationTokenSource.cancel();
  }
}
class UpToDateInlineCompletions {
  get inlineCompletions() {
    return this._inlineCompletions;
  }
  constructor(inlineCompletionProviderResult, request, textModel, versionId) {
    this.inlineCompletionProviderResult = inlineCompletionProviderResult;
    this.request = request;
    this.textModel = textModel;
    this.versionId = versionId;
    this._refCount = 1;
    this._prependedInlineCompletionItems = [];
    this._rangeVersionIdValue = 0;
    this._rangeVersionId = derived("ranges", (reader) => {
      this.versionId.read(reader);
      let changed = false;
      for (const i of this._inlineCompletions) {
        changed = changed || i._updateRange(this.textModel);
      }
      if (changed) {
        this._rangeVersionIdValue++;
      }
      return this._rangeVersionIdValue;
    });
    const ids = textModel.deltaDecorations([], inlineCompletionProviderResult.completions.map((i) => ({
      range: i.range,
      options: {
        description: "inline-completion-tracking-range"
      }
    })));
    this._inlineCompletions = inlineCompletionProviderResult.completions.map((i, index) => new InlineCompletionWithUpdatedRange(i, ids[index], this._rangeVersionId));
  }
  clone() {
    this._refCount++;
    return this;
  }
  dispose() {
    this._refCount--;
    if (this._refCount === 0) {
      setTimeout(() => {
        if (!this.textModel.isDisposed()) {
          this.textModel.deltaDecorations(this._inlineCompletions.map((i) => i.decorationId), []);
        }
      }, 0);
      this.inlineCompletionProviderResult.dispose();
      for (const i of this._prependedInlineCompletionItems) {
        i.source.removeRef();
      }
    }
  }
  prepend(inlineCompletion, range2, addRefToSource) {
    if (addRefToSource) {
      inlineCompletion.source.addRef();
    }
    const id3 = this.textModel.deltaDecorations([], [{
      range: range2,
      options: {
        description: "inline-completion-tracking-range"
      }
    }])[0];
    this._inlineCompletions.unshift(new InlineCompletionWithUpdatedRange(inlineCompletion, id3, this._rangeVersionId, range2));
    this._prependedInlineCompletionItems.push(inlineCompletion);
  }
}
class InlineCompletionWithUpdatedRange {
  get forwardStable() {
    var _a2;
    return (_a2 = this.inlineCompletion.source.inlineCompletions.enableForwardStability) !== null && _a2 !== void 0 ? _a2 : false;
  }
  constructor(inlineCompletion, decorationId, rangeVersion, initialRange) {
    this.inlineCompletion = inlineCompletion;
    this.decorationId = decorationId;
    this.rangeVersion = rangeVersion;
    this.semanticId = JSON.stringify([
      this.inlineCompletion.filterText,
      this.inlineCompletion.insertText,
      this.inlineCompletion.range.getStartPosition().toString()
    ]);
    this._isValid = true;
    this._updatedRange = initialRange !== null && initialRange !== void 0 ? initialRange : inlineCompletion.range;
  }
  toInlineCompletion(reader) {
    return this.inlineCompletion.withRange(this._getUpdatedRange(reader));
  }
  toSingleTextEdit(reader) {
    return new SingleTextEdit(this._getUpdatedRange(reader), this.inlineCompletion.insertText);
  }
  isVisible(model, cursorPosition, reader) {
    const minimizedReplacement = this._toFilterTextReplacement(reader).removeCommonPrefix(model);
    if (!this._isValid || !this.inlineCompletion.range.getStartPosition().equals(this._getUpdatedRange(reader).getStartPosition()) || cursorPosition.lineNumber !== minimizedReplacement.range.startLineNumber) {
      return false;
    }
    const originalValue = model.getValueInRange(
      minimizedReplacement.range,
      1
      /* EndOfLinePreference.LF */
    ).toLowerCase();
    const filterText = minimizedReplacement.text.toLowerCase();
    const cursorPosIndex = Math.max(0, cursorPosition.column - minimizedReplacement.range.startColumn);
    let filterTextBefore = filterText.substring(0, cursorPosIndex);
    let filterTextAfter = filterText.substring(cursorPosIndex);
    let originalValueBefore = originalValue.substring(0, cursorPosIndex);
    let originalValueAfter = originalValue.substring(cursorPosIndex);
    const originalValueIndent = model.getLineIndentColumn(minimizedReplacement.range.startLineNumber);
    if (minimizedReplacement.range.startColumn <= originalValueIndent) {
      originalValueBefore = originalValueBefore.trimStart();
      if (originalValueBefore.length === 0) {
        originalValueAfter = originalValueAfter.trimStart();
      }
      filterTextBefore = filterTextBefore.trimStart();
      if (filterTextBefore.length === 0) {
        filterTextAfter = filterTextAfter.trimStart();
      }
    }
    return filterTextBefore.startsWith(originalValueBefore) && !!matchesSubString(originalValueAfter, filterTextAfter);
  }
  canBeReused(model, position) {
    const result2 = this._isValid && this._getUpdatedRange(void 0).containsPosition(position) && this.isVisible(model, position, void 0) && !this._isSmallerThanOriginal(void 0);
    return result2;
  }
  _toFilterTextReplacement(reader) {
    return new SingleTextEdit(this._getUpdatedRange(reader), this.inlineCompletion.filterText);
  }
  _isSmallerThanOriginal(reader) {
    return length(this._getUpdatedRange(reader)).isBefore(length(this.inlineCompletion.range));
  }
  _getUpdatedRange(reader) {
    this.rangeVersion.read(reader);
    return this._updatedRange;
  }
  _updateRange(textModel) {
    const range2 = textModel.getDecorationRange(this.decorationId);
    if (!range2) {
      this._isValid = false;
      return true;
    }
    if (!this._updatedRange.equalsRange(range2)) {
      this._updatedRange = range2;
      return true;
    }
    return false;
  }
}
function length(range2) {
  if (range2.startLineNumber === range2.endLineNumber) {
    return new Position$2(1, 1 + range2.endColumn - range2.startColumn);
  } else {
    return new Position$2(1 + range2.endLineNumber - range2.startLineNumber, range2.endColumn);
  }
}
var __awaiter$I = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
const Context$2 = {
  Visible: historyNavigationVisible,
  HasFocusedSuggestion: new RawContextKey("suggestWidgetHasFocusedSuggestion", false, localize("suggestWidgetHasSelection", "Whether any suggestion is focused")),
  DetailsVisible: new RawContextKey("suggestWidgetDetailsVisible", false, localize("suggestWidgetDetailsVisible", "Whether suggestion details are visible")),
  MultipleSuggestions: new RawContextKey("suggestWidgetMultipleSuggestions", false, localize("suggestWidgetMultipleSuggestions", "Whether there are multiple suggestions to pick from")),
  MakesTextEdit: new RawContextKey("suggestionMakesTextEdit", true, localize("suggestionMakesTextEdit", "Whether inserting the current suggestion yields in a change or has everything already been typed")),
  AcceptSuggestionsOnEnter: new RawContextKey("acceptSuggestionOnEnter", true, localize("acceptSuggestionOnEnter", "Whether suggestions are inserted when pressing Enter")),
  HasInsertAndReplaceRange: new RawContextKey("suggestionHasInsertAndReplaceRange", false, localize("suggestionHasInsertAndReplaceRange", "Whether the current suggestion has insert and replace behaviour")),
  InsertMode: new RawContextKey("suggestionInsertMode", void 0, { type: "string", description: localize("suggestionInsertMode", "Whether the default behaviour is to insert or replace") }),
  CanResolve: new RawContextKey("suggestionCanResolve", false, localize("suggestionCanResolve", "Whether the current suggestion supports to resolve further details"))
};
const suggestWidgetStatusbarMenu = new MenuId("suggestWidgetStatusBar");
class CompletionItem {
  constructor(position, completion, container2, provider) {
    var _a2;
    this.position = position;
    this.completion = completion;
    this.container = container2;
    this.provider = provider;
    this.isInvalid = false;
    this.score = FuzzyScore.Default;
    this.distance = 0;
    this.textLabel = typeof completion.label === "string" ? completion.label : (_a2 = completion.label) === null || _a2 === void 0 ? void 0 : _a2.label;
    this.labelLow = this.textLabel.toLowerCase();
    this.isInvalid = !this.textLabel;
    this.sortTextLow = completion.sortText && completion.sortText.toLowerCase();
    this.filterTextLow = completion.filterText && completion.filterText.toLowerCase();
    this.extensionId = completion.extensionId;
    if (Range$2.isIRange(completion.range)) {
      this.editStart = new Position$2(completion.range.startLineNumber, completion.range.startColumn);
      this.editInsertEnd = new Position$2(completion.range.endLineNumber, completion.range.endColumn);
      this.editReplaceEnd = new Position$2(completion.range.endLineNumber, completion.range.endColumn);
      this.isInvalid = this.isInvalid || Range$2.spansMultipleLines(completion.range) || completion.range.startLineNumber !== position.lineNumber;
    } else {
      this.editStart = new Position$2(completion.range.insert.startLineNumber, completion.range.insert.startColumn);
      this.editInsertEnd = new Position$2(completion.range.insert.endLineNumber, completion.range.insert.endColumn);
      this.editReplaceEnd = new Position$2(completion.range.replace.endLineNumber, completion.range.replace.endColumn);
      this.isInvalid = this.isInvalid || Range$2.spansMultipleLines(completion.range.insert) || Range$2.spansMultipleLines(completion.range.replace) || completion.range.insert.startLineNumber !== position.lineNumber || completion.range.replace.startLineNumber !== position.lineNumber || completion.range.insert.startColumn !== completion.range.replace.startColumn;
    }
    if (typeof provider.resolveCompletionItem !== "function") {
      this._resolveCache = Promise.resolve();
      this._resolveDuration = 0;
    }
  }
  // ---- resolving
  get isResolved() {
    return this._resolveDuration !== void 0;
  }
  get resolveDuration() {
    return this._resolveDuration !== void 0 ? this._resolveDuration : -1;
  }
  resolve(token) {
    return __awaiter$I(this, void 0, void 0, function* () {
      if (!this._resolveCache) {
        const sub = token.onCancellationRequested(() => {
          this._resolveCache = void 0;
          this._resolveDuration = void 0;
        });
        const sw = new StopWatch(true);
        this._resolveCache = Promise.resolve(this.provider.resolveCompletionItem(this.completion, token)).then((value) => {
          Object.assign(this.completion, value);
          this._resolveDuration = sw.elapsed();
          sub.dispose();
        }, (err) => {
          if (isCancellationError(err)) {
            this._resolveCache = void 0;
            this._resolveDuration = void 0;
          }
        });
      }
      return this._resolveCache;
    });
  }
}
class CompletionOptions {
  constructor(snippetSortOrder = 2, kindFilter = /* @__PURE__ */ new Set(), providerFilter = /* @__PURE__ */ new Set(), providerItemsToReuse = /* @__PURE__ */ new Map(), showDeprecated = true) {
    this.snippetSortOrder = snippetSortOrder;
    this.kindFilter = kindFilter;
    this.providerFilter = providerFilter;
    this.providerItemsToReuse = providerItemsToReuse;
    this.showDeprecated = showDeprecated;
  }
}
CompletionOptions.default = new CompletionOptions();
let _snippetSuggestSupport;
function getSnippetSuggestSupport() {
  return _snippetSuggestSupport;
}
class CompletionItemModel {
  constructor(items, needsClipboard, durations, disposable) {
    this.items = items;
    this.needsClipboard = needsClipboard;
    this.durations = durations;
    this.disposable = disposable;
  }
}
function provideSuggestionItems(registry, model, position, options = CompletionOptions.default, context = {
  triggerKind: 0
  /* languages.CompletionTriggerKind.Invoke */
}, token = CancellationToken.None) {
  return __awaiter$I(this, void 0, void 0, function* () {
    const sw = new StopWatch();
    position = position.clone();
    const word2 = model.getWordAtPosition(position);
    const defaultReplaceRange = word2 ? new Range$2(position.lineNumber, word2.startColumn, position.lineNumber, word2.endColumn) : Range$2.fromPositions(position);
    const defaultRange = { replace: defaultReplaceRange, insert: defaultReplaceRange.setEndPosition(position.lineNumber, position.column) };
    const result2 = [];
    const disposables = new DisposableStore();
    const durations = [];
    let needsClipboard = false;
    const onCompletionList = (provider, container2, sw2) => {
      var _a2, _b2, _c2;
      let didAddResult = false;
      if (!container2) {
        return didAddResult;
      }
      for (const suggestion of container2.suggestions) {
        if (!options.kindFilter.has(suggestion.kind)) {
          if (!options.showDeprecated && ((_a2 = suggestion === null || suggestion === void 0 ? void 0 : suggestion.tags) === null || _a2 === void 0 ? void 0 : _a2.includes(
            1
            /* languages.CompletionItemTag.Deprecated */
          ))) {
            continue;
          }
          if (!suggestion.range) {
            suggestion.range = defaultRange;
          }
          if (!suggestion.sortText) {
            suggestion.sortText = typeof suggestion.label === "string" ? suggestion.label : suggestion.label.label;
          }
          if (!needsClipboard && suggestion.insertTextRules && suggestion.insertTextRules & 4) {
            needsClipboard = SnippetParser.guessNeedsClipboard(suggestion.insertText);
          }
          result2.push(new CompletionItem(position, suggestion, container2, provider));
          didAddResult = true;
        }
      }
      if (isDisposable(container2)) {
        disposables.add(container2);
      }
      durations.push({
        providerName: (_b2 = provider._debugDisplayName) !== null && _b2 !== void 0 ? _b2 : "unknown_provider",
        elapsedProvider: (_c2 = container2.duration) !== null && _c2 !== void 0 ? _c2 : -1,
        elapsedOverall: sw2.elapsed()
      });
      return didAddResult;
    };
    const snippetCompletions = (() => __awaiter$I(this, void 0, void 0, function* () {
      {
        return;
      }
    }))();
    for (const providerGroup of registry.orderedGroups(model)) {
      let didAddResult = false;
      yield Promise.all(providerGroup.map((provider) => __awaiter$I(this, void 0, void 0, function* () {
        if (options.providerItemsToReuse.has(provider)) {
          const items = options.providerItemsToReuse.get(provider);
          items.forEach((item) => result2.push(item));
          didAddResult = didAddResult || items.length > 0;
          return;
        }
        if (options.providerFilter.size > 0 && !options.providerFilter.has(provider)) {
          return;
        }
        try {
          const sw2 = new StopWatch();
          const list2 = yield provider.provideCompletionItems(model, position, context, token);
          didAddResult = onCompletionList(provider, list2, sw2) || didAddResult;
        } catch (err) {
          onUnexpectedExternalError(err);
        }
      })));
      if (didAddResult || token.isCancellationRequested) {
        break;
      }
    }
    yield snippetCompletions;
    if (token.isCancellationRequested) {
      disposables.dispose();
      return Promise.reject(new CancellationError());
    }
    return new CompletionItemModel(result2.sort(getSuggestionComparator(options.snippetSortOrder)), needsClipboard, { entries: durations, elapsed: sw.elapsed() }, disposables);
  });
}
function defaultComparator(a, b) {
  if (a.sortTextLow && b.sortTextLow) {
    if (a.sortTextLow < b.sortTextLow) {
      return -1;
    } else if (a.sortTextLow > b.sortTextLow) {
      return 1;
    }
  }
  if (a.textLabel < b.textLabel) {
    return -1;
  } else if (a.textLabel > b.textLabel) {
    return 1;
  }
  return a.completion.kind - b.completion.kind;
}
function snippetUpComparator(a, b) {
  if (a.completion.kind !== b.completion.kind) {
    if (a.completion.kind === 27) {
      return -1;
    } else if (b.completion.kind === 27) {
      return 1;
    }
  }
  return defaultComparator(a, b);
}
function snippetDownComparator(a, b) {
  if (a.completion.kind !== b.completion.kind) {
    if (a.completion.kind === 27) {
      return 1;
    } else if (b.completion.kind === 27) {
      return -1;
    }
  }
  return defaultComparator(a, b);
}
const _snippetComparators = /* @__PURE__ */ new Map();
_snippetComparators.set(0, snippetUpComparator);
_snippetComparators.set(2, snippetDownComparator);
_snippetComparators.set(1, defaultComparator);
function getSuggestionComparator(snippetConfig) {
  return _snippetComparators.get(snippetConfig);
}
CommandsRegistry.registerCommand("_executeCompletionItemProvider", (accessor, ...args) => __awaiter$I(void 0, void 0, void 0, function* () {
  const [uri, position, triggerCharacter, maxItemsToResolve] = args;
  assertType(URI.isUri(uri));
  assertType(Position$2.isIPosition(position));
  assertType(typeof triggerCharacter === "string" || !triggerCharacter);
  assertType(typeof maxItemsToResolve === "number" || !maxItemsToResolve);
  const { completionProvider } = accessor.get(ILanguageFeaturesService);
  const ref2 = yield accessor.get(ITextModelService).createModelReference(uri);
  try {
    const result2 = {
      incomplete: false,
      suggestions: []
    };
    const resolving = [];
    const actualPosition = ref2.object.textEditorModel.validatePosition(position);
    const completions = yield provideSuggestionItems(completionProvider, ref2.object.textEditorModel, actualPosition, void 0, {
      triggerCharacter: triggerCharacter !== null && triggerCharacter !== void 0 ? triggerCharacter : void 0,
      triggerKind: triggerCharacter ? 1 : 0
      /* languages.CompletionTriggerKind.Invoke */
    });
    for (const item of completions.items) {
      if (resolving.length < (maxItemsToResolve !== null && maxItemsToResolve !== void 0 ? maxItemsToResolve : 0)) {
        resolving.push(item.resolve(CancellationToken.None));
      }
      result2.incomplete = result2.incomplete || item.container.incomplete;
      result2.suggestions.push(item.completion);
    }
    try {
      yield Promise.all(resolving);
      return result2;
    } finally {
      setTimeout(() => completions.disposable.dispose(), 100);
    }
  } finally {
    ref2.dispose();
  }
}));
function showSimpleSuggestions(editor2, provider) {
  var _a2;
  (_a2 = editor2.getContribution("editor.contrib.suggestController")) === null || _a2 === void 0 ? void 0 : _a2.triggerSuggest((/* @__PURE__ */ new Set()).add(provider), void 0, true);
}
class QuickSuggestionsOptions {
  static isAllOff(config2) {
    return config2.other === "off" && config2.comments === "off" && config2.strings === "off";
  }
  static isAllOn(config2) {
    return config2.other === "on" && config2.comments === "on" && config2.strings === "on";
  }
  static valueFor(config2, tokenType) {
    switch (tokenType) {
      case 1:
        return config2.comments;
      case 2:
        return config2.strings;
      default:
        return config2.other;
    }
  }
}
const snippetSession = "";
function normalizeDriveLetter(path2, isWindowsOS = isWindows) {
  if (hasDriveLetter(path2, isWindowsOS)) {
    return path2.charAt(0).toUpperCase() + path2.slice(1);
  }
  return path2;
}
var __decorate$1a = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$18 = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
class CompositeSnippetVariableResolver {
  constructor(_delegates) {
    this._delegates = _delegates;
  }
  resolve(variable) {
    for (const delegate of this._delegates) {
      const value = delegate.resolve(variable);
      if (value !== void 0) {
        return value;
      }
    }
    return void 0;
  }
}
class SelectionBasedVariableResolver {
  constructor(_model, _selection, _selectionIdx, _overtypingCapturer) {
    this._model = _model;
    this._selection = _selection;
    this._selectionIdx = _selectionIdx;
    this._overtypingCapturer = _overtypingCapturer;
  }
  resolve(variable) {
    const { name } = variable;
    if (name === "SELECTION" || name === "TM_SELECTED_TEXT") {
      let value = this._model.getValueInRange(this._selection) || void 0;
      let isMultiline = this._selection.startLineNumber !== this._selection.endLineNumber;
      if (!value && this._overtypingCapturer) {
        const info = this._overtypingCapturer.getLastOvertypedInfo(this._selectionIdx);
        if (info) {
          value = info.value;
          isMultiline = info.multiline;
        }
      }
      if (value && isMultiline && variable.snippet) {
        const line = this._model.getLineContent(this._selection.startLineNumber);
        const lineLeadingWhitespace = getLeadingWhitespace(line, 0, this._selection.startColumn - 1);
        let varLeadingWhitespace = lineLeadingWhitespace;
        variable.snippet.walk((marker) => {
          if (marker === variable) {
            return false;
          }
          if (marker instanceof Text) {
            varLeadingWhitespace = getLeadingWhitespace(splitLines(marker.value).pop());
          }
          return true;
        });
        const whitespaceCommonLength = commonPrefixLength(varLeadingWhitespace, lineLeadingWhitespace);
        value = value.replace(/(\r\n|\r|\n)(.*)/g, (m, newline2, rest) => `${newline2}${varLeadingWhitespace.substr(whitespaceCommonLength)}${rest}`);
      }
      return value;
    } else if (name === "TM_CURRENT_LINE") {
      return this._model.getLineContent(this._selection.positionLineNumber);
    } else if (name === "TM_CURRENT_WORD") {
      const info = this._model.getWordAtPosition({
        lineNumber: this._selection.positionLineNumber,
        column: this._selection.positionColumn
      });
      return info && info.word || void 0;
    } else if (name === "TM_LINE_INDEX") {
      return String(this._selection.positionLineNumber - 1);
    } else if (name === "TM_LINE_NUMBER") {
      return String(this._selection.positionLineNumber);
    } else if (name === "CURSOR_INDEX") {
      return String(this._selectionIdx);
    } else if (name === "CURSOR_NUMBER") {
      return String(this._selectionIdx + 1);
    }
    return void 0;
  }
}
class ModelBasedVariableResolver {
  constructor(_labelService, _model) {
    this._labelService = _labelService;
    this._model = _model;
  }
  resolve(variable) {
    const { name } = variable;
    if (name === "TM_FILENAME") {
      return basename$2(this._model.uri.fsPath);
    } else if (name === "TM_FILENAME_BASE") {
      const name2 = basename$2(this._model.uri.fsPath);
      const idx = name2.lastIndexOf(".");
      if (idx <= 0) {
        return name2;
      } else {
        return name2.slice(0, idx);
      }
    } else if (name === "TM_DIRECTORY") {
      if (dirname$4(this._model.uri.fsPath) === ".") {
        return "";
      }
      return this._labelService.getUriLabel(dirname$3(this._model.uri));
    } else if (name === "TM_FILEPATH") {
      return this._labelService.getUriLabel(this._model.uri);
    } else if (name === "RELATIVE_FILEPATH") {
      return this._labelService.getUriLabel(this._model.uri, { relative: true, noPrefix: true });
    }
    return void 0;
  }
}
class ClipboardBasedVariableResolver {
  constructor(_readClipboardText, _selectionIdx, _selectionCount, _spread) {
    this._readClipboardText = _readClipboardText;
    this._selectionIdx = _selectionIdx;
    this._selectionCount = _selectionCount;
    this._spread = _spread;
  }
  resolve(variable) {
    if (variable.name !== "CLIPBOARD") {
      return void 0;
    }
    const clipboardText = this._readClipboardText();
    if (!clipboardText) {
      return void 0;
    }
    if (this._spread) {
      const lines = clipboardText.split(/\r\n|\n|\r/).filter((s) => !isFalsyOrWhitespace(s));
      if (lines.length === this._selectionCount) {
        return lines[this._selectionIdx];
      }
    }
    return clipboardText;
  }
}
let CommentBasedVariableResolver = class CommentBasedVariableResolver2 {
  constructor(_model, _selection, _languageConfigurationService) {
    this._model = _model;
    this._selection = _selection;
    this._languageConfigurationService = _languageConfigurationService;
  }
  resolve(variable) {
    const { name } = variable;
    const langId = this._model.getLanguageIdAtPosition(this._selection.selectionStartLineNumber, this._selection.selectionStartColumn);
    const config2 = this._languageConfigurationService.getLanguageConfiguration(langId).comments;
    if (!config2) {
      return void 0;
    }
    if (name === "LINE_COMMENT") {
      return config2.lineCommentToken || void 0;
    } else if (name === "BLOCK_COMMENT_START") {
      return config2.blockCommentStartToken || void 0;
    } else if (name === "BLOCK_COMMENT_END") {
      return config2.blockCommentEndToken || void 0;
    }
    return void 0;
  }
};
CommentBasedVariableResolver = __decorate$1a([
  __param$18(2, ILanguageConfigurationService)
], CommentBasedVariableResolver);
class TimeBasedVariableResolver {
  constructor() {
    this._date = /* @__PURE__ */ new Date();
  }
  resolve(variable) {
    const { name } = variable;
    if (name === "CURRENT_YEAR") {
      return String(this._date.getFullYear());
    } else if (name === "CURRENT_YEAR_SHORT") {
      return String(this._date.getFullYear()).slice(-2);
    } else if (name === "CURRENT_MONTH") {
      return String(this._date.getMonth().valueOf() + 1).padStart(2, "0");
    } else if (name === "CURRENT_DATE") {
      return String(this._date.getDate().valueOf()).padStart(2, "0");
    } else if (name === "CURRENT_HOUR") {
      return String(this._date.getHours().valueOf()).padStart(2, "0");
    } else if (name === "CURRENT_MINUTE") {
      return String(this._date.getMinutes().valueOf()).padStart(2, "0");
    } else if (name === "CURRENT_SECOND") {
      return String(this._date.getSeconds().valueOf()).padStart(2, "0");
    } else if (name === "CURRENT_DAY_NAME") {
      return TimeBasedVariableResolver.dayNames[this._date.getDay()];
    } else if (name === "CURRENT_DAY_NAME_SHORT") {
      return TimeBasedVariableResolver.dayNamesShort[this._date.getDay()];
    } else if (name === "CURRENT_MONTH_NAME") {
      return TimeBasedVariableResolver.monthNames[this._date.getMonth()];
    } else if (name === "CURRENT_MONTH_NAME_SHORT") {
      return TimeBasedVariableResolver.monthNamesShort[this._date.getMonth()];
    } else if (name === "CURRENT_SECONDS_UNIX") {
      return String(Math.floor(this._date.getTime() / 1e3));
    } else if (name === "CURRENT_TIMEZONE_OFFSET") {
      const rawTimeOffset = this._date.getTimezoneOffset();
      const sign = rawTimeOffset > 0 ? "-" : "+";
      const hours = Math.trunc(Math.abs(rawTimeOffset / 60));
      const hoursString = hours < 10 ? "0" + hours : hours;
      const minutes = Math.abs(rawTimeOffset) - hours * 60;
      const minutesString = minutes < 10 ? "0" + minutes : minutes;
      return sign + hoursString + ":" + minutesString;
    }
    return void 0;
  }
}
TimeBasedVariableResolver.dayNames = [localize("Sunday", "Sunday"), localize("Monday", "Monday"), localize("Tuesday", "Tuesday"), localize("Wednesday", "Wednesday"), localize("Thursday", "Thursday"), localize("Friday", "Friday"), localize("Saturday", "Saturday")];
TimeBasedVariableResolver.dayNamesShort = [localize("SundayShort", "Sun"), localize("MondayShort", "Mon"), localize("TuesdayShort", "Tue"), localize("WednesdayShort", "Wed"), localize("ThursdayShort", "Thu"), localize("FridayShort", "Fri"), localize("SaturdayShort", "Sat")];
TimeBasedVariableResolver.monthNames = [localize("January", "January"), localize("February", "February"), localize("March", "March"), localize("April", "April"), localize("May", "May"), localize("June", "June"), localize("July", "July"), localize("August", "August"), localize("September", "September"), localize("October", "October"), localize("November", "November"), localize("December", "December")];
TimeBasedVariableResolver.monthNamesShort = [localize("JanuaryShort", "Jan"), localize("FebruaryShort", "Feb"), localize("MarchShort", "Mar"), localize("AprilShort", "Apr"), localize("MayShort", "May"), localize("JuneShort", "Jun"), localize("JulyShort", "Jul"), localize("AugustShort", "Aug"), localize("SeptemberShort", "Sep"), localize("OctoberShort", "Oct"), localize("NovemberShort", "Nov"), localize("DecemberShort", "Dec")];
class WorkspaceBasedVariableResolver {
  constructor(_workspaceService) {
    this._workspaceService = _workspaceService;
  }
  resolve(variable) {
    if (!this._workspaceService) {
      return void 0;
    }
    const workspaceIdentifier = toWorkspaceIdentifier(this._workspaceService.getWorkspace());
    if (isEmptyWorkspaceIdentifier(workspaceIdentifier)) {
      return void 0;
    }
    if (variable.name === "WORKSPACE_NAME") {
      return this._resolveWorkspaceName(workspaceIdentifier);
    } else if (variable.name === "WORKSPACE_FOLDER") {
      return this._resoveWorkspacePath(workspaceIdentifier);
    }
    return void 0;
  }
  _resolveWorkspaceName(workspaceIdentifier) {
    if (isSingleFolderWorkspaceIdentifier(workspaceIdentifier)) {
      return basename$2(workspaceIdentifier.uri.path);
    }
    let filename = basename$2(workspaceIdentifier.configPath.path);
    if (filename.endsWith(WORKSPACE_EXTENSION)) {
      filename = filename.substr(0, filename.length - WORKSPACE_EXTENSION.length - 1);
    }
    return filename;
  }
  _resoveWorkspacePath(workspaceIdentifier) {
    if (isSingleFolderWorkspaceIdentifier(workspaceIdentifier)) {
      return normalizeDriveLetter(workspaceIdentifier.uri.fsPath);
    }
    const filename = basename$2(workspaceIdentifier.configPath.path);
    let folderpath = workspaceIdentifier.configPath.fsPath;
    if (folderpath.endsWith(filename)) {
      folderpath = folderpath.substr(0, folderpath.length - filename.length - 1);
    }
    return folderpath ? normalizeDriveLetter(folderpath) : "/";
  }
}
class RandomBasedVariableResolver {
  resolve(variable) {
    const { name } = variable;
    if (name === "RANDOM") {
      return Math.random().toString().slice(-6);
    } else if (name === "RANDOM_HEX") {
      return Math.random().toString(16).slice(-6);
    } else if (name === "UUID") {
      return generateUuid();
    }
    return void 0;
  }
}
var __decorate$19 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$17 = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
class OneSnippet {
  constructor(_editor, _snippet, _snippetLineLeadingWhitespace) {
    this._editor = _editor;
    this._snippet = _snippet;
    this._snippetLineLeadingWhitespace = _snippetLineLeadingWhitespace;
    this._offset = -1;
    this._nestingLevel = 1;
    this._placeholderGroups = groupBy(_snippet.placeholders, Placeholder.compareByIndex);
    this._placeholderGroupsIdx = -1;
  }
  initialize(textChange) {
    this._offset = textChange.newPosition;
  }
  dispose() {
    if (this._placeholderDecorations) {
      this._editor.removeDecorations([...this._placeholderDecorations.values()]);
    }
    this._placeholderGroups.length = 0;
  }
  _initDecorations() {
    if (this._offset === -1) {
      throw new Error(`Snippet not initialized!`);
    }
    if (this._placeholderDecorations) {
      return;
    }
    this._placeholderDecorations = /* @__PURE__ */ new Map();
    const model = this._editor.getModel();
    this._editor.changeDecorations((accessor) => {
      for (const placeholder of this._snippet.placeholders) {
        const placeholderOffset = this._snippet.offset(placeholder);
        const placeholderLen = this._snippet.fullLen(placeholder);
        const range2 = Range$2.fromPositions(model.getPositionAt(this._offset + placeholderOffset), model.getPositionAt(this._offset + placeholderOffset + placeholderLen));
        const options = placeholder.isFinalTabstop ? OneSnippet._decor.inactiveFinal : OneSnippet._decor.inactive;
        const handle = accessor.addDecoration(range2, options);
        this._placeholderDecorations.set(placeholder, handle);
      }
    });
  }
  move(fwd) {
    if (!this._editor.hasModel()) {
      return [];
    }
    this._initDecorations();
    if (this._placeholderGroupsIdx >= 0) {
      const operations = [];
      for (const placeholder of this._placeholderGroups[this._placeholderGroupsIdx]) {
        if (placeholder.transform) {
          const id3 = this._placeholderDecorations.get(placeholder);
          const range2 = this._editor.getModel().getDecorationRange(id3);
          const currentValue = this._editor.getModel().getValueInRange(range2);
          const transformedValueLines = placeholder.transform.resolve(currentValue).split(/\r\n|\r|\n/);
          for (let i = 1; i < transformedValueLines.length; i++) {
            transformedValueLines[i] = this._editor.getModel().normalizeIndentation(this._snippetLineLeadingWhitespace + transformedValueLines[i]);
          }
          operations.push(EditOperation.replace(range2, transformedValueLines.join(this._editor.getModel().getEOL())));
        }
      }
      if (operations.length > 0) {
        this._editor.executeEdits("snippet.placeholderTransform", operations);
      }
    }
    let couldSkipThisPlaceholder = false;
    if (fwd === true && this._placeholderGroupsIdx < this._placeholderGroups.length - 1) {
      this._placeholderGroupsIdx += 1;
      couldSkipThisPlaceholder = true;
    } else if (fwd === false && this._placeholderGroupsIdx > 0) {
      this._placeholderGroupsIdx -= 1;
      couldSkipThisPlaceholder = true;
    } else
      ;
    const newSelections = this._editor.getModel().changeDecorations((accessor) => {
      const activePlaceholders = /* @__PURE__ */ new Set();
      const selections2 = [];
      for (const placeholder of this._placeholderGroups[this._placeholderGroupsIdx]) {
        const id3 = this._placeholderDecorations.get(placeholder);
        const range2 = this._editor.getModel().getDecorationRange(id3);
        selections2.push(new Selection$1(range2.startLineNumber, range2.startColumn, range2.endLineNumber, range2.endColumn));
        couldSkipThisPlaceholder = couldSkipThisPlaceholder && this._hasPlaceholderBeenCollapsed(placeholder);
        accessor.changeDecorationOptions(id3, placeholder.isFinalTabstop ? OneSnippet._decor.activeFinal : OneSnippet._decor.active);
        activePlaceholders.add(placeholder);
        for (const enclosingPlaceholder of this._snippet.enclosingPlaceholders(placeholder)) {
          const id4 = this._placeholderDecorations.get(enclosingPlaceholder);
          accessor.changeDecorationOptions(id4, enclosingPlaceholder.isFinalTabstop ? OneSnippet._decor.activeFinal : OneSnippet._decor.active);
          activePlaceholders.add(enclosingPlaceholder);
        }
      }
      for (const [placeholder, id3] of this._placeholderDecorations) {
        if (!activePlaceholders.has(placeholder)) {
          accessor.changeDecorationOptions(id3, placeholder.isFinalTabstop ? OneSnippet._decor.inactiveFinal : OneSnippet._decor.inactive);
        }
      }
      return selections2;
    });
    return !couldSkipThisPlaceholder ? newSelections !== null && newSelections !== void 0 ? newSelections : [] : this.move(fwd);
  }
  _hasPlaceholderBeenCollapsed(placeholder) {
    let marker = placeholder;
    while (marker) {
      if (marker instanceof Placeholder) {
        const id3 = this._placeholderDecorations.get(marker);
        const range2 = this._editor.getModel().getDecorationRange(id3);
        if (range2.isEmpty() && marker.toString().length > 0) {
          return true;
        }
      }
      marker = marker.parent;
    }
    return false;
  }
  get isAtFirstPlaceholder() {
    return this._placeholderGroupsIdx <= 0 || this._placeholderGroups.length === 0;
  }
  get isAtLastPlaceholder() {
    return this._placeholderGroupsIdx === this._placeholderGroups.length - 1;
  }
  get hasPlaceholder() {
    return this._snippet.placeholders.length > 0;
  }
  /**
   * A snippet is trivial when it has no placeholder or only a final placeholder at
   * its very end
   */
  get isTrivialSnippet() {
    if (this._snippet.placeholders.length === 0) {
      return true;
    }
    if (this._snippet.placeholders.length === 1) {
      const [placeholder] = this._snippet.placeholders;
      if (placeholder.isFinalTabstop) {
        if (this._snippet.rightMostDescendant === placeholder) {
          return true;
        }
      }
    }
    return false;
  }
  computePossibleSelections() {
    const result2 = /* @__PURE__ */ new Map();
    for (const placeholdersWithEqualIndex of this._placeholderGroups) {
      let ranges;
      for (const placeholder of placeholdersWithEqualIndex) {
        if (placeholder.isFinalTabstop) {
          break;
        }
        if (!ranges) {
          ranges = [];
          result2.set(placeholder.index, ranges);
        }
        const id3 = this._placeholderDecorations.get(placeholder);
        const range2 = this._editor.getModel().getDecorationRange(id3);
        if (!range2) {
          result2.delete(placeholder.index);
          break;
        }
        ranges.push(range2);
      }
    }
    return result2;
  }
  get activeChoice() {
    if (!this._placeholderDecorations) {
      return void 0;
    }
    const placeholder = this._placeholderGroups[this._placeholderGroupsIdx][0];
    if (!(placeholder === null || placeholder === void 0 ? void 0 : placeholder.choice)) {
      return void 0;
    }
    const id3 = this._placeholderDecorations.get(placeholder);
    if (!id3) {
      return void 0;
    }
    const range2 = this._editor.getModel().getDecorationRange(id3);
    if (!range2) {
      return void 0;
    }
    return { range: range2, choice: placeholder.choice };
  }
  get hasChoice() {
    let result2 = false;
    this._snippet.walk((marker) => {
      result2 = marker instanceof Choice;
      return !result2;
    });
    return result2;
  }
  merge(others) {
    const model = this._editor.getModel();
    this._nestingLevel *= 10;
    this._editor.changeDecorations((accessor) => {
      for (const placeholder of this._placeholderGroups[this._placeholderGroupsIdx]) {
        const nested = others.shift();
        console.assert(nested._offset !== -1);
        console.assert(!nested._placeholderDecorations);
        const indexLastPlaceholder = nested._snippet.placeholderInfo.last.index;
        for (const nestedPlaceholder of nested._snippet.placeholderInfo.all) {
          if (nestedPlaceholder.isFinalTabstop) {
            nestedPlaceholder.index = placeholder.index + (indexLastPlaceholder + 1) / this._nestingLevel;
          } else {
            nestedPlaceholder.index = placeholder.index + nestedPlaceholder.index / this._nestingLevel;
          }
        }
        this._snippet.replace(placeholder, nested._snippet.children);
        const id3 = this._placeholderDecorations.get(placeholder);
        accessor.removeDecoration(id3);
        this._placeholderDecorations.delete(placeholder);
        for (const placeholder2 of nested._snippet.placeholders) {
          const placeholderOffset = nested._snippet.offset(placeholder2);
          const placeholderLen = nested._snippet.fullLen(placeholder2);
          const range2 = Range$2.fromPositions(model.getPositionAt(nested._offset + placeholderOffset), model.getPositionAt(nested._offset + placeholderOffset + placeholderLen));
          const handle = accessor.addDecoration(range2, OneSnippet._decor.inactive);
          this._placeholderDecorations.set(placeholder2, handle);
        }
      }
      this._placeholderGroups = groupBy(this._snippet.placeholders, Placeholder.compareByIndex);
    });
  }
}
OneSnippet._decor = {
  active: ModelDecorationOptions.register({ description: "snippet-placeholder-1", stickiness: 0, className: "snippet-placeholder" }),
  inactive: ModelDecorationOptions.register({ description: "snippet-placeholder-2", stickiness: 1, className: "snippet-placeholder" }),
  activeFinal: ModelDecorationOptions.register({ description: "snippet-placeholder-3", stickiness: 1, className: "finish-snippet-placeholder" }),
  inactiveFinal: ModelDecorationOptions.register({ description: "snippet-placeholder-4", stickiness: 1, className: "finish-snippet-placeholder" })
};
const _defaultOptions$1 = {
  overwriteBefore: 0,
  overwriteAfter: 0,
  adjustWhitespace: true,
  clipboardText: void 0,
  overtypingCapturer: void 0
};
let SnippetSession = class SnippetSession2 {
  static adjustWhitespace(model, position, adjustIndentation, snippet, filter2) {
    const line = model.getLineContent(position.lineNumber);
    const lineLeadingWhitespace = getLeadingWhitespace(line, 0, position.column - 1);
    let snippetTextString;
    snippet.walk((marker) => {
      if (!(marker instanceof Text) || marker.parent instanceof Choice) {
        return true;
      }
      if (filter2 && !filter2.has(marker)) {
        return true;
      }
      const lines = marker.value.split(/\r\n|\r|\n/);
      if (adjustIndentation) {
        const offset = snippet.offset(marker);
        if (offset === 0) {
          lines[0] = model.normalizeIndentation(lines[0]);
        } else {
          snippetTextString = snippetTextString !== null && snippetTextString !== void 0 ? snippetTextString : snippet.toString();
          const prevChar = snippetTextString.charCodeAt(offset - 1);
          if (prevChar === 10 || prevChar === 13) {
            lines[0] = model.normalizeIndentation(lineLeadingWhitespace + lines[0]);
          }
        }
        for (let i = 1; i < lines.length; i++) {
          lines[i] = model.normalizeIndentation(lineLeadingWhitespace + lines[i]);
        }
      }
      const newValue = lines.join(model.getEOL());
      if (newValue !== marker.value) {
        marker.parent.replace(marker, [new Text(newValue)]);
        snippetTextString = void 0;
      }
      return true;
    });
    return lineLeadingWhitespace;
  }
  static adjustSelection(model, selection, overwriteBefore, overwriteAfter) {
    if (overwriteBefore !== 0 || overwriteAfter !== 0) {
      const { positionLineNumber, positionColumn } = selection;
      const positionColumnBefore = positionColumn - overwriteBefore;
      const positionColumnAfter = positionColumn + overwriteAfter;
      const range2 = model.validateRange({
        startLineNumber: positionLineNumber,
        startColumn: positionColumnBefore,
        endLineNumber: positionLineNumber,
        endColumn: positionColumnAfter
      });
      selection = Selection$1.createWithDirection(range2.startLineNumber, range2.startColumn, range2.endLineNumber, range2.endColumn, selection.getDirection());
    }
    return selection;
  }
  static createEditsAndSnippetsFromSelections(editor2, template, overwriteBefore, overwriteAfter, enforceFinalTabstop, adjustWhitespace, clipboardText, overtypingCapturer, languageConfigurationService) {
    const edits = [];
    const snippets = [];
    if (!editor2.hasModel()) {
      return { edits, snippets };
    }
    const model = editor2.getModel();
    const workspaceService = editor2.invokeWithinContext((accessor) => accessor.get(IWorkspaceContextService));
    const modelBasedVariableResolver = editor2.invokeWithinContext((accessor) => new ModelBasedVariableResolver(accessor.get(ILabelService), model));
    const readClipboardText = () => clipboardText;
    const firstBeforeText = model.getValueInRange(SnippetSession2.adjustSelection(model, editor2.getSelection(), overwriteBefore, 0));
    const firstAfterText = model.getValueInRange(SnippetSession2.adjustSelection(model, editor2.getSelection(), 0, overwriteAfter));
    const firstLineFirstNonWhitespace = model.getLineFirstNonWhitespaceColumn(editor2.getSelection().positionLineNumber);
    const indexedSelections = editor2.getSelections().map((selection, idx) => ({ selection, idx })).sort((a, b) => Range$2.compareRangesUsingStarts(a.selection, b.selection));
    for (const { selection, idx } of indexedSelections) {
      let extensionBefore = SnippetSession2.adjustSelection(model, selection, overwriteBefore, 0);
      let extensionAfter = SnippetSession2.adjustSelection(model, selection, 0, overwriteAfter);
      if (firstBeforeText !== model.getValueInRange(extensionBefore)) {
        extensionBefore = selection;
      }
      if (firstAfterText !== model.getValueInRange(extensionAfter)) {
        extensionAfter = selection;
      }
      const snippetSelection = selection.setStartPosition(extensionBefore.startLineNumber, extensionBefore.startColumn).setEndPosition(extensionAfter.endLineNumber, extensionAfter.endColumn);
      const snippet = new SnippetParser().parse(template, true, enforceFinalTabstop);
      const start = snippetSelection.getStartPosition();
      const snippetLineLeadingWhitespace = SnippetSession2.adjustWhitespace(model, start, adjustWhitespace || idx > 0 && firstLineFirstNonWhitespace !== model.getLineFirstNonWhitespaceColumn(selection.positionLineNumber), snippet);
      snippet.resolveVariables(new CompositeSnippetVariableResolver([
        modelBasedVariableResolver,
        new ClipboardBasedVariableResolver(readClipboardText, idx, indexedSelections.length, editor2.getOption(
          77
          /* EditorOption.multiCursorPaste */
        ) === "spread"),
        new SelectionBasedVariableResolver(model, selection, idx, overtypingCapturer),
        new CommentBasedVariableResolver(model, selection, languageConfigurationService),
        new TimeBasedVariableResolver(),
        new WorkspaceBasedVariableResolver(workspaceService),
        new RandomBasedVariableResolver()
      ]));
      edits[idx] = EditOperation.replace(snippetSelection, snippet.toString());
      edits[idx].identifier = { major: idx, minor: 0 };
      edits[idx]._isTracked = true;
      snippets[idx] = new OneSnippet(editor2, snippet, snippetLineLeadingWhitespace);
    }
    return { edits, snippets };
  }
  static createEditsAndSnippetsFromEdits(editor2, snippetEdits, enforceFinalTabstop, adjustWhitespace, clipboardText, overtypingCapturer, languageConfigurationService) {
    if (!editor2.hasModel() || snippetEdits.length === 0) {
      return { edits: [], snippets: [] };
    }
    const edits = [];
    const model = editor2.getModel();
    const parser2 = new SnippetParser();
    const snippet = new TextmateSnippet();
    const resolver = new CompositeSnippetVariableResolver([
      editor2.invokeWithinContext((accessor) => new ModelBasedVariableResolver(accessor.get(ILabelService), model)),
      new ClipboardBasedVariableResolver(() => clipboardText, 0, editor2.getSelections().length, editor2.getOption(
        77
        /* EditorOption.multiCursorPaste */
      ) === "spread"),
      new SelectionBasedVariableResolver(model, editor2.getSelection(), 0, overtypingCapturer),
      new CommentBasedVariableResolver(model, editor2.getSelection(), languageConfigurationService),
      new TimeBasedVariableResolver(),
      new WorkspaceBasedVariableResolver(editor2.invokeWithinContext((accessor) => accessor.get(IWorkspaceContextService))),
      new RandomBasedVariableResolver()
    ]);
    snippetEdits = snippetEdits.sort((a, b) => Range$2.compareRangesUsingStarts(a.range, b.range));
    let offset = 0;
    for (let i = 0; i < snippetEdits.length; i++) {
      const { range: range2, template } = snippetEdits[i];
      if (i > 0) {
        const lastRange = snippetEdits[i - 1].range;
        const textRange = Range$2.fromPositions(lastRange.getEndPosition(), range2.getStartPosition());
        const textNode = new Text(model.getValueInRange(textRange));
        snippet.appendChild(textNode);
        offset += textNode.value.length;
      }
      const newNodes = parser2.parseFragment(template, snippet);
      SnippetSession2.adjustWhitespace(model, range2.getStartPosition(), true, snippet, new Set(newNodes));
      snippet.resolveVariables(resolver);
      const snippetText = snippet.toString();
      const snippetFragmentText = snippetText.slice(offset);
      offset = snippetText.length;
      const edit = EditOperation.replace(range2, snippetFragmentText);
      edit.identifier = { major: i, minor: 0 };
      edit._isTracked = true;
      edits.push(edit);
    }
    parser2.ensureFinalTabstop(snippet, enforceFinalTabstop, true);
    return {
      edits,
      snippets: [new OneSnippet(editor2, snippet, "")]
    };
  }
  constructor(_editor, _template, _options = _defaultOptions$1, _languageConfigurationService) {
    this._editor = _editor;
    this._template = _template;
    this._options = _options;
    this._languageConfigurationService = _languageConfigurationService;
    this._templateMerges = [];
    this._snippets = [];
  }
  dispose() {
    dispose(this._snippets);
  }
  _logInfo() {
    return `template="${this._template}", merged_templates="${this._templateMerges.join(" -> ")}"`;
  }
  insert() {
    if (!this._editor.hasModel()) {
      return;
    }
    const { edits, snippets } = typeof this._template === "string" ? SnippetSession2.createEditsAndSnippetsFromSelections(this._editor, this._template, this._options.overwriteBefore, this._options.overwriteAfter, false, this._options.adjustWhitespace, this._options.clipboardText, this._options.overtypingCapturer, this._languageConfigurationService) : SnippetSession2.createEditsAndSnippetsFromEdits(this._editor, this._template, false, this._options.adjustWhitespace, this._options.clipboardText, this._options.overtypingCapturer, this._languageConfigurationService);
    this._snippets = snippets;
    this._editor.executeEdits("snippet", edits, (_undoEdits) => {
      const undoEdits = _undoEdits.filter((edit) => !!edit.identifier);
      for (let idx = 0; idx < snippets.length; idx++) {
        snippets[idx].initialize(undoEdits[idx].textChange);
      }
      if (this._snippets[0].hasPlaceholder) {
        return this._move(true);
      } else {
        return undoEdits.map((edit) => Selection$1.fromPositions(edit.range.getEndPosition()));
      }
    });
    this._editor.revealRange(this._editor.getSelections()[0]);
  }
  merge(template, options = _defaultOptions$1) {
    if (!this._editor.hasModel()) {
      return;
    }
    this._templateMerges.push([this._snippets[0]._nestingLevel, this._snippets[0]._placeholderGroupsIdx, template]);
    const { edits, snippets } = SnippetSession2.createEditsAndSnippetsFromSelections(this._editor, template, options.overwriteBefore, options.overwriteAfter, true, options.adjustWhitespace, options.clipboardText, options.overtypingCapturer, this._languageConfigurationService);
    this._editor.executeEdits("snippet", edits, (_undoEdits) => {
      const undoEdits = _undoEdits.filter((edit) => !!edit.identifier);
      for (let idx = 0; idx < snippets.length; idx++) {
        snippets[idx].initialize(undoEdits[idx].textChange);
      }
      const isTrivialSnippet = snippets[0].isTrivialSnippet;
      if (!isTrivialSnippet) {
        for (const snippet of this._snippets) {
          snippet.merge(snippets);
        }
        console.assert(snippets.length === 0);
      }
      if (this._snippets[0].hasPlaceholder && !isTrivialSnippet) {
        return this._move(void 0);
      } else {
        return undoEdits.map((edit) => Selection$1.fromPositions(edit.range.getEndPosition()));
      }
    });
  }
  next() {
    const newSelections = this._move(true);
    this._editor.setSelections(newSelections);
    this._editor.revealPositionInCenterIfOutsideViewport(newSelections[0].getPosition());
  }
  prev() {
    const newSelections = this._move(false);
    this._editor.setSelections(newSelections);
    this._editor.revealPositionInCenterIfOutsideViewport(newSelections[0].getPosition());
  }
  _move(fwd) {
    const selections2 = [];
    for (const snippet of this._snippets) {
      const oneSelection = snippet.move(fwd);
      selections2.push(...oneSelection);
    }
    return selections2;
  }
  get isAtFirstPlaceholder() {
    return this._snippets[0].isAtFirstPlaceholder;
  }
  get isAtLastPlaceholder() {
    return this._snippets[0].isAtLastPlaceholder;
  }
  get hasPlaceholder() {
    return this._snippets[0].hasPlaceholder;
  }
  get hasChoice() {
    return this._snippets[0].hasChoice;
  }
  get activeChoice() {
    return this._snippets[0].activeChoice;
  }
  isSelectionWithinPlaceholders() {
    if (!this.hasPlaceholder) {
      return false;
    }
    const selections2 = this._editor.getSelections();
    if (selections2.length < this._snippets.length) {
      return false;
    }
    const allPossibleSelections = /* @__PURE__ */ new Map();
    for (const snippet of this._snippets) {
      const possibleSelections = snippet.computePossibleSelections();
      if (allPossibleSelections.size === 0) {
        for (const [index, ranges] of possibleSelections) {
          ranges.sort(Range$2.compareRangesUsingStarts);
          for (const selection of selections2) {
            if (ranges[0].containsRange(selection)) {
              allPossibleSelections.set(index, []);
              break;
            }
          }
        }
      }
      if (allPossibleSelections.size === 0) {
        return false;
      }
      allPossibleSelections.forEach((array2, index) => {
        array2.push(...possibleSelections.get(index));
      });
    }
    selections2.sort(Range$2.compareRangesUsingStarts);
    for (const [index, ranges] of allPossibleSelections) {
      if (ranges.length !== selections2.length) {
        allPossibleSelections.delete(index);
        continue;
      }
      ranges.sort(Range$2.compareRangesUsingStarts);
      for (let i = 0; i < ranges.length; i++) {
        if (!ranges[i].containsRange(selections2[i])) {
          allPossibleSelections.delete(index);
          continue;
        }
      }
    }
    return allPossibleSelections.size > 0;
  }
};
SnippetSession = __decorate$19([
  __param$17(3, ILanguageConfigurationService)
], SnippetSession);
var __decorate$18 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$16 = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
const _defaultOptions = {
  overwriteBefore: 0,
  overwriteAfter: 0,
  undoStopBefore: true,
  undoStopAfter: true,
  adjustWhitespace: true,
  clipboardText: void 0,
  overtypingCapturer: void 0
};
let SnippetController2 = class SnippetController22 {
  static get(editor2) {
    return editor2.getContribution(SnippetController22.ID);
  }
  constructor(_editor, _logService, _languageFeaturesService, contextKeyService, _languageConfigurationService) {
    this._editor = _editor;
    this._logService = _logService;
    this._languageFeaturesService = _languageFeaturesService;
    this._languageConfigurationService = _languageConfigurationService;
    this._snippetListener = new DisposableStore();
    this._modelVersionId = -1;
    this._inSnippet = SnippetController22.InSnippetMode.bindTo(contextKeyService);
    this._hasNextTabstop = SnippetController22.HasNextTabstop.bindTo(contextKeyService);
    this._hasPrevTabstop = SnippetController22.HasPrevTabstop.bindTo(contextKeyService);
  }
  dispose() {
    var _a2;
    this._inSnippet.reset();
    this._hasPrevTabstop.reset();
    this._hasNextTabstop.reset();
    (_a2 = this._session) === null || _a2 === void 0 ? void 0 : _a2.dispose();
    this._snippetListener.dispose();
  }
  insert(template, opts) {
    try {
      this._doInsert(template, typeof opts === "undefined" ? _defaultOptions : Object.assign(Object.assign({}, _defaultOptions), opts));
    } catch (e) {
      this.cancel();
      this._logService.error(e);
      this._logService.error("snippet_error");
      this._logService.error("insert_template=", template);
      this._logService.error("existing_template=", this._session ? this._session._logInfo() : "<no_session>");
    }
  }
  _doInsert(template, opts) {
    var _a2;
    if (!this._editor.hasModel()) {
      return;
    }
    this._snippetListener.clear();
    if (opts.undoStopBefore) {
      this._editor.getModel().pushStackElement();
    }
    if (this._session && typeof template !== "string") {
      this.cancel();
    }
    if (!this._session) {
      this._modelVersionId = this._editor.getModel().getAlternativeVersionId();
      this._session = new SnippetSession(this._editor, template, opts, this._languageConfigurationService);
      this._session.insert();
    } else {
      assertType(typeof template === "string");
      this._session.merge(template, opts);
    }
    if (opts.undoStopAfter) {
      this._editor.getModel().pushStackElement();
    }
    if ((_a2 = this._session) === null || _a2 === void 0 ? void 0 : _a2.hasChoice) {
      const provider = {
        _debugDisplayName: "snippetChoiceCompletions",
        provideCompletionItems: (model2, position) => {
          if (!this._session || model2 !== this._editor.getModel() || !Position$2.equals(this._editor.getPosition(), position)) {
            return void 0;
          }
          const { activeChoice } = this._session;
          if (!activeChoice || activeChoice.choice.options.length === 0) {
            return void 0;
          }
          const word2 = model2.getValueInRange(activeChoice.range);
          const isAnyOfOptions = Boolean(activeChoice.choice.options.find((o) => o.value === word2));
          const suggestions = [];
          for (let i = 0; i < activeChoice.choice.options.length; i++) {
            const option = activeChoice.choice.options[i];
            suggestions.push({
              kind: 13,
              label: option.value,
              insertText: option.value,
              sortText: "a".repeat(i + 1),
              range: activeChoice.range,
              filterText: isAnyOfOptions ? `${word2}_${option.value}` : void 0,
              command: { id: "jumpToNextSnippetPlaceholder", title: localize("next", "Go to next placeholder...") }
            });
          }
          return { suggestions };
        }
      };
      const model = this._editor.getModel();
      let registration;
      let isRegistered = false;
      const disable = () => {
        registration === null || registration === void 0 ? void 0 : registration.dispose();
        isRegistered = false;
      };
      const enable = () => {
        if (!isRegistered) {
          registration = this._languageFeaturesService.completionProvider.register({
            language: model.getLanguageId(),
            pattern: model.uri.fsPath,
            scheme: model.uri.scheme,
            exclusive: true
          }, provider);
          this._snippetListener.add(registration);
          isRegistered = true;
        }
      };
      this._choiceCompletions = { provider, enable, disable };
    }
    this._updateState();
    this._snippetListener.add(this._editor.onDidChangeModelContent((e) => e.isFlush && this.cancel()));
    this._snippetListener.add(this._editor.onDidChangeModel(() => this.cancel()));
    this._snippetListener.add(this._editor.onDidChangeCursorSelection(() => this._updateState()));
  }
  _updateState() {
    if (!this._session || !this._editor.hasModel()) {
      return;
    }
    if (this._modelVersionId === this._editor.getModel().getAlternativeVersionId()) {
      return this.cancel();
    }
    if (!this._session.hasPlaceholder) {
      return this.cancel();
    }
    if (this._session.isAtLastPlaceholder || !this._session.isSelectionWithinPlaceholders()) {
      this._editor.getModel().pushStackElement();
      return this.cancel();
    }
    this._inSnippet.set(true);
    this._hasPrevTabstop.set(!this._session.isAtFirstPlaceholder);
    this._hasNextTabstop.set(!this._session.isAtLastPlaceholder);
    this._handleChoice();
  }
  _handleChoice() {
    var _a2;
    if (!this._session || !this._editor.hasModel()) {
      this._currentChoice = void 0;
      return;
    }
    const { activeChoice } = this._session;
    if (!activeChoice || !this._choiceCompletions) {
      (_a2 = this._choiceCompletions) === null || _a2 === void 0 ? void 0 : _a2.disable();
      this._currentChoice = void 0;
      return;
    }
    if (this._currentChoice !== activeChoice.choice) {
      this._currentChoice = activeChoice.choice;
      this._choiceCompletions.enable();
      queueMicrotask(() => {
        showSimpleSuggestions(this._editor, this._choiceCompletions.provider);
      });
    }
  }
  finish() {
    while (this._inSnippet.get()) {
      this.next();
    }
  }
  cancel(resetSelection = false) {
    var _a2;
    this._inSnippet.reset();
    this._hasPrevTabstop.reset();
    this._hasNextTabstop.reset();
    this._snippetListener.clear();
    this._currentChoice = void 0;
    (_a2 = this._session) === null || _a2 === void 0 ? void 0 : _a2.dispose();
    this._session = void 0;
    this._modelVersionId = -1;
    if (resetSelection) {
      this._editor.setSelections([this._editor.getSelection()]);
    }
  }
  prev() {
    var _a2;
    (_a2 = this._session) === null || _a2 === void 0 ? void 0 : _a2.prev();
    this._updateState();
  }
  next() {
    var _a2;
    (_a2 = this._session) === null || _a2 === void 0 ? void 0 : _a2.next();
    this._updateState();
  }
  isInSnippet() {
    return Boolean(this._inSnippet.get());
  }
};
SnippetController2.ID = "snippetController2";
SnippetController2.InSnippetMode = new RawContextKey("inSnippetMode", false, localize("inSnippetMode", "Whether the editor in current in snippet mode"));
SnippetController2.HasNextTabstop = new RawContextKey("hasNextTabstop", false, localize("hasNextTabstop", "Whether there is a next tab stop when in snippet mode"));
SnippetController2.HasPrevTabstop = new RawContextKey("hasPrevTabstop", false, localize("hasPrevTabstop", "Whether there is a previous tab stop when in snippet mode"));
SnippetController2 = __decorate$18([
  __param$16(1, ILogService),
  __param$16(2, ILanguageFeaturesService),
  __param$16(3, IContextKeyService),
  __param$16(4, ILanguageConfigurationService)
], SnippetController2);
registerEditorContribution(
  SnippetController2.ID,
  SnippetController2,
  4
  /* EditorContributionInstantiation.Lazy */
);
const CommandCtor = EditorCommand.bindToContribution(SnippetController2.get);
registerEditorCommand(new CommandCtor({
  id: "jumpToNextSnippetPlaceholder",
  precondition: ContextKeyExpr.and(SnippetController2.InSnippetMode, SnippetController2.HasNextTabstop),
  handler: (ctrl) => ctrl.next(),
  kbOpts: {
    weight: 100 + 30,
    kbExpr: EditorContextKeys.editorTextFocus,
    primary: 2
    /* KeyCode.Tab */
  }
}));
registerEditorCommand(new CommandCtor({
  id: "jumpToPrevSnippetPlaceholder",
  precondition: ContextKeyExpr.and(SnippetController2.InSnippetMode, SnippetController2.HasPrevTabstop),
  handler: (ctrl) => ctrl.prev(),
  kbOpts: {
    weight: 100 + 30,
    kbExpr: EditorContextKeys.editorTextFocus,
    primary: 1024 | 2
    /* KeyCode.Tab */
  }
}));
registerEditorCommand(new CommandCtor({
  id: "leaveSnippet",
  precondition: SnippetController2.InSnippetMode,
  handler: (ctrl) => ctrl.cancel(true),
  kbOpts: {
    weight: 100 + 30,
    kbExpr: EditorContextKeys.editorTextFocus,
    primary: 9,
    secondary: [
      1024 | 9
      /* KeyCode.Escape */
    ]
  }
}));
registerEditorCommand(new CommandCtor({
  id: "acceptSnippet",
  precondition: SnippetController2.InSnippetMode,
  handler: (ctrl) => ctrl.finish()
  // kbOpts: {
  // 	weight: KeybindingWeight.EditorContrib + 30,
  // 	kbExpr: EditorContextKeys.textFocus,
  // 	primary: KeyCode.Enter,
  // }
}));
var __decorate$17 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$15 = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$H = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var VersionIdChangeReason;
(function(VersionIdChangeReason2) {
  VersionIdChangeReason2[VersionIdChangeReason2["Undo"] = 0] = "Undo";
  VersionIdChangeReason2[VersionIdChangeReason2["Redo"] = 1] = "Redo";
  VersionIdChangeReason2[VersionIdChangeReason2["AcceptWord"] = 2] = "AcceptWord";
  VersionIdChangeReason2[VersionIdChangeReason2["Other"] = 3] = "Other";
})(VersionIdChangeReason || (VersionIdChangeReason = {}));
let InlineCompletionsModel = class InlineCompletionsModel2 extends Disposable {
  get isAcceptingPartially() {
    return this._isAcceptingPartially;
  }
  constructor(textModel, selectedSuggestItem, cursorPosition, textModelVersionId, _debounceValue, _suggestPreviewEnabled, _suggestPreviewMode, _inlineSuggestMode, _enabled, _instantiationService, _commandService, _languageConfigurationService) {
    super();
    this.textModel = textModel;
    this.selectedSuggestItem = selectedSuggestItem;
    this.cursorPosition = cursorPosition;
    this.textModelVersionId = textModelVersionId;
    this._debounceValue = _debounceValue;
    this._suggestPreviewEnabled = _suggestPreviewEnabled;
    this._suggestPreviewMode = _suggestPreviewMode;
    this._inlineSuggestMode = _inlineSuggestMode;
    this._enabled = _enabled;
    this._instantiationService = _instantiationService;
    this._commandService = _commandService;
    this._languageConfigurationService = _languageConfigurationService;
    this._source = this._register(this._instantiationService.createInstance(InlineCompletionsSource, this.textModel, this.textModelVersionId, this._debounceValue));
    this._isActive = observableValue("isActive", false);
    this._forceUpdate = observableSignal("forceUpdate");
    this._selectedInlineCompletionId = observableValue("selectedInlineCompletionId", void 0);
    this._isAcceptingPartially = false;
    this._preserveCurrentCompletionReasons = /* @__PURE__ */ new Set([
      VersionIdChangeReason.Redo,
      VersionIdChangeReason.Undo,
      VersionIdChangeReason.AcceptWord
    ]);
    this._fetchInlineCompletions = derivedHandleChanges("fetch inline completions", {
      createEmptyChangeSummary: () => ({
        preserveCurrentCompletion: false,
        inlineCompletionTriggerKind: InlineCompletionTriggerKind$1.Automatic
      }),
      handleChange: (ctx, changeSummary) => {
        if (ctx.didChange(this.textModelVersionId) && this._preserveCurrentCompletionReasons.has(ctx.change)) {
          changeSummary.preserveCurrentCompletion = true;
        } else if (ctx.didChange(this._forceUpdate)) {
          changeSummary.inlineCompletionTriggerKind = ctx.change;
        }
        return true;
      }
    }, (reader, changeSummary) => {
      this._forceUpdate.read(reader);
      const shouldUpdate = this._enabled.read(reader) && this.selectedSuggestItem.read(reader) || this._isActive.read(reader);
      if (!shouldUpdate) {
        this._source.cancelUpdate();
        return void 0;
      }
      this.textModelVersionId.read(reader);
      const itemToPreserveCandidate = this.selectedInlineCompletion.get();
      const itemToPreserve = changeSummary.preserveCurrentCompletion || (itemToPreserveCandidate === null || itemToPreserveCandidate === void 0 ? void 0 : itemToPreserveCandidate.forwardStable) ? itemToPreserveCandidate : void 0;
      const suggestWidgetInlineCompletions = this._source.suggestWidgetInlineCompletions.get();
      const suggestItem = this.selectedSuggestItem.read(reader);
      if (suggestWidgetInlineCompletions && !suggestItem) {
        const inlineCompletions = this._source.inlineCompletions.get();
        transaction((tx) => {
          if (inlineCompletions && suggestWidgetInlineCompletions.request.versionId > inlineCompletions.request.versionId) {
            this._source.inlineCompletions.set(suggestWidgetInlineCompletions.clone(), tx);
          }
          this._source.clearSuggestWidgetInlineCompletions(tx);
        });
      }
      const cursorPosition2 = this.cursorPosition.read(reader);
      const context = {
        triggerKind: changeSummary.inlineCompletionTriggerKind,
        selectedSuggestionInfo: suggestItem === null || suggestItem === void 0 ? void 0 : suggestItem.toSelectedSuggestionInfo()
      };
      return this._source.fetch(cursorPosition2, context, itemToPreserve);
    });
    this._filteredInlineCompletionItems = derived("filteredInlineCompletionItems", (reader) => {
      const c = this._source.inlineCompletions.read(reader);
      if (!c) {
        return [];
      }
      const cursorPosition2 = this.cursorPosition.read(reader);
      const filteredCompletions = c.inlineCompletions.filter((c2) => c2.isVisible(this.textModel, cursorPosition2, reader));
      return filteredCompletions;
    });
    this.selectedInlineCompletionIndex = derived("selectedCachedCompletionIndex", (reader) => {
      const selectedInlineCompletionId = this._selectedInlineCompletionId.read(reader);
      const filteredCompletions = this._filteredInlineCompletionItems.read(reader);
      const idx = this._selectedInlineCompletionId === void 0 ? -1 : filteredCompletions.findIndex((v) => v.semanticId === selectedInlineCompletionId);
      if (idx === -1) {
        this._selectedInlineCompletionId.set(void 0, void 0);
        return 0;
      }
      return idx;
    });
    this.selectedInlineCompletion = derived("selectedCachedCompletion", (reader) => {
      const filteredCompletions = this._filteredInlineCompletionItems.read(reader);
      const idx = this.selectedInlineCompletionIndex.read(reader);
      return filteredCompletions[idx];
    });
    this.lastTriggerKind = this._source.inlineCompletions.map((v) => (
      /** @description lastTriggerKind */
      v === null || v === void 0 ? void 0 : v.request.context.triggerKind
    ));
    this.inlineCompletionsCount = derived("selectedInlineCompletionsCount", (reader) => {
      if (this.lastTriggerKind.read(reader) === InlineCompletionTriggerKind$1.Explicit) {
        return this._filteredInlineCompletionItems.read(reader).length;
      } else {
        return void 0;
      }
    });
    this.state = derived("ghostTextAndCompletion", (reader) => {
      var _a2;
      const model = this.textModel;
      const suggestItem = this.selectedSuggestItem.read(reader);
      if (suggestItem) {
        const suggestWidgetInlineCompletions = this._source.suggestWidgetInlineCompletions.read(reader);
        const candidateInlineCompletions = suggestWidgetInlineCompletions ? suggestWidgetInlineCompletions.inlineCompletions : [this.selectedInlineCompletion.read(reader)].filter(isDefined);
        const suggestCompletion = suggestItem.toSingleTextEdit().removeCommonPrefix(model);
        const augmentedCompletion = mapFind(candidateInlineCompletions, (completion) => {
          let r = completion.toSingleTextEdit(reader);
          r = r.removeCommonPrefix(model, Range$2.fromPositions(r.range.getStartPosition(), suggestItem.range.getEndPosition()));
          return r.augments(suggestCompletion) ? { edit: r, completion } : void 0;
        });
        const isSuggestionPreviewEnabled = this._suggestPreviewEnabled.read(reader);
        if (!isSuggestionPreviewEnabled && !augmentedCompletion) {
          return void 0;
        }
        const edit = (_a2 = augmentedCompletion === null || augmentedCompletion === void 0 ? void 0 : augmentedCompletion.edit) !== null && _a2 !== void 0 ? _a2 : suggestCompletion;
        const editPreviewLength = augmentedCompletion ? augmentedCompletion.edit.text.length - suggestCompletion.text.length : 0;
        const mode = this._suggestPreviewMode.read(reader);
        const cursor = this.cursorPosition.read(reader);
        const newGhostText = edit.computeGhostText(model, mode, cursor, editPreviewLength);
        const ghostText2 = newGhostText !== null && newGhostText !== void 0 ? newGhostText : new GhostText(edit.range.endLineNumber, []);
        return { ghostText: ghostText2, inlineCompletion: augmentedCompletion === null || augmentedCompletion === void 0 ? void 0 : augmentedCompletion.completion, suggestItem };
      } else {
        if (!this._isActive.read(reader)) {
          return void 0;
        }
        const item = this.selectedInlineCompletion.read(reader);
        if (!item) {
          return void 0;
        }
        const replacement = item.toSingleTextEdit(reader);
        const mode = this._inlineSuggestMode.read(reader);
        const cursor = this.cursorPosition.read(reader);
        const ghostText2 = replacement.computeGhostText(model, mode, cursor);
        return ghostText2 ? { ghostText: ghostText2, inlineCompletion: item, suggestItem: void 0 } : void 0;
      }
    });
    this.ghostText = derived("ghostText", (reader) => {
      const v = this.state.read(reader);
      if (!v) {
        return void 0;
      }
      return v.ghostText;
    });
    this._register(keepAlive(this._fetchInlineCompletions, true));
    let lastItem = void 0;
    this._register(autorun("call handleItemDidShow", (reader) => {
      var _a2, _b2;
      const item = this.state.read(reader);
      const completion = item === null || item === void 0 ? void 0 : item.inlineCompletion;
      if ((completion === null || completion === void 0 ? void 0 : completion.semanticId) !== (lastItem === null || lastItem === void 0 ? void 0 : lastItem.semanticId)) {
        lastItem = completion;
        if (completion) {
          const i = completion.inlineCompletion;
          const src = i.source;
          (_b2 = (_a2 = src.provider).handleItemDidShow) === null || _b2 === void 0 ? void 0 : _b2.call(_a2, src.inlineCompletions, i.sourceInlineCompletion, i.insertText);
        }
      }
    }));
  }
  trigger(tx) {
    return __awaiter$H(this, void 0, void 0, function* () {
      this._isActive.set(true, tx);
      yield this._fetchInlineCompletions.get();
    });
  }
  triggerExplicitly(tx) {
    return __awaiter$H(this, void 0, void 0, function* () {
      subtransaction(tx, (tx2) => {
        this._isActive.set(true, tx2);
        this._forceUpdate.trigger(tx2, InlineCompletionTriggerKind$1.Explicit);
      });
      yield this._fetchInlineCompletions.get();
    });
  }
  stop(tx) {
    subtransaction(tx, (tx2) => {
      this._isActive.set(false, tx2);
      this._source.clear(tx2);
    });
  }
  _deltaSelectedInlineCompletionIndex(delta) {
    return __awaiter$H(this, void 0, void 0, function* () {
      yield this.triggerExplicitly();
      const completions = this._filteredInlineCompletionItems.get() || [];
      if (completions.length > 0) {
        const newIdx = (this.selectedInlineCompletionIndex.get() + delta + completions.length) % completions.length;
        this._selectedInlineCompletionId.set(completions[newIdx].semanticId, void 0);
      } else {
        this._selectedInlineCompletionId.set(void 0, void 0);
      }
    });
  }
  next() {
    return __awaiter$H(this, void 0, void 0, function* () {
      yield this._deltaSelectedInlineCompletionIndex(1);
    });
  }
  previous() {
    return __awaiter$H(this, void 0, void 0, function* () {
      yield this._deltaSelectedInlineCompletionIndex(-1);
    });
  }
  accept(editor2) {
    var _a2;
    return __awaiter$H(this, void 0, void 0, function* () {
      if (editor2.getModel() !== this.textModel) {
        throw new BugIndicatingError();
      }
      const state = this.state.get();
      if (!state || state.ghostText.isEmpty() || !state.inlineCompletion) {
        return;
      }
      const completion = state.inlineCompletion.toInlineCompletion(void 0);
      editor2.pushUndoStop();
      if (completion.snippetInfo) {
        editor2.executeEdits("inlineSuggestion.accept", [
          EditOperation.replaceMove(completion.range, ""),
          ...completion.additionalTextEdits
        ]);
        editor2.setPosition(completion.snippetInfo.range.getStartPosition());
        (_a2 = SnippetController2.get(editor2)) === null || _a2 === void 0 ? void 0 : _a2.insert(completion.snippetInfo.snippet, { undoStopBefore: false });
      } else {
        editor2.executeEdits("inlineSuggestion.accept", [
          EditOperation.replaceMove(completion.range, completion.insertText),
          ...completion.additionalTextEdits
        ]);
      }
      if (completion.command) {
        completion.source.addRef();
      }
      transaction((tx) => {
        this._source.clear(tx);
        this._isActive.set(false, tx);
      });
      if (completion.command) {
        yield this._commandService.executeCommand(completion.command.id, ...completion.command.arguments || []).then(void 0, onUnexpectedExternalError);
        completion.source.removeRef();
      }
    });
  }
  acceptNextWord(editor2) {
    return __awaiter$H(this, void 0, void 0, function* () {
      yield this._acceptNext(editor2, (pos, text2) => {
        const langId = this.textModel.getLanguageIdAtPosition(pos.lineNumber, pos.column);
        const config2 = this._languageConfigurationService.getLanguageConfiguration(langId);
        const wordRegExp = new RegExp(config2.wordDefinition.source, config2.wordDefinition.flags.replace("g", ""));
        const m1 = text2.match(wordRegExp);
        let acceptUntilIndexExclusive = 0;
        if (m1 && m1.index !== void 0) {
          if (m1.index === 0) {
            acceptUntilIndexExclusive = m1[0].length;
          } else {
            acceptUntilIndexExclusive = m1.index;
          }
        } else {
          acceptUntilIndexExclusive = text2.length;
        }
        const wsRegExp = /\s+/g;
        const m2 = wsRegExp.exec(text2);
        if (m2 && m2.index !== void 0) {
          if (m2.index + m2[0].length < acceptUntilIndexExclusive) {
            acceptUntilIndexExclusive = m2.index + m2[0].length;
          }
        }
        return acceptUntilIndexExclusive;
      });
    });
  }
  acceptNextLine(editor2) {
    return __awaiter$H(this, void 0, void 0, function* () {
      yield this._acceptNext(editor2, (pos, text2) => {
        const m = text2.match(/\n/);
        if (m && m.index !== void 0) {
          return m.index + 1;
        }
        return text2.length;
      });
    });
  }
  _acceptNext(editor2, getAcceptUntilIndex) {
    return __awaiter$H(this, void 0, void 0, function* () {
      if (editor2.getModel() !== this.textModel) {
        throw new BugIndicatingError();
      }
      const state = this.state.get();
      if (!state || state.ghostText.isEmpty() || !state.inlineCompletion) {
        return;
      }
      const ghostText2 = state.ghostText;
      const completion = state.inlineCompletion.toInlineCompletion(void 0);
      if (completion.snippetInfo || completion.filterText !== completion.insertText) {
        yield this.accept(editor2);
        return;
      }
      const firstPart = ghostText2.parts[0];
      const position = new Position$2(ghostText2.lineNumber, firstPart.column);
      const line = firstPart.lines.join("\n");
      const acceptUntilIndexExclusive = getAcceptUntilIndex(position, line);
      if (acceptUntilIndexExclusive === line.length && ghostText2.parts.length === 1) {
        this.accept(editor2);
        return;
      }
      const partialText = line.substring(0, acceptUntilIndexExclusive);
      this._isAcceptingPartially = true;
      try {
        editor2.pushUndoStop();
        editor2.executeEdits("inlineSuggestion.accept", [
          EditOperation.replace(Range$2.fromPositions(position), partialText)
        ]);
        const length2 = lengthOfText(partialText);
        editor2.setPosition(addPositions(position, length2));
      } finally {
        this._isAcceptingPartially = false;
      }
      if (completion.source.provider.handlePartialAccept) {
        const acceptedRange = Range$2.fromPositions(completion.range.getStartPosition(), addPositions(position, lengthOfText(partialText)));
        const text2 = editor2.getModel().getValueInRange(
          acceptedRange,
          1
          /* EndOfLinePreference.LF */
        );
        completion.source.provider.handlePartialAccept(completion.source.inlineCompletions, completion.sourceInlineCompletion, text2.length);
      }
    });
  }
};
InlineCompletionsModel = __decorate$17([
  __param$15(9, IInstantiationService),
  __param$15(10, ICommandService),
  __param$15(11, ILanguageConfigurationService)
], InlineCompletionsModel);
var __decorate$16 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$14 = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
class Memory {
  constructor(name) {
    this.name = name;
  }
  select(model, pos, items) {
    if (items.length === 0) {
      return 0;
    }
    const topScore = items[0].score[0];
    for (let i = 0; i < items.length; i++) {
      const { score: score2, completion: suggestion } = items[i];
      if (score2[0] !== topScore) {
        break;
      }
      if (suggestion.preselect) {
        return i;
      }
    }
    return 0;
  }
}
class NoMemory extends Memory {
  constructor() {
    super("first");
  }
  memorize(model, pos, item) {
  }
  toJSON() {
    return void 0;
  }
  fromJSON() {
  }
}
class LRUMemory extends Memory {
  constructor() {
    super("recentlyUsed");
    this._cache = new LRUCache$2(300, 0.66);
    this._seq = 0;
  }
  memorize(model, pos, item) {
    const key = `${model.getLanguageId()}/${item.textLabel}`;
    this._cache.set(key, {
      touch: this._seq++,
      type: item.completion.kind,
      insertText: item.completion.insertText
    });
  }
  select(model, pos, items) {
    if (items.length === 0) {
      return 0;
    }
    const lineSuffix = model.getLineContent(pos.lineNumber).substr(pos.column - 10, pos.column - 1);
    if (/\s$/.test(lineSuffix)) {
      return super.select(model, pos, items);
    }
    const topScore = items[0].score[0];
    let indexPreselect = -1;
    let indexRecency = -1;
    let seq = -1;
    for (let i = 0; i < items.length; i++) {
      if (items[i].score[0] !== topScore) {
        break;
      }
      const key = `${model.getLanguageId()}/${items[i].textLabel}`;
      const item = this._cache.peek(key);
      if (item && item.touch > seq && item.type === items[i].completion.kind && item.insertText === items[i].completion.insertText) {
        seq = item.touch;
        indexRecency = i;
      }
      if (items[i].completion.preselect && indexPreselect === -1) {
        return indexPreselect = i;
      }
    }
    if (indexRecency !== -1) {
      return indexRecency;
    } else if (indexPreselect !== -1) {
      return indexPreselect;
    } else {
      return 0;
    }
  }
  toJSON() {
    return this._cache.toJSON();
  }
  fromJSON(data) {
    this._cache.clear();
    const seq = 0;
    for (const [key, value] of data) {
      value.touch = seq;
      value.type = typeof value.type === "number" ? value.type : CompletionItemKinds.fromString(value.type);
      this._cache.set(key, value);
    }
    this._seq = this._cache.size;
  }
}
class PrefixMemory extends Memory {
  constructor() {
    super("recentlyUsedByPrefix");
    this._trie = TernarySearchTree.forStrings();
    this._seq = 0;
  }
  memorize(model, pos, item) {
    const { word: word2 } = model.getWordUntilPosition(pos);
    const key = `${model.getLanguageId()}/${word2}`;
    this._trie.set(key, {
      type: item.completion.kind,
      insertText: item.completion.insertText,
      touch: this._seq++
    });
  }
  select(model, pos, items) {
    const { word: word2 } = model.getWordUntilPosition(pos);
    if (!word2) {
      return super.select(model, pos, items);
    }
    const key = `${model.getLanguageId()}/${word2}`;
    let item = this._trie.get(key);
    if (!item) {
      item = this._trie.findSubstr(key);
    }
    if (item) {
      for (let i = 0; i < items.length; i++) {
        const { kind, insertText } = items[i].completion;
        if (kind === item.type && insertText === item.insertText) {
          return i;
        }
      }
    }
    return super.select(model, pos, items);
  }
  toJSON() {
    const entries = [];
    this._trie.forEach((value, key) => entries.push([key, value]));
    entries.sort((a, b) => -(a[1].touch - b[1].touch)).forEach((value, i) => value[1].touch = i);
    return entries.slice(0, 200);
  }
  fromJSON(data) {
    this._trie.clear();
    if (data.length > 0) {
      this._seq = data[0][1].touch + 1;
      for (const [key, value] of data) {
        value.type = typeof value.type === "number" ? value.type : CompletionItemKinds.fromString(value.type);
        this._trie.set(key, value);
      }
    }
  }
}
let SuggestMemoryService = class SuggestMemoryService2 {
  constructor(_storageService, _configService) {
    this._storageService = _storageService;
    this._configService = _configService;
    this._disposables = new DisposableStore();
    this._persistSoon = new RunOnceScheduler(() => this._saveState(), 500);
    this._disposables.add(_storageService.onWillSaveState((e) => {
      if (e.reason === WillSaveStateReason.SHUTDOWN) {
        this._saveState();
      }
    }));
  }
  dispose() {
    this._disposables.dispose();
    this._persistSoon.dispose();
  }
  memorize(model, pos, item) {
    this._withStrategy(model, pos).memorize(model, pos, item);
    this._persistSoon.schedule();
  }
  select(model, pos, items) {
    return this._withStrategy(model, pos).select(model, pos, items);
  }
  _withStrategy(model, pos) {
    var _a2;
    const mode = this._configService.getValue("editor.suggestSelection", {
      overrideIdentifier: model.getLanguageIdAtPosition(pos.lineNumber, pos.column),
      resource: model.uri
    });
    if (((_a2 = this._strategy) === null || _a2 === void 0 ? void 0 : _a2.name) !== mode) {
      this._saveState();
      const ctor = SuggestMemoryService2._strategyCtors.get(mode) || NoMemory;
      this._strategy = new ctor();
      try {
        const share = this._configService.getValue("editor.suggest.shareSuggestSelections");
        const scope = share ? 0 : 1;
        const raw = this._storageService.get(`${SuggestMemoryService2._storagePrefix}/${mode}`, scope);
        if (raw) {
          this._strategy.fromJSON(JSON.parse(raw));
        }
      } catch (e) {
      }
    }
    return this._strategy;
  }
  _saveState() {
    if (this._strategy) {
      const share = this._configService.getValue("editor.suggest.shareSuggestSelections");
      const scope = share ? 0 : 1;
      const raw = JSON.stringify(this._strategy);
      this._storageService.store(
        `${SuggestMemoryService2._storagePrefix}/${this._strategy.name}`,
        raw,
        scope,
        1
        /* StorageTarget.MACHINE */
      );
    }
  }
};
SuggestMemoryService._strategyCtors = /* @__PURE__ */ new Map([
  ["recentlyUsedByPrefix", PrefixMemory],
  ["recentlyUsed", LRUMemory],
  ["first", NoMemory]
]);
SuggestMemoryService._storagePrefix = "suggest/memories";
SuggestMemoryService = __decorate$16([
  __param$14(0, IStorageService),
  __param$14(1, IConfigurationService)
], SuggestMemoryService);
const ISuggestMemoryService = createDecorator("ISuggestMemories");
registerSingleton(
  ISuggestMemoryService,
  SuggestMemoryService,
  1
  /* InstantiationType.Delayed */
);
var __decorate$15 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$13 = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let WordContextKey = class WordContextKey2 {
  constructor(_editor, contextKeyService) {
    this._editor = _editor;
    this._enabled = false;
    this._ckAtEnd = WordContextKey2.AtEnd.bindTo(contextKeyService);
    this._configListener = this._editor.onDidChangeConfiguration((e) => e.hasChanged(
      121
      /* EditorOption.tabCompletion */
    ) && this._update());
    this._update();
  }
  dispose() {
    var _a2;
    this._configListener.dispose();
    (_a2 = this._selectionListener) === null || _a2 === void 0 ? void 0 : _a2.dispose();
    this._ckAtEnd.reset();
  }
  _update() {
    const enabled = this._editor.getOption(
      121
      /* EditorOption.tabCompletion */
    ) === "on";
    if (this._enabled === enabled) {
      return;
    }
    this._enabled = enabled;
    if (this._enabled) {
      const checkForWordEnd = () => {
        if (!this._editor.hasModel()) {
          this._ckAtEnd.set(false);
          return;
        }
        const model = this._editor.getModel();
        const selection = this._editor.getSelection();
        const word2 = model.getWordAtPosition(selection.getStartPosition());
        if (!word2) {
          this._ckAtEnd.set(false);
          return;
        }
        this._ckAtEnd.set(word2.endColumn === selection.getStartPosition().column);
      };
      this._selectionListener = this._editor.onDidChangeCursorSelection(checkForWordEnd);
      checkForWordEnd();
    } else if (this._selectionListener) {
      this._ckAtEnd.reset();
      this._selectionListener.dispose();
      this._selectionListener = void 0;
    }
  }
};
WordContextKey.AtEnd = new RawContextKey("atEndOfWord", false);
WordContextKey = __decorate$15([
  __param$13(1, IContextKeyService)
], WordContextKey);
var __decorate$14 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$12 = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let SuggestAlternatives = class SuggestAlternatives2 {
  constructor(_editor, contextKeyService) {
    this._editor = _editor;
    this._index = 0;
    this._ckOtherSuggestions = SuggestAlternatives2.OtherSuggestions.bindTo(contextKeyService);
  }
  dispose() {
    this.reset();
  }
  reset() {
    var _a2;
    this._ckOtherSuggestions.reset();
    (_a2 = this._listener) === null || _a2 === void 0 ? void 0 : _a2.dispose();
    this._model = void 0;
    this._acceptNext = void 0;
    this._ignore = false;
  }
  set({ model, index }, acceptNext) {
    if (model.items.length === 0) {
      this.reset();
      return;
    }
    const nextIndex = SuggestAlternatives2._moveIndex(true, model, index);
    if (nextIndex === index) {
      this.reset();
      return;
    }
    this._acceptNext = acceptNext;
    this._model = model;
    this._index = index;
    this._listener = this._editor.onDidChangeCursorPosition(() => {
      if (!this._ignore) {
        this.reset();
      }
    });
    this._ckOtherSuggestions.set(true);
  }
  static _moveIndex(fwd, model, index) {
    let newIndex = index;
    for (let rounds = model.items.length; rounds > 0; rounds--) {
      newIndex = (newIndex + model.items.length + (fwd ? 1 : -1)) % model.items.length;
      if (newIndex === index) {
        break;
      }
      if (!model.items[newIndex].completion.additionalTextEdits) {
        break;
      }
    }
    return newIndex;
  }
  next() {
    this._move(true);
  }
  prev() {
    this._move(false);
  }
  _move(fwd) {
    if (!this._model) {
      return;
    }
    try {
      this._ignore = true;
      this._index = SuggestAlternatives2._moveIndex(fwd, this._model, this._index);
      this._acceptNext({ index: this._index, item: this._model.items[this._index], model: this._model });
    } finally {
      this._ignore = false;
    }
  }
};
SuggestAlternatives.OtherSuggestions = new RawContextKey("hasOtherSuggestions", false);
SuggestAlternatives = __decorate$14([
  __param$12(1, IContextKeyService)
], SuggestAlternatives);
class CommitCharacterController {
  constructor(editor2, widget, model, accept) {
    this._disposables = new DisposableStore();
    this._disposables.add(model.onDidSuggest((e) => {
      if (e.completionModel.items.length === 0) {
        this.reset();
      }
    }));
    this._disposables.add(model.onDidCancel((e) => {
      this.reset();
    }));
    this._disposables.add(widget.onDidShow(() => this._onItem(widget.getFocusedItem())));
    this._disposables.add(widget.onDidFocus(this._onItem, this));
    this._disposables.add(widget.onDidHide(this.reset, this));
    this._disposables.add(editor2.onWillType((text2) => {
      if (this._active && !widget.isFrozen() && model.state !== 0) {
        const ch = text2.charCodeAt(text2.length - 1);
        if (this._active.acceptCharacters.has(ch) && editor2.getOption(
          0
          /* EditorOption.acceptSuggestionOnCommitCharacter */
        )) {
          accept(this._active.item);
        }
      }
    }));
  }
  _onItem(selected) {
    if (!selected || !isNonEmptyArray(selected.item.completion.commitCharacters)) {
      this.reset();
      return;
    }
    if (this._active && this._active.item.item === selected.item) {
      return;
    }
    const acceptCharacters = new CharacterSet();
    for (const ch of selected.item.completion.commitCharacters) {
      if (ch.length > 0) {
        acceptCharacters.add(ch.charCodeAt(0));
      }
    }
    this._active = { acceptCharacters, item: selected };
  }
  reset() {
    this._active = void 0;
  }
  dispose() {
    this._disposables.dispose();
  }
}
var __awaiter$G = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class BracketSelectionRangeProvider {
  provideSelectionRanges(model, positions) {
    return __awaiter$G(this, void 0, void 0, function* () {
      const result2 = [];
      for (const position of positions) {
        const bucket = [];
        result2.push(bucket);
        const ranges = /* @__PURE__ */ new Map();
        yield new Promise((resolve2) => BracketSelectionRangeProvider._bracketsRightYield(resolve2, 0, model, position, ranges));
        yield new Promise((resolve2) => BracketSelectionRangeProvider._bracketsLeftYield(resolve2, 0, model, position, ranges, bucket));
      }
      return result2;
    });
  }
  static _bracketsRightYield(resolve2, round, model, pos, ranges) {
    const counts = /* @__PURE__ */ new Map();
    const t1 = Date.now();
    while (true) {
      if (round >= BracketSelectionRangeProvider._maxRounds) {
        resolve2();
        break;
      }
      if (!pos) {
        resolve2();
        break;
      }
      const bracket = model.bracketPairs.findNextBracket(pos);
      if (!bracket) {
        resolve2();
        break;
      }
      const d = Date.now() - t1;
      if (d > BracketSelectionRangeProvider._maxDuration) {
        setTimeout(() => BracketSelectionRangeProvider._bracketsRightYield(resolve2, round + 1, model, pos, ranges));
        break;
      }
      if (bracket.bracketInfo.isOpeningBracket) {
        const key = bracket.bracketInfo.bracketText;
        const val = counts.has(key) ? counts.get(key) : 0;
        counts.set(key, val + 1);
      } else {
        const key = bracket.bracketInfo.getOpeningBrackets()[0].bracketText;
        let val = counts.has(key) ? counts.get(key) : 0;
        val -= 1;
        counts.set(key, Math.max(0, val));
        if (val < 0) {
          let list2 = ranges.get(key);
          if (!list2) {
            list2 = new LinkedList();
            ranges.set(key, list2);
          }
          list2.push(bracket.range);
        }
      }
      pos = bracket.range.getEndPosition();
    }
  }
  static _bracketsLeftYield(resolve2, round, model, pos, ranges, bucket) {
    const counts = /* @__PURE__ */ new Map();
    const t1 = Date.now();
    while (true) {
      if (round >= BracketSelectionRangeProvider._maxRounds && ranges.size === 0) {
        resolve2();
        break;
      }
      if (!pos) {
        resolve2();
        break;
      }
      const bracket = model.bracketPairs.findPrevBracket(pos);
      if (!bracket) {
        resolve2();
        break;
      }
      const d = Date.now() - t1;
      if (d > BracketSelectionRangeProvider._maxDuration) {
        setTimeout(() => BracketSelectionRangeProvider._bracketsLeftYield(resolve2, round + 1, model, pos, ranges, bucket));
        break;
      }
      if (!bracket.bracketInfo.isOpeningBracket) {
        const key = bracket.bracketInfo.getOpeningBrackets()[0].bracketText;
        const val = counts.has(key) ? counts.get(key) : 0;
        counts.set(key, val + 1);
      } else {
        const key = bracket.bracketInfo.bracketText;
        let val = counts.has(key) ? counts.get(key) : 0;
        val -= 1;
        counts.set(key, Math.max(0, val));
        if (val < 0) {
          const list2 = ranges.get(key);
          if (list2) {
            const closing = list2.shift();
            if (list2.size === 0) {
              ranges.delete(key);
            }
            const innerBracket = Range$2.fromPositions(bracket.range.getEndPosition(), closing.getStartPosition());
            const outerBracket = Range$2.fromPositions(bracket.range.getStartPosition(), closing.getEndPosition());
            bucket.push({ range: innerBracket });
            bucket.push({ range: outerBracket });
            BracketSelectionRangeProvider._addBracketLeading(model, outerBracket, bucket);
          }
        }
      }
      pos = bracket.range.getStartPosition();
    }
  }
  static _addBracketLeading(model, bracket, bucket) {
    if (bracket.startLineNumber === bracket.endLineNumber) {
      return;
    }
    const startLine = bracket.startLineNumber;
    const column = model.getLineFirstNonWhitespaceColumn(startLine);
    if (column !== 0 && column !== bracket.startColumn) {
      bucket.push({ range: Range$2.fromPositions(new Position$2(startLine, column), bracket.getEndPosition()) });
      bucket.push({ range: Range$2.fromPositions(new Position$2(startLine, 1), bracket.getEndPosition()) });
    }
    const aboveLine = startLine - 1;
    if (aboveLine > 0) {
      const column2 = model.getLineFirstNonWhitespaceColumn(aboveLine);
      if (column2 === bracket.startColumn && column2 !== model.getLineLastNonWhitespaceColumn(aboveLine)) {
        bucket.push({ range: Range$2.fromPositions(new Position$2(aboveLine, column2), bracket.getEndPosition()) });
        bucket.push({ range: Range$2.fromPositions(new Position$2(aboveLine, 1), bracket.getEndPosition()) });
      }
    }
  }
}
BracketSelectionRangeProvider._maxDuration = 30;
BracketSelectionRangeProvider._maxRounds = 2;
var __awaiter$F = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class WordDistance {
  static create(service, editor2) {
    return __awaiter$F(this, void 0, void 0, function* () {
      if (!editor2.getOption(
        116
        /* EditorOption.suggest */
      ).localityBonus) {
        return WordDistance.None;
      }
      if (!editor2.hasModel()) {
        return WordDistance.None;
      }
      const model = editor2.getModel();
      const position = editor2.getPosition();
      if (!service.canComputeWordRanges(model.uri)) {
        return WordDistance.None;
      }
      const [ranges] = yield new BracketSelectionRangeProvider().provideSelectionRanges(model, [position]);
      if (ranges.length === 0) {
        return WordDistance.None;
      }
      const wordRanges = yield service.computeWordRanges(model.uri, ranges[0].range);
      if (!wordRanges) {
        return WordDistance.None;
      }
      const wordUntilPos = model.getWordUntilPosition(position);
      delete wordRanges[wordUntilPos.word];
      return new class extends WordDistance {
        distance(anchor, item) {
          if (!position.equals(editor2.getPosition())) {
            return 0;
          }
          if (item.kind === 17) {
            return 2 << 20;
          }
          const word2 = typeof item.label === "string" ? item.label : item.label.label;
          const wordLines = wordRanges[word2];
          if (isFalsyOrEmpty(wordLines)) {
            return 2 << 20;
          }
          const idx = binarySearch$4(wordLines, Range$2.fromPositions(anchor), Range$2.compareRangesUsingStarts);
          const bestWordRange = idx >= 0 ? wordLines[idx] : wordLines[Math.max(0, ~idx - 1)];
          let blockDistance = ranges.length;
          for (const range2 of ranges) {
            if (!Range$2.containsRange(range2.range, bestWordRange)) {
              break;
            }
            blockDistance -= 1;
          }
          return blockDistance;
        }
      }();
    });
  }
}
WordDistance.None = new class extends WordDistance {
  distance() {
    return 0;
  }
}();
let LineContext$1 = class LineContext {
  constructor(leadingLineContent, characterCountDelta) {
    this.leadingLineContent = leadingLineContent;
    this.characterCountDelta = characterCountDelta;
  }
};
class CompletionModel {
  constructor(items, column, lineContext, wordDistance, options, snippetSuggestions, fuzzyScoreOptions = FuzzyScoreOptions.default, clipboardText = void 0) {
    this.clipboardText = clipboardText;
    this._snippetCompareFn = CompletionModel._compareCompletionItems;
    this._items = items;
    this._column = column;
    this._wordDistance = wordDistance;
    this._options = options;
    this._refilterKind = 1;
    this._lineContext = lineContext;
    this._fuzzyScoreOptions = fuzzyScoreOptions;
    if (snippetSuggestions === "top") {
      this._snippetCompareFn = CompletionModel._compareCompletionItemsSnippetsUp;
    } else if (snippetSuggestions === "bottom") {
      this._snippetCompareFn = CompletionModel._compareCompletionItemsSnippetsDown;
    }
  }
  get lineContext() {
    return this._lineContext;
  }
  set lineContext(value) {
    if (this._lineContext.leadingLineContent !== value.leadingLineContent || this._lineContext.characterCountDelta !== value.characterCountDelta) {
      this._refilterKind = this._lineContext.characterCountDelta < value.characterCountDelta && this._filteredItems ? 2 : 1;
      this._lineContext = value;
    }
  }
  get items() {
    this._ensureCachedState();
    return this._filteredItems;
  }
  getItemsByProvider() {
    this._ensureCachedState();
    return this._itemsByProvider;
  }
  getIncompleteProvider() {
    this._ensureCachedState();
    const result2 = /* @__PURE__ */ new Set();
    for (const [provider, items] of this.getItemsByProvider()) {
      if (items.length > 0 && items[0].container.incomplete) {
        result2.add(provider);
      }
    }
    return result2;
  }
  get stats() {
    this._ensureCachedState();
    return this._stats;
  }
  _ensureCachedState() {
    if (this._refilterKind !== 0) {
      this._createCachedState();
    }
  }
  _createCachedState() {
    this._itemsByProvider = /* @__PURE__ */ new Map();
    const labelLengths = [];
    const { leadingLineContent, characterCountDelta } = this._lineContext;
    let word2 = "";
    let wordLow = "";
    const source = this._refilterKind === 1 ? this._items : this._filteredItems;
    const target = [];
    const scoreFn = !this._options.filterGraceful || source.length > 2e3 ? fuzzyScore : fuzzyScoreGracefulAggressive;
    for (let i = 0; i < source.length; i++) {
      const item = source[i];
      if (item.isInvalid) {
        continue;
      }
      const arr = this._itemsByProvider.get(item.provider);
      if (arr) {
        arr.push(item);
      } else {
        this._itemsByProvider.set(item.provider, [item]);
      }
      const overwriteBefore = item.position.column - item.editStart.column;
      const wordLen = overwriteBefore + characterCountDelta - (item.position.column - this._column);
      if (word2.length !== wordLen) {
        word2 = wordLen === 0 ? "" : leadingLineContent.slice(-wordLen);
        wordLow = word2.toLowerCase();
      }
      item.word = word2;
      if (wordLen === 0) {
        item.score = FuzzyScore.Default;
      } else {
        let wordPos = 0;
        while (wordPos < overwriteBefore) {
          const ch = word2.charCodeAt(wordPos);
          if (ch === 32 || ch === 9) {
            wordPos += 1;
          } else {
            break;
          }
        }
        if (wordPos >= wordLen) {
          item.score = FuzzyScore.Default;
        } else if (typeof item.completion.filterText === "string") {
          const match2 = scoreFn(word2, wordLow, wordPos, item.completion.filterText, item.filterTextLow, 0, this._fuzzyScoreOptions);
          if (!match2) {
            continue;
          }
          if (compareIgnoreCase(item.completion.filterText, item.textLabel) === 0) {
            item.score = match2;
          } else {
            item.score = anyScore(word2, wordLow, wordPos, item.textLabel, item.labelLow, 0);
            item.score[0] = match2[0];
          }
        } else {
          const match2 = scoreFn(word2, wordLow, wordPos, item.textLabel, item.labelLow, 0, this._fuzzyScoreOptions);
          if (!match2) {
            continue;
          }
          item.score = match2;
        }
      }
      item.idx = i;
      item.distance = this._wordDistance.distance(item.position, item.completion);
      target.push(item);
      labelLengths.push(item.textLabel.length);
    }
    this._filteredItems = target.sort(this._snippetCompareFn);
    this._refilterKind = 0;
    this._stats = {
      pLabelLen: labelLengths.length ? quickSelect(labelLengths.length - 0.85, labelLengths, (a, b) => a - b) : 0
    };
  }
  static _compareCompletionItems(a, b) {
    if (a.score[0] > b.score[0]) {
      return -1;
    } else if (a.score[0] < b.score[0]) {
      return 1;
    } else if (a.distance < b.distance) {
      return -1;
    } else if (a.distance > b.distance) {
      return 1;
    } else if (a.idx < b.idx) {
      return -1;
    } else if (a.idx > b.idx) {
      return 1;
    } else {
      return 0;
    }
  }
  static _compareCompletionItemsSnippetsDown(a, b) {
    if (a.completion.kind !== b.completion.kind) {
      if (a.completion.kind === 27) {
        return 1;
      } else if (b.completion.kind === 27) {
        return -1;
      }
    }
    return CompletionModel._compareCompletionItems(a, b);
  }
  static _compareCompletionItemsSnippetsUp(a, b) {
    if (a.completion.kind !== b.completion.kind) {
      if (a.completion.kind === 27) {
        return -1;
      } else if (b.completion.kind === 27) {
        return 1;
      }
    }
    return CompletionModel._compareCompletionItems(a, b);
  }
}
var __decorate$13 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$11 = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$E = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class LineContext2 {
  static shouldAutoTrigger(editor2) {
    if (!editor2.hasModel()) {
      return false;
    }
    const model = editor2.getModel();
    const pos = editor2.getPosition();
    model.tokenization.tokenizeIfCheap(pos.lineNumber);
    const word2 = model.getWordAtPosition(pos);
    if (!word2) {
      return false;
    }
    if (word2.endColumn !== pos.column && word2.startColumn + 1 !== pos.column) {
      return false;
    }
    if (!isNaN(Number(word2.word))) {
      return false;
    }
    return true;
  }
  constructor(model, position, triggerOptions) {
    this.leadingLineContent = model.getLineContent(position.lineNumber).substr(0, position.column - 1);
    this.leadingWord = model.getWordUntilPosition(position);
    this.lineNumber = position.lineNumber;
    this.column = position.column;
    this.triggerOptions = triggerOptions;
  }
}
function canShowQuickSuggest(editor2, contextKeyService, configurationService) {
  if (!Boolean(contextKeyService.getContextKeyValue(InlineCompletionContextKeys.inlineSuggestionVisible.key))) {
    return true;
  }
  const suppressSuggestions = contextKeyService.getContextKeyValue(InlineCompletionContextKeys.suppressSuggestions.key);
  if (suppressSuggestions !== void 0) {
    return !suppressSuggestions;
  }
  return !editor2.getOption(
    61
    /* EditorOption.inlineSuggest */
  ).suppressSuggestions;
}
function canShowSuggestOnTriggerCharacters(editor2, contextKeyService, configurationService) {
  if (!Boolean(contextKeyService.getContextKeyValue("inlineSuggestionVisible"))) {
    return true;
  }
  const suppressSuggestions = contextKeyService.getContextKeyValue(InlineCompletionContextKeys.suppressSuggestions.key);
  if (suppressSuggestions !== void 0) {
    return !suppressSuggestions;
  }
  return !editor2.getOption(
    61
    /* EditorOption.inlineSuggest */
  ).suppressSuggestions;
}
let SuggestModel = class SuggestModel2 {
  constructor(_editor, _editorWorkerService, _clipboardService, _telemetryService, _logService, _contextKeyService, _configurationService, _languageFeaturesService, _envService) {
    this._editor = _editor;
    this._editorWorkerService = _editorWorkerService;
    this._clipboardService = _clipboardService;
    this._telemetryService = _telemetryService;
    this._logService = _logService;
    this._contextKeyService = _contextKeyService;
    this._configurationService = _configurationService;
    this._languageFeaturesService = _languageFeaturesService;
    this._envService = _envService;
    this._toDispose = new DisposableStore();
    this._triggerCharacterListener = new DisposableStore();
    this._triggerQuickSuggest = new TimeoutTimer();
    this._triggerState = void 0;
    this._completionDisposables = new DisposableStore();
    this._onDidCancel = new Emitter$1();
    this._onDidTrigger = new Emitter$1();
    this._onDidSuggest = new Emitter$1();
    this.onDidCancel = this._onDidCancel.event;
    this.onDidTrigger = this._onDidTrigger.event;
    this.onDidSuggest = this._onDidSuggest.event;
    this._telemetryGate = 0;
    this._currentSelection = this._editor.getSelection() || new Selection$1(1, 1, 1, 1);
    this._toDispose.add(this._editor.onDidChangeModel(() => {
      this._updateTriggerCharacters();
      this.cancel();
    }));
    this._toDispose.add(this._editor.onDidChangeModelLanguage(() => {
      this._updateTriggerCharacters();
      this.cancel();
    }));
    this._toDispose.add(this._editor.onDidChangeConfiguration(() => {
      this._updateTriggerCharacters();
    }));
    this._toDispose.add(this._languageFeaturesService.completionProvider.onDidChange(() => {
      this._updateTriggerCharacters();
      this._updateActiveSuggestSession();
    }));
    let editorIsComposing = false;
    this._toDispose.add(this._editor.onDidCompositionStart(() => {
      editorIsComposing = true;
    }));
    this._toDispose.add(this._editor.onDidCompositionEnd(() => {
      editorIsComposing = false;
      this._onCompositionEnd();
    }));
    this._toDispose.add(this._editor.onDidChangeCursorSelection((e) => {
      if (!editorIsComposing) {
        this._onCursorChange(e);
      }
    }));
    this._toDispose.add(this._editor.onDidChangeModelContent(() => {
      if (!editorIsComposing && this._triggerState !== void 0) {
        this._refilterCompletionItems();
      }
    }));
    this._updateTriggerCharacters();
  }
  dispose() {
    dispose(this._triggerCharacterListener);
    dispose([this._onDidCancel, this._onDidSuggest, this._onDidTrigger, this._triggerQuickSuggest]);
    this._toDispose.dispose();
    this._completionDisposables.dispose();
    this.cancel();
  }
  _updateTriggerCharacters() {
    this._triggerCharacterListener.clear();
    if (this._editor.getOption(
      89
      /* EditorOption.readOnly */
    ) || !this._editor.hasModel() || !this._editor.getOption(
      119
      /* EditorOption.suggestOnTriggerCharacters */
    )) {
      return;
    }
    const supportsByTriggerCharacter = /* @__PURE__ */ new Map();
    for (const support of this._languageFeaturesService.completionProvider.all(this._editor.getModel())) {
      for (const ch of support.triggerCharacters || []) {
        let set2 = supportsByTriggerCharacter.get(ch);
        if (!set2) {
          set2 = /* @__PURE__ */ new Set();
          set2.add(getSnippetSuggestSupport());
          supportsByTriggerCharacter.set(ch, set2);
        }
        set2.add(support);
      }
    }
    const checkTriggerCharacter = (text2) => {
      var _a2;
      if (!canShowSuggestOnTriggerCharacters(this._editor, this._contextKeyService, this._configurationService)) {
        return;
      }
      if (LineContext2.shouldAutoTrigger(this._editor)) {
        return;
      }
      if (!text2) {
        const position = this._editor.getPosition();
        const model = this._editor.getModel();
        text2 = model.getLineContent(position.lineNumber).substr(0, position.column - 1);
      }
      let lastChar = "";
      if (isLowSurrogate(text2.charCodeAt(text2.length - 1))) {
        if (isHighSurrogate(text2.charCodeAt(text2.length - 2))) {
          lastChar = text2.substr(text2.length - 2);
        }
      } else {
        lastChar = text2.charAt(text2.length - 1);
      }
      const supports = supportsByTriggerCharacter.get(lastChar);
      if (supports) {
        const providerItemsToReuse = /* @__PURE__ */ new Map();
        if (this._completionModel) {
          for (const [provider, items] of this._completionModel.getItemsByProvider()) {
            if (!supports.has(provider)) {
              providerItemsToReuse.set(provider, items);
            }
          }
        }
        this.trigger({
          auto: true,
          triggerKind: 1,
          triggerCharacter: lastChar,
          retrigger: Boolean(this._completionModel),
          clipboardText: (_a2 = this._completionModel) === null || _a2 === void 0 ? void 0 : _a2.clipboardText,
          completionOptions: { providerFilter: supports, providerItemsToReuse }
        });
      }
    };
    this._triggerCharacterListener.add(this._editor.onDidType(checkTriggerCharacter));
    this._triggerCharacterListener.add(this._editor.onDidCompositionEnd(() => checkTriggerCharacter()));
  }
  // --- trigger/retrigger/cancel suggest
  get state() {
    if (!this._triggerState) {
      return 0;
    } else if (!this._triggerState.auto) {
      return 1;
    } else {
      return 2;
    }
  }
  cancel(retrigger = false) {
    var _a2;
    if (this._triggerState !== void 0) {
      this._triggerQuickSuggest.cancel();
      (_a2 = this._requestToken) === null || _a2 === void 0 ? void 0 : _a2.cancel();
      this._requestToken = void 0;
      this._triggerState = void 0;
      this._completionModel = void 0;
      this._context = void 0;
      this._onDidCancel.fire({ retrigger });
    }
  }
  clear() {
    this._completionDisposables.clear();
  }
  _updateActiveSuggestSession() {
    if (this._triggerState !== void 0) {
      if (!this._editor.hasModel() || !this._languageFeaturesService.completionProvider.has(this._editor.getModel())) {
        this.cancel();
      } else {
        this.trigger({ auto: this._triggerState.auto, retrigger: true });
      }
    }
  }
  _onCursorChange(e) {
    if (!this._editor.hasModel()) {
      return;
    }
    const prevSelection = this._currentSelection;
    this._currentSelection = this._editor.getSelection();
    if (!e.selection.isEmpty() || e.reason !== 0 && e.reason !== 3 || e.source !== "keyboard" && e.source !== "deleteLeft") {
      this.cancel();
      return;
    }
    if (this._triggerState === void 0 && e.reason === 0) {
      if (prevSelection.containsRange(this._currentSelection) || prevSelection.getEndPosition().isBeforeOrEqual(this._currentSelection.getPosition())) {
        this._doTriggerQuickSuggest();
      }
    } else if (this._triggerState !== void 0 && e.reason === 3) {
      this._refilterCompletionItems();
    }
  }
  _onCompositionEnd() {
    if (this._triggerState === void 0) {
      this._doTriggerQuickSuggest();
    } else {
      this._refilterCompletionItems();
    }
  }
  _doTriggerQuickSuggest() {
    var _a2;
    if (QuickSuggestionsOptions.isAllOff(this._editor.getOption(
      87
      /* EditorOption.quickSuggestions */
    ))) {
      return;
    }
    if (this._editor.getOption(
      116
      /* EditorOption.suggest */
    ).snippetsPreventQuickSuggestions && ((_a2 = SnippetController2.get(this._editor)) === null || _a2 === void 0 ? void 0 : _a2.isInSnippet())) {
      return;
    }
    this.cancel();
    this._triggerQuickSuggest.cancelAndSet(() => {
      if (this._triggerState !== void 0) {
        return;
      }
      if (!LineContext2.shouldAutoTrigger(this._editor)) {
        return;
      }
      if (!this._editor.hasModel() || !this._editor.hasWidgetFocus()) {
        return;
      }
      const model = this._editor.getModel();
      const pos = this._editor.getPosition();
      const config2 = this._editor.getOption(
        87
        /* EditorOption.quickSuggestions */
      );
      if (QuickSuggestionsOptions.isAllOff(config2)) {
        return;
      }
      if (!QuickSuggestionsOptions.isAllOn(config2)) {
        model.tokenization.tokenizeIfCheap(pos.lineNumber);
        const lineTokens = model.tokenization.getLineTokens(pos.lineNumber);
        const tokenType = lineTokens.getStandardTokenType(lineTokens.findTokenIndexAtOffset(Math.max(pos.column - 1 - 1, 0)));
        if (QuickSuggestionsOptions.valueFor(config2, tokenType) !== "on") {
          return;
        }
      }
      if (!canShowQuickSuggest(this._editor, this._contextKeyService, this._configurationService)) {
        return;
      }
      if (!this._languageFeaturesService.completionProvider.has(model)) {
        return;
      }
      this.trigger({ auto: true });
    }, this._editor.getOption(
      88
      /* EditorOption.quickSuggestionsDelay */
    ));
  }
  _refilterCompletionItems() {
    assertType(this._editor.hasModel());
    assertType(this._triggerState !== void 0);
    const model = this._editor.getModel();
    const position = this._editor.getPosition();
    const ctx = new LineContext2(model, position, Object.assign(Object.assign({}, this._triggerState), { refilter: true }));
    this._onNewContext(ctx);
  }
  trigger(options) {
    var _a2, _b2, _c2, _d2, _e2, _f2;
    if (!this._editor.hasModel()) {
      return;
    }
    const model = this._editor.getModel();
    const ctx = new LineContext2(model, this._editor.getPosition(), options);
    this.cancel(options.retrigger);
    this._triggerState = options;
    this._onDidTrigger.fire({ auto: options.auto, shy: (_a2 = options.shy) !== null && _a2 !== void 0 ? _a2 : false, position: this._editor.getPosition() });
    this._context = ctx;
    let suggestCtx = {
      triggerKind: (_b2 = options.triggerKind) !== null && _b2 !== void 0 ? _b2 : 0
      /* CompletionTriggerKind.Invoke */
    };
    if (options.triggerCharacter) {
      suggestCtx = {
        triggerKind: 1,
        triggerCharacter: options.triggerCharacter
      };
    }
    this._requestToken = new CancellationTokenSource$1();
    const snippetSuggestions = this._editor.getOption(
      110
      /* EditorOption.snippetSuggestions */
    );
    let snippetSortOrder = 1;
    switch (snippetSuggestions) {
      case "top":
        snippetSortOrder = 0;
        break;
      case "bottom":
        snippetSortOrder = 2;
        break;
    }
    const { itemKind: itemKindFilter, showDeprecated } = SuggestModel2._createSuggestFilter(this._editor);
    const completionOptions = new CompletionOptions(snippetSortOrder, (_d2 = (_c2 = options.completionOptions) === null || _c2 === void 0 ? void 0 : _c2.kindFilter) !== null && _d2 !== void 0 ? _d2 : itemKindFilter, (_e2 = options.completionOptions) === null || _e2 === void 0 ? void 0 : _e2.providerFilter, (_f2 = options.completionOptions) === null || _f2 === void 0 ? void 0 : _f2.providerItemsToReuse, showDeprecated);
    const wordDistance = WordDistance.create(this._editorWorkerService, this._editor);
    const completions = provideSuggestionItems(this._languageFeaturesService.completionProvider, model, this._editor.getPosition(), completionOptions, suggestCtx, this._requestToken.token);
    Promise.all([completions, wordDistance]).then(([completions2, wordDistance2]) => __awaiter$E(this, void 0, void 0, function* () {
      var _g2;
      (_g2 = this._requestToken) === null || _g2 === void 0 ? void 0 : _g2.dispose();
      if (!this._editor.hasModel()) {
        return;
      }
      let clipboardText = options === null || options === void 0 ? void 0 : options.clipboardText;
      if (!clipboardText && completions2.needsClipboard) {
        clipboardText = yield this._clipboardService.readText();
      }
      if (this._triggerState === void 0) {
        return;
      }
      const model2 = this._editor.getModel();
      const ctx2 = new LineContext2(model2, this._editor.getPosition(), options);
      const fuzzySearchOptions = Object.assign(Object.assign({}, FuzzyScoreOptions.default), { firstMatchCanBeWeak: !this._editor.getOption(
        116
        /* EditorOption.suggest */
      ).matchOnWordStartOnly });
      this._completionModel = new CompletionModel(completions2.items, this._context.column, {
        leadingLineContent: ctx2.leadingLineContent,
        characterCountDelta: ctx2.column - this._context.column
      }, wordDistance2, this._editor.getOption(
        116
        /* EditorOption.suggest */
      ), this._editor.getOption(
        110
        /* EditorOption.snippetSuggestions */
      ), fuzzySearchOptions, clipboardText);
      this._completionDisposables.add(completions2.disposable);
      this._onNewContext(ctx2);
      this._reportDurationsTelemetry(completions2.durations);
      if (!this._envService.isBuilt || this._envService.isExtensionDevelopment) {
        for (const item of completions2.items) {
          if (item.isInvalid) {
            this._logService.warn(`[suggest] did IGNORE invalid completion item from ${item.provider._debugDisplayName}`, item.completion);
          }
        }
      }
    })).catch(onUnexpectedError);
  }
  _reportDurationsTelemetry(durations) {
    if (this._telemetryGate++ % 230 !== 0) {
      return;
    }
    setTimeout(() => {
      this._telemetryService.publicLog2("suggest.durations.json", { data: JSON.stringify(durations) });
      this._logService.debug("suggest.durations.json", durations);
    });
  }
  static _createSuggestFilter(editor2) {
    const result2 = /* @__PURE__ */ new Set();
    const snippetSuggestions = editor2.getOption(
      110
      /* EditorOption.snippetSuggestions */
    );
    if (snippetSuggestions === "none") {
      result2.add(
        27
        /* CompletionItemKind.Snippet */
      );
    }
    const suggestOptions = editor2.getOption(
      116
      /* EditorOption.suggest */
    );
    if (!suggestOptions.showMethods) {
      result2.add(
        0
        /* CompletionItemKind.Method */
      );
    }
    if (!suggestOptions.showFunctions) {
      result2.add(
        1
        /* CompletionItemKind.Function */
      );
    }
    if (!suggestOptions.showConstructors) {
      result2.add(
        2
        /* CompletionItemKind.Constructor */
      );
    }
    if (!suggestOptions.showFields) {
      result2.add(
        3
        /* CompletionItemKind.Field */
      );
    }
    if (!suggestOptions.showVariables) {
      result2.add(
        4
        /* CompletionItemKind.Variable */
      );
    }
    if (!suggestOptions.showClasses) {
      result2.add(
        5
        /* CompletionItemKind.Class */
      );
    }
    if (!suggestOptions.showStructs) {
      result2.add(
        6
        /* CompletionItemKind.Struct */
      );
    }
    if (!suggestOptions.showInterfaces) {
      result2.add(
        7
        /* CompletionItemKind.Interface */
      );
    }
    if (!suggestOptions.showModules) {
      result2.add(
        8
        /* CompletionItemKind.Module */
      );
    }
    if (!suggestOptions.showProperties) {
      result2.add(
        9
        /* CompletionItemKind.Property */
      );
    }
    if (!suggestOptions.showEvents) {
      result2.add(
        10
        /* CompletionItemKind.Event */
      );
    }
    if (!suggestOptions.showOperators) {
      result2.add(
        11
        /* CompletionItemKind.Operator */
      );
    }
    if (!suggestOptions.showUnits) {
      result2.add(
        12
        /* CompletionItemKind.Unit */
      );
    }
    if (!suggestOptions.showValues) {
      result2.add(
        13
        /* CompletionItemKind.Value */
      );
    }
    if (!suggestOptions.showConstants) {
      result2.add(
        14
        /* CompletionItemKind.Constant */
      );
    }
    if (!suggestOptions.showEnums) {
      result2.add(
        15
        /* CompletionItemKind.Enum */
      );
    }
    if (!suggestOptions.showEnumMembers) {
      result2.add(
        16
        /* CompletionItemKind.EnumMember */
      );
    }
    if (!suggestOptions.showKeywords) {
      result2.add(
        17
        /* CompletionItemKind.Keyword */
      );
    }
    if (!suggestOptions.showWords) {
      result2.add(
        18
        /* CompletionItemKind.Text */
      );
    }
    if (!suggestOptions.showColors) {
      result2.add(
        19
        /* CompletionItemKind.Color */
      );
    }
    if (!suggestOptions.showFiles) {
      result2.add(
        20
        /* CompletionItemKind.File */
      );
    }
    if (!suggestOptions.showReferences) {
      result2.add(
        21
        /* CompletionItemKind.Reference */
      );
    }
    if (!suggestOptions.showColors) {
      result2.add(
        22
        /* CompletionItemKind.Customcolor */
      );
    }
    if (!suggestOptions.showFolders) {
      result2.add(
        23
        /* CompletionItemKind.Folder */
      );
    }
    if (!suggestOptions.showTypeParameters) {
      result2.add(
        24
        /* CompletionItemKind.TypeParameter */
      );
    }
    if (!suggestOptions.showSnippets) {
      result2.add(
        27
        /* CompletionItemKind.Snippet */
      );
    }
    if (!suggestOptions.showUsers) {
      result2.add(
        25
        /* CompletionItemKind.User */
      );
    }
    if (!suggestOptions.showIssues) {
      result2.add(
        26
        /* CompletionItemKind.Issue */
      );
    }
    return { itemKind: result2, showDeprecated: suggestOptions.showDeprecated };
  }
  _onNewContext(ctx) {
    if (!this._context) {
      return;
    }
    if (ctx.lineNumber !== this._context.lineNumber) {
      this.cancel();
      return;
    }
    if (getLeadingWhitespace(ctx.leadingLineContent) !== getLeadingWhitespace(this._context.leadingLineContent)) {
      this.cancel();
      return;
    }
    if (ctx.column < this._context.column) {
      if (ctx.leadingWord.word) {
        this.trigger({ auto: this._context.triggerOptions.auto, retrigger: true });
      } else {
        this.cancel();
      }
      return;
    }
    if (!this._completionModel) {
      return;
    }
    if (ctx.leadingWord.word.length !== 0 && ctx.leadingWord.startColumn > this._context.leadingWord.startColumn) {
      const shouldAutoTrigger = LineContext2.shouldAutoTrigger(this._editor);
      if (shouldAutoTrigger && this._context) {
        const map2 = this._completionModel.getItemsByProvider();
        this.trigger({
          auto: this._context.triggerOptions.auto,
          retrigger: true,
          clipboardText: this._completionModel.clipboardText,
          completionOptions: { providerItemsToReuse: map2 }
        });
      }
      return;
    }
    if (ctx.column > this._context.column && this._completionModel.getIncompleteProvider().size > 0 && ctx.leadingWord.word.length !== 0) {
      const providerItemsToReuse = /* @__PURE__ */ new Map();
      const providerFilter = /* @__PURE__ */ new Set();
      for (const [provider, items] of this._completionModel.getItemsByProvider()) {
        if (items.length > 0 && items[0].container.incomplete) {
          providerFilter.add(provider);
        } else {
          providerItemsToReuse.set(provider, items);
        }
      }
      this.trigger({
        auto: this._context.triggerOptions.auto,
        triggerKind: 2,
        retrigger: true,
        clipboardText: this._completionModel.clipboardText,
        completionOptions: { providerFilter, providerItemsToReuse }
      });
    } else {
      const oldLineContext = this._completionModel.lineContext;
      let isFrozen2 = false;
      this._completionModel.lineContext = {
        leadingLineContent: ctx.leadingLineContent,
        characterCountDelta: ctx.column - this._context.column
      };
      if (this._completionModel.items.length === 0) {
        const shouldAutoTrigger = LineContext2.shouldAutoTrigger(this._editor);
        if (!this._context) {
          this.cancel();
          return;
        }
        if (shouldAutoTrigger && this._context.leadingWord.endColumn < ctx.leadingWord.startColumn) {
          this.trigger({ auto: this._context.triggerOptions.auto, retrigger: true });
          return;
        }
        if (!this._context.triggerOptions.auto) {
          this._completionModel.lineContext = oldLineContext;
          isFrozen2 = this._completionModel.items.length > 0;
          if (isFrozen2 && ctx.leadingWord.word.length === 0) {
            this.cancel();
            return;
          }
        } else {
          this.cancel();
          return;
        }
      }
      this._onDidSuggest.fire({
        completionModel: this._completionModel,
        triggerOptions: ctx.triggerOptions,
        isFrozen: isFrozen2
      });
    }
  }
};
SuggestModel = __decorate$13([
  __param$11(1, IEditorWorkerService),
  __param$11(2, IClipboardService),
  __param$11(3, ITelemetryService),
  __param$11(4, ILogService),
  __param$11(5, IContextKeyService),
  __param$11(6, IConfigurationService),
  __param$11(7, ILanguageFeaturesService),
  __param$11(8, IEnvironmentService)
], SuggestModel);
class OvertypingCapturer {
  constructor(editor2, suggestModel) {
    this._disposables = new DisposableStore();
    this._lastOvertyped = [];
    this._locked = false;
    this._disposables.add(editor2.onWillType(() => {
      if (this._locked || !editor2.hasModel()) {
        return;
      }
      const selections2 = editor2.getSelections();
      const selectionsLength = selections2.length;
      let willOvertype = false;
      for (let i = 0; i < selectionsLength; i++) {
        if (!selections2[i].isEmpty()) {
          willOvertype = true;
          break;
        }
      }
      if (!willOvertype) {
        if (this._lastOvertyped.length !== 0) {
          this._lastOvertyped.length = 0;
        }
        return;
      }
      this._lastOvertyped = [];
      const model = editor2.getModel();
      for (let i = 0; i < selectionsLength; i++) {
        const selection = selections2[i];
        if (model.getValueLengthInRange(selection) > OvertypingCapturer._maxSelectionLength) {
          return;
        }
        this._lastOvertyped[i] = { value: model.getValueInRange(selection), multiline: selection.startLineNumber !== selection.endLineNumber };
      }
    }));
    this._disposables.add(suggestModel.onDidTrigger((e) => {
      this._locked = true;
    }));
    this._disposables.add(suggestModel.onDidCancel((e) => {
      this._locked = false;
    }));
  }
  getLastOvertypedInfo(idx) {
    if (idx >= 0 && idx < this._lastOvertyped.length) {
      return this._lastOvertyped[idx];
    }
    return void 0;
  }
  dispose() {
    this._disposables.dispose();
  }
}
OvertypingCapturer._maxSelectionLength = 51200;
const suggest = "";
var __decorate$12 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$10 = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
class StatusBarViewItem2 extends MenuEntryActionViewItem {
  updateLabel() {
    const kb = this._keybindingService.lookupKeybinding(this._action.id, this._contextKeyService);
    if (!kb) {
      return super.updateLabel();
    }
    if (this.label) {
      this.label.textContent = localize({ key: "content", comment: ["A label", "A keybinding"] }, "{0} ({1})", this._action.label, StatusBarViewItem2.symbolPrintEnter(kb));
    }
  }
  static symbolPrintEnter(kb) {
    var _a2;
    return (_a2 = kb.getLabel()) === null || _a2 === void 0 ? void 0 : _a2.replace(/\benter\b/gi, "⏎");
  }
}
let SuggestWidgetStatus = class SuggestWidgetStatus2 {
  constructor(container2, _menuId, instantiationService, _menuService, _contextKeyService) {
    this._menuId = _menuId;
    this._menuService = _menuService;
    this._contextKeyService = _contextKeyService;
    this._menuDisposables = new DisposableStore();
    this.element = append$1(container2, $$d(".suggest-status-bar"));
    const actionViewItemProvider = (action) => {
      return action instanceof MenuItemAction ? instantiationService.createInstance(StatusBarViewItem2, action, void 0) : void 0;
    };
    this._leftActions = new ActionBar(this.element, { actionViewItemProvider });
    this._rightActions = new ActionBar(this.element, { actionViewItemProvider });
    this._leftActions.domNode.classList.add("left");
    this._rightActions.domNode.classList.add("right");
  }
  dispose() {
    this._menuDisposables.dispose();
    this.element.remove();
  }
  show() {
    const menu = this._menuService.createMenu(this._menuId, this._contextKeyService);
    const renderMenu = () => {
      const left = [];
      const right = [];
      for (const [group2, actions] of menu.getActions()) {
        if (group2 === "left") {
          left.push(...actions);
        } else {
          right.push(...actions);
        }
      }
      this._leftActions.clear();
      this._leftActions.push(left);
      this._rightActions.clear();
      this._rightActions.push(right);
    };
    this._menuDisposables.add(menu.onDidChange(() => renderMenu()));
    this._menuDisposables.add(menu);
  }
  hide() {
    this._menuDisposables.clear();
  }
};
SuggestWidgetStatus = __decorate$12([
  __param$10(2, IInstantiationService),
  __param$10(3, IMenuService),
  __param$10(4, IContextKeyService)
], SuggestWidgetStatus);
var __decorate$11 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$$ = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
function canExpandCompletionItem(item) {
  return !!item && Boolean(item.completion.documentation || item.completion.detail && item.completion.detail !== item.completion.label);
}
let SuggestDetailsWidget = class SuggestDetailsWidget2 {
  constructor(_editor, instaService) {
    this._editor = _editor;
    this._onDidClose = new Emitter$1();
    this.onDidClose = this._onDidClose.event;
    this._onDidChangeContents = new Emitter$1();
    this.onDidChangeContents = this._onDidChangeContents.event;
    this._disposables = new DisposableStore();
    this._renderDisposeable = new DisposableStore();
    this._borderWidth = 1;
    this._size = new Dimension(330, 0);
    this.domNode = $$d(".suggest-details");
    this.domNode.classList.add("no-docs");
    this._markdownRenderer = instaService.createInstance(MarkdownRenderer, { editor: _editor });
    this._body = $$d(".body");
    this._scrollbar = new DomScrollableElement(this._body, {
      alwaysConsumeMouseWheel: true
    });
    append$1(this.domNode, this._scrollbar.getDomNode());
    this._disposables.add(this._scrollbar);
    this._header = append$1(this._body, $$d(".header"));
    this._close = append$1(this._header, $$d("span" + ThemeIcon.asCSSSelector(Codicon.close)));
    this._close.title = localize("details.close", "Close");
    this._type = append$1(this._header, $$d("p.type"));
    this._docs = append$1(this._body, $$d("p.docs"));
    this._configureFont();
    this._disposables.add(this._editor.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        49
        /* EditorOption.fontInfo */
      )) {
        this._configureFont();
      }
    }));
  }
  dispose() {
    this._disposables.dispose();
    this._renderDisposeable.dispose();
  }
  _configureFont() {
    const options = this._editor.getOptions();
    const fontInfo = options.get(
      49
      /* EditorOption.fontInfo */
    );
    const fontFamily = fontInfo.getMassagedFontFamily();
    const fontSize = options.get(
      117
      /* EditorOption.suggestFontSize */
    ) || fontInfo.fontSize;
    const lineHeight = options.get(
      118
      /* EditorOption.suggestLineHeight */
    ) || fontInfo.lineHeight;
    const fontWeight = fontInfo.fontWeight;
    const fontSizePx = `${fontSize}px`;
    const lineHeightPx = `${lineHeight}px`;
    this.domNode.style.fontSize = fontSizePx;
    this.domNode.style.lineHeight = `${lineHeight / fontSize}`;
    this.domNode.style.fontWeight = fontWeight;
    this.domNode.style.fontFeatureSettings = fontInfo.fontFeatureSettings;
    this._type.style.fontFamily = fontFamily;
    this._close.style.height = lineHeightPx;
    this._close.style.width = lineHeightPx;
  }
  getLayoutInfo() {
    const lineHeight = this._editor.getOption(
      118
      /* EditorOption.suggestLineHeight */
    ) || this._editor.getOption(
      49
      /* EditorOption.fontInfo */
    ).lineHeight;
    const borderWidth = this._borderWidth;
    const borderHeight = borderWidth * 2;
    return {
      lineHeight,
      borderWidth,
      borderHeight,
      verticalPadding: 22,
      horizontalPadding: 14
    };
  }
  renderLoading() {
    this._type.textContent = localize("loading", "Loading...");
    this._docs.textContent = "";
    this.domNode.classList.remove("no-docs", "no-type");
    this.layout(this.size.width, this.getLayoutInfo().lineHeight * 2);
    this._onDidChangeContents.fire(this);
  }
  renderItem(item, explainMode) {
    var _a2, _b2;
    this._renderDisposeable.clear();
    let { detail, documentation } = item.completion;
    if (explainMode) {
      let md = "";
      md += `score: ${item.score[0]}
`;
      md += `prefix: ${(_a2 = item.word) !== null && _a2 !== void 0 ? _a2 : "(no prefix)"}
`;
      md += `word: ${item.completion.filterText ? item.completion.filterText + " (filterText)" : item.textLabel}
`;
      md += `distance: ${item.distance} (localityBonus-setting)
`;
      md += `index: ${item.idx}, based on ${item.completion.sortText && `sortText: "${item.completion.sortText}"` || "label"}
`;
      md += `commit_chars: ${(_b2 = item.completion.commitCharacters) === null || _b2 === void 0 ? void 0 : _b2.join("")}
`;
      documentation = new MarkdownString().appendCodeblock("empty", md);
      detail = `Provider: ${item.provider._debugDisplayName}`;
    }
    if (!explainMode && !canExpandCompletionItem(item)) {
      this.clearContents();
      return;
    }
    this.domNode.classList.remove("no-docs", "no-type");
    if (detail) {
      const cappedDetail = detail.length > 1e5 ? `${detail.substr(0, 1e5)}…` : detail;
      this._type.textContent = cappedDetail;
      this._type.title = cappedDetail;
      show(this._type);
      this._type.classList.toggle("auto-wrap", !/\r?\n^\s+/gmi.test(cappedDetail));
    } else {
      clearNode(this._type);
      this._type.title = "";
      hide(this._type);
      this.domNode.classList.add("no-type");
    }
    clearNode(this._docs);
    if (typeof documentation === "string") {
      this._docs.classList.remove("markdown-docs");
      this._docs.textContent = documentation;
    } else if (documentation) {
      this._docs.classList.add("markdown-docs");
      clearNode(this._docs);
      const renderedContents = this._markdownRenderer.render(documentation);
      this._docs.appendChild(renderedContents.element);
      this._renderDisposeable.add(renderedContents);
      this._renderDisposeable.add(this._markdownRenderer.onDidRenderAsync(() => {
        this.layout(this._size.width, this._type.clientHeight + this._docs.clientHeight);
        this._onDidChangeContents.fire(this);
      }));
    }
    this.domNode.style.userSelect = "text";
    this.domNode.tabIndex = -1;
    this._close.onmousedown = (e) => {
      e.preventDefault();
      e.stopPropagation();
    };
    this._close.onclick = (e) => {
      e.preventDefault();
      e.stopPropagation();
      this._onDidClose.fire();
    };
    this._body.scrollTop = 0;
    this.layout(this._size.width, this._type.clientHeight + this._docs.clientHeight);
    this._onDidChangeContents.fire(this);
  }
  clearContents() {
    this.domNode.classList.add("no-docs");
    this._type.textContent = "";
    this._docs.textContent = "";
  }
  get size() {
    return this._size;
  }
  layout(width, height) {
    const newSize = new Dimension(width, height);
    if (!Dimension.equals(newSize, this._size)) {
      this._size = newSize;
      size(this.domNode, width, height);
    }
    this._scrollbar.scanDomNode();
  }
  scrollDown(much = 8) {
    this._body.scrollTop += much;
  }
  scrollUp(much = 8) {
    this._body.scrollTop -= much;
  }
  scrollTop() {
    this._body.scrollTop = 0;
  }
  scrollBottom() {
    this._body.scrollTop = this._body.scrollHeight;
  }
  pageDown() {
    this.scrollDown(80);
  }
  pageUp() {
    this.scrollUp(80);
  }
  set borderWidth(width) {
    this._borderWidth = width;
  }
  get borderWidth() {
    return this._borderWidth;
  }
};
SuggestDetailsWidget = __decorate$11([
  __param$$(1, IInstantiationService)
], SuggestDetailsWidget);
class SuggestDetailsOverlay {
  constructor(widget, _editor) {
    this.widget = widget;
    this._editor = _editor;
    this._disposables = new DisposableStore();
    this._added = false;
    this._preferAlignAtTop = true;
    this._resizable = new ResizableHTMLElement();
    this._resizable.domNode.classList.add("suggest-details-container");
    this._resizable.domNode.appendChild(widget.domNode);
    this._resizable.enableSashes(false, true, true, false);
    let topLeftNow;
    let sizeNow;
    let deltaTop = 0;
    let deltaLeft = 0;
    this._disposables.add(this._resizable.onDidWillResize(() => {
      topLeftNow = this._topLeft;
      sizeNow = this._resizable.size;
    }));
    this._disposables.add(this._resizable.onDidResize((e) => {
      if (topLeftNow && sizeNow) {
        this.widget.layout(e.dimension.width, e.dimension.height);
        let updateTopLeft = false;
        if (e.west) {
          deltaLeft = sizeNow.width - e.dimension.width;
          updateTopLeft = true;
        }
        if (e.north) {
          deltaTop = sizeNow.height - e.dimension.height;
          updateTopLeft = true;
        }
        if (updateTopLeft) {
          this._applyTopLeft({
            top: topLeftNow.top + deltaTop,
            left: topLeftNow.left + deltaLeft
          });
        }
      }
      if (e.done) {
        topLeftNow = void 0;
        sizeNow = void 0;
        deltaTop = 0;
        deltaLeft = 0;
        this._userSize = e.dimension;
      }
    }));
    this._disposables.add(this.widget.onDidChangeContents(() => {
      var _a2;
      if (this._anchorBox) {
        this._placeAtAnchor(this._anchorBox, (_a2 = this._userSize) !== null && _a2 !== void 0 ? _a2 : this.widget.size, this._preferAlignAtTop);
      }
    }));
  }
  dispose() {
    this._resizable.dispose();
    this._disposables.dispose();
    this.hide();
  }
  getId() {
    return "suggest.details";
  }
  getDomNode() {
    return this._resizable.domNode;
  }
  getPosition() {
    return null;
  }
  show() {
    if (!this._added) {
      this._editor.addOverlayWidget(this);
      this.getDomNode().style.position = "fixed";
      this._added = true;
    }
  }
  hide(sessionEnded = false) {
    this._resizable.clearSashHoverState();
    if (this._added) {
      this._editor.removeOverlayWidget(this);
      this._added = false;
      this._anchorBox = void 0;
      this._topLeft = void 0;
    }
    if (sessionEnded) {
      this._userSize = void 0;
      this.widget.clearContents();
    }
  }
  placeAtAnchor(anchor, preferAlignAtTop) {
    var _a2;
    const anchorBox = anchor.getBoundingClientRect();
    this._anchorBox = anchorBox;
    this._preferAlignAtTop = preferAlignAtTop;
    this._placeAtAnchor(this._anchorBox, (_a2 = this._userSize) !== null && _a2 !== void 0 ? _a2 : this.widget.size, preferAlignAtTop);
  }
  _placeAtAnchor(anchorBox, size2, preferAlignAtTop) {
    var _a2;
    const bodyBox = getClientArea(document.body);
    const info = this.widget.getLayoutInfo();
    const defaultMinSize = new Dimension(220, 2 * info.lineHeight);
    const defaultTop = anchorBox.top;
    const eastPlacement = function() {
      const width = bodyBox.width - (anchorBox.left + anchorBox.width + info.borderWidth + info.horizontalPadding);
      const left = -info.borderWidth + anchorBox.left + anchorBox.width;
      const maxSizeTop = new Dimension(width, bodyBox.height - anchorBox.top - info.borderHeight - info.verticalPadding);
      const maxSizeBottom = maxSizeTop.with(void 0, anchorBox.top + anchorBox.height - info.borderHeight - info.verticalPadding);
      return { top: defaultTop, left, fit: width - size2.width, maxSizeTop, maxSizeBottom, minSize: defaultMinSize.with(Math.min(width, defaultMinSize.width)) };
    }();
    const westPlacement = function() {
      const width = anchorBox.left - info.borderWidth - info.horizontalPadding;
      const left = Math.max(info.horizontalPadding, anchorBox.left - size2.width - info.borderWidth);
      const maxSizeTop = new Dimension(width, bodyBox.height - anchorBox.top - info.borderHeight - info.verticalPadding);
      const maxSizeBottom = maxSizeTop.with(void 0, anchorBox.top + anchorBox.height - info.borderHeight - info.verticalPadding);
      return { top: defaultTop, left, fit: width - size2.width, maxSizeTop, maxSizeBottom, minSize: defaultMinSize.with(Math.min(width, defaultMinSize.width)) };
    }();
    const southPacement = function() {
      const left = anchorBox.left;
      const top = -info.borderWidth + anchorBox.top + anchorBox.height;
      const maxSizeBottom = new Dimension(anchorBox.width - info.borderHeight, bodyBox.height - anchorBox.top - anchorBox.height - info.verticalPadding);
      return { top, left, fit: maxSizeBottom.height - size2.height, maxSizeBottom, maxSizeTop: maxSizeBottom, minSize: defaultMinSize.with(maxSizeBottom.width) };
    }();
    const placements = [eastPlacement, westPlacement, southPacement];
    const placement = (_a2 = placements.find((p2) => p2.fit >= 0)) !== null && _a2 !== void 0 ? _a2 : placements.sort((a, b) => b.fit - a.fit)[0];
    const bottom = anchorBox.top + anchorBox.height - info.borderHeight;
    let alignAtTop;
    let height = size2.height;
    const maxHeight = Math.max(placement.maxSizeTop.height, placement.maxSizeBottom.height);
    if (height > maxHeight) {
      height = maxHeight;
    }
    let maxSize;
    if (preferAlignAtTop) {
      if (height <= placement.maxSizeTop.height) {
        alignAtTop = true;
        maxSize = placement.maxSizeTop;
      } else {
        alignAtTop = false;
        maxSize = placement.maxSizeBottom;
      }
    } else {
      if (height <= placement.maxSizeBottom.height) {
        alignAtTop = false;
        maxSize = placement.maxSizeBottom;
      } else {
        alignAtTop = true;
        maxSize = placement.maxSizeTop;
      }
    }
    this._applyTopLeft({ left: placement.left, top: alignAtTop ? placement.top : bottom - height });
    this.getDomNode().style.position = "fixed";
    this._resizable.enableSashes(!alignAtTop, placement === eastPlacement, alignAtTop, placement !== eastPlacement);
    this._resizable.minSize = placement.minSize;
    this._resizable.maxSize = maxSize;
    this._resizable.layout(height, Math.min(maxSize.width, size2.width));
    this.widget.layout(this._resizable.size.width, this._resizable.size.height);
  }
  _applyTopLeft(topLeft) {
    this._topLeft = topLeft;
    this.getDomNode().style.left = `${this._topLeft.left}px`;
    this.getDomNode().style.top = `${this._topLeft.top}px`;
  }
}
var FileKind;
(function(FileKind2) {
  FileKind2[FileKind2["FILE"] = 0] = "FILE";
  FileKind2[FileKind2["FOLDER"] = 1] = "FOLDER";
  FileKind2[FileKind2["ROOT_FOLDER"] = 2] = "ROOT_FOLDER";
})(FileKind || (FileKind = {}));
const fileIconDirectoryRegex = /(?:\/|^)(?:([^\/]+)\/)?([^\/]+)$/;
function getIconClasses(modelService, languageService, resource, fileKind) {
  const classes = fileKind === FileKind.ROOT_FOLDER ? ["rootfolder-icon"] : fileKind === FileKind.FOLDER ? ["folder-icon"] : ["file-icon"];
  if (resource) {
    let name;
    if (resource.scheme === Schemas.data) {
      const metadata = DataUri.parseMetaData(resource);
      name = metadata.get(DataUri.META_DATA_LABEL);
    } else {
      const match2 = resource.path.match(fileIconDirectoryRegex);
      if (match2) {
        name = cssEscape(match2[2].toLowerCase());
        if (match2[1]) {
          classes.push(`${cssEscape(match2[1].toLowerCase())}-name-dir-icon`);
        }
      } else {
        name = cssEscape(resource.authority.toLowerCase());
      }
    }
    if (fileKind === FileKind.FOLDER) {
      classes.push(`${name}-name-folder-icon`);
    } else {
      if (name) {
        classes.push(`${name}-name-file-icon`);
        classes.push(`name-file-icon`);
        if (name.length <= 255) {
          const dotSegments = name.split(".");
          for (let i = 1; i < dotSegments.length; i++) {
            classes.push(`${dotSegments.slice(i).join(".")}-ext-file-icon`);
          }
        }
        classes.push(`ext-file-icon`);
      }
      const detectedLanguageId = detectLanguageId(modelService, languageService, resource);
      if (detectedLanguageId) {
        classes.push(`${cssEscape(detectedLanguageId)}-lang-file-icon`);
      }
    }
  }
  return classes;
}
function detectLanguageId(modelService, languageService, resource) {
  if (!resource) {
    return null;
  }
  let languageId = null;
  if (resource.scheme === Schemas.data) {
    const metadata = DataUri.parseMetaData(resource);
    const mime = metadata.get(DataUri.META_DATA_MIME);
    if (mime) {
      languageId = languageService.getLanguageIdByMimeType(mime);
    }
  } else {
    const model = modelService.getModel(resource);
    if (model) {
      languageId = model.getLanguageId();
    }
  }
  if (languageId && languageId !== PLAINTEXT_LANGUAGE_ID) {
    return languageId;
  }
  return languageService.guessLanguageIdByFilepathOrFirstLine(resource);
}
function cssEscape(str2) {
  return str2.replace(/[\11\12\14\15\40]/g, "/");
}
var __decorate$10 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$_ = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var _a;
function getAriaId(index) {
  return `suggest-aria-id:${index}`;
}
const suggestMoreInfoIcon = registerIcon("suggest-more-info", Codicon.chevronRight, localize("suggestMoreInfoIcon", "Icon for more information in the suggest widget."));
const _completionItemColor = new (_a = class ColorExtractor {
  extract(item, out) {
    if (item.textLabel.match(ColorExtractor._regexStrict)) {
      out[0] = item.textLabel;
      return true;
    }
    if (item.completion.detail && item.completion.detail.match(ColorExtractor._regexStrict)) {
      out[0] = item.completion.detail;
      return true;
    }
    if (typeof item.completion.documentation === "string") {
      const match2 = ColorExtractor._regexRelaxed.exec(item.completion.documentation);
      if (match2 && (match2.index === 0 || match2.index + match2[0].length === item.completion.documentation.length)) {
        out[0] = match2[0];
        return true;
      }
    }
    return false;
  }
}, _a._regexRelaxed = /(#([\da-fA-F]{3}){1,2}|(rgb|hsl)a\(\s*(\d{1,3}%?\s*,\s*){3}(1|0?\.\d+)\)|(rgb|hsl)\(\s*\d{1,3}%?(\s*,\s*\d{1,3}%?){2}\s*\))/, _a._regexStrict = new RegExp(`^${_a._regexRelaxed.source}$`, "i"), _a)();
let ItemRenderer = class ItemRenderer2 {
  constructor(_editor, _modelService, _languageService, _themeService) {
    this._editor = _editor;
    this._modelService = _modelService;
    this._languageService = _languageService;
    this._themeService = _themeService;
    this._onDidToggleDetails = new Emitter$1();
    this.onDidToggleDetails = this._onDidToggleDetails.event;
    this.templateId = "suggestion";
  }
  dispose() {
    this._onDidToggleDetails.dispose();
  }
  renderTemplate(container2) {
    const disposables = new DisposableStore();
    const root3 = container2;
    root3.classList.add("show-file-icons");
    const icon = append$1(container2, $$d(".icon"));
    const colorspan = append$1(icon, $$d("span.colorspan"));
    const text2 = append$1(container2, $$d(".contents"));
    const main = append$1(text2, $$d(".main"));
    const iconContainer = append$1(main, $$d(".icon-label.codicon"));
    const left = append$1(main, $$d("span.left"));
    const right = append$1(main, $$d("span.right"));
    const iconLabel = new IconLabel(left, { supportHighlights: true, supportIcons: true });
    disposables.add(iconLabel);
    const parametersLabel = append$1(left, $$d("span.signature-label"));
    const qualifierLabel = append$1(left, $$d("span.qualifier-label"));
    const detailsLabel = append$1(right, $$d("span.details-label"));
    const readMore = append$1(right, $$d("span.readMore" + ThemeIcon.asCSSSelector(suggestMoreInfoIcon)));
    readMore.title = localize("readMore", "Read More");
    const configureFont = () => {
      const options = this._editor.getOptions();
      const fontInfo = options.get(
        49
        /* EditorOption.fontInfo */
      );
      const fontFamily = fontInfo.getMassagedFontFamily();
      const fontFeatureSettings = fontInfo.fontFeatureSettings;
      const fontSize = options.get(
        117
        /* EditorOption.suggestFontSize */
      ) || fontInfo.fontSize;
      const lineHeight = options.get(
        118
        /* EditorOption.suggestLineHeight */
      ) || fontInfo.lineHeight;
      const fontWeight = fontInfo.fontWeight;
      const letterSpacing = fontInfo.letterSpacing;
      const fontSizePx = `${fontSize}px`;
      const lineHeightPx = `${lineHeight}px`;
      const letterSpacingPx = `${letterSpacing}px`;
      root3.style.fontSize = fontSizePx;
      root3.style.fontWeight = fontWeight;
      root3.style.letterSpacing = letterSpacingPx;
      main.style.fontFamily = fontFamily;
      main.style.fontFeatureSettings = fontFeatureSettings;
      main.style.lineHeight = lineHeightPx;
      icon.style.height = lineHeightPx;
      icon.style.width = lineHeightPx;
      readMore.style.height = lineHeightPx;
      readMore.style.width = lineHeightPx;
    };
    configureFont();
    disposables.add(this._editor.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        49
        /* EditorOption.fontInfo */
      ) || e.hasChanged(
        117
        /* EditorOption.suggestFontSize */
      ) || e.hasChanged(
        118
        /* EditorOption.suggestLineHeight */
      )) {
        configureFont();
      }
    }));
    return { root: root3, left, right, icon, colorspan, iconLabel, iconContainer, parametersLabel, qualifierLabel, detailsLabel, readMore, disposables };
  }
  renderElement(element, index, data) {
    const { completion } = element;
    data.root.id = getAriaId(index);
    data.colorspan.style.backgroundColor = "";
    const labelOptions = {
      labelEscapeNewLines: true,
      matches: createMatches(element.score)
    };
    const color = [];
    if (completion.kind === 19 && _completionItemColor.extract(element, color)) {
      data.icon.className = "icon customcolor";
      data.iconContainer.className = "icon hide";
      data.colorspan.style.backgroundColor = color[0];
    } else if (completion.kind === 20 && this._themeService.getFileIconTheme().hasFileIcons) {
      data.icon.className = "icon hide";
      data.iconContainer.className = "icon hide";
      const labelClasses = getIconClasses(this._modelService, this._languageService, URI.from({ scheme: "fake", path: element.textLabel }), FileKind.FILE);
      const detailClasses = getIconClasses(this._modelService, this._languageService, URI.from({ scheme: "fake", path: completion.detail }), FileKind.FILE);
      labelOptions.extraClasses = labelClasses.length > detailClasses.length ? labelClasses : detailClasses;
    } else if (completion.kind === 23 && this._themeService.getFileIconTheme().hasFolderIcons) {
      data.icon.className = "icon hide";
      data.iconContainer.className = "icon hide";
      labelOptions.extraClasses = [
        getIconClasses(this._modelService, this._languageService, URI.from({ scheme: "fake", path: element.textLabel }), FileKind.FOLDER),
        getIconClasses(this._modelService, this._languageService, URI.from({ scheme: "fake", path: completion.detail }), FileKind.FOLDER)
      ].flat();
    } else {
      data.icon.className = "icon hide";
      data.iconContainer.className = "";
      data.iconContainer.classList.add("suggest-icon", ...ThemeIcon.asClassNameArray(CompletionItemKinds.toIcon(completion.kind)));
    }
    if (completion.tags && completion.tags.indexOf(
      1
      /* CompletionItemTag.Deprecated */
    ) >= 0) {
      labelOptions.extraClasses = (labelOptions.extraClasses || []).concat(["deprecated"]);
      labelOptions.matches = [];
    }
    data.iconLabel.setLabel(element.textLabel, void 0, labelOptions);
    if (typeof completion.label === "string") {
      data.parametersLabel.textContent = "";
      data.detailsLabel.textContent = stripNewLines(completion.detail || "");
      data.root.classList.add("string-label");
    } else {
      data.parametersLabel.textContent = stripNewLines(completion.label.detail || "");
      data.detailsLabel.textContent = stripNewLines(completion.label.description || "");
      data.root.classList.remove("string-label");
    }
    if (this._editor.getOption(
      116
      /* EditorOption.suggest */
    ).showInlineDetails) {
      show(data.detailsLabel);
    } else {
      hide(data.detailsLabel);
    }
    if (canExpandCompletionItem(element)) {
      data.right.classList.add("can-expand-details");
      show(data.readMore);
      data.readMore.onmousedown = (e) => {
        e.stopPropagation();
        e.preventDefault();
      };
      data.readMore.onclick = (e) => {
        e.stopPropagation();
        e.preventDefault();
        this._onDidToggleDetails.fire();
      };
    } else {
      data.right.classList.remove("can-expand-details");
      hide(data.readMore);
      data.readMore.onmousedown = null;
      data.readMore.onclick = null;
    }
  }
  disposeTemplate(templateData) {
    templateData.disposables.dispose();
  }
};
ItemRenderer = __decorate$10([
  __param$_(1, IModelService),
  __param$_(2, ILanguageService),
  __param$_(3, IThemeService)
], ItemRenderer);
function stripNewLines(str2) {
  return str2.replace(/\r\n|\r|\n/g, "");
}
var __decorate$$ = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$Z = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$D = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
registerColor("editorSuggestWidget.background", { dark: editorWidgetBackground, light: editorWidgetBackground, hcDark: editorWidgetBackground, hcLight: editorWidgetBackground }, localize("editorSuggestWidgetBackground", "Background color of the suggest widget."));
registerColor("editorSuggestWidget.border", { dark: editorWidgetBorder, light: editorWidgetBorder, hcDark: editorWidgetBorder, hcLight: editorWidgetBorder }, localize("editorSuggestWidgetBorder", "Border color of the suggest widget."));
const editorSuggestWidgetForeground = registerColor("editorSuggestWidget.foreground", { dark: editorForeground, light: editorForeground, hcDark: editorForeground, hcLight: editorForeground }, localize("editorSuggestWidgetForeground", "Foreground color of the suggest widget."));
registerColor("editorSuggestWidget.selectedForeground", { dark: quickInputListFocusForeground, light: quickInputListFocusForeground, hcDark: quickInputListFocusForeground, hcLight: quickInputListFocusForeground }, localize("editorSuggestWidgetSelectedForeground", "Foreground color of the selected entry in the suggest widget."));
registerColor("editorSuggestWidget.selectedIconForeground", { dark: quickInputListFocusIconForeground, light: quickInputListFocusIconForeground, hcDark: quickInputListFocusIconForeground, hcLight: quickInputListFocusIconForeground }, localize("editorSuggestWidgetSelectedIconForeground", "Icon foreground color of the selected entry in the suggest widget."));
const editorSuggestWidgetSelectedBackground = registerColor("editorSuggestWidget.selectedBackground", { dark: quickInputListFocusBackground, light: quickInputListFocusBackground, hcDark: quickInputListFocusBackground, hcLight: quickInputListFocusBackground }, localize("editorSuggestWidgetSelectedBackground", "Background color of the selected entry in the suggest widget."));
registerColor("editorSuggestWidget.highlightForeground", { dark: listHighlightForeground, light: listHighlightForeground, hcDark: listHighlightForeground, hcLight: listHighlightForeground }, localize("editorSuggestWidgetHighlightForeground", "Color of the match highlights in the suggest widget."));
registerColor("editorSuggestWidget.focusHighlightForeground", { dark: listFocusHighlightForeground, light: listFocusHighlightForeground, hcDark: listFocusHighlightForeground, hcLight: listFocusHighlightForeground }, localize("editorSuggestWidgetFocusHighlightForeground", "Color of the match highlights in the suggest widget when an item is focused."));
registerColor("editorSuggestWidgetStatus.foreground", { dark: transparent(editorSuggestWidgetForeground, 0.5), light: transparent(editorSuggestWidgetForeground, 0.5), hcDark: transparent(editorSuggestWidgetForeground, 0.5), hcLight: transparent(editorSuggestWidgetForeground, 0.5) }, localize("editorSuggestWidgetStatusForeground", "Foreground color of the suggest widget status."));
class PersistedWidgetSize {
  constructor(_service, editor2) {
    this._service = _service;
    this._key = `suggestWidget.size/${editor2.getEditorType()}/${editor2 instanceof EmbeddedCodeEditorWidget}`;
  }
  restore() {
    var _a2;
    const raw = (_a2 = this._service.get(
      this._key,
      0
      /* StorageScope.PROFILE */
    )) !== null && _a2 !== void 0 ? _a2 : "";
    try {
      const obj = JSON.parse(raw);
      if (Dimension.is(obj)) {
        return Dimension.lift(obj);
      }
    } catch (_b2) {
    }
    return void 0;
  }
  store(size2) {
    this._service.store(
      this._key,
      JSON.stringify(size2),
      0,
      1
      /* StorageTarget.MACHINE */
    );
  }
  reset() {
    this._service.remove(
      this._key,
      0
      /* StorageScope.PROFILE */
    );
  }
}
let SuggestWidget = class SuggestWidget2 {
  constructor(editor2, _storageService, _contextKeyService, _themeService, instantiationService) {
    this.editor = editor2;
    this._storageService = _storageService;
    this._state = 0;
    this._isAuto = false;
    this._pendingLayout = new MutableDisposable();
    this._pendingShowDetails = new MutableDisposable();
    this._ignoreFocusEvents = false;
    this._forceRenderingAbove = false;
    this._explainMode = false;
    this._showTimeout = new TimeoutTimer();
    this._disposables = new DisposableStore();
    this._onDidSelect = new PauseableEmitter();
    this._onDidFocus = new PauseableEmitter();
    this._onDidHide = new Emitter$1();
    this._onDidShow = new Emitter$1();
    this.onDidSelect = this._onDidSelect.event;
    this.onDidFocus = this._onDidFocus.event;
    this.onDidHide = this._onDidHide.event;
    this.onDidShow = this._onDidShow.event;
    this._onDetailsKeydown = new Emitter$1();
    this.onDetailsKeyDown = this._onDetailsKeydown.event;
    this.element = new ResizableHTMLElement();
    this.element.domNode.classList.add("editor-widget", "suggest-widget");
    this._contentWidget = new SuggestContentWidget(this, editor2);
    this._persistedSize = new PersistedWidgetSize(_storageService, editor2);
    class ResizeState {
      constructor(persistedSize, currentSize, persistHeight = false, persistWidth = false) {
        this.persistedSize = persistedSize;
        this.currentSize = currentSize;
        this.persistHeight = persistHeight;
        this.persistWidth = persistWidth;
      }
    }
    let state;
    this._disposables.add(this.element.onDidWillResize(() => {
      this._contentWidget.lockPreference();
      state = new ResizeState(this._persistedSize.restore(), this.element.size);
    }));
    this._disposables.add(this.element.onDidResize((e) => {
      var _a2, _b2, _c2, _d2;
      this._resize(e.dimension.width, e.dimension.height);
      if (state) {
        state.persistHeight = state.persistHeight || !!e.north || !!e.south;
        state.persistWidth = state.persistWidth || !!e.east || !!e.west;
      }
      if (!e.done) {
        return;
      }
      if (state) {
        const { itemHeight, defaultSize } = this.getLayoutInfo();
        const threshold = Math.round(itemHeight / 2);
        let { width, height } = this.element.size;
        if (!state.persistHeight || Math.abs(state.currentSize.height - height) <= threshold) {
          height = (_b2 = (_a2 = state.persistedSize) === null || _a2 === void 0 ? void 0 : _a2.height) !== null && _b2 !== void 0 ? _b2 : defaultSize.height;
        }
        if (!state.persistWidth || Math.abs(state.currentSize.width - width) <= threshold) {
          width = (_d2 = (_c2 = state.persistedSize) === null || _c2 === void 0 ? void 0 : _c2.width) !== null && _d2 !== void 0 ? _d2 : defaultSize.width;
        }
        this._persistedSize.store(new Dimension(width, height));
      }
      this._contentWidget.unlockPreference();
      state = void 0;
    }));
    this._messageElement = append$1(this.element.domNode, $$d(".message"));
    this._listElement = append$1(this.element.domNode, $$d(".tree"));
    const details = instantiationService.createInstance(SuggestDetailsWidget, this.editor);
    details.onDidClose(this.toggleDetails, this, this._disposables);
    this._details = new SuggestDetailsOverlay(details, this.editor);
    const applyIconStyle = () => this.element.domNode.classList.toggle("no-icons", !this.editor.getOption(
      116
      /* EditorOption.suggest */
    ).showIcons);
    applyIconStyle();
    const renderer2 = instantiationService.createInstance(ItemRenderer, this.editor);
    this._disposables.add(renderer2);
    this._disposables.add(renderer2.onDidToggleDetails(() => this.toggleDetails()));
    this._list = new List("SuggestWidget", this._listElement, {
      getHeight: (_element) => this.getLayoutInfo().itemHeight,
      getTemplateId: (_element) => "suggestion"
    }, [renderer2], {
      alwaysConsumeMouseWheel: true,
      useShadows: false,
      mouseSupport: false,
      multipleSelectionSupport: false,
      accessibilityProvider: {
        getRole: () => "option",
        getWidgetAriaLabel: () => localize("suggest", "Suggest"),
        getWidgetRole: () => "listbox",
        getAriaLabel: (item) => {
          let label = item.textLabel;
          if (typeof item.completion.label !== "string") {
            const { detail: detail2, description } = item.completion.label;
            if (detail2 && description) {
              label = localize("label.full", "{0} {1}, {2}", label, detail2, description);
            } else if (detail2) {
              label = localize("label.detail", "{0} {1}", label, detail2);
            } else if (description) {
              label = localize("label.desc", "{0}, {1}", label, description);
            }
          }
          if (!item.isResolved || !this._isDetailsVisible()) {
            return label;
          }
          const { documentation, detail } = item.completion;
          const docs = format$2("{0}{1}", detail || "", documentation ? typeof documentation === "string" ? documentation : documentation.value : "");
          return localize("ariaCurrenttSuggestionReadDetails", "{0}, docs: {1}", label, docs);
        }
      }
    });
    this._list.style(getListStyles({
      listInactiveFocusBackground: editorSuggestWidgetSelectedBackground,
      listInactiveFocusOutline: activeContrastBorder
    }));
    this._status = instantiationService.createInstance(SuggestWidgetStatus, this.element.domNode, suggestWidgetStatusbarMenu);
    const applyStatusBarStyle = () => this.element.domNode.classList.toggle("with-status-bar", this.editor.getOption(
      116
      /* EditorOption.suggest */
    ).showStatusBar);
    applyStatusBarStyle();
    this._disposables.add(_themeService.onDidColorThemeChange((t) => this._onThemeChange(t)));
    this._onThemeChange(_themeService.getColorTheme());
    this._disposables.add(this._list.onMouseDown((e) => this._onListMouseDownOrTap(e)));
    this._disposables.add(this._list.onTap((e) => this._onListMouseDownOrTap(e)));
    this._disposables.add(this._list.onDidChangeSelection((e) => this._onListSelection(e)));
    this._disposables.add(this._list.onDidChangeFocus((e) => this._onListFocus(e)));
    this._disposables.add(this.editor.onDidChangeCursorSelection(() => this._onCursorSelectionChanged()));
    this._disposables.add(this.editor.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        116
        /* EditorOption.suggest */
      )) {
        applyStatusBarStyle();
        applyIconStyle();
      }
    }));
    this._ctxSuggestWidgetVisible = Context$2.Visible.bindTo(_contextKeyService);
    this._ctxSuggestWidgetDetailsVisible = Context$2.DetailsVisible.bindTo(_contextKeyService);
    this._ctxSuggestWidgetMultipleSuggestions = Context$2.MultipleSuggestions.bindTo(_contextKeyService);
    this._ctxSuggestWidgetHasFocusedSuggestion = Context$2.HasFocusedSuggestion.bindTo(_contextKeyService);
    this._disposables.add(addStandardDisposableListener(this._details.widget.domNode, "keydown", (e) => {
      this._onDetailsKeydown.fire(e);
    }));
    this._disposables.add(this.editor.onMouseDown((e) => this._onEditorMouseDown(e)));
  }
  dispose() {
    var _a2;
    this._details.widget.dispose();
    this._details.dispose();
    this._list.dispose();
    this._status.dispose();
    this._disposables.dispose();
    (_a2 = this._loadingTimeout) === null || _a2 === void 0 ? void 0 : _a2.dispose();
    this._pendingLayout.dispose();
    this._pendingShowDetails.dispose();
    this._showTimeout.dispose();
    this._contentWidget.dispose();
    this.element.dispose();
  }
  _onEditorMouseDown(mouseEvent) {
    if (this._details.widget.domNode.contains(mouseEvent.target.element)) {
      this._details.widget.domNode.focus();
    } else {
      if (this.element.domNode.contains(mouseEvent.target.element)) {
        this.editor.focus();
      }
    }
  }
  _onCursorSelectionChanged() {
    if (this._state !== 0) {
      this._contentWidget.layout();
    }
  }
  _onListMouseDownOrTap(e) {
    if (typeof e.element === "undefined" || typeof e.index === "undefined") {
      return;
    }
    e.browserEvent.preventDefault();
    e.browserEvent.stopPropagation();
    this._select(e.element, e.index);
  }
  _onListSelection(e) {
    if (e.elements.length) {
      this._select(e.elements[0], e.indexes[0]);
    }
  }
  _select(item, index) {
    const completionModel = this._completionModel;
    if (completionModel) {
      this._onDidSelect.fire({ item, index, model: completionModel });
      this.editor.focus();
    }
  }
  _onThemeChange(theme) {
    this._details.widget.borderWidth = isHighContrast(theme.type) ? 2 : 1;
  }
  _onListFocus(e) {
    var _a2;
    if (this._ignoreFocusEvents) {
      return;
    }
    if (!e.elements.length) {
      if (this._currentSuggestionDetails) {
        this._currentSuggestionDetails.cancel();
        this._currentSuggestionDetails = void 0;
        this._focusedItem = void 0;
      }
      this.editor.setAriaOptions({ activeDescendant: void 0 });
      this._ctxSuggestWidgetHasFocusedSuggestion.set(false);
      return;
    }
    if (!this._completionModel) {
      return;
    }
    this._ctxSuggestWidgetHasFocusedSuggestion.set(true);
    const item = e.elements[0];
    const index = e.indexes[0];
    if (item !== this._focusedItem) {
      (_a2 = this._currentSuggestionDetails) === null || _a2 === void 0 ? void 0 : _a2.cancel();
      this._currentSuggestionDetails = void 0;
      this._focusedItem = item;
      this._list.reveal(index);
      this._currentSuggestionDetails = createCancelablePromise((token) => __awaiter$D(this, void 0, void 0, function* () {
        const loading = disposableTimeout(() => {
          if (this._isDetailsVisible()) {
            this.showDetails(true);
          }
        }, 250);
        const sub = token.onCancellationRequested(() => loading.dispose());
        const result2 = yield item.resolve(token);
        loading.dispose();
        sub.dispose();
        return result2;
      }));
      this._currentSuggestionDetails.then(() => {
        if (index >= this._list.length || item !== this._list.element(index)) {
          return;
        }
        this._ignoreFocusEvents = true;
        this._list.splice(index, 1, [item]);
        this._list.setFocus([index]);
        this._ignoreFocusEvents = false;
        if (this._isDetailsVisible()) {
          this.showDetails(false);
        } else {
          this.element.domNode.classList.remove("docs-side");
        }
        this.editor.setAriaOptions({ activeDescendant: getAriaId(index) });
      }).catch(onUnexpectedError);
    }
    this._onDidFocus.fire({ item, index, model: this._completionModel });
  }
  _setState(state) {
    if (this._state === state) {
      return;
    }
    this._state = state;
    this.element.domNode.classList.toggle(
      "frozen",
      state === 4
      /* State.Frozen */
    );
    this.element.domNode.classList.remove("message");
    switch (state) {
      case 0:
        hide(this._messageElement, this._listElement, this._status.element);
        this._details.hide(true);
        this._status.hide();
        this._contentWidget.hide();
        this._ctxSuggestWidgetVisible.reset();
        this._ctxSuggestWidgetMultipleSuggestions.reset();
        this._ctxSuggestWidgetHasFocusedSuggestion.reset();
        this._showTimeout.cancel();
        this.element.domNode.classList.remove("visible");
        this._list.splice(0, this._list.length);
        this._focusedItem = void 0;
        this._cappedHeight = void 0;
        this._explainMode = false;
        break;
      case 1:
        this.element.domNode.classList.add("message");
        this._messageElement.textContent = SuggestWidget2.LOADING_MESSAGE;
        hide(this._listElement, this._status.element);
        show(this._messageElement);
        this._details.hide();
        this._show();
        this._focusedItem = void 0;
        break;
      case 2:
        this.element.domNode.classList.add("message");
        this._messageElement.textContent = SuggestWidget2.NO_SUGGESTIONS_MESSAGE;
        hide(this._listElement, this._status.element);
        show(this._messageElement);
        this._details.hide();
        this._show();
        this._focusedItem = void 0;
        break;
      case 3:
        hide(this._messageElement);
        show(this._listElement, this._status.element);
        this._show();
        break;
      case 4:
        hide(this._messageElement);
        show(this._listElement, this._status.element);
        this._show();
        break;
      case 5:
        hide(this._messageElement);
        show(this._listElement, this._status.element);
        this._details.show();
        this._show();
        break;
    }
  }
  _show() {
    this._status.show();
    this._contentWidget.show();
    this._layout(this._persistedSize.restore());
    this._ctxSuggestWidgetVisible.set(true);
    this._showTimeout.cancelAndSet(() => {
      this.element.domNode.classList.add("visible");
      this._onDidShow.fire(this);
    }, 100);
  }
  showTriggered(auto, delay) {
    if (this._state !== 0) {
      return;
    }
    this._contentWidget.setPosition(this.editor.getPosition());
    this._isAuto = !!auto;
    if (!this._isAuto) {
      this._loadingTimeout = disposableTimeout(() => this._setState(
        1
        /* State.Loading */
      ), delay);
    }
  }
  showSuggestions(completionModel, selectionIndex, isFrozen2, isAuto, noFocus) {
    var _a2, _b2;
    this._contentWidget.setPosition(this.editor.getPosition());
    (_a2 = this._loadingTimeout) === null || _a2 === void 0 ? void 0 : _a2.dispose();
    (_b2 = this._currentSuggestionDetails) === null || _b2 === void 0 ? void 0 : _b2.cancel();
    this._currentSuggestionDetails = void 0;
    if (this._completionModel !== completionModel) {
      this._completionModel = completionModel;
    }
    if (isFrozen2 && this._state !== 2 && this._state !== 0) {
      this._setState(
        4
        /* State.Frozen */
      );
      return;
    }
    const visibleCount = this._completionModel.items.length;
    const isEmpty2 = visibleCount === 0;
    this._ctxSuggestWidgetMultipleSuggestions.set(visibleCount > 1);
    if (isEmpty2) {
      this._setState(
        isAuto ? 0 : 2
        /* State.Empty */
      );
      this._completionModel = void 0;
      return;
    }
    this._focusedItem = void 0;
    this._onDidFocus.pause();
    this._onDidSelect.pause();
    try {
      this._list.splice(0, this._list.length, this._completionModel.items);
      this._setState(
        isFrozen2 ? 4 : 3
        /* State.Open */
      );
      this._list.reveal(selectionIndex, 0);
      this._list.setFocus(noFocus ? [] : [selectionIndex]);
    } finally {
      this._onDidFocus.resume();
      this._onDidSelect.resume();
    }
    this._pendingLayout.value = runAtThisOrScheduleAtNextAnimationFrame(() => {
      this._pendingLayout.clear();
      this._layout(this.element.size);
      this._details.widget.domNode.classList.remove("focused");
    });
  }
  focusSelected() {
    if (this._list.length > 0) {
      this._list.setFocus([0]);
    }
  }
  selectNextPage() {
    switch (this._state) {
      case 0:
        return false;
      case 5:
        this._details.widget.pageDown();
        return true;
      case 1:
        return !this._isAuto;
      default:
        this._list.focusNextPage();
        return true;
    }
  }
  selectNext() {
    switch (this._state) {
      case 0:
        return false;
      case 1:
        return !this._isAuto;
      default:
        this._list.focusNext(1, true);
        return true;
    }
  }
  selectLast() {
    switch (this._state) {
      case 0:
        return false;
      case 5:
        this._details.widget.scrollBottom();
        return true;
      case 1:
        return !this._isAuto;
      default:
        this._list.focusLast();
        return true;
    }
  }
  selectPreviousPage() {
    switch (this._state) {
      case 0:
        return false;
      case 5:
        this._details.widget.pageUp();
        return true;
      case 1:
        return !this._isAuto;
      default:
        this._list.focusPreviousPage();
        return true;
    }
  }
  selectPrevious() {
    switch (this._state) {
      case 0:
        return false;
      case 1:
        return !this._isAuto;
      default:
        this._list.focusPrevious(1, true);
        return false;
    }
  }
  selectFirst() {
    switch (this._state) {
      case 0:
        return false;
      case 5:
        this._details.widget.scrollTop();
        return true;
      case 1:
        return !this._isAuto;
      default:
        this._list.focusFirst();
        return true;
    }
  }
  getFocusedItem() {
    if (this._state !== 0 && this._state !== 2 && this._state !== 1 && this._completionModel && this._list.getFocus().length > 0) {
      return {
        item: this._list.getFocusedElements()[0],
        index: this._list.getFocus()[0],
        model: this._completionModel
      };
    }
    return void 0;
  }
  toggleDetailsFocus() {
    if (this._state === 5) {
      this._setState(
        3
        /* State.Open */
      );
      this._details.widget.domNode.classList.remove("focused");
    } else if (this._state === 3 && this._isDetailsVisible()) {
      this._setState(
        5
        /* State.Details */
      );
      this._details.widget.domNode.classList.add("focused");
    }
  }
  toggleDetails() {
    if (this._isDetailsVisible()) {
      this._pendingShowDetails.clear();
      this._ctxSuggestWidgetDetailsVisible.set(false);
      this._setDetailsVisible(false);
      this._details.hide();
      this.element.domNode.classList.remove("shows-details");
    } else if ((canExpandCompletionItem(this._list.getFocusedElements()[0]) || this._explainMode) && (this._state === 3 || this._state === 5 || this._state === 4)) {
      this._ctxSuggestWidgetDetailsVisible.set(true);
      this._setDetailsVisible(true);
      this.showDetails(false);
    }
  }
  showDetails(loading) {
    this._pendingShowDetails.value = runAtThisOrScheduleAtNextAnimationFrame(() => {
      this._pendingShowDetails.clear();
      this._details.show();
      if (loading) {
        this._details.widget.renderLoading();
      } else {
        this._details.widget.renderItem(this._list.getFocusedElements()[0], this._explainMode);
      }
      this._positionDetails();
      this.editor.focus();
      this.element.domNode.classList.add("shows-details");
    });
  }
  toggleExplainMode() {
    if (this._list.getFocusedElements()[0]) {
      this._explainMode = !this._explainMode;
      if (!this._isDetailsVisible()) {
        this.toggleDetails();
      } else {
        this.showDetails(false);
      }
    }
  }
  resetPersistedSize() {
    this._persistedSize.reset();
  }
  hideWidget() {
    var _a2;
    this._pendingLayout.clear();
    this._pendingShowDetails.clear();
    (_a2 = this._loadingTimeout) === null || _a2 === void 0 ? void 0 : _a2.dispose();
    this._setState(
      0
      /* State.Hidden */
    );
    this._onDidHide.fire(this);
    this.element.clearSashHoverState();
    const dim = this._persistedSize.restore();
    const minPersistedHeight = Math.ceil(this.getLayoutInfo().itemHeight * 4.3);
    if (dim && dim.height < minPersistedHeight) {
      this._persistedSize.store(dim.with(void 0, minPersistedHeight));
    }
  }
  isFrozen() {
    return this._state === 4;
  }
  _afterRender(position) {
    if (position === null) {
      if (this._isDetailsVisible()) {
        this._details.hide();
      }
      return;
    }
    if (this._state === 2 || this._state === 1) {
      return;
    }
    if (this._isDetailsVisible()) {
      this._details.show();
    }
    this._positionDetails();
  }
  _layout(size2) {
    var _a2, _b2, _c2;
    if (!this.editor.hasModel()) {
      return;
    }
    if (!this.editor.getDomNode()) {
      return;
    }
    const bodyBox = getClientArea(document.body);
    const info = this.getLayoutInfo();
    if (!size2) {
      size2 = info.defaultSize;
    }
    let height = size2.height;
    let width = size2.width;
    this._status.element.style.height = `${info.itemHeight}px`;
    if (this._state === 2 || this._state === 1) {
      height = info.itemHeight + info.borderHeight;
      width = info.defaultSize.width / 2;
      this.element.enableSashes(false, false, false, false);
      this.element.minSize = this.element.maxSize = new Dimension(width, height);
      this._contentWidget.setPreference(
        2
        /* ContentWidgetPositionPreference.BELOW */
      );
    } else {
      const maxWidth = bodyBox.width - info.borderHeight - 2 * info.horizontalPadding;
      if (width > maxWidth) {
        width = maxWidth;
      }
      const preferredWidth = this._completionModel ? this._completionModel.stats.pLabelLen * info.typicalHalfwidthCharacterWidth : width;
      const fullHeight = info.statusBarHeight + this._list.contentHeight + info.borderHeight;
      const minHeight = info.itemHeight + info.statusBarHeight;
      const editorBox = getDomNodePagePosition(this.editor.getDomNode());
      const cursorBox = this.editor.getScrolledVisiblePosition(this.editor.getPosition());
      const cursorBottom = editorBox.top + cursorBox.top + cursorBox.height;
      const maxHeightBelow = Math.min(bodyBox.height - cursorBottom - info.verticalPadding, fullHeight);
      const availableSpaceAbove = editorBox.top + cursorBox.top - info.verticalPadding;
      const maxHeightAbove = Math.min(availableSpaceAbove, fullHeight);
      let maxHeight = Math.min(Math.max(maxHeightAbove, maxHeightBelow) + info.borderHeight, fullHeight);
      if (height === ((_a2 = this._cappedHeight) === null || _a2 === void 0 ? void 0 : _a2.capped)) {
        height = this._cappedHeight.wanted;
      }
      if (height < minHeight) {
        height = minHeight;
      }
      if (height > maxHeight) {
        height = maxHeight;
      }
      const forceRenderingAboveRequiredSpace = 150;
      if (height > maxHeightBelow || this._forceRenderingAbove && availableSpaceAbove > forceRenderingAboveRequiredSpace) {
        this._contentWidget.setPreference(
          1
          /* ContentWidgetPositionPreference.ABOVE */
        );
        this.element.enableSashes(true, true, false, false);
        maxHeight = maxHeightAbove;
      } else {
        this._contentWidget.setPreference(
          2
          /* ContentWidgetPositionPreference.BELOW */
        );
        this.element.enableSashes(false, true, true, false);
        maxHeight = maxHeightBelow;
      }
      this.element.preferredSize = new Dimension(preferredWidth, info.defaultSize.height);
      this.element.maxSize = new Dimension(maxWidth, maxHeight);
      this.element.minSize = new Dimension(220, minHeight);
      this._cappedHeight = height === fullHeight ? { wanted: (_c2 = (_b2 = this._cappedHeight) === null || _b2 === void 0 ? void 0 : _b2.wanted) !== null && _c2 !== void 0 ? _c2 : size2.height, capped: height } : void 0;
    }
    this._resize(width, height);
  }
  _resize(width, height) {
    const { width: maxWidth, height: maxHeight } = this.element.maxSize;
    width = Math.min(maxWidth, width);
    height = Math.min(maxHeight, height);
    const { statusBarHeight } = this.getLayoutInfo();
    this._list.layout(height - statusBarHeight, width);
    this._listElement.style.height = `${height - statusBarHeight}px`;
    this.element.layout(height, width);
    this._contentWidget.layout();
    this._positionDetails();
  }
  _positionDetails() {
    var _a2;
    if (this._isDetailsVisible()) {
      this._details.placeAtAnchor(
        this.element.domNode,
        ((_a2 = this._contentWidget.getPosition()) === null || _a2 === void 0 ? void 0 : _a2.preference[0]) === 2
        /* ContentWidgetPositionPreference.BELOW */
      );
    }
  }
  getLayoutInfo() {
    const fontInfo = this.editor.getOption(
      49
      /* EditorOption.fontInfo */
    );
    const itemHeight = clamp(this.editor.getOption(
      118
      /* EditorOption.suggestLineHeight */
    ) || fontInfo.lineHeight, 8, 1e3);
    const statusBarHeight = !this.editor.getOption(
      116
      /* EditorOption.suggest */
    ).showStatusBar || this._state === 2 || this._state === 1 ? 0 : itemHeight;
    const borderWidth = this._details.widget.borderWidth;
    const borderHeight = 2 * borderWidth;
    return {
      itemHeight,
      statusBarHeight,
      borderWidth,
      borderHeight,
      typicalHalfwidthCharacterWidth: fontInfo.typicalHalfwidthCharacterWidth,
      verticalPadding: 22,
      horizontalPadding: 14,
      defaultSize: new Dimension(430, statusBarHeight + 12 * itemHeight + borderHeight)
    };
  }
  _isDetailsVisible() {
    return this._storageService.getBoolean("expandSuggestionDocs", 0, false);
  }
  _setDetailsVisible(value) {
    this._storageService.store(
      "expandSuggestionDocs",
      value,
      0,
      0
      /* StorageTarget.USER */
    );
  }
  forceRenderingAbove() {
    if (!this._forceRenderingAbove) {
      this._forceRenderingAbove = true;
      this._layout(this._persistedSize.restore());
    }
  }
  stopForceRenderingAbove() {
    this._forceRenderingAbove = false;
  }
};
SuggestWidget.LOADING_MESSAGE = localize("suggestWidget.loading", "Loading...");
SuggestWidget.NO_SUGGESTIONS_MESSAGE = localize("suggestWidget.noSuggestions", "No suggestions.");
SuggestWidget = __decorate$$([
  __param$Z(1, IStorageService),
  __param$Z(2, IContextKeyService),
  __param$Z(3, IThemeService),
  __param$Z(4, IInstantiationService)
], SuggestWidget);
class SuggestContentWidget {
  constructor(_widget, _editor) {
    this._widget = _widget;
    this._editor = _editor;
    this.allowEditorOverflow = true;
    this.suppressMouseDown = false;
    this._preferenceLocked = false;
    this._added = false;
    this._hidden = false;
  }
  dispose() {
    if (this._added) {
      this._added = false;
      this._editor.removeContentWidget(this);
    }
  }
  getId() {
    return "editor.widget.suggestWidget";
  }
  getDomNode() {
    return this._widget.element.domNode;
  }
  show() {
    this._hidden = false;
    if (!this._added) {
      this._added = true;
      this._editor.addContentWidget(this);
    }
  }
  hide() {
    if (!this._hidden) {
      this._hidden = true;
      this.layout();
    }
  }
  layout() {
    this._editor.layoutContentWidget(this);
  }
  getPosition() {
    if (this._hidden || !this._position || !this._preference) {
      return null;
    }
    return {
      position: this._position,
      preference: [this._preference]
    };
  }
  beforeRender() {
    const { height, width } = this._widget.element.size;
    const { borderWidth, horizontalPadding } = this._widget.getLayoutInfo();
    return new Dimension(width + 2 * borderWidth + horizontalPadding, height + 2 * borderWidth);
  }
  afterRender(position) {
    this._widget._afterRender(position);
  }
  setPreference(preference) {
    if (!this._preferenceLocked) {
      this._preference = preference;
    }
  }
  lockPreference() {
    this._preferenceLocked = true;
  }
  unlockPreference() {
    this._preferenceLocked = false;
  }
  setPosition(position) {
    this._position = position;
  }
}
var __decorate$_ = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$Y = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
class LineSuffix {
  constructor(_model, _position) {
    this._model = _model;
    this._position = _position;
    const maxColumn = _model.getLineMaxColumn(_position.lineNumber);
    if (maxColumn !== _position.column) {
      const offset = _model.getOffsetAt(_position);
      const end = _model.getPositionAt(offset + 1);
      this._marker = _model.deltaDecorations([], [{
        range: Range$2.fromPositions(_position, end),
        options: {
          description: "suggest-line-suffix",
          stickiness: 1
          /* TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */
        }
      }]);
    }
  }
  dispose() {
    if (this._marker && !this._model.isDisposed()) {
      this._model.deltaDecorations(this._marker, []);
    }
  }
  delta(position) {
    if (this._model.isDisposed() || this._position.lineNumber !== position.lineNumber) {
      return 0;
    }
    if (this._marker) {
      const range2 = this._model.getDecorationRange(this._marker[0]);
      const end = this._model.getOffsetAt(range2.getStartPosition());
      return end - this._model.getOffsetAt(position);
    } else {
      return this._model.getLineMaxColumn(position.lineNumber) - position.column;
    }
  }
}
let SuggestController = class SuggestController2 {
  static get(editor2) {
    return editor2.getContribution(SuggestController2.ID);
  }
  constructor(editor2, _memoryService, _commandService, _contextKeyService, _instantiationService, _logService, _telemetryService) {
    this._memoryService = _memoryService;
    this._commandService = _commandService;
    this._contextKeyService = _contextKeyService;
    this._instantiationService = _instantiationService;
    this._logService = _logService;
    this._telemetryService = _telemetryService;
    this._lineSuffix = new MutableDisposable();
    this._toDispose = new DisposableStore();
    this._selectors = new PriorityRegistry((s) => s.priority);
    this.editor = editor2;
    this.model = _instantiationService.createInstance(SuggestModel, this.editor);
    this._selectors.register({
      priority: 0,
      select: (model, pos, items) => this._memoryService.select(model, pos, items)
    });
    const ctxInsertMode = Context$2.InsertMode.bindTo(_contextKeyService);
    ctxInsertMode.set(editor2.getOption(
      116
      /* EditorOption.suggest */
    ).insertMode);
    this.model.onDidTrigger(() => ctxInsertMode.set(editor2.getOption(
      116
      /* EditorOption.suggest */
    ).insertMode));
    this.widget = this._toDispose.add(new IdleValue(() => {
      const widget = this._instantiationService.createInstance(SuggestWidget, this.editor);
      this._toDispose.add(widget);
      this._toDispose.add(widget.onDidSelect((item) => this._insertSuggestion(
        item,
        0
        /* InsertFlags.None */
      ), this));
      const commitCharacterController = new CommitCharacterController(this.editor, widget, this.model, (item) => this._insertSuggestion(
        item,
        2
        /* InsertFlags.NoAfterUndoStop */
      ));
      this._toDispose.add(commitCharacterController);
      const ctxMakesTextEdit = Context$2.MakesTextEdit.bindTo(this._contextKeyService);
      const ctxHasInsertAndReplace = Context$2.HasInsertAndReplaceRange.bindTo(this._contextKeyService);
      const ctxCanResolve = Context$2.CanResolve.bindTo(this._contextKeyService);
      this._toDispose.add(toDisposable(() => {
        ctxMakesTextEdit.reset();
        ctxHasInsertAndReplace.reset();
        ctxCanResolve.reset();
      }));
      this._toDispose.add(widget.onDidFocus(({ item }) => {
        const position = this.editor.getPosition();
        const startColumn = item.editStart.column;
        const endColumn = position.column;
        let value = true;
        if (this.editor.getOption(
          1
          /* EditorOption.acceptSuggestionOnEnter */
        ) === "smart" && this.model.state === 2 && !item.completion.additionalTextEdits && !(item.completion.insertTextRules & 4) && endColumn - startColumn === item.completion.insertText.length) {
          const oldText = this.editor.getModel().getValueInRange({
            startLineNumber: position.lineNumber,
            startColumn,
            endLineNumber: position.lineNumber,
            endColumn
          });
          value = oldText !== item.completion.insertText;
        }
        ctxMakesTextEdit.set(value);
        ctxHasInsertAndReplace.set(!Position$2.equals(item.editInsertEnd, item.editReplaceEnd));
        ctxCanResolve.set(Boolean(item.provider.resolveCompletionItem) || Boolean(item.completion.documentation) || item.completion.detail !== item.completion.label);
      }));
      this._toDispose.add(widget.onDetailsKeyDown((e) => {
        if (e.toKeyCodeChord().equals(new KeyCodeChord(
          true,
          false,
          false,
          false,
          33
          /* KeyCode.KeyC */
        )) || isMacintosh && e.toKeyCodeChord().equals(new KeyCodeChord(
          false,
          false,
          false,
          true,
          33
          /* KeyCode.KeyC */
        ))) {
          e.stopPropagation();
          return;
        }
        if (!e.toKeyCodeChord().isModifierKey()) {
          this.editor.focus();
        }
      }));
      return widget;
    }));
    this._overtypingCapturer = this._toDispose.add(new IdleValue(() => {
      return this._toDispose.add(new OvertypingCapturer(this.editor, this.model));
    }));
    this._alternatives = this._toDispose.add(new IdleValue(() => {
      return this._toDispose.add(new SuggestAlternatives(this.editor, this._contextKeyService));
    }));
    this._toDispose.add(_instantiationService.createInstance(WordContextKey, editor2));
    this._toDispose.add(this.model.onDidTrigger((e) => {
      this.widget.value.showTriggered(e.auto, e.shy ? 250 : 50);
      this._lineSuffix.value = new LineSuffix(this.editor.getModel(), e.position);
    }));
    this._toDispose.add(this.model.onDidSuggest((e) => {
      if (e.triggerOptions.shy) {
        return;
      }
      let index = -1;
      for (const selector3 of this._selectors.itemsOrderedByPriorityDesc) {
        index = selector3.select(this.editor.getModel(), this.editor.getPosition(), e.completionModel.items);
        if (index !== -1) {
          break;
        }
      }
      if (index === -1) {
        index = 0;
      }
      let noFocus = false;
      if (e.triggerOptions.auto) {
        const options = this.editor.getOption(
          116
          /* EditorOption.suggest */
        );
        if (options.selectionMode === "never" || options.selectionMode === "always") {
          noFocus = options.selectionMode === "never";
        } else if (options.selectionMode === "whenTriggerCharacter") {
          noFocus = e.triggerOptions.triggerKind !== 1;
        } else if (options.selectionMode === "whenQuickSuggestion") {
          noFocus = e.triggerOptions.triggerKind === 1 && !e.triggerOptions.refilter;
        }
      }
      this.widget.value.showSuggestions(e.completionModel, index, e.isFrozen, e.triggerOptions.auto, noFocus);
    }));
    this._toDispose.add(this.model.onDidCancel((e) => {
      if (!e.retrigger) {
        this.widget.value.hideWidget();
      }
    }));
    this._toDispose.add(this.editor.onDidBlurEditorWidget(() => {
      {
        this.model.cancel();
        this.model.clear();
      }
    }));
    const acceptSuggestionsOnEnter = Context$2.AcceptSuggestionsOnEnter.bindTo(_contextKeyService);
    const updateFromConfig = () => {
      const acceptSuggestionOnEnter = this.editor.getOption(
        1
        /* EditorOption.acceptSuggestionOnEnter */
      );
      acceptSuggestionsOnEnter.set(acceptSuggestionOnEnter === "on" || acceptSuggestionOnEnter === "smart");
    };
    this._toDispose.add(this.editor.onDidChangeConfiguration(() => updateFromConfig()));
    updateFromConfig();
  }
  dispose() {
    this._alternatives.dispose();
    this._toDispose.dispose();
    this.widget.dispose();
    this.model.dispose();
    this._lineSuffix.dispose();
  }
  _insertSuggestion(event, flags) {
    if (!event || !event.item) {
      this._alternatives.value.reset();
      this.model.cancel();
      this.model.clear();
      return;
    }
    if (!this.editor.hasModel()) {
      return;
    }
    const snippetController = SnippetController2.get(this.editor);
    if (!snippetController) {
      return;
    }
    const model = this.editor.getModel();
    const modelVersionNow = model.getAlternativeVersionId();
    const { item } = event;
    const tasks = [];
    const cts = new CancellationTokenSource$1();
    if (!(flags & 1)) {
      this.editor.pushUndoStop();
    }
    const info = this.getOverwriteInfo(item, Boolean(
      flags & 8
      /* InsertFlags.AlternativeOverwriteConfig */
    ));
    this._memoryService.memorize(model, this.editor.getPosition(), item);
    const isResolved = item.isResolved;
    let _commandExectionDuration = -1;
    let _additionalEditsAppliedAsync = -1;
    if (Array.isArray(item.completion.additionalTextEdits)) {
      this.model.cancel();
      const scrollState = StableEditorScrollState.capture(this.editor);
      this.editor.executeEdits("suggestController.additionalTextEdits.sync", item.completion.additionalTextEdits.map((edit) => EditOperation.replaceMove(Range$2.lift(edit.range), edit.text)));
      scrollState.restoreRelativeVerticalPositionOfCursor(this.editor);
    } else if (!isResolved) {
      const sw = new StopWatch();
      let position;
      const docListener = model.onDidChangeContent((e) => {
        if (e.isFlush) {
          cts.cancel();
          docListener.dispose();
          return;
        }
        for (const change of e.changes) {
          const thisPosition = Range$2.getEndPosition(change.range);
          if (!position || Position$2.isBefore(thisPosition, position)) {
            position = thisPosition;
          }
        }
      });
      const oldFlags = flags;
      flags |= 2;
      let didType = false;
      const typeListener = this.editor.onWillType(() => {
        typeListener.dispose();
        didType = true;
        if (!(oldFlags & 2)) {
          this.editor.pushUndoStop();
        }
      });
      tasks.push(item.resolve(cts.token).then(() => {
        if (!item.completion.additionalTextEdits || cts.token.isCancellationRequested) {
          return void 0;
        }
        if (position && item.completion.additionalTextEdits.some((edit) => Position$2.isBefore(position, Range$2.getStartPosition(edit.range)))) {
          return false;
        }
        if (didType) {
          this.editor.pushUndoStop();
        }
        const scrollState = StableEditorScrollState.capture(this.editor);
        this.editor.executeEdits("suggestController.additionalTextEdits.async", item.completion.additionalTextEdits.map((edit) => EditOperation.replaceMove(Range$2.lift(edit.range), edit.text)));
        scrollState.restoreRelativeVerticalPositionOfCursor(this.editor);
        if (didType || !(oldFlags & 2)) {
          this.editor.pushUndoStop();
        }
        return true;
      }).then((applied) => {
        this._logService.trace("[suggest] async resolving of edits DONE (ms, applied?)", sw.elapsed(), applied);
        _additionalEditsAppliedAsync = applied === true ? 1 : applied === false ? 0 : -2;
      }).finally(() => {
        docListener.dispose();
        typeListener.dispose();
      }));
    }
    let { insertText } = item.completion;
    if (!(item.completion.insertTextRules & 4)) {
      insertText = SnippetParser.escape(insertText);
    }
    this.model.cancel();
    snippetController.insert(insertText, {
      overwriteBefore: info.overwriteBefore,
      overwriteAfter: info.overwriteAfter,
      undoStopBefore: false,
      undoStopAfter: false,
      adjustWhitespace: !(item.completion.insertTextRules & 1),
      clipboardText: event.model.clipboardText,
      overtypingCapturer: this._overtypingCapturer.value
    });
    if (!(flags & 2)) {
      this.editor.pushUndoStop();
    }
    if (item.completion.command) {
      if (item.completion.command.id === TriggerSuggestAction.id) {
        this.model.trigger({ auto: true, retrigger: true });
      } else {
        const sw = new StopWatch();
        tasks.push(this._commandService.executeCommand(item.completion.command.id, ...item.completion.command.arguments ? [...item.completion.command.arguments] : []).catch((e) => {
          if (item.completion.extensionId) {
            onUnexpectedExternalError(e);
          } else {
            onUnexpectedError(e);
          }
        }).finally(() => {
          _commandExectionDuration = sw.elapsed();
        }));
      }
    }
    if (flags & 4) {
      this._alternatives.value.set(event, (next) => {
        cts.cancel();
        while (model.canUndo()) {
          if (modelVersionNow !== model.getAlternativeVersionId()) {
            model.undo();
          }
          this._insertSuggestion(next, 1 | 2 | (flags & 8 ? 8 : 0));
          break;
        }
      });
    }
    this._alertCompletionItem(item);
    Promise.all(tasks).finally(() => {
      this._reportSuggestionAcceptedTelemetry(item, model, isResolved, _commandExectionDuration, _additionalEditsAppliedAsync);
      this.model.clear();
      cts.dispose();
    });
  }
  _reportSuggestionAcceptedTelemetry(item, model, itemResolved, commandExectionDuration, additionalEditsAppliedAsync) {
    var _a2, _b2, _c2;
    if (Math.floor(Math.random() * 100) === 0) {
      return;
    }
    this._telemetryService.publicLog2("suggest.acceptedSuggestion", {
      extensionId: (_b2 = (_a2 = item.extensionId) === null || _a2 === void 0 ? void 0 : _a2.value) !== null && _b2 !== void 0 ? _b2 : "unknown",
      providerId: (_c2 = item.provider._debugDisplayName) !== null && _c2 !== void 0 ? _c2 : "unknown",
      kind: item.completion.kind,
      basenameHash: hash(basename$1(model.uri)).toString(16),
      languageId: model.getLanguageId(),
      fileExtension: extname$1(model.uri),
      resolveInfo: !item.provider.resolveCompletionItem ? -1 : itemResolved ? 1 : 0,
      resolveDuration: item.resolveDuration,
      commandDuration: commandExectionDuration,
      additionalEditsAsync: additionalEditsAppliedAsync
    });
  }
  getOverwriteInfo(item, toggleMode) {
    assertType(this.editor.hasModel());
    let replace = this.editor.getOption(
      116
      /* EditorOption.suggest */
    ).insertMode === "replace";
    if (toggleMode) {
      replace = !replace;
    }
    const overwriteBefore = item.position.column - item.editStart.column;
    const overwriteAfter = (replace ? item.editReplaceEnd.column : item.editInsertEnd.column) - item.position.column;
    const columnDelta = this.editor.getPosition().column - item.position.column;
    const suffixDelta = this._lineSuffix.value ? this._lineSuffix.value.delta(this.editor.getPosition()) : 0;
    return {
      overwriteBefore: overwriteBefore + columnDelta,
      overwriteAfter: overwriteAfter + suffixDelta
    };
  }
  _alertCompletionItem(item) {
    if (isNonEmptyArray(item.completion.additionalTextEdits)) {
      const msg = localize("aria.alert.snippet", "Accepting '{0}' made {1} additional edits", item.textLabel, item.completion.additionalTextEdits.length);
      alert(msg);
    }
  }
  triggerSuggest(onlyFrom, auto, noFilter) {
    if (this.editor.hasModel()) {
      this.model.trigger({
        auto: auto !== null && auto !== void 0 ? auto : false,
        completionOptions: { providerFilter: onlyFrom, kindFilter: noFilter ? /* @__PURE__ */ new Set() : void 0 }
      });
      this.editor.revealPosition(
        this.editor.getPosition(),
        0
        /* ScrollType.Smooth */
      );
      this.editor.focus();
    }
  }
  triggerSuggestAndAcceptBest(arg) {
    if (!this.editor.hasModel()) {
      return;
    }
    const positionNow = this.editor.getPosition();
    const fallback2 = () => {
      if (positionNow.equals(this.editor.getPosition())) {
        this._commandService.executeCommand(arg.fallback);
      }
    };
    const makesTextEdit = (item) => {
      if (item.completion.insertTextRules & 4 || item.completion.additionalTextEdits) {
        return true;
      }
      const position = this.editor.getPosition();
      const startColumn = item.editStart.column;
      const endColumn = position.column;
      if (endColumn - startColumn !== item.completion.insertText.length) {
        return true;
      }
      const textNow = this.editor.getModel().getValueInRange({
        startLineNumber: position.lineNumber,
        startColumn,
        endLineNumber: position.lineNumber,
        endColumn
      });
      return textNow !== item.completion.insertText;
    };
    Event$1.once(this.model.onDidTrigger)((_) => {
      const listener = [];
      Event$1.any(this.model.onDidTrigger, this.model.onDidCancel)(() => {
        dispose(listener);
        fallback2();
      }, void 0, listener);
      this.model.onDidSuggest(({ completionModel }) => {
        dispose(listener);
        if (completionModel.items.length === 0) {
          fallback2();
          return;
        }
        const index = this._memoryService.select(this.editor.getModel(), this.editor.getPosition(), completionModel.items);
        const item = completionModel.items[index];
        if (!makesTextEdit(item)) {
          fallback2();
          return;
        }
        this.editor.pushUndoStop();
        this._insertSuggestion(
          { index, item, model: completionModel },
          4 | 1 | 2
          /* InsertFlags.NoAfterUndoStop */
        );
      }, void 0, listener);
    });
    this.model.trigger({ auto: false, shy: true });
    this.editor.revealPosition(
      positionNow,
      0
      /* ScrollType.Smooth */
    );
    this.editor.focus();
  }
  acceptSelectedSuggestion(keepAlternativeSuggestions, alternativeOverwriteConfig) {
    const item = this.widget.value.getFocusedItem();
    let flags = 0;
    if (keepAlternativeSuggestions) {
      flags |= 4;
    }
    if (alternativeOverwriteConfig) {
      flags |= 8;
    }
    this._insertSuggestion(item, flags);
  }
  acceptNextSuggestion() {
    this._alternatives.value.next();
  }
  acceptPrevSuggestion() {
    this._alternatives.value.prev();
  }
  cancelSuggestWidget() {
    this.model.cancel();
    this.model.clear();
    this.widget.value.hideWidget();
  }
  focusSuggestion() {
    this.widget.value.focusSelected();
  }
  selectNextSuggestion() {
    this.widget.value.selectNext();
  }
  selectNextPageSuggestion() {
    this.widget.value.selectNextPage();
  }
  selectLastSuggestion() {
    this.widget.value.selectLast();
  }
  selectPrevSuggestion() {
    this.widget.value.selectPrevious();
  }
  selectPrevPageSuggestion() {
    this.widget.value.selectPreviousPage();
  }
  selectFirstSuggestion() {
    this.widget.value.selectFirst();
  }
  toggleSuggestionDetails() {
    this.widget.value.toggleDetails();
  }
  toggleExplainMode() {
    this.widget.value.toggleExplainMode();
  }
  toggleSuggestionFocus() {
    this.widget.value.toggleDetailsFocus();
  }
  resetWidgetSize() {
    this.widget.value.resetPersistedSize();
  }
  forceRenderingAbove() {
    this.widget.value.forceRenderingAbove();
  }
  stopForceRenderingAbove() {
    if (!this.widget.isInitialized) {
      return;
    }
    this.widget.value.stopForceRenderingAbove();
  }
  registerSelector(selector3) {
    return this._selectors.register(selector3);
  }
};
SuggestController.ID = "editor.contrib.suggestController";
SuggestController = __decorate$_([
  __param$Y(1, ISuggestMemoryService),
  __param$Y(2, ICommandService),
  __param$Y(3, IContextKeyService),
  __param$Y(4, IInstantiationService),
  __param$Y(5, ILogService),
  __param$Y(6, ITelemetryService)
], SuggestController);
class PriorityRegistry {
  constructor(prioritySelector) {
    this.prioritySelector = prioritySelector;
    this._items = new Array();
  }
  register(value) {
    if (this._items.indexOf(value) !== -1) {
      throw new Error("Value is already registered");
    }
    this._items.push(value);
    this._items.sort((s1, s2) => this.prioritySelector(s2) - this.prioritySelector(s1));
    return {
      dispose: () => {
        const idx = this._items.indexOf(value);
        if (idx >= 0) {
          this._items.splice(idx, 1);
        }
      }
    };
  }
  get itemsOrderedByPriorityDesc() {
    return this._items;
  }
}
class TriggerSuggestAction extends EditorAction {
  constructor() {
    super({
      id: TriggerSuggestAction.id,
      label: localize("suggest.trigger.label", "Trigger Suggest"),
      alias: "Trigger Suggest",
      precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasCompletionItemProvider, Context$2.Visible.toNegated()),
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 2048 | 10,
        secondary: [
          2048 | 39
          /* KeyCode.KeyI */
        ],
        mac: { primary: 256 | 10, secondary: [
          512 | 9,
          2048 | 39
          /* KeyCode.KeyI */
        ] },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(_accessor, editor2, args) {
    const controller = SuggestController.get(editor2);
    if (!controller) {
      return;
    }
    let auto;
    if (args && typeof args === "object") {
      if (args.auto === true) {
        auto = true;
      }
    }
    controller.triggerSuggest(void 0, auto, void 0);
  }
}
TriggerSuggestAction.id = "editor.action.triggerSuggest";
registerEditorContribution(
  SuggestController.ID,
  SuggestController,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);
registerEditorAction(TriggerSuggestAction);
const weight$2 = 100 + 90;
const SuggestCommand = EditorCommand.bindToContribution(SuggestController.get);
registerEditorCommand(new SuggestCommand({
  id: "acceptSelectedSuggestion",
  precondition: ContextKeyExpr.and(Context$2.Visible, Context$2.HasFocusedSuggestion),
  handler(x) {
    x.acceptSelectedSuggestion(true, false);
  },
  kbOpts: [{
    // normal tab
    primary: 2,
    kbExpr: ContextKeyExpr.and(Context$2.Visible, EditorContextKeys.textInputFocus),
    weight: weight$2
  }, {
    // accept on enter has special rules
    primary: 3,
    kbExpr: ContextKeyExpr.and(Context$2.Visible, EditorContextKeys.textInputFocus, Context$2.AcceptSuggestionsOnEnter, Context$2.MakesTextEdit),
    weight: weight$2
  }],
  menuOpts: [{
    menuId: suggestWidgetStatusbarMenu,
    title: localize("accept.insert", "Insert"),
    group: "left",
    order: 1,
    when: Context$2.HasInsertAndReplaceRange.toNegated()
  }, {
    menuId: suggestWidgetStatusbarMenu,
    title: localize("accept.insert", "Insert"),
    group: "left",
    order: 1,
    when: ContextKeyExpr.and(Context$2.HasInsertAndReplaceRange, Context$2.InsertMode.isEqualTo("insert"))
  }, {
    menuId: suggestWidgetStatusbarMenu,
    title: localize("accept.replace", "Replace"),
    group: "left",
    order: 1,
    when: ContextKeyExpr.and(Context$2.HasInsertAndReplaceRange, Context$2.InsertMode.isEqualTo("replace"))
  }]
}));
registerEditorCommand(new SuggestCommand({
  id: "acceptAlternativeSelectedSuggestion",
  precondition: ContextKeyExpr.and(Context$2.Visible, EditorContextKeys.textInputFocus, Context$2.HasFocusedSuggestion),
  kbOpts: {
    weight: weight$2,
    kbExpr: EditorContextKeys.textInputFocus,
    primary: 1024 | 3,
    secondary: [
      1024 | 2
      /* KeyCode.Tab */
    ]
  },
  handler(x) {
    x.acceptSelectedSuggestion(false, true);
  },
  menuOpts: [{
    menuId: suggestWidgetStatusbarMenu,
    group: "left",
    order: 2,
    when: ContextKeyExpr.and(Context$2.HasInsertAndReplaceRange, Context$2.InsertMode.isEqualTo("insert")),
    title: localize("accept.replace", "Replace")
  }, {
    menuId: suggestWidgetStatusbarMenu,
    group: "left",
    order: 2,
    when: ContextKeyExpr.and(Context$2.HasInsertAndReplaceRange, Context$2.InsertMode.isEqualTo("replace")),
    title: localize("accept.insert", "Insert")
  }]
}));
CommandsRegistry.registerCommandAlias("acceptSelectedSuggestionOnEnter", "acceptSelectedSuggestion");
registerEditorCommand(new SuggestCommand({
  id: "hideSuggestWidget",
  precondition: Context$2.Visible,
  handler: (x) => x.cancelSuggestWidget(),
  kbOpts: {
    weight: weight$2,
    kbExpr: EditorContextKeys.textInputFocus,
    primary: 9,
    secondary: [
      1024 | 9
      /* KeyCode.Escape */
    ]
  }
}));
registerEditorCommand(new SuggestCommand({
  id: "selectNextSuggestion",
  precondition: ContextKeyExpr.and(Context$2.Visible, ContextKeyExpr.or(Context$2.MultipleSuggestions, Context$2.HasFocusedSuggestion.negate())),
  handler: (c) => c.selectNextSuggestion(),
  kbOpts: {
    weight: weight$2,
    kbExpr: EditorContextKeys.textInputFocus,
    primary: 18,
    secondary: [
      2048 | 18
      /* KeyCode.DownArrow */
    ],
    mac: { primary: 18, secondary: [
      2048 | 18,
      256 | 44
      /* KeyCode.KeyN */
    ] }
  }
}));
registerEditorCommand(new SuggestCommand({
  id: "selectNextPageSuggestion",
  precondition: ContextKeyExpr.and(Context$2.Visible, ContextKeyExpr.or(Context$2.MultipleSuggestions, Context$2.HasFocusedSuggestion.negate())),
  handler: (c) => c.selectNextPageSuggestion(),
  kbOpts: {
    weight: weight$2,
    kbExpr: EditorContextKeys.textInputFocus,
    primary: 12,
    secondary: [
      2048 | 12
      /* KeyCode.PageDown */
    ]
  }
}));
registerEditorCommand(new SuggestCommand({
  id: "selectLastSuggestion",
  precondition: ContextKeyExpr.and(Context$2.Visible, ContextKeyExpr.or(Context$2.MultipleSuggestions, Context$2.HasFocusedSuggestion.negate())),
  handler: (c) => c.selectLastSuggestion()
}));
registerEditorCommand(new SuggestCommand({
  id: "selectPrevSuggestion",
  precondition: ContextKeyExpr.and(Context$2.Visible, ContextKeyExpr.or(Context$2.MultipleSuggestions, Context$2.HasFocusedSuggestion.negate())),
  handler: (c) => c.selectPrevSuggestion(),
  kbOpts: {
    weight: weight$2,
    kbExpr: EditorContextKeys.textInputFocus,
    primary: 16,
    secondary: [
      2048 | 16
      /* KeyCode.UpArrow */
    ],
    mac: { primary: 16, secondary: [
      2048 | 16,
      256 | 46
      /* KeyCode.KeyP */
    ] }
  }
}));
registerEditorCommand(new SuggestCommand({
  id: "selectPrevPageSuggestion",
  precondition: ContextKeyExpr.and(Context$2.Visible, ContextKeyExpr.or(Context$2.MultipleSuggestions, Context$2.HasFocusedSuggestion.negate())),
  handler: (c) => c.selectPrevPageSuggestion(),
  kbOpts: {
    weight: weight$2,
    kbExpr: EditorContextKeys.textInputFocus,
    primary: 11,
    secondary: [
      2048 | 11
      /* KeyCode.PageUp */
    ]
  }
}));
registerEditorCommand(new SuggestCommand({
  id: "selectFirstSuggestion",
  precondition: ContextKeyExpr.and(Context$2.Visible, ContextKeyExpr.or(Context$2.MultipleSuggestions, Context$2.HasFocusedSuggestion.negate())),
  handler: (c) => c.selectFirstSuggestion()
}));
registerEditorCommand(new SuggestCommand({
  id: "focusSuggestion",
  precondition: ContextKeyExpr.and(Context$2.Visible, Context$2.HasFocusedSuggestion.negate()),
  handler: (x) => x.focusSuggestion(),
  kbOpts: {
    weight: weight$2,
    kbExpr: EditorContextKeys.textInputFocus,
    primary: 2048 | 10,
    secondary: [
      2048 | 39
      /* KeyCode.KeyI */
    ],
    mac: { primary: 256 | 10, secondary: [
      2048 | 39
      /* KeyCode.KeyI */
    ] }
  }
}));
registerEditorCommand(new SuggestCommand({
  id: "focusAndAcceptSuggestion",
  precondition: ContextKeyExpr.and(Context$2.Visible, Context$2.HasFocusedSuggestion.negate()),
  handler: (c) => {
    c.focusSuggestion();
    c.acceptSelectedSuggestion(true, false);
  }
}));
registerEditorCommand(new SuggestCommand({
  id: "toggleSuggestionDetails",
  precondition: ContextKeyExpr.and(Context$2.Visible, Context$2.HasFocusedSuggestion),
  handler: (x) => x.toggleSuggestionDetails(),
  kbOpts: {
    weight: weight$2,
    kbExpr: EditorContextKeys.textInputFocus,
    primary: 2048 | 10,
    secondary: [
      2048 | 39
      /* KeyCode.KeyI */
    ],
    mac: { primary: 256 | 10, secondary: [
      2048 | 39
      /* KeyCode.KeyI */
    ] }
  },
  menuOpts: [{
    menuId: suggestWidgetStatusbarMenu,
    group: "right",
    order: 1,
    when: ContextKeyExpr.and(Context$2.DetailsVisible, Context$2.CanResolve),
    title: localize("detail.more", "show less")
  }, {
    menuId: suggestWidgetStatusbarMenu,
    group: "right",
    order: 1,
    when: ContextKeyExpr.and(Context$2.DetailsVisible.toNegated(), Context$2.CanResolve),
    title: localize("detail.less", "show more")
  }]
}));
registerEditorCommand(new SuggestCommand({
  id: "toggleExplainMode",
  precondition: Context$2.Visible,
  handler: (x) => x.toggleExplainMode(),
  kbOpts: {
    weight: 100,
    primary: 2048 | 90
  }
}));
registerEditorCommand(new SuggestCommand({
  id: "toggleSuggestionFocus",
  precondition: Context$2.Visible,
  handler: (x) => x.toggleSuggestionFocus(),
  kbOpts: {
    weight: weight$2,
    kbExpr: EditorContextKeys.textInputFocus,
    primary: 2048 | 512 | 10,
    mac: {
      primary: 256 | 512 | 10
      /* KeyCode.Space */
    }
  }
}));
registerEditorCommand(new SuggestCommand({
  id: "insertBestCompletion",
  precondition: ContextKeyExpr.and(EditorContextKeys.textInputFocus, ContextKeyExpr.equals("config.editor.tabCompletion", "on"), WordContextKey.AtEnd, Context$2.Visible.toNegated(), SuggestAlternatives.OtherSuggestions.toNegated(), SnippetController2.InSnippetMode.toNegated()),
  handler: (x, arg) => {
    x.triggerSuggestAndAcceptBest(isObject$4(arg) ? Object.assign({ fallback: "tab" }, arg) : { fallback: "tab" });
  },
  kbOpts: {
    weight: weight$2,
    primary: 2
    /* KeyCode.Tab */
  }
}));
registerEditorCommand(new SuggestCommand({
  id: "insertNextSuggestion",
  precondition: ContextKeyExpr.and(EditorContextKeys.textInputFocus, ContextKeyExpr.equals("config.editor.tabCompletion", "on"), SuggestAlternatives.OtherSuggestions, Context$2.Visible.toNegated(), SnippetController2.InSnippetMode.toNegated()),
  handler: (x) => x.acceptNextSuggestion(),
  kbOpts: {
    weight: weight$2,
    kbExpr: EditorContextKeys.textInputFocus,
    primary: 2
    /* KeyCode.Tab */
  }
}));
registerEditorCommand(new SuggestCommand({
  id: "insertPrevSuggestion",
  precondition: ContextKeyExpr.and(EditorContextKeys.textInputFocus, ContextKeyExpr.equals("config.editor.tabCompletion", "on"), SuggestAlternatives.OtherSuggestions, Context$2.Visible.toNegated(), SnippetController2.InSnippetMode.toNegated()),
  handler: (x) => x.acceptPrevSuggestion(),
  kbOpts: {
    weight: weight$2,
    kbExpr: EditorContextKeys.textInputFocus,
    primary: 1024 | 2
    /* KeyCode.Tab */
  }
}));
registerEditorAction(class extends EditorAction {
  constructor() {
    super({
      id: "editor.action.resetSuggestSize",
      label: localize("suggest.reset.label", "Reset Suggest Widget Size"),
      alias: "Reset Suggest Widget Size",
      precondition: void 0
    });
  }
  run(_accessor, editor2) {
    var _a2;
    (_a2 = SuggestController.get(editor2)) === null || _a2 === void 0 ? void 0 : _a2.resetWidgetSize();
  }
});
class SuggestWidgetAdaptor extends Disposable {
  get selectedItem() {
    return this._selectedItem;
  }
  constructor(editor2, suggestControllerPreselector, checkModelVersion) {
    super();
    this.editor = editor2;
    this.suggestControllerPreselector = suggestControllerPreselector;
    this.checkModelVersion = checkModelVersion;
    this.isSuggestWidgetVisible = false;
    this.isShiftKeyPressed = false;
    this._isActive = false;
    this._currentSuggestItemInfo = void 0;
    this._selectedItem = observableValue("suggestWidgetInlineCompletionProvider.selectedItem", void 0);
    this._register(editor2.onKeyDown((e) => {
      if (e.shiftKey && !this.isShiftKeyPressed) {
        this.isShiftKeyPressed = true;
        this.update(this._isActive);
      }
    }));
    this._register(editor2.onKeyUp((e) => {
      if (e.shiftKey && this.isShiftKeyPressed) {
        this.isShiftKeyPressed = false;
        this.update(this._isActive);
      }
    }));
    const suggestController = SuggestController.get(this.editor);
    if (suggestController) {
      this._register(suggestController.registerSelector({
        priority: 100,
        select: (model, pos, suggestItems) => {
          var _a2;
          transaction((tx) => this.checkModelVersion(tx));
          const textModel = this.editor.getModel();
          if (!textModel) {
            return -1;
          }
          const itemToPreselect = (_a2 = this.suggestControllerPreselector()) === null || _a2 === void 0 ? void 0 : _a2.removeCommonPrefix(textModel);
          if (!itemToPreselect) {
            return -1;
          }
          const position = Position$2.lift(pos);
          const candidates = suggestItems.map((suggestItem, index) => {
            const suggestItemInfo = SuggestItemInfo.fromSuggestion(suggestController, textModel, position, suggestItem, this.isShiftKeyPressed);
            const suggestItemTextEdit = suggestItemInfo.toSingleTextEdit().removeCommonPrefix(textModel);
            const valid = itemToPreselect.augments(suggestItemTextEdit);
            return { index, valid, prefixLength: suggestItemTextEdit.text.length, suggestItem };
          }).filter((item) => item && item.valid && item.prefixLength > 0);
          const result2 = findMaxBy(candidates, compareBy((s) => s.prefixLength, numberComparator));
          return result2 ? result2.index : -1;
        }
      }));
      let isBoundToSuggestWidget = false;
      const bindToSuggestWidget = () => {
        if (isBoundToSuggestWidget) {
          return;
        }
        isBoundToSuggestWidget = true;
        this._register(suggestController.widget.value.onDidShow(() => {
          this.isSuggestWidgetVisible = true;
          this.update(true);
        }));
        this._register(suggestController.widget.value.onDidHide(() => {
          this.isSuggestWidgetVisible = false;
          this.update(false);
        }));
        this._register(suggestController.widget.value.onDidFocus(() => {
          this.isSuggestWidgetVisible = true;
          this.update(true);
        }));
      };
      this._register(Event$1.once(suggestController.model.onDidTrigger)((e) => {
        bindToSuggestWidget();
      }));
    }
    this.update(this._isActive);
  }
  update(newActive) {
    const newInlineCompletion = this.getSuggestItemInfo();
    if (this._isActive !== newActive || !suggestItemInfoEquals(this._currentSuggestItemInfo, newInlineCompletion)) {
      this._isActive = newActive;
      this._currentSuggestItemInfo = newInlineCompletion;
      transaction((tx) => {
        this.checkModelVersion(tx);
        this._selectedItem.set(this._isActive ? this._currentSuggestItemInfo : void 0, tx);
      });
    }
  }
  getSuggestItemInfo() {
    const suggestController = SuggestController.get(this.editor);
    if (!suggestController || !this.isSuggestWidgetVisible) {
      return void 0;
    }
    const focusedItem = suggestController.widget.value.getFocusedItem();
    const position = this.editor.getPosition();
    const model = this.editor.getModel();
    if (!focusedItem || !position || !model) {
      return void 0;
    }
    return SuggestItemInfo.fromSuggestion(suggestController, model, position, focusedItem.item, this.isShiftKeyPressed);
  }
  stopForceRenderingAbove() {
    const suggestController = SuggestController.get(this.editor);
    suggestController === null || suggestController === void 0 ? void 0 : suggestController.stopForceRenderingAbove();
  }
  forceRenderingAbove() {
    const suggestController = SuggestController.get(this.editor);
    suggestController === null || suggestController === void 0 ? void 0 : suggestController.forceRenderingAbove();
  }
}
class SuggestItemInfo {
  static fromSuggestion(suggestController, model, position, item, toggleMode) {
    let { insertText } = item.completion;
    let isSnippetText = false;
    if (item.completion.insertTextRules & 4) {
      const snippet = new SnippetParser().parse(insertText);
      if (snippet.children.length < 100) {
        SnippetSession.adjustWhitespace(model, position, true, snippet);
      }
      insertText = snippet.toString();
      isSnippetText = true;
    }
    const info = suggestController.getOverwriteInfo(item, toggleMode);
    return new SuggestItemInfo(Range$2.fromPositions(position.delta(0, -info.overwriteBefore), position.delta(0, Math.max(info.overwriteAfter, 0))), insertText, item.completion.kind, isSnippetText);
  }
  constructor(range2, insertText, completionItemKind, isSnippetText) {
    this.range = range2;
    this.insertText = insertText;
    this.completionItemKind = completionItemKind;
    this.isSnippetText = isSnippetText;
  }
  equals(other) {
    return this.range.equalsRange(other.range) && this.insertText === other.insertText && this.completionItemKind === other.completionItemKind && this.isSnippetText === other.isSnippetText;
  }
  toSelectedSuggestionInfo() {
    return new SelectedSuggestionInfo(this.range, this.insertText, this.completionItemKind, this.isSnippetText);
  }
  toSingleTextEdit() {
    return new SingleTextEdit(this.range, this.insertText);
  }
}
function suggestItemInfoEquals(a, b) {
  if (a === b) {
    return true;
  }
  if (!a || !b) {
    return false;
  }
  return a.equals(b);
}
var __decorate$Z = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$X = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let InlineCompletionsController = class InlineCompletionsController2 extends Disposable {
  static get(editor2) {
    return editor2.getContribution(InlineCompletionsController2.ID);
  }
  constructor(editor2, instantiationService, contextKeyService, configurationService, commandService, debounceService, languageFeaturesService, audioCueService) {
    super();
    this.editor = editor2;
    this.instantiationService = instantiationService;
    this.contextKeyService = contextKeyService;
    this.configurationService = configurationService;
    this.commandService = commandService;
    this.debounceService = debounceService;
    this.languageFeaturesService = languageFeaturesService;
    this.audioCueService = audioCueService;
    this.model = disposableObservableValue("inlineCompletionModel", void 0);
    this.textModelVersionId = observableValue("textModelVersionId", -1);
    this.cursorPosition = observableValue("cursorPosition", new Position$2(1, 1));
    this.suggestWidgetAdaptor = this._register(new SuggestWidgetAdaptor(this.editor, () => {
      var _a2, _b2;
      return (_b2 = (_a2 = this.model.get()) === null || _a2 === void 0 ? void 0 : _a2.selectedInlineCompletion.get()) === null || _b2 === void 0 ? void 0 : _b2.toSingleTextEdit(void 0);
    }, (tx) => this.updateObservables(tx, VersionIdChangeReason.Other)));
    this._enabled = observableFromEvent(this.editor.onDidChangeConfiguration, () => this.editor.getOption(
      61
      /* EditorOption.inlineSuggest */
    ).enabled);
    this.ghostTextWidget = this._register(this.instantiationService.createInstance(GhostTextWidget, this.editor, {
      ghostText: this.model.map((v, reader) => v === null || v === void 0 ? void 0 : v.ghostText.read(reader)),
      minReservedLineCount: constObservable(0),
      targetTextModel: this.model.map((v) => v === null || v === void 0 ? void 0 : v.textModel)
    }));
    this._debounceValue = this.debounceService.for(this.languageFeaturesService.inlineCompletionsProvider, "InlineCompletionsDebounce", { min: 50, max: 50 });
    this._register(new InlineCompletionContextKeys(this.contextKeyService, this.model));
    this._register(Event$1.runAndSubscribe(editor2.onDidChangeModel, () => transaction((tx) => {
      this.model.set(void 0, tx);
      this.updateObservables(tx, VersionIdChangeReason.Other);
      const textModel = editor2.getModel();
      if (textModel) {
        const model = instantiationService.createInstance(InlineCompletionsModel, textModel, this.suggestWidgetAdaptor.selectedItem, this.cursorPosition, this.textModelVersionId, this._debounceValue, observableFromEvent(editor2.onDidChangeConfiguration, () => editor2.getOption(
          116
          /* EditorOption.suggest */
        ).preview), observableFromEvent(editor2.onDidChangeConfiguration, () => editor2.getOption(
          116
          /* EditorOption.suggest */
        ).previewMode), observableFromEvent(editor2.onDidChangeConfiguration, () => editor2.getOption(
          61
          /* EditorOption.inlineSuggest */
        ).mode), this._enabled);
        this.model.set(model, tx);
      }
    })));
    const getReason = (e) => {
      var _a2;
      if (e.isUndoing) {
        return VersionIdChangeReason.Undo;
      }
      if (e.isRedoing) {
        return VersionIdChangeReason.Redo;
      }
      if ((_a2 = this.model.get()) === null || _a2 === void 0 ? void 0 : _a2.isAcceptingPartially) {
        return VersionIdChangeReason.AcceptWord;
      }
      return VersionIdChangeReason.Other;
    };
    this._register(editor2.onDidChangeModelContent((e) => transaction((tx) => (
      /** @description onDidChangeModelContent */
      this.updateObservables(tx, getReason(e))
    ))));
    this._register(editor2.onDidChangeCursorPosition((e) => transaction((tx) => {
      var _a2;
      this.updateObservables(tx, VersionIdChangeReason.Other);
      if (e.reason === 3) {
        (_a2 = this.model.get()) === null || _a2 === void 0 ? void 0 : _a2.stop(tx);
      }
    })));
    this._register(editor2.onDidType(() => transaction((tx) => {
      var _a2;
      this.updateObservables(tx, VersionIdChangeReason.Other);
      if (this._enabled.get()) {
        (_a2 = this.model.get()) === null || _a2 === void 0 ? void 0 : _a2.trigger(tx);
      }
    })));
    this._register(this.commandService.onDidExecuteCommand((e) => {
      const commands = /* @__PURE__ */ new Set([
        CoreEditingCommands.Tab.id,
        CoreEditingCommands.DeleteLeft.id,
        CoreEditingCommands.DeleteRight.id,
        inlineSuggestCommitId,
        "acceptSelectedSuggestion"
      ]);
      if (commands.has(e.commandId) && editor2.hasTextFocus() && this._enabled.get()) {
        transaction((tx) => {
          var _a2;
          (_a2 = this.model.get()) === null || _a2 === void 0 ? void 0 : _a2.trigger(tx);
        });
      }
    }));
    this._register(this.editor.onDidBlurEditorWidget(() => {
      if (this.configurationService.getValue("editor.inlineSuggest.keepOnBlur") || editor2.getOption(
        61
        /* EditorOption.inlineSuggest */
      ).keepOnBlur) {
        return;
      }
      if (InlineSuggestionHintsContentWidget.dropDownVisible) {
        return;
      }
      transaction((tx) => {
        var _a2;
        (_a2 = this.model.get()) === null || _a2 === void 0 ? void 0 : _a2.stop(tx);
      });
    }));
    this._register(autorun("forceRenderingAbove", (reader) => {
      var _a2;
      const state = (_a2 = this.model.read(reader)) === null || _a2 === void 0 ? void 0 : _a2.state.read(reader);
      if (state === null || state === void 0 ? void 0 : state.suggestItem) {
        if (state.ghostText.lineCount >= 2) {
          this.suggestWidgetAdaptor.forceRenderingAbove();
        }
      } else {
        this.suggestWidgetAdaptor.stopForceRenderingAbove();
      }
    }));
    this._register(toDisposable(() => {
      this.suggestWidgetAdaptor.stopForceRenderingAbove();
    }));
    let lastInlineCompletionId = void 0;
    this._register(autorun("play audio cue & read suggestion", (reader) => {
      const model = this.model.read(reader);
      const state = model === null || model === void 0 ? void 0 : model.state.read(reader);
      if (!model || !state || !state.inlineCompletion) {
        lastInlineCompletionId = void 0;
        return;
      }
      if (state.inlineCompletion.semanticId !== lastInlineCompletionId) {
        lastInlineCompletionId = state.inlineCompletion.semanticId;
        const lineText = model.textModel.getLineContent(state.ghostText.lineNumber);
        this.audioCueService.playAudioCue(AudioCue.inlineSuggestion).then(() => {
          if (this.editor.getOption(
            7
            /* EditorOption.screenReaderAnnounceInlineSuggestion */
          )) {
            alert(state.ghostText.renderForScreenReader(lineText));
          }
        });
      }
    }));
    this._register(new InlineCompletionsHintsWidget(this.editor, this.model, this.instantiationService));
  }
  /**
   * Copies over the relevant state from the text model to observables.
   * This solves all kind of eventing issues, as we make sure we always operate on the latest state,
   * regardless of who calls into us.
   */
  updateObservables(tx, changeReason) {
    var _a2, _b2;
    const newModel = this.editor.getModel();
    this.textModelVersionId.set((_a2 = newModel === null || newModel === void 0 ? void 0 : newModel.getVersionId()) !== null && _a2 !== void 0 ? _a2 : -1, tx, changeReason);
    this.cursorPosition.set((_b2 = this.editor.getPosition()) !== null && _b2 !== void 0 ? _b2 : new Position$2(1, 1), tx);
  }
  shouldShowHoverAt(range2) {
    var _a2;
    const ghostText2 = (_a2 = this.model.get()) === null || _a2 === void 0 ? void 0 : _a2.ghostText.get();
    if (ghostText2) {
      return ghostText2.parts.some((p2) => range2.containsPosition(new Position$2(ghostText2.lineNumber, p2.column)));
    }
    return false;
  }
  shouldShowHoverAtViewZone(viewZoneId) {
    return this.ghostTextWidget.ownsViewZone(viewZoneId);
  }
};
InlineCompletionsController.ID = "editor.contrib.inlineCompletionsController";
InlineCompletionsController = __decorate$Z([
  __param$X(1, IInstantiationService),
  __param$X(2, IContextKeyService),
  __param$X(3, IConfigurationService),
  __param$X(4, ICommandService),
  __param$X(5, ILanguageFeatureDebounceService),
  __param$X(6, ILanguageFeaturesService),
  __param$X(7, IAudioCueService)
], InlineCompletionsController);
var __awaiter$C = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class ShowNextInlineSuggestionAction extends EditorAction {
  constructor() {
    super({
      id: ShowNextInlineSuggestionAction.ID,
      label: localize("action.inlineSuggest.showNext", "Show Next Inline Suggestion"),
      alias: "Show Next Inline Suggestion",
      precondition: ContextKeyExpr.and(EditorContextKeys.writable, InlineCompletionContextKeys.inlineSuggestionVisible),
      kbOpts: {
        weight: 100,
        primary: 512 | 94
      }
    });
  }
  run(accessor, editor2) {
    var _a2;
    return __awaiter$C(this, void 0, void 0, function* () {
      const controller = InlineCompletionsController.get(editor2);
      (_a2 = controller === null || controller === void 0 ? void 0 : controller.model.get()) === null || _a2 === void 0 ? void 0 : _a2.next();
    });
  }
}
ShowNextInlineSuggestionAction.ID = showNextInlineSuggestionActionId;
class ShowPreviousInlineSuggestionAction extends EditorAction {
  constructor() {
    super({
      id: ShowPreviousInlineSuggestionAction.ID,
      label: localize("action.inlineSuggest.showPrevious", "Show Previous Inline Suggestion"),
      alias: "Show Previous Inline Suggestion",
      precondition: ContextKeyExpr.and(EditorContextKeys.writable, InlineCompletionContextKeys.inlineSuggestionVisible),
      kbOpts: {
        weight: 100,
        primary: 512 | 92
      }
    });
  }
  run(accessor, editor2) {
    var _a2;
    return __awaiter$C(this, void 0, void 0, function* () {
      const controller = InlineCompletionsController.get(editor2);
      (_a2 = controller === null || controller === void 0 ? void 0 : controller.model.get()) === null || _a2 === void 0 ? void 0 : _a2.previous();
    });
  }
}
ShowPreviousInlineSuggestionAction.ID = showPreviousInlineSuggestionActionId;
class TriggerInlineSuggestionAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.inlineSuggest.trigger",
      label: localize("action.inlineSuggest.trigger", "Trigger Inline Suggestion"),
      alias: "Trigger Inline Suggestion",
      precondition: EditorContextKeys.writable
    });
  }
  run(accessor, editor2) {
    var _a2;
    return __awaiter$C(this, void 0, void 0, function* () {
      const controller = InlineCompletionsController.get(editor2);
      (_a2 = controller === null || controller === void 0 ? void 0 : controller.model.get()) === null || _a2 === void 0 ? void 0 : _a2.triggerExplicitly();
    });
  }
}
class AcceptNextWordOfInlineCompletion extends EditorAction {
  constructor() {
    super({
      id: "editor.action.inlineSuggest.acceptNextWord",
      label: localize("action.inlineSuggest.acceptNextWord", "Accept Next Word Of Inline Suggestion"),
      alias: "Accept Next Word Of Inline Suggestion",
      precondition: ContextKeyExpr.and(EditorContextKeys.writable, InlineCompletionContextKeys.inlineSuggestionVisible),
      kbOpts: {
        weight: 100 + 1,
        primary: 2048 | 17,
        kbExpr: ContextKeyExpr.and(EditorContextKeys.writable, InlineCompletionContextKeys.inlineSuggestionVisible)
      },
      menuOpts: [{
        menuId: MenuId.InlineSuggestionToolbar,
        title: localize("acceptWord", "Accept Word"),
        group: "primary",
        order: 2
      }]
    });
  }
  run(accessor, editor2) {
    var _a2;
    return __awaiter$C(this, void 0, void 0, function* () {
      const controller = InlineCompletionsController.get(editor2);
      yield (_a2 = controller === null || controller === void 0 ? void 0 : controller.model.get()) === null || _a2 === void 0 ? void 0 : _a2.acceptNextWord(controller.editor);
    });
  }
}
class AcceptNextLineOfInlineCompletion extends EditorAction {
  constructor() {
    super({
      id: "editor.action.inlineSuggest.acceptNextLine",
      label: localize("action.inlineSuggest.acceptNextLine", "Accept Next Line Of Inline Suggestion"),
      alias: "Accept Next Line Of Inline Suggestion",
      precondition: ContextKeyExpr.and(EditorContextKeys.writable, InlineCompletionContextKeys.inlineSuggestionVisible),
      kbOpts: {
        weight: 100 + 1
      },
      menuOpts: [{
        menuId: MenuId.InlineSuggestionToolbar,
        title: localize("acceptLine", "Accept Line"),
        group: "secondary",
        order: 2
      }]
    });
  }
  run(accessor, editor2) {
    var _a2;
    return __awaiter$C(this, void 0, void 0, function* () {
      const controller = InlineCompletionsController.get(editor2);
      yield (_a2 = controller === null || controller === void 0 ? void 0 : controller.model.get()) === null || _a2 === void 0 ? void 0 : _a2.acceptNextLine(controller.editor);
    });
  }
}
class AcceptInlineCompletion extends EditorAction {
  constructor() {
    super({
      id: inlineSuggestCommitId,
      label: localize("action.inlineSuggest.accept", "Accept Inline Suggestion"),
      alias: "Accept Inline Suggestion",
      precondition: InlineCompletionContextKeys.inlineSuggestionVisible,
      menuOpts: [{
        menuId: MenuId.InlineSuggestionToolbar,
        title: localize("accept", "Accept"),
        group: "primary",
        order: 1
      }],
      kbOpts: {
        primary: 2,
        weight: 200,
        kbExpr: ContextKeyExpr.and(InlineCompletionContextKeys.inlineSuggestionVisible, EditorContextKeys.tabMovesFocus.toNegated(), InlineCompletionContextKeys.inlineSuggestionHasIndentationLessThanTabSize, Context$2.Visible.toNegated())
      }
    });
  }
  run(accessor, editor2) {
    var _a2;
    return __awaiter$C(this, void 0, void 0, function* () {
      const controller = InlineCompletionsController.get(editor2);
      if (controller) {
        (_a2 = controller.model.get()) === null || _a2 === void 0 ? void 0 : _a2.accept(controller.editor);
        controller.editor.focus();
      }
    });
  }
}
class HideInlineCompletion extends EditorAction {
  constructor() {
    super({
      id: HideInlineCompletion.ID,
      label: localize("action.inlineSuggest.hide", "Hide Inline Suggestion"),
      alias: "Hide Inline Suggestion",
      precondition: InlineCompletionContextKeys.inlineSuggestionVisible,
      kbOpts: {
        weight: 100,
        primary: 9
      }
    });
  }
  run(accessor, editor2) {
    return __awaiter$C(this, void 0, void 0, function* () {
      const controller = InlineCompletionsController.get(editor2);
      transaction((tx) => {
        var _a2;
        (_a2 = controller === null || controller === void 0 ? void 0 : controller.model.get()) === null || _a2 === void 0 ? void 0 : _a2.stop(tx);
      });
    });
  }
}
HideInlineCompletion.ID = "editor.action.inlineSuggest.hide";
class ToggleAlwaysShowInlineSuggestionToolbar extends Action2 {
  constructor() {
    super({
      id: ToggleAlwaysShowInlineSuggestionToolbar.ID,
      title: localize("action.inlineSuggest.alwaysShowToolbar", "Always Show Toolbar"),
      f1: false,
      precondition: void 0,
      menu: [{
        id: MenuId.InlineSuggestionToolbar,
        group: "secondary",
        order: 10
      }],
      toggled: ContextKeyExpr.equals("config.editor.inlineSuggest.showToolbar", "always")
    });
  }
  run(accessor, editor2) {
    return __awaiter$C(this, void 0, void 0, function* () {
      const configService = accessor.get(IConfigurationService);
      const currentValue = configService.getValue("editor.inlineSuggest.showToolbar");
      const newValue = currentValue === "always" ? "onHover" : "always";
      configService.updateValue("editor.inlineSuggest.showToolbar", newValue);
    });
  }
}
ToggleAlwaysShowInlineSuggestionToolbar.ID = "editor.action.inlineSuggest.toggleAlwaysShowToolbar";
var __decorate$Y = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$W = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
class InlineCompletionsHover {
  constructor(owner, range2, controller) {
    this.owner = owner;
    this.range = range2;
    this.controller = controller;
  }
  isValidForHoverAnchor(anchor) {
    return anchor.type === 1 && this.range.startColumn <= anchor.range.startColumn && this.range.endColumn >= anchor.range.endColumn;
  }
}
let InlineCompletionsHoverParticipant = class InlineCompletionsHoverParticipant2 {
  constructor(_editor, _languageService, _openerService, accessibilityService, _instantiationService, _telemetryService) {
    this._editor = _editor;
    this._languageService = _languageService;
    this._openerService = _openerService;
    this.accessibilityService = accessibilityService;
    this._instantiationService = _instantiationService;
    this._telemetryService = _telemetryService;
    this.hoverOrdinal = 4;
  }
  suggestHoverAnchor(mouseEvent) {
    const controller = InlineCompletionsController.get(this._editor);
    if (!controller) {
      return null;
    }
    const target = mouseEvent.target;
    if (target.type === 8) {
      const viewZoneData = target.detail;
      if (controller.shouldShowHoverAtViewZone(viewZoneData.viewZoneId)) {
        return new HoverForeignElementAnchor(1e3, this, Range$2.fromPositions(this._editor.getModel().validatePosition(viewZoneData.positionBefore || viewZoneData.position)), mouseEvent.event.posx, mouseEvent.event.posy, false);
      }
    }
    if (target.type === 7) {
      if (controller.shouldShowHoverAt(target.range)) {
        return new HoverForeignElementAnchor(1e3, this, target.range, mouseEvent.event.posx, mouseEvent.event.posy, false);
      }
    }
    if (target.type === 6) {
      const mightBeForeignElement = target.detail.mightBeForeignElement;
      if (mightBeForeignElement && controller.shouldShowHoverAt(target.range)) {
        return new HoverForeignElementAnchor(1e3, this, target.range, mouseEvent.event.posx, mouseEvent.event.posy, false);
      }
    }
    return null;
  }
  computeSync(anchor, lineDecorations) {
    if (this._editor.getOption(
      61
      /* EditorOption.inlineSuggest */
    ).showToolbar === "always") {
      return [];
    }
    const controller = InlineCompletionsController.get(this._editor);
    if (controller && controller.shouldShowHoverAt(anchor.range)) {
      return [new InlineCompletionsHover(this, anchor.range, controller)];
    }
    return [];
  }
  renderHoverParts(context, hoverParts) {
    const disposableStore = new DisposableStore();
    const part = hoverParts[0];
    this._telemetryService.publicLog2("inlineCompletionHover.shown");
    if (this.accessibilityService.isScreenReaderOptimized() && !this._editor.getOption(
      7
      /* EditorOption.screenReaderAnnounceInlineSuggestion */
    )) {
      this.renderScreenReaderText(context, part, disposableStore);
    }
    const model = part.controller.model.get();
    const w = this._instantiationService.createInstance(InlineSuggestionHintsContentWidget, this._editor, false, constObservable(null), model.selectedInlineCompletionIndex, model.inlineCompletionsCount, model.selectedInlineCompletion.map((v) => {
      var _a2;
      return (_a2 = v === null || v === void 0 ? void 0 : v.inlineCompletion.source.inlineCompletions.commands) !== null && _a2 !== void 0 ? _a2 : [];
    }));
    context.fragment.appendChild(w.getDomNode());
    model.triggerExplicitly();
    disposableStore.add(w);
    return disposableStore;
  }
  renderScreenReaderText(context, part, disposableStore) {
    const $2 = $$d;
    const markdownHoverElement = $2("div.hover-row.markdown-hover");
    const hoverContentsElement = append$1(markdownHoverElement, $2("div.hover-contents", { ["aria-live"]: "assertive" }));
    const renderer2 = disposableStore.add(new MarkdownRenderer({ editor: this._editor }, this._languageService, this._openerService));
    const render = (code) => {
      disposableStore.add(renderer2.onDidRenderAsync(() => {
        hoverContentsElement.className = "hover-contents code-hover-contents";
        context.onContentsChanged();
      }));
      const inlineSuggestionAvailable = localize("inlineSuggestionFollows", "Suggestion:");
      const renderedContents = disposableStore.add(renderer2.render(new MarkdownString().appendText(inlineSuggestionAvailable).appendCodeblock("text", code)));
      hoverContentsElement.replaceChildren(renderedContents.element);
    };
    disposableStore.add(autorun("update hover", (reader) => {
      var _a2;
      const ghostText2 = (_a2 = part.controller.model.read(reader)) === null || _a2 === void 0 ? void 0 : _a2.ghostText.read(reader);
      if (ghostText2) {
        const lineText = this._editor.getModel().getLineContent(ghostText2.lineNumber);
        render(ghostText2.renderForScreenReader(lineText));
      } else {
        reset(hoverContentsElement);
      }
    }));
    context.fragment.appendChild(markdownHoverElement);
  }
};
InlineCompletionsHoverParticipant = __decorate$Y([
  __param$W(1, ILanguageService),
  __param$W(2, IOpenerService),
  __param$W(3, IAccessibilityService),
  __param$W(4, IInstantiationService),
  __param$W(5, ITelemetryService)
], InlineCompletionsHoverParticipant);
registerEditorContribution(
  InlineCompletionsController.ID,
  InlineCompletionsController,
  3
  /* EditorContributionInstantiation.Eventually */
);
registerEditorAction(TriggerInlineSuggestionAction);
registerEditorAction(ShowNextInlineSuggestionAction);
registerEditorAction(ShowPreviousInlineSuggestionAction);
registerEditorAction(AcceptNextWordOfInlineCompletion);
registerEditorAction(AcceptNextLineOfInlineCompletion);
registerEditorAction(AcceptInlineCompletion);
registerEditorAction(HideInlineCompletion);
registerAction2(ToggleAlwaysShowInlineSuggestionToolbar);
HoverParticipantRegistry.register(InlineCompletionsHoverParticipant);
function getSpaceCnt(str2, tabSize) {
  let spacesCnt = 0;
  for (let i = 0; i < str2.length; i++) {
    if (str2.charAt(i) === "	") {
      spacesCnt += tabSize;
    } else {
      spacesCnt++;
    }
  }
  return spacesCnt;
}
function generateIndent(spacesCnt, tabSize, insertSpaces) {
  spacesCnt = spacesCnt < 0 ? 0 : spacesCnt;
  let result2 = "";
  if (!insertSpaces) {
    const tabsCnt = Math.floor(spacesCnt / tabSize);
    spacesCnt = spacesCnt % tabSize;
    for (let i = 0; i < tabsCnt; i++) {
      result2 += "	";
    }
  }
  for (let i = 0; i < spacesCnt; i++) {
    result2 += " ";
  }
  return result2;
}
var __decorate$X = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$V = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
function getReindentEditOperations(model, languageConfigurationService, startLineNumber, endLineNumber, inheritedIndent) {
  if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) {
    return [];
  }
  const indentationRules = languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).indentationRules;
  if (!indentationRules) {
    return [];
  }
  endLineNumber = Math.min(endLineNumber, model.getLineCount());
  while (startLineNumber <= endLineNumber) {
    if (!indentationRules.unIndentedLinePattern) {
      break;
    }
    const text2 = model.getLineContent(startLineNumber);
    if (!indentationRules.unIndentedLinePattern.test(text2)) {
      break;
    }
    startLineNumber++;
  }
  if (startLineNumber > endLineNumber - 1) {
    return [];
  }
  const { tabSize, indentSize, insertSpaces } = model.getOptions();
  const shiftIndent = (indentation, count) => {
    count = count || 1;
    return ShiftCommand.shiftIndent(indentation, indentation.length + count, tabSize, indentSize, insertSpaces);
  };
  const unshiftIndent = (indentation, count) => {
    count = count || 1;
    return ShiftCommand.unshiftIndent(indentation, indentation.length + count, tabSize, indentSize, insertSpaces);
  };
  const indentEdits = [];
  let globalIndent;
  const currentLineText = model.getLineContent(startLineNumber);
  let adjustedLineContent = currentLineText;
  if (inheritedIndent !== void 0 && inheritedIndent !== null) {
    globalIndent = inheritedIndent;
    const oldIndentation = getLeadingWhitespace(currentLineText);
    adjustedLineContent = globalIndent + currentLineText.substring(oldIndentation.length);
    if (indentationRules.decreaseIndentPattern && indentationRules.decreaseIndentPattern.test(adjustedLineContent)) {
      globalIndent = unshiftIndent(globalIndent);
      adjustedLineContent = globalIndent + currentLineText.substring(oldIndentation.length);
    }
    if (currentLineText !== adjustedLineContent) {
      indentEdits.push(EditOperation.replaceMove(new Selection$1(startLineNumber, 1, startLineNumber, oldIndentation.length + 1), normalizeIndentation(globalIndent, indentSize, insertSpaces)));
    }
  } else {
    globalIndent = getLeadingWhitespace(currentLineText);
  }
  let idealIndentForNextLine = globalIndent;
  if (indentationRules.increaseIndentPattern && indentationRules.increaseIndentPattern.test(adjustedLineContent)) {
    idealIndentForNextLine = shiftIndent(idealIndentForNextLine);
    globalIndent = shiftIndent(globalIndent);
  } else if (indentationRules.indentNextLinePattern && indentationRules.indentNextLinePattern.test(adjustedLineContent)) {
    idealIndentForNextLine = shiftIndent(idealIndentForNextLine);
  }
  startLineNumber++;
  for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
    const text2 = model.getLineContent(lineNumber);
    const oldIndentation = getLeadingWhitespace(text2);
    const adjustedLineContent2 = idealIndentForNextLine + text2.substring(oldIndentation.length);
    if (indentationRules.decreaseIndentPattern && indentationRules.decreaseIndentPattern.test(adjustedLineContent2)) {
      idealIndentForNextLine = unshiftIndent(idealIndentForNextLine);
      globalIndent = unshiftIndent(globalIndent);
    }
    if (oldIndentation !== idealIndentForNextLine) {
      indentEdits.push(EditOperation.replaceMove(new Selection$1(lineNumber, 1, lineNumber, oldIndentation.length + 1), normalizeIndentation(idealIndentForNextLine, indentSize, insertSpaces)));
    }
    if (indentationRules.unIndentedLinePattern && indentationRules.unIndentedLinePattern.test(text2)) {
      continue;
    } else if (indentationRules.increaseIndentPattern && indentationRules.increaseIndentPattern.test(adjustedLineContent2)) {
      globalIndent = shiftIndent(globalIndent);
      idealIndentForNextLine = globalIndent;
    } else if (indentationRules.indentNextLinePattern && indentationRules.indentNextLinePattern.test(adjustedLineContent2)) {
      idealIndentForNextLine = shiftIndent(idealIndentForNextLine);
    } else {
      idealIndentForNextLine = globalIndent;
    }
  }
  return indentEdits;
}
class IndentationToSpacesAction extends EditorAction {
  constructor() {
    super({
      id: IndentationToSpacesAction.ID,
      label: localize("indentationToSpaces", "Convert Indentation to Spaces"),
      alias: "Convert Indentation to Spaces",
      precondition: EditorContextKeys.writable
    });
  }
  run(accessor, editor2) {
    const model = editor2.getModel();
    if (!model) {
      return;
    }
    const modelOpts = model.getOptions();
    const selection = editor2.getSelection();
    if (!selection) {
      return;
    }
    const command = new IndentationToSpacesCommand(selection, modelOpts.tabSize);
    editor2.pushUndoStop();
    editor2.executeCommands(this.id, [command]);
    editor2.pushUndoStop();
    model.updateOptions({
      insertSpaces: true
    });
  }
}
IndentationToSpacesAction.ID = "editor.action.indentationToSpaces";
class IndentationToTabsAction extends EditorAction {
  constructor() {
    super({
      id: IndentationToTabsAction.ID,
      label: localize("indentationToTabs", "Convert Indentation to Tabs"),
      alias: "Convert Indentation to Tabs",
      precondition: EditorContextKeys.writable
    });
  }
  run(accessor, editor2) {
    const model = editor2.getModel();
    if (!model) {
      return;
    }
    const modelOpts = model.getOptions();
    const selection = editor2.getSelection();
    if (!selection) {
      return;
    }
    const command = new IndentationToTabsCommand(selection, modelOpts.tabSize);
    editor2.pushUndoStop();
    editor2.executeCommands(this.id, [command]);
    editor2.pushUndoStop();
    model.updateOptions({
      insertSpaces: false
    });
  }
}
IndentationToTabsAction.ID = "editor.action.indentationToTabs";
class ChangeIndentationSizeAction extends EditorAction {
  constructor(insertSpaces, displaySizeOnly, opts) {
    super(opts);
    this.insertSpaces = insertSpaces;
    this.displaySizeOnly = displaySizeOnly;
  }
  run(accessor, editor2) {
    const quickInputService = accessor.get(IQuickInputService);
    const modelService = accessor.get(IModelService);
    const model = editor2.getModel();
    if (!model) {
      return;
    }
    const creationOpts = modelService.getCreationOptions(model.getLanguageId(), model.uri, model.isForSimpleWidget);
    const modelOpts = model.getOptions();
    const picks = [1, 2, 3, 4, 5, 6, 7, 8].map((n2) => ({
      id: n2.toString(),
      label: n2.toString(),
      // add description for tabSize value set in the configuration
      description: n2 === creationOpts.tabSize && n2 === modelOpts.tabSize ? localize("configuredTabSize", "Configured Tab Size") : n2 === creationOpts.tabSize ? localize("defaultTabSize", "Default Tab Size") : n2 === modelOpts.tabSize ? localize("currentTabSize", "Current Tab Size") : void 0
    }));
    const autoFocusIndex = Math.min(model.getOptions().tabSize - 1, 7);
    setTimeout(
      () => {
        quickInputService.pick(picks, { placeHolder: localize({ key: "selectTabWidth", comment: ["Tab corresponds to the tab key"] }, "Select Tab Size for Current File"), activeItem: picks[autoFocusIndex] }).then((pick) => {
          if (pick) {
            if (model && !model.isDisposed()) {
              const pickedVal = parseInt(pick.label, 10);
              if (this.displaySizeOnly) {
                model.updateOptions({
                  tabSize: pickedVal
                });
              } else {
                model.updateOptions({
                  tabSize: pickedVal,
                  indentSize: pickedVal,
                  insertSpaces: this.insertSpaces
                });
              }
            }
          }
        });
      },
      50
      /* quick input is sensitive to being opened so soon after another */
    );
  }
}
class IndentUsingTabs extends ChangeIndentationSizeAction {
  constructor() {
    super(false, false, {
      id: IndentUsingTabs.ID,
      label: localize("indentUsingTabs", "Indent Using Tabs"),
      alias: "Indent Using Tabs",
      precondition: void 0
    });
  }
}
IndentUsingTabs.ID = "editor.action.indentUsingTabs";
class IndentUsingSpaces extends ChangeIndentationSizeAction {
  constructor() {
    super(true, false, {
      id: IndentUsingSpaces.ID,
      label: localize("indentUsingSpaces", "Indent Using Spaces"),
      alias: "Indent Using Spaces",
      precondition: void 0
    });
  }
}
IndentUsingSpaces.ID = "editor.action.indentUsingSpaces";
class ChangeTabDisplaySize extends ChangeIndentationSizeAction {
  constructor() {
    super(true, true, {
      id: ChangeTabDisplaySize.ID,
      label: localize("changeTabDisplaySize", "Change Tab Display Size"),
      alias: "Change Tab Display Size",
      precondition: void 0
    });
  }
}
ChangeTabDisplaySize.ID = "editor.action.changeTabDisplaySize";
class DetectIndentation extends EditorAction {
  constructor() {
    super({
      id: DetectIndentation.ID,
      label: localize("detectIndentation", "Detect Indentation from Content"),
      alias: "Detect Indentation from Content",
      precondition: void 0
    });
  }
  run(accessor, editor2) {
    const modelService = accessor.get(IModelService);
    const model = editor2.getModel();
    if (!model) {
      return;
    }
    const creationOpts = modelService.getCreationOptions(model.getLanguageId(), model.uri, model.isForSimpleWidget);
    model.detectIndentation(creationOpts.insertSpaces, creationOpts.tabSize);
  }
}
DetectIndentation.ID = "editor.action.detectIndentation";
class ReindentLinesAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.reindentlines",
      label: localize("editor.reindentlines", "Reindent Lines"),
      alias: "Reindent Lines",
      precondition: EditorContextKeys.writable
    });
  }
  run(accessor, editor2) {
    const languageConfigurationService = accessor.get(ILanguageConfigurationService);
    const model = editor2.getModel();
    if (!model) {
      return;
    }
    const edits = getReindentEditOperations(model, languageConfigurationService, 1, model.getLineCount());
    if (edits.length > 0) {
      editor2.pushUndoStop();
      editor2.executeEdits(this.id, edits);
      editor2.pushUndoStop();
    }
  }
}
class ReindentSelectedLinesAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.reindentselectedlines",
      label: localize("editor.reindentselectedlines", "Reindent Selected Lines"),
      alias: "Reindent Selected Lines",
      precondition: EditorContextKeys.writable
    });
  }
  run(accessor, editor2) {
    const languageConfigurationService = accessor.get(ILanguageConfigurationService);
    const model = editor2.getModel();
    if (!model) {
      return;
    }
    const selections2 = editor2.getSelections();
    if (selections2 === null) {
      return;
    }
    const edits = [];
    for (const selection of selections2) {
      let startLineNumber = selection.startLineNumber;
      let endLineNumber = selection.endLineNumber;
      if (startLineNumber !== endLineNumber && selection.endColumn === 1) {
        endLineNumber--;
      }
      if (startLineNumber === 1) {
        if (startLineNumber === endLineNumber) {
          continue;
        }
      } else {
        startLineNumber--;
      }
      const editOperations = getReindentEditOperations(model, languageConfigurationService, startLineNumber, endLineNumber);
      edits.push(...editOperations);
    }
    if (edits.length > 0) {
      editor2.pushUndoStop();
      editor2.executeEdits(this.id, edits);
      editor2.pushUndoStop();
    }
  }
}
class AutoIndentOnPasteCommand {
  constructor(edits, initialSelection) {
    this._initialSelection = initialSelection;
    this._edits = [];
    this._selectionId = null;
    for (const edit of edits) {
      if (edit.range && typeof edit.text === "string") {
        this._edits.push(edit);
      }
    }
  }
  getEditOperations(model, builder) {
    for (const edit of this._edits) {
      builder.addEditOperation(Range$2.lift(edit.range), edit.text);
    }
    let selectionIsSet = false;
    if (Array.isArray(this._edits) && this._edits.length === 1 && this._initialSelection.isEmpty()) {
      if (this._edits[0].range.startColumn === this._initialSelection.endColumn && this._edits[0].range.startLineNumber === this._initialSelection.endLineNumber) {
        selectionIsSet = true;
        this._selectionId = builder.trackSelection(this._initialSelection, true);
      } else if (this._edits[0].range.endColumn === this._initialSelection.startColumn && this._edits[0].range.endLineNumber === this._initialSelection.startLineNumber) {
        selectionIsSet = true;
        this._selectionId = builder.trackSelection(this._initialSelection, false);
      }
    }
    if (!selectionIsSet) {
      this._selectionId = builder.trackSelection(this._initialSelection);
    }
  }
  computeCursorState(model, helper) {
    return helper.getTrackedSelection(this._selectionId);
  }
}
let AutoIndentOnPaste = class AutoIndentOnPaste2 {
  constructor(editor2, _languageConfigurationService) {
    this.editor = editor2;
    this._languageConfigurationService = _languageConfigurationService;
    this.callOnDispose = new DisposableStore();
    this.callOnModel = new DisposableStore();
    this.callOnDispose.add(editor2.onDidChangeConfiguration(() => this.update()));
    this.callOnDispose.add(editor2.onDidChangeModel(() => this.update()));
    this.callOnDispose.add(editor2.onDidChangeModelLanguage(() => this.update()));
  }
  update() {
    this.callOnModel.clear();
    if (this.editor.getOption(
      11
      /* EditorOption.autoIndent */
    ) < 4 || this.editor.getOption(
      54
      /* EditorOption.formatOnPaste */
    )) {
      return;
    }
    if (!this.editor.hasModel()) {
      return;
    }
    this.callOnModel.add(this.editor.onDidPaste(({ range: range2 }) => {
      this.trigger(range2);
    }));
  }
  trigger(range2) {
    const selections2 = this.editor.getSelections();
    if (selections2 === null || selections2.length > 1) {
      return;
    }
    const model = this.editor.getModel();
    if (!model) {
      return;
    }
    if (!model.tokenization.isCheapToTokenize(range2.getStartPosition().lineNumber)) {
      return;
    }
    const autoIndent = this.editor.getOption(
      11
      /* EditorOption.autoIndent */
    );
    const { tabSize, indentSize, insertSpaces } = model.getOptions();
    const textEdits = [];
    const indentConverter = {
      shiftIndent: (indentation) => {
        return ShiftCommand.shiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces);
      },
      unshiftIndent: (indentation) => {
        return ShiftCommand.unshiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces);
      }
    };
    let startLineNumber = range2.startLineNumber;
    while (startLineNumber <= range2.endLineNumber) {
      if (this.shouldIgnoreLine(model, startLineNumber)) {
        startLineNumber++;
        continue;
      }
      break;
    }
    if (startLineNumber > range2.endLineNumber) {
      return;
    }
    let firstLineText = model.getLineContent(startLineNumber);
    if (!/\S/.test(firstLineText.substring(0, range2.startColumn - 1))) {
      const indentOfFirstLine = getGoodIndentForLine(autoIndent, model, model.getLanguageId(), startLineNumber, indentConverter, this._languageConfigurationService);
      if (indentOfFirstLine !== null) {
        const oldIndentation = getLeadingWhitespace(firstLineText);
        const newSpaceCnt = getSpaceCnt(indentOfFirstLine, tabSize);
        const oldSpaceCnt = getSpaceCnt(oldIndentation, tabSize);
        if (newSpaceCnt !== oldSpaceCnt) {
          const newIndent = generateIndent(newSpaceCnt, tabSize, insertSpaces);
          textEdits.push({
            range: new Range$2(startLineNumber, 1, startLineNumber, oldIndentation.length + 1),
            text: newIndent
          });
          firstLineText = newIndent + firstLineText.substr(oldIndentation.length);
        } else {
          const indentMetadata = getIndentMetadata(model, startLineNumber, this._languageConfigurationService);
          if (indentMetadata === 0 || indentMetadata === 8) {
            return;
          }
        }
      }
    }
    const firstLineNumber = startLineNumber;
    while (startLineNumber < range2.endLineNumber) {
      if (!/\S/.test(model.getLineContent(startLineNumber + 1))) {
        startLineNumber++;
        continue;
      }
      break;
    }
    if (startLineNumber !== range2.endLineNumber) {
      const virtualModel = {
        tokenization: {
          getLineTokens: (lineNumber) => {
            return model.tokenization.getLineTokens(lineNumber);
          },
          getLanguageId: () => {
            return model.getLanguageId();
          },
          getLanguageIdAtPosition: (lineNumber, column) => {
            return model.getLanguageIdAtPosition(lineNumber, column);
          }
        },
        getLineContent: (lineNumber) => {
          if (lineNumber === firstLineNumber) {
            return firstLineText;
          } else {
            return model.getLineContent(lineNumber);
          }
        }
      };
      const indentOfSecondLine = getGoodIndentForLine(autoIndent, virtualModel, model.getLanguageId(), startLineNumber + 1, indentConverter, this._languageConfigurationService);
      if (indentOfSecondLine !== null) {
        const newSpaceCntOfSecondLine = getSpaceCnt(indentOfSecondLine, tabSize);
        const oldSpaceCntOfSecondLine = getSpaceCnt(getLeadingWhitespace(model.getLineContent(startLineNumber + 1)), tabSize);
        if (newSpaceCntOfSecondLine !== oldSpaceCntOfSecondLine) {
          const spaceCntOffset = newSpaceCntOfSecondLine - oldSpaceCntOfSecondLine;
          for (let i = startLineNumber + 1; i <= range2.endLineNumber; i++) {
            const lineContent = model.getLineContent(i);
            const originalIndent = getLeadingWhitespace(lineContent);
            const originalSpacesCnt = getSpaceCnt(originalIndent, tabSize);
            const newSpacesCnt = originalSpacesCnt + spaceCntOffset;
            const newIndent = generateIndent(newSpacesCnt, tabSize, insertSpaces);
            if (newIndent !== originalIndent) {
              textEdits.push({
                range: new Range$2(i, 1, i, originalIndent.length + 1),
                text: newIndent
              });
            }
          }
        }
      }
    }
    if (textEdits.length > 0) {
      this.editor.pushUndoStop();
      const cmd = new AutoIndentOnPasteCommand(textEdits, this.editor.getSelection());
      this.editor.executeCommand("autoIndentOnPaste", cmd);
      this.editor.pushUndoStop();
    }
  }
  shouldIgnoreLine(model, lineNumber) {
    model.tokenization.forceTokenization(lineNumber);
    const nonWhitespaceColumn = model.getLineFirstNonWhitespaceColumn(lineNumber);
    if (nonWhitespaceColumn === 0) {
      return true;
    }
    const tokens = model.tokenization.getLineTokens(lineNumber);
    if (tokens.getCount() > 0) {
      const firstNonWhitespaceTokenIndex = tokens.findTokenIndexAtOffset(nonWhitespaceColumn);
      if (firstNonWhitespaceTokenIndex >= 0 && tokens.getStandardTokenType(firstNonWhitespaceTokenIndex) === 1) {
        return true;
      }
    }
    return false;
  }
  dispose() {
    this.callOnDispose.dispose();
    this.callOnModel.dispose();
  }
};
AutoIndentOnPaste.ID = "editor.contrib.autoIndentOnPaste";
AutoIndentOnPaste = __decorate$X([
  __param$V(1, ILanguageConfigurationService)
], AutoIndentOnPaste);
function getIndentationEditOperations(model, builder, tabSize, tabsToSpaces) {
  if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) {
    return;
  }
  let spaces2 = "";
  for (let i = 0; i < tabSize; i++) {
    spaces2 += " ";
  }
  const spacesRegExp = new RegExp(spaces2, "gi");
  for (let lineNumber = 1, lineCount = model.getLineCount(); lineNumber <= lineCount; lineNumber++) {
    let lastIndentationColumn = model.getLineFirstNonWhitespaceColumn(lineNumber);
    if (lastIndentationColumn === 0) {
      lastIndentationColumn = model.getLineMaxColumn(lineNumber);
    }
    if (lastIndentationColumn === 1) {
      continue;
    }
    const originalIndentationRange = new Range$2(lineNumber, 1, lineNumber, lastIndentationColumn);
    const originalIndentation = model.getValueInRange(originalIndentationRange);
    const newIndentation = tabsToSpaces ? originalIndentation.replace(/\t/ig, spaces2) : originalIndentation.replace(spacesRegExp, "	");
    builder.addEditOperation(originalIndentationRange, newIndentation);
  }
}
class IndentationToSpacesCommand {
  constructor(selection, tabSize) {
    this.selection = selection;
    this.tabSize = tabSize;
    this.selectionId = null;
  }
  getEditOperations(model, builder) {
    this.selectionId = builder.trackSelection(this.selection);
    getIndentationEditOperations(model, builder, this.tabSize, true);
  }
  computeCursorState(model, helper) {
    return helper.getTrackedSelection(this.selectionId);
  }
}
class IndentationToTabsCommand {
  constructor(selection, tabSize) {
    this.selection = selection;
    this.tabSize = tabSize;
    this.selectionId = null;
  }
  getEditOperations(model, builder) {
    this.selectionId = builder.trackSelection(this.selection);
    getIndentationEditOperations(model, builder, this.tabSize, false);
  }
  computeCursorState(model, helper) {
    return helper.getTrackedSelection(this.selectionId);
  }
}
registerEditorContribution(
  AutoIndentOnPaste.ID,
  AutoIndentOnPaste,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);
registerEditorAction(IndentationToSpacesAction);
registerEditorAction(IndentationToTabsAction);
registerEditorAction(IndentUsingTabs);
registerEditorAction(IndentUsingSpaces);
registerEditorAction(ChangeTabDisplaySize);
registerEditorAction(DetectIndentation);
registerEditorAction(ReindentLinesAction);
registerEditorAction(ReindentSelectedLinesAction);
var __awaiter$B = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class InlayHintAnchor {
  constructor(range2, direction) {
    this.range = range2;
    this.direction = direction;
  }
}
class InlayHintItem {
  constructor(hint, anchor, provider) {
    this.hint = hint;
    this.anchor = anchor;
    this.provider = provider;
    this._isResolved = false;
  }
  with(delta) {
    const result2 = new InlayHintItem(this.hint, delta.anchor, this.provider);
    result2._isResolved = this._isResolved;
    result2._currentResolve = this._currentResolve;
    return result2;
  }
  resolve(token) {
    return __awaiter$B(this, void 0, void 0, function* () {
      if (typeof this.provider.resolveInlayHint !== "function") {
        return;
      }
      if (this._currentResolve) {
        yield this._currentResolve;
        if (token.isCancellationRequested) {
          return;
        }
        return this.resolve(token);
      }
      if (!this._isResolved) {
        this._currentResolve = this._doResolve(token).finally(() => this._currentResolve = void 0);
      }
      yield this._currentResolve;
    });
  }
  _doResolve(token) {
    var _a2, _b2;
    return __awaiter$B(this, void 0, void 0, function* () {
      try {
        const newHint = yield Promise.resolve(this.provider.resolveInlayHint(this.hint, token));
        this.hint.tooltip = (_a2 = newHint === null || newHint === void 0 ? void 0 : newHint.tooltip) !== null && _a2 !== void 0 ? _a2 : this.hint.tooltip;
        this.hint.label = (_b2 = newHint === null || newHint === void 0 ? void 0 : newHint.label) !== null && _b2 !== void 0 ? _b2 : this.hint.label;
        this._isResolved = true;
      } catch (err) {
        onUnexpectedExternalError(err);
        this._isResolved = false;
      }
    });
  }
}
class InlayHintsFragments {
  static create(registry, model, ranges, token) {
    return __awaiter$B(this, void 0, void 0, function* () {
      const data = [];
      const promises = registry.ordered(model).reverse().map((provider) => ranges.map((range2) => __awaiter$B(this, void 0, void 0, function* () {
        try {
          const result2 = yield provider.provideInlayHints(model, range2, token);
          if (result2 === null || result2 === void 0 ? void 0 : result2.hints.length) {
            data.push([result2, provider]);
          }
        } catch (err) {
          onUnexpectedExternalError(err);
        }
      })));
      yield Promise.all(promises.flat());
      if (token.isCancellationRequested || model.isDisposed()) {
        throw new CancellationError();
      }
      return new InlayHintsFragments(ranges, data, model);
    });
  }
  constructor(ranges, data, model) {
    this._disposables = new DisposableStore();
    this.ranges = ranges;
    this.provider = /* @__PURE__ */ new Set();
    const items = [];
    for (const [list2, provider] of data) {
      this._disposables.add(list2);
      this.provider.add(provider);
      for (const hint of list2.hints) {
        const position = model.validatePosition(hint.position);
        let direction = "before";
        const wordRange = InlayHintsFragments._getRangeAtPosition(model, position);
        let range2;
        if (wordRange.getStartPosition().isBefore(position)) {
          range2 = Range$2.fromPositions(wordRange.getStartPosition(), position);
          direction = "after";
        } else {
          range2 = Range$2.fromPositions(position, wordRange.getEndPosition());
          direction = "before";
        }
        items.push(new InlayHintItem(hint, new InlayHintAnchor(range2, direction), provider));
      }
    }
    this.items = items.sort((a, b) => Position$2.compare(a.hint.position, b.hint.position));
  }
  dispose() {
    this._disposables.dispose();
  }
  static _getRangeAtPosition(model, position) {
    const line = position.lineNumber;
    const word2 = model.getWordAtPosition(position);
    if (word2) {
      return new Range$2(line, word2.startColumn, line, word2.endColumn);
    }
    model.tokenization.tokenizeIfCheap(line);
    const tokens = model.tokenization.getLineTokens(line);
    const offset = position.column - 1;
    const idx = tokens.findTokenIndexAtOffset(offset);
    let start = tokens.getStartOffset(idx);
    let end = tokens.getEndOffset(idx);
    if (end - start === 1) {
      if (start === offset && idx > 1) {
        start = tokens.getStartOffset(idx - 1);
        end = tokens.getEndOffset(idx - 1);
      } else if (end === offset && idx < tokens.getCount() - 1) {
        start = tokens.getStartOffset(idx + 1);
        end = tokens.getEndOffset(idx + 1);
      }
    }
    return new Range$2(line, start + 1, line, end + 1);
  }
}
function asCommandLink(command) {
  return URI.from({
    scheme: Schemas.command,
    path: command.id,
    query: command.arguments && encodeURIComponent(JSON.stringify(command.arguments))
  }).toString();
}
var __awaiter$A = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
function showGoToContextMenu(accessor, editor2, anchor, part) {
  var _a2;
  return __awaiter$A(this, void 0, void 0, function* () {
    const resolverService = accessor.get(ITextModelService);
    const contextMenuService = accessor.get(IContextMenuService);
    const commandService = accessor.get(ICommandService);
    const instaService = accessor.get(IInstantiationService);
    const notificationService = accessor.get(INotificationService);
    yield part.item.resolve(CancellationToken.None);
    if (!part.part.location) {
      return;
    }
    const location = part.part.location;
    const menuActions = [];
    const filter2 = new Set(MenuRegistry.getMenuItems(MenuId.EditorContext).map((item) => isIMenuItem(item) ? item.command.id : generateUuid()));
    for (const delegate of SymbolNavigationAction.all()) {
      if (filter2.has(delegate.desc.id)) {
        menuActions.push(new Action(delegate.desc.id, MenuItemAction.label(delegate.desc, { renderShortTitle: true }), void 0, true, () => __awaiter$A(this, void 0, void 0, function* () {
          const ref2 = yield resolverService.createModelReference(location.uri);
          try {
            const symbolAnchor = new SymbolNavigationAnchor(ref2.object.textEditorModel, Range$2.getStartPosition(location.range));
            const range2 = part.item.anchor.range;
            yield instaService.invokeFunction(delegate.runEditorCommand.bind(delegate), editor2, symbolAnchor, range2);
          } finally {
            ref2.dispose();
          }
        })));
      }
    }
    if (part.part.command) {
      const { command } = part.part;
      menuActions.push(new Separator());
      menuActions.push(new Action(command.id, command.title, void 0, true, () => __awaiter$A(this, void 0, void 0, function* () {
        var _b2;
        try {
          yield commandService.executeCommand(command.id, ...(_b2 = command.arguments) !== null && _b2 !== void 0 ? _b2 : []);
        } catch (err) {
          notificationService.notify({
            severity: Severity.Error,
            source: part.item.provider.displayName,
            message: err
          });
        }
      })));
    }
    const useShadowDOM = editor2.getOption(
      125
      /* EditorOption.useShadowDOM */
    );
    contextMenuService.showContextMenu({
      domForShadowRoot: useShadowDOM ? (_a2 = editor2.getDomNode()) !== null && _a2 !== void 0 ? _a2 : void 0 : void 0,
      getAnchor: () => {
        const box = getDomNodePagePosition(anchor);
        return { x: box.left, y: box.top + box.height + 8 };
      },
      getActions: () => menuActions,
      onHide: () => {
        editor2.focus();
      },
      autoSelectFirstItem: true
    });
  });
}
function goToDefinitionWithLocation(accessor, event, editor2, location) {
  return __awaiter$A(this, void 0, void 0, function* () {
    const resolverService = accessor.get(ITextModelService);
    const ref2 = yield resolverService.createModelReference(location.uri);
    yield editor2.invokeWithinContext((accessor2) => __awaiter$A(this, void 0, void 0, function* () {
      const openToSide = event.hasSideBySideModifier;
      const contextKeyService = accessor2.get(IContextKeyService);
      const isInPeek = PeekContext.inPeekEditor.getValue(contextKeyService);
      const canPeek = !openToSide && editor2.getOption(
        86
        /* EditorOption.definitionLinkOpensInPeek */
      ) && !isInPeek;
      const action = new DefinitionAction({ openToSide, openInPeek: canPeek, muteMessage: true }, { title: { value: "", original: "" }, id: "", precondition: void 0 });
      return action.run(accessor2, new SymbolNavigationAnchor(ref2.object.textEditorModel, Range$2.getStartPosition(location.range)), Range$2.lift(location.range));
    }));
    ref2.dispose();
  });
}
var __decorate$W = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$U = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$z = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class InlayHintsCache {
  constructor() {
    this._entries = new LRUCache$2(50);
  }
  get(model) {
    const key = InlayHintsCache._key(model);
    return this._entries.get(key);
  }
  set(model, value) {
    const key = InlayHintsCache._key(model);
    this._entries.set(key, value);
  }
  static _key(model) {
    return `${model.uri.toString()}/${model.getVersionId()}`;
  }
}
const IInlayHintsCache = createDecorator("IInlayHintsCache");
registerSingleton(
  IInlayHintsCache,
  InlayHintsCache,
  1
  /* InstantiationType.Delayed */
);
class RenderedInlayHintLabelPart {
  constructor(item, index) {
    this.item = item;
    this.index = index;
  }
  get part() {
    const label = this.item.hint.label;
    if (typeof label === "string") {
      return { label };
    } else {
      return label[this.index];
    }
  }
}
class ActiveInlayHintInfo {
  constructor(part, hasTriggerModifier2) {
    this.part = part;
    this.hasTriggerModifier = hasTriggerModifier2;
  }
}
let InlayHintsController = class InlayHintsController2 {
  static get(editor2) {
    var _a2;
    return (_a2 = editor2.getContribution(InlayHintsController2.ID)) !== null && _a2 !== void 0 ? _a2 : void 0;
  }
  constructor(_editor, _languageFeaturesService, _featureDebounce, _inlayHintsCache, _commandService, _notificationService, _instaService) {
    this._editor = _editor;
    this._languageFeaturesService = _languageFeaturesService;
    this._inlayHintsCache = _inlayHintsCache;
    this._commandService = _commandService;
    this._notificationService = _notificationService;
    this._instaService = _instaService;
    this._disposables = new DisposableStore();
    this._sessionDisposables = new DisposableStore();
    this._decorationsMetadata = /* @__PURE__ */ new Map();
    this._ruleFactory = new DynamicCssRules(this._editor);
    this._activeRenderMode = 0;
    this._debounceInfo = _featureDebounce.for(_languageFeaturesService.inlayHintsProvider, "InlayHint", { min: 25 });
    this._disposables.add(_languageFeaturesService.inlayHintsProvider.onDidChange(() => this._update()));
    this._disposables.add(_editor.onDidChangeModel(() => this._update()));
    this._disposables.add(_editor.onDidChangeModelLanguage(() => this._update()));
    this._disposables.add(_editor.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        138
        /* EditorOption.inlayHints */
      )) {
        this._update();
      }
    }));
    this._update();
  }
  dispose() {
    this._sessionDisposables.dispose();
    this._removeAllDecorations();
    this._disposables.dispose();
  }
  _update() {
    this._sessionDisposables.clear();
    this._removeAllDecorations();
    const options = this._editor.getOption(
      138
      /* EditorOption.inlayHints */
    );
    if (options.enabled === "off") {
      return;
    }
    const model = this._editor.getModel();
    if (!model || !this._languageFeaturesService.inlayHintsProvider.has(model)) {
      return;
    }
    const cached = this._inlayHintsCache.get(model);
    if (cached) {
      this._updateHintsDecorators([model.getFullModelRange()], cached);
    }
    this._sessionDisposables.add(toDisposable(() => {
      if (!model.isDisposed()) {
        this._cacheHintsForFastRestore(model);
      }
    }));
    let cts;
    const watchedProviders = /* @__PURE__ */ new Set();
    const scheduler = new RunOnceScheduler(() => __awaiter$z(this, void 0, void 0, function* () {
      const t1 = Date.now();
      cts === null || cts === void 0 ? void 0 : cts.dispose(true);
      cts = new CancellationTokenSource$1();
      const listener = model.onWillDispose(() => cts === null || cts === void 0 ? void 0 : cts.cancel());
      try {
        const myToken = cts.token;
        const inlayHints = yield InlayHintsFragments.create(this._languageFeaturesService.inlayHintsProvider, model, this._getHintsRanges(), myToken);
        scheduler.delay = this._debounceInfo.update(model, Date.now() - t1);
        if (myToken.isCancellationRequested) {
          inlayHints.dispose();
          return;
        }
        for (const provider of inlayHints.provider) {
          if (typeof provider.onDidChangeInlayHints === "function" && !watchedProviders.has(provider)) {
            watchedProviders.add(provider);
            this._sessionDisposables.add(provider.onDidChangeInlayHints(() => {
              if (!scheduler.isScheduled()) {
                scheduler.schedule();
              }
            }));
          }
        }
        this._sessionDisposables.add(inlayHints);
        this._updateHintsDecorators(inlayHints.ranges, inlayHints.items);
        this._cacheHintsForFastRestore(model);
      } catch (err) {
        onUnexpectedError(err);
      } finally {
        cts.dispose();
        listener.dispose();
      }
    }), this._debounceInfo.get(model));
    this._sessionDisposables.add(scheduler);
    this._sessionDisposables.add(toDisposable(() => cts === null || cts === void 0 ? void 0 : cts.dispose(true)));
    scheduler.schedule(0);
    this._sessionDisposables.add(this._editor.onDidScrollChange((e) => {
      if (e.scrollTopChanged || !scheduler.isScheduled()) {
        scheduler.schedule();
      }
    }));
    this._sessionDisposables.add(this._editor.onDidChangeModelContent((e) => {
      const delay = Math.max(scheduler.delay, 1250);
      scheduler.schedule(delay);
    }));
    if (options.enabled === "on") {
      this._activeRenderMode = 0;
    } else {
      let defaultMode;
      let altMode;
      if (options.enabled === "onUnlessPressed") {
        defaultMode = 0;
        altMode = 1;
      } else {
        defaultMode = 1;
        altMode = 0;
      }
      this._activeRenderMode = defaultMode;
      this._sessionDisposables.add(ModifierKeyEmitter.getInstance().event((e) => {
        if (!this._editor.hasModel()) {
          return;
        }
        const newRenderMode = e.altKey && e.ctrlKey && !(e.shiftKey || e.metaKey) ? altMode : defaultMode;
        if (newRenderMode !== this._activeRenderMode) {
          this._activeRenderMode = newRenderMode;
          const model2 = this._editor.getModel();
          const copies = this._copyInlayHintsWithCurrentAnchor(model2);
          this._updateHintsDecorators([model2.getFullModelRange()], copies);
          scheduler.schedule(0);
        }
      }));
    }
    this._sessionDisposables.add(this._installDblClickGesture(() => scheduler.schedule(0)));
    this._sessionDisposables.add(this._installLinkGesture());
    this._sessionDisposables.add(this._installContextMenu());
  }
  _installLinkGesture() {
    const store = new DisposableStore();
    const gesture = store.add(new ClickLinkGesture(this._editor));
    const sessionStore = new DisposableStore();
    store.add(sessionStore);
    store.add(gesture.onMouseMoveOrRelevantKeyDown((e) => {
      const [mouseEvent] = e;
      const labelPart = this._getInlayHintLabelPart(mouseEvent);
      const model = this._editor.getModel();
      if (!labelPart || !model) {
        sessionStore.clear();
        return;
      }
      const cts = new CancellationTokenSource$1();
      sessionStore.add(toDisposable(() => cts.dispose(true)));
      labelPart.item.resolve(cts.token);
      this._activeInlayHintPart = labelPart.part.command || labelPart.part.location ? new ActiveInlayHintInfo(labelPart, mouseEvent.hasTriggerModifier) : void 0;
      const lineNumber = model.validatePosition(labelPart.item.hint.position).lineNumber;
      const range2 = new Range$2(lineNumber, 1, lineNumber, model.getLineMaxColumn(lineNumber));
      const lineHints = this._getInlineHintsForRange(range2);
      this._updateHintsDecorators([range2], lineHints);
      sessionStore.add(toDisposable(() => {
        this._activeInlayHintPart = void 0;
        this._updateHintsDecorators([range2], lineHints);
      }));
    }));
    store.add(gesture.onCancel(() => sessionStore.clear()));
    store.add(gesture.onExecute((e) => __awaiter$z(this, void 0, void 0, function* () {
      const label = this._getInlayHintLabelPart(e);
      if (label) {
        const part = label.part;
        if (part.location) {
          this._instaService.invokeFunction(goToDefinitionWithLocation, e, this._editor, part.location);
        } else if (Command2.is(part.command)) {
          yield this._invokeCommand(part.command, label.item);
        }
      }
    })));
    return store;
  }
  _getInlineHintsForRange(range2) {
    const lineHints = /* @__PURE__ */ new Set();
    for (const data of this._decorationsMetadata.values()) {
      if (range2.containsRange(data.item.anchor.range)) {
        lineHints.add(data.item);
      }
    }
    return Array.from(lineHints);
  }
  _installDblClickGesture(updateInlayHints) {
    return this._editor.onMouseUp((e) => __awaiter$z(this, void 0, void 0, function* () {
      if (e.event.detail !== 2) {
        return;
      }
      const part = this._getInlayHintLabelPart(e);
      if (!part) {
        return;
      }
      e.event.preventDefault();
      yield part.item.resolve(CancellationToken.None);
      if (isNonEmptyArray(part.item.hint.textEdits)) {
        const edits = part.item.hint.textEdits.map((edit) => EditOperation.replace(Range$2.lift(edit.range), edit.text));
        this._editor.executeEdits("inlayHint.default", edits);
        updateInlayHints();
      }
    }));
  }
  _installContextMenu() {
    return this._editor.onContextMenu((e) => __awaiter$z(this, void 0, void 0, function* () {
      if (!(e.event.target instanceof HTMLElement)) {
        return;
      }
      const part = this._getInlayHintLabelPart(e);
      if (part) {
        yield this._instaService.invokeFunction(showGoToContextMenu, this._editor, e.event.target, part);
      }
    }));
  }
  _getInlayHintLabelPart(e) {
    var _a2;
    if (e.target.type !== 6) {
      return void 0;
    }
    const options = (_a2 = e.target.detail.injectedText) === null || _a2 === void 0 ? void 0 : _a2.options;
    if (options instanceof ModelDecorationInjectedTextOptions && (options === null || options === void 0 ? void 0 : options.attachedData) instanceof RenderedInlayHintLabelPart) {
      return options.attachedData;
    }
    return void 0;
  }
  _invokeCommand(command, item) {
    var _a2;
    return __awaiter$z(this, void 0, void 0, function* () {
      try {
        yield this._commandService.executeCommand(command.id, ...(_a2 = command.arguments) !== null && _a2 !== void 0 ? _a2 : []);
      } catch (err) {
        this._notificationService.notify({
          severity: Severity.Error,
          source: item.provider.displayName,
          message: err
        });
      }
    });
  }
  _cacheHintsForFastRestore(model) {
    const hints = this._copyInlayHintsWithCurrentAnchor(model);
    this._inlayHintsCache.set(model, hints);
  }
  // return inlay hints but with an anchor that reflects "updates"
  // that happened after receiving them, e.g adding new lines before a hint
  _copyInlayHintsWithCurrentAnchor(model) {
    const items = /* @__PURE__ */ new Map();
    for (const [id3, obj] of this._decorationsMetadata) {
      if (items.has(obj.item)) {
        continue;
      }
      const range2 = model.getDecorationRange(id3);
      if (range2) {
        const anchor = new InlayHintAnchor(range2, obj.item.anchor.direction);
        const copy2 = obj.item.with({ anchor });
        items.set(obj.item, copy2);
      }
    }
    return Array.from(items.values());
  }
  _getHintsRanges() {
    const extra = 30;
    const model = this._editor.getModel();
    const visibleRanges = this._editor.getVisibleRangesPlusViewportAboveBelow();
    const result2 = [];
    for (const range2 of visibleRanges.sort(Range$2.compareRangesUsingStarts)) {
      const extendedRange = model.validateRange(new Range$2(range2.startLineNumber - extra, range2.startColumn, range2.endLineNumber + extra, range2.endColumn));
      if (result2.length === 0 || !Range$2.areIntersectingOrTouching(result2[result2.length - 1], extendedRange)) {
        result2.push(extendedRange);
      } else {
        result2[result2.length - 1] = Range$2.plusRange(result2[result2.length - 1], extendedRange);
      }
    }
    return result2;
  }
  _updateHintsDecorators(ranges, items) {
    var _a2, _b2;
    const newDecorationsData = [];
    const addInjectedText = (item, ref2, content, cursorStops, attachedData) => {
      const opts = {
        content,
        inlineClassNameAffectsLetterSpacing: true,
        inlineClassName: ref2.className,
        cursorStops,
        attachedData
      };
      newDecorationsData.push({
        item,
        classNameRef: ref2,
        decoration: {
          range: item.anchor.range,
          options: {
            // className: "rangeHighlight", // DEBUG highlight to see to what range a hint is attached
            description: "InlayHint",
            showIfCollapsed: item.anchor.range.isEmpty(),
            collapseOnReplaceEdit: !item.anchor.range.isEmpty(),
            stickiness: 0,
            [item.anchor.direction]: this._activeRenderMode === 0 ? opts : void 0
          }
        }
      });
    };
    const addInjectedWhitespace = (item, isLast) => {
      const marginRule = this._ruleFactory.createClassNameRef({
        width: `${fontSize / 3 | 0}px`,
        display: "inline-block"
      });
      addInjectedText(item, marginRule, " ", isLast ? InjectedTextCursorStops$1.Right : InjectedTextCursorStops$1.None);
    };
    const { fontSize, fontFamily, padding, isUniform } = this._getLayoutInfo();
    const fontFamilyVar = "--code-editorInlayHintsFontFamily";
    this._editor.getContainerDomNode().style.setProperty(fontFamilyVar, fontFamily);
    for (const item of items) {
      if (item.hint.paddingLeft) {
        addInjectedWhitespace(item, false);
      }
      const parts = typeof item.hint.label === "string" ? [{ label: item.hint.label }] : item.hint.label;
      for (let i = 0; i < parts.length; i++) {
        const part = parts[i];
        const isFirst = i === 0;
        const isLast = i === parts.length - 1;
        const cssProperties = {
          fontSize: `${fontSize}px`,
          fontFamily: `var(${fontFamilyVar}), ${EDITOR_FONT_DEFAULTS.fontFamily}`,
          verticalAlign: isUniform ? "baseline" : "middle",
          unicodeBidi: "isolate"
        };
        if (isNonEmptyArray(item.hint.textEdits)) {
          cssProperties.cursor = "default";
        }
        this._fillInColors(cssProperties, item.hint);
        if ((part.command || part.location) && ((_a2 = this._activeInlayHintPart) === null || _a2 === void 0 ? void 0 : _a2.part.item) === item && this._activeInlayHintPart.part.index === i) {
          cssProperties.textDecoration = "underline";
          if (this._activeInlayHintPart.hasTriggerModifier) {
            cssProperties.color = themeColorFromId(editorActiveLinkForeground);
            cssProperties.cursor = "pointer";
          }
        }
        if (padding) {
          if (isFirst && isLast) {
            cssProperties.padding = `1px ${Math.max(1, fontSize / 4) | 0}px`;
            cssProperties.borderRadius = `${fontSize / 4 | 0}px`;
          } else if (isFirst) {
            cssProperties.padding = `1px 0 1px ${Math.max(1, fontSize / 4) | 0}px`;
            cssProperties.borderRadius = `${fontSize / 4 | 0}px 0 0 ${fontSize / 4 | 0}px`;
          } else if (isLast) {
            cssProperties.padding = `1px ${Math.max(1, fontSize / 4) | 0}px 1px 0`;
            cssProperties.borderRadius = `0 ${fontSize / 4 | 0}px ${fontSize / 4 | 0}px 0`;
          } else {
            cssProperties.padding = `1px 0 1px 0`;
          }
        }
        addInjectedText(item, this._ruleFactory.createClassNameRef(cssProperties), fixSpace(part.label), isLast && !item.hint.paddingRight ? InjectedTextCursorStops$1.Right : InjectedTextCursorStops$1.None, new RenderedInlayHintLabelPart(item, i));
      }
      if (item.hint.paddingRight) {
        addInjectedWhitespace(item, true);
      }
      if (newDecorationsData.length > InlayHintsController2._MAX_DECORATORS) {
        break;
      }
    }
    const decorationIdsToReplace = [];
    for (const range2 of ranges) {
      for (const { id: id3 } of (_b2 = this._editor.getDecorationsInRange(range2)) !== null && _b2 !== void 0 ? _b2 : []) {
        const metadata = this._decorationsMetadata.get(id3);
        if (metadata) {
          decorationIdsToReplace.push(id3);
          metadata.classNameRef.dispose();
          this._decorationsMetadata.delete(id3);
        }
      }
    }
    const scrollState = StableEditorScrollState.capture(this._editor);
    this._editor.changeDecorations((accessor) => {
      const newDecorationIds = accessor.deltaDecorations(decorationIdsToReplace, newDecorationsData.map((d) => d.decoration));
      for (let i = 0; i < newDecorationIds.length; i++) {
        const data = newDecorationsData[i];
        this._decorationsMetadata.set(newDecorationIds[i], data);
      }
    });
    scrollState.restore(this._editor);
  }
  _fillInColors(props, hint) {
    if (hint.kind === InlayHintKind$1.Parameter) {
      props.backgroundColor = themeColorFromId(editorInlayHintParameterBackground);
      props.color = themeColorFromId(editorInlayHintParameterForeground);
    } else if (hint.kind === InlayHintKind$1.Type) {
      props.backgroundColor = themeColorFromId(editorInlayHintTypeBackground);
      props.color = themeColorFromId(editorInlayHintTypeForeground);
    } else {
      props.backgroundColor = themeColorFromId(editorInlayHintBackground);
      props.color = themeColorFromId(editorInlayHintForeground);
    }
  }
  _getLayoutInfo() {
    const options = this._editor.getOption(
      138
      /* EditorOption.inlayHints */
    );
    const padding = options.padding;
    const editorFontSize = this._editor.getOption(
      51
      /* EditorOption.fontSize */
    );
    const editorFontFamily = this._editor.getOption(
      48
      /* EditorOption.fontFamily */
    );
    let fontSize = options.fontSize;
    if (!fontSize || fontSize < 5 || fontSize > editorFontSize) {
      fontSize = editorFontSize;
    }
    const fontFamily = options.fontFamily || editorFontFamily;
    const isUniform = !padding && fontFamily === editorFontFamily && fontSize === editorFontSize;
    return { fontSize, fontFamily, padding, isUniform };
  }
  _removeAllDecorations() {
    this._editor.removeDecorations(Array.from(this._decorationsMetadata.keys()));
    for (const obj of this._decorationsMetadata.values()) {
      obj.classNameRef.dispose();
    }
    this._decorationsMetadata.clear();
  }
};
InlayHintsController.ID = "editor.contrib.InlayHints";
InlayHintsController._MAX_DECORATORS = 1500;
InlayHintsController = __decorate$W([
  __param$U(1, ILanguageFeaturesService),
  __param$U(2, ILanguageFeatureDebounceService),
  __param$U(3, IInlayHintsCache),
  __param$U(4, ICommandService),
  __param$U(5, INotificationService),
  __param$U(6, IInstantiationService)
], InlayHintsController);
function fixSpace(str2) {
  const noBreakWhitespace2 = " ";
  return str2.replace(/[ \t]/g, noBreakWhitespace2);
}
CommandsRegistry.registerCommand("_executeInlayHintProvider", (accessor, ...args) => __awaiter$z(void 0, void 0, void 0, function* () {
  const [uri, range2] = args;
  assertType(URI.isUri(uri));
  assertType(Range$2.isIRange(range2));
  const { inlayHintsProvider } = accessor.get(ILanguageFeaturesService);
  const ref2 = yield accessor.get(ITextModelService).createModelReference(uri);
  try {
    const model = yield InlayHintsFragments.create(inlayHintsProvider, ref2.object.textEditorModel, [Range$2.lift(range2)], CancellationToken.None);
    const result2 = model.items.map((i) => i.hint);
    setTimeout(() => model.dispose(), 0);
    return result2;
  } finally {
    ref2.dispose();
  }
}));
var __decorate$V = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$T = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$y = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var __asyncValues = globalThis && globalThis.__asyncValues || function(o) {
  if (!Symbol.asyncIterator)
    throw new TypeError("Symbol.asyncIterator is not defined.");
  var m = o[Symbol.asyncIterator], i;
  return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
    return this;
  }, i);
  function verb(n2) {
    i[n2] = o[n2] && function(v) {
      return new Promise(function(resolve2, reject) {
        v = o[n2](v), settle(resolve2, reject, v.done, v.value);
      });
    };
  }
  function settle(resolve2, reject, d, v) {
    Promise.resolve(v).then(function(v2) {
      resolve2({ value: v2, done: d });
    }, reject);
  }
};
class InlayHintsHoverAnchor extends HoverForeignElementAnchor {
  constructor(part, owner, initialMousePosX, initialMousePosY) {
    super(10, owner, part.item.anchor.range, initialMousePosX, initialMousePosY, true);
    this.part = part;
  }
}
let InlayHintsHover = class InlayHintsHover2 extends MarkdownHoverParticipant {
  constructor(editor2, languageService, openerService, configurationService, _resolverService, languageFeaturesService) {
    super(editor2, languageService, openerService, configurationService, languageFeaturesService);
    this._resolverService = _resolverService;
    this.hoverOrdinal = 6;
  }
  suggestHoverAnchor(mouseEvent) {
    var _a2;
    const controller = InlayHintsController.get(this._editor);
    if (!controller) {
      return null;
    }
    if (mouseEvent.target.type !== 6) {
      return null;
    }
    const options = (_a2 = mouseEvent.target.detail.injectedText) === null || _a2 === void 0 ? void 0 : _a2.options;
    if (!(options instanceof ModelDecorationInjectedTextOptions && options.attachedData instanceof RenderedInlayHintLabelPart)) {
      return null;
    }
    return new InlayHintsHoverAnchor(options.attachedData, this, mouseEvent.event.posx, mouseEvent.event.posy);
  }
  computeSync() {
    return [];
  }
  computeAsync(anchor, _lineDecorations, token) {
    if (!(anchor instanceof InlayHintsHoverAnchor)) {
      return AsyncIterableObject.EMPTY;
    }
    return new AsyncIterableObject((executor) => __awaiter$y(this, void 0, void 0, function* () {
      var _a2, e_1, _b2, _c2;
      const { part } = anchor;
      yield part.item.resolve(token);
      if (token.isCancellationRequested) {
        return;
      }
      let itemTooltip;
      if (typeof part.item.hint.tooltip === "string") {
        itemTooltip = new MarkdownString().appendText(part.item.hint.tooltip);
      } else if (part.item.hint.tooltip) {
        itemTooltip = part.item.hint.tooltip;
      }
      if (itemTooltip) {
        executor.emitOne(new MarkdownHover(this, anchor.range, [itemTooltip], false, 0));
      }
      if (isNonEmptyArray(part.item.hint.textEdits)) {
        executor.emitOne(new MarkdownHover(this, anchor.range, [new MarkdownString().appendText(localize("hint.dbl", "Double-click to insert"))], false, 10001));
      }
      let partTooltip;
      if (typeof part.part.tooltip === "string") {
        partTooltip = new MarkdownString().appendText(part.part.tooltip);
      } else if (part.part.tooltip) {
        partTooltip = part.part.tooltip;
      }
      if (partTooltip) {
        executor.emitOne(new MarkdownHover(this, anchor.range, [partTooltip], false, 1));
      }
      if (part.part.location || part.part.command) {
        let linkHint;
        const useMetaKey = this._editor.getOption(
          76
          /* EditorOption.multiCursorModifier */
        ) === "altKey";
        const kb = useMetaKey ? isMacintosh ? localize("links.navigate.kb.meta.mac", "cmd + click") : localize("links.navigate.kb.meta", "ctrl + click") : isMacintosh ? localize("links.navigate.kb.alt.mac", "option + click") : localize("links.navigate.kb.alt", "alt + click");
        if (part.part.location && part.part.command) {
          linkHint = new MarkdownString().appendText(localize("hint.defAndCommand", "Go to Definition ({0}), right click for more", kb));
        } else if (part.part.location) {
          linkHint = new MarkdownString().appendText(localize("hint.def", "Go to Definition ({0})", kb));
        } else if (part.part.command) {
          linkHint = new MarkdownString(`[${localize("hint.cmd", "Execute Command")}](${asCommandLink(part.part.command)} "${part.part.command.title}") (${kb})`, { isTrusted: true });
        }
        if (linkHint) {
          executor.emitOne(new MarkdownHover(this, anchor.range, [linkHint], false, 1e4));
        }
      }
      const iterable = yield this._resolveInlayHintLabelPartHover(part, token);
      try {
        for (var _d2 = true, iterable_1 = __asyncValues(iterable), iterable_1_1; iterable_1_1 = yield iterable_1.next(), _a2 = iterable_1_1.done, !_a2; _d2 = true) {
          _c2 = iterable_1_1.value;
          _d2 = false;
          const item = _c2;
          executor.emitOne(item);
        }
      } catch (e_1_1) {
        e_1 = { error: e_1_1 };
      } finally {
        try {
          if (!_d2 && !_a2 && (_b2 = iterable_1.return))
            yield _b2.call(iterable_1);
        } finally {
          if (e_1)
            throw e_1.error;
        }
      }
    }));
  }
  _resolveInlayHintLabelPartHover(part, token) {
    return __awaiter$y(this, void 0, void 0, function* () {
      if (!part.part.location) {
        return AsyncIterableObject.EMPTY;
      }
      const { uri, range: range2 } = part.part.location;
      const ref2 = yield this._resolverService.createModelReference(uri);
      try {
        const model = ref2.object.textEditorModel;
        if (!this._languageFeaturesService.hoverProvider.has(model)) {
          return AsyncIterableObject.EMPTY;
        }
        return getHover(this._languageFeaturesService.hoverProvider, model, new Position$2(range2.startLineNumber, range2.startColumn), token).filter((item) => !isEmptyMarkdownString(item.hover.contents)).map((item) => new MarkdownHover(this, part.item.anchor.range, item.hover.contents, false, 2 + item.ordinal));
      } finally {
        ref2.dispose();
      }
    });
  }
};
InlayHintsHover = __decorate$V([
  __param$T(1, ILanguageService),
  __param$T(2, IOpenerService),
  __param$T(3, IConfigurationService),
  __param$T(4, ITextModelService),
  __param$T(5, ILanguageFeaturesService)
], InlayHintsHover);
registerEditorContribution(
  InlayHintsController.ID,
  InlayHintsController,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
HoverParticipantRegistry.register(InlayHintsHover);
class InPlaceReplaceCommand {
  constructor(editRange, originalSelection, text2) {
    this._editRange = editRange;
    this._originalSelection = originalSelection;
    this._text = text2;
  }
  getEditOperations(model, builder) {
    builder.addTrackedEditOperation(this._editRange, this._text);
  }
  computeCursorState(model, helper) {
    const inverseEditOperations = helper.getInverseEditOperations();
    const srcRange = inverseEditOperations[0].range;
    if (!this._originalSelection.isEmpty()) {
      return new Selection$1(srcRange.endLineNumber, srcRange.endColumn - this._text.length, srcRange.endLineNumber, srcRange.endColumn);
    }
    return new Selection$1(srcRange.endLineNumber, Math.min(this._originalSelection.positionColumn, srcRange.endColumn), srcRange.endLineNumber, Math.min(this._originalSelection.positionColumn, srcRange.endColumn));
  }
}
const inPlaceReplace = "";
var __decorate$U = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$S = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let InPlaceReplaceController = class InPlaceReplaceController2 {
  static get(editor2) {
    return editor2.getContribution(InPlaceReplaceController2.ID);
  }
  constructor(editor2, editorWorkerService) {
    this.editor = editor2;
    this.editorWorkerService = editorWorkerService;
    this.decorations = this.editor.createDecorationsCollection();
  }
  dispose() {
  }
  run(source, up) {
    var _a2;
    (_a2 = this.currentRequest) === null || _a2 === void 0 ? void 0 : _a2.cancel();
    const editorSelection = this.editor.getSelection();
    const model = this.editor.getModel();
    if (!model || !editorSelection) {
      return void 0;
    }
    let selection = editorSelection;
    if (selection.startLineNumber !== selection.endLineNumber) {
      return void 0;
    }
    const state = new EditorState$1(
      this.editor,
      1 | 4
      /* CodeEditorStateFlag.Position */
    );
    const modelURI = model.uri;
    if (!this.editorWorkerService.canNavigateValueSet(modelURI)) {
      return Promise.resolve(void 0);
    }
    this.currentRequest = createCancelablePromise((token) => this.editorWorkerService.navigateValueSet(modelURI, selection, up));
    return this.currentRequest.then((result2) => {
      var _a3;
      if (!result2 || !result2.range || !result2.value) {
        return;
      }
      if (!state.validate(this.editor)) {
        return;
      }
      const editRange = Range$2.lift(result2.range);
      let highlightRange = result2.range;
      const diff = result2.value.length - (selection.endColumn - selection.startColumn);
      highlightRange = {
        startLineNumber: highlightRange.startLineNumber,
        startColumn: highlightRange.startColumn,
        endLineNumber: highlightRange.endLineNumber,
        endColumn: highlightRange.startColumn + result2.value.length
      };
      if (diff > 1) {
        selection = new Selection$1(selection.startLineNumber, selection.startColumn, selection.endLineNumber, selection.endColumn + diff - 1);
      }
      const command = new InPlaceReplaceCommand(editRange, selection, result2.value);
      this.editor.pushUndoStop();
      this.editor.executeCommand(source, command);
      this.editor.pushUndoStop();
      this.decorations.set([{
        range: highlightRange,
        options: InPlaceReplaceController2.DECORATION
      }]);
      (_a3 = this.decorationRemover) === null || _a3 === void 0 ? void 0 : _a3.cancel();
      this.decorationRemover = timeout(350);
      this.decorationRemover.then(() => this.decorations.clear()).catch(onUnexpectedError);
    }).catch(onUnexpectedError);
  }
};
InPlaceReplaceController.ID = "editor.contrib.inPlaceReplaceController";
InPlaceReplaceController.DECORATION = ModelDecorationOptions.register({
  description: "in-place-replace",
  className: "valueSetReplacement"
});
InPlaceReplaceController = __decorate$U([
  __param$S(1, IEditorWorkerService)
], InPlaceReplaceController);
class InPlaceReplaceUp extends EditorAction {
  constructor() {
    super({
      id: "editor.action.inPlaceReplace.up",
      label: localize("InPlaceReplaceAction.previous.label", "Replace with Previous Value"),
      alias: "Replace with Previous Value",
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 1024 | 87,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor2) {
    const controller = InPlaceReplaceController.get(editor2);
    if (!controller) {
      return Promise.resolve(void 0);
    }
    return controller.run(this.id, false);
  }
}
class InPlaceReplaceDown extends EditorAction {
  constructor() {
    super({
      id: "editor.action.inPlaceReplace.down",
      label: localize("InPlaceReplaceAction.next.label", "Replace with Next Value"),
      alias: "Replace with Next Value",
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 1024 | 89,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor2) {
    const controller = InPlaceReplaceController.get(editor2);
    if (!controller) {
      return Promise.resolve(void 0);
    }
    return controller.run(this.id, true);
  }
}
registerEditorContribution(
  InPlaceReplaceController.ID,
  InPlaceReplaceController,
  4
  /* EditorContributionInstantiation.Lazy */
);
registerEditorAction(InPlaceReplaceUp);
registerEditorAction(InPlaceReplaceDown);
class ExpandLineSelectionAction extends EditorAction {
  constructor() {
    super({
      id: "expandLineSelection",
      label: localize("expandLineSelection", "Expand Line Selection"),
      alias: "Expand Line Selection",
      precondition: void 0,
      kbOpts: {
        weight: 0,
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 2048 | 42
        /* KeyCode.KeyL */
      }
    });
  }
  run(_accessor, editor2, args) {
    args = args || {};
    if (!editor2.hasModel()) {
      return;
    }
    const viewModel = editor2._getViewModel();
    viewModel.model.pushStackElement();
    viewModel.setCursorStates(args.source, 3, CursorMoveCommands.expandLineSelection(viewModel, viewModel.getCursorStates()));
    viewModel.revealPrimaryCursor(args.source, true);
  }
}
registerEditorAction(ExpandLineSelectionAction);
class TrimTrailingWhitespaceCommand {
  constructor(selection, cursors) {
    this._selection = selection;
    this._cursors = cursors;
    this._selectionId = null;
  }
  getEditOperations(model, builder) {
    const ops = trimTrailingWhitespace(model, this._cursors);
    for (let i = 0, len = ops.length; i < len; i++) {
      const op = ops[i];
      builder.addEditOperation(op.range, op.text);
    }
    this._selectionId = builder.trackSelection(this._selection);
  }
  computeCursorState(model, helper) {
    return helper.getTrackedSelection(this._selectionId);
  }
}
function trimTrailingWhitespace(model, cursors) {
  cursors.sort((a, b) => {
    if (a.lineNumber === b.lineNumber) {
      return a.column - b.column;
    }
    return a.lineNumber - b.lineNumber;
  });
  for (let i = cursors.length - 2; i >= 0; i--) {
    if (cursors[i].lineNumber === cursors[i + 1].lineNumber) {
      cursors.splice(i, 1);
    }
  }
  const r = [];
  let rLen = 0;
  let cursorIndex = 0;
  const cursorLen = cursors.length;
  for (let lineNumber = 1, lineCount = model.getLineCount(); lineNumber <= lineCount; lineNumber++) {
    const lineContent = model.getLineContent(lineNumber);
    const maxLineColumn = lineContent.length + 1;
    let minEditColumn = 0;
    if (cursorIndex < cursorLen && cursors[cursorIndex].lineNumber === lineNumber) {
      minEditColumn = cursors[cursorIndex].column;
      cursorIndex++;
      if (minEditColumn === maxLineColumn) {
        continue;
      }
    }
    if (lineContent.length === 0) {
      continue;
    }
    const lastNonWhitespaceIndex$1 = lastNonWhitespaceIndex(lineContent);
    let fromColumn = 0;
    if (lastNonWhitespaceIndex$1 === -1) {
      fromColumn = 1;
    } else if (lastNonWhitespaceIndex$1 !== lineContent.length - 1) {
      fromColumn = lastNonWhitespaceIndex$1 + 2;
    } else {
      continue;
    }
    fromColumn = Math.max(minEditColumn, fromColumn);
    r[rLen++] = EditOperation.delete(new Range$2(lineNumber, fromColumn, lineNumber, maxLineColumn));
  }
  return r;
}
class CopyLinesCommand {
  constructor(selection, isCopyingDown, noop2) {
    this._selection = selection;
    this._isCopyingDown = isCopyingDown;
    this._noop = noop2 || false;
    this._selectionDirection = 0;
    this._selectionId = null;
    this._startLineNumberDelta = 0;
    this._endLineNumberDelta = 0;
  }
  getEditOperations(model, builder) {
    let s = this._selection;
    this._startLineNumberDelta = 0;
    this._endLineNumberDelta = 0;
    if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) {
      this._endLineNumberDelta = 1;
      s = s.setEndPosition(s.endLineNumber - 1, model.getLineMaxColumn(s.endLineNumber - 1));
    }
    const sourceLines = [];
    for (let i = s.startLineNumber; i <= s.endLineNumber; i++) {
      sourceLines.push(model.getLineContent(i));
    }
    const sourceText = sourceLines.join("\n");
    if (sourceText === "") {
      if (this._isCopyingDown) {
        this._startLineNumberDelta++;
        this._endLineNumberDelta++;
      }
    }
    if (this._noop) {
      builder.addEditOperation(new Range$2(s.endLineNumber, model.getLineMaxColumn(s.endLineNumber), s.endLineNumber + 1, 1), s.endLineNumber === model.getLineCount() ? "" : "\n");
    } else {
      if (!this._isCopyingDown) {
        builder.addEditOperation(new Range$2(s.endLineNumber, model.getLineMaxColumn(s.endLineNumber), s.endLineNumber, model.getLineMaxColumn(s.endLineNumber)), "\n" + sourceText);
      } else {
        builder.addEditOperation(new Range$2(s.startLineNumber, 1, s.startLineNumber, 1), sourceText + "\n");
      }
    }
    this._selectionId = builder.trackSelection(s);
    this._selectionDirection = this._selection.getDirection();
  }
  computeCursorState(model, helper) {
    let result2 = helper.getTrackedSelection(this._selectionId);
    if (this._startLineNumberDelta !== 0 || this._endLineNumberDelta !== 0) {
      let startLineNumber = result2.startLineNumber;
      let startColumn = result2.startColumn;
      let endLineNumber = result2.endLineNumber;
      let endColumn = result2.endColumn;
      if (this._startLineNumberDelta !== 0) {
        startLineNumber = startLineNumber + this._startLineNumberDelta;
        startColumn = 1;
      }
      if (this._endLineNumberDelta !== 0) {
        endLineNumber = endLineNumber + this._endLineNumberDelta;
        endColumn = 1;
      }
      result2 = Selection$1.createWithDirection(startLineNumber, startColumn, endLineNumber, endColumn, this._selectionDirection);
    }
    return result2;
  }
}
var __decorate$T = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$R = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let MoveLinesCommand = class MoveLinesCommand2 {
  constructor(selection, isMovingDown, autoIndent, _languageConfigurationService) {
    this._languageConfigurationService = _languageConfigurationService;
    this._selection = selection;
    this._isMovingDown = isMovingDown;
    this._autoIndent = autoIndent;
    this._selectionId = null;
    this._moveEndLineSelectionShrink = false;
  }
  getEditOperations(model, builder) {
    const modelLineCount = model.getLineCount();
    if (this._isMovingDown && this._selection.endLineNumber === modelLineCount) {
      this._selectionId = builder.trackSelection(this._selection);
      return;
    }
    if (!this._isMovingDown && this._selection.startLineNumber === 1) {
      this._selectionId = builder.trackSelection(this._selection);
      return;
    }
    this._moveEndPositionDown = false;
    let s = this._selection;
    if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) {
      this._moveEndPositionDown = true;
      s = s.setEndPosition(s.endLineNumber - 1, model.getLineMaxColumn(s.endLineNumber - 1));
    }
    const { tabSize, indentSize, insertSpaces } = model.getOptions();
    const indentConverter = this.buildIndentConverter(tabSize, indentSize, insertSpaces);
    const virtualModel = {
      tokenization: {
        getLineTokens: (lineNumber) => {
          return model.tokenization.getLineTokens(lineNumber);
        },
        getLanguageId: () => {
          return model.getLanguageId();
        },
        getLanguageIdAtPosition: (lineNumber, column) => {
          return model.getLanguageIdAtPosition(lineNumber, column);
        }
      },
      getLineContent: null
    };
    if (s.startLineNumber === s.endLineNumber && model.getLineMaxColumn(s.startLineNumber) === 1) {
      const lineNumber = s.startLineNumber;
      const otherLineNumber = this._isMovingDown ? lineNumber + 1 : lineNumber - 1;
      if (model.getLineMaxColumn(otherLineNumber) === 1) {
        builder.addEditOperation(new Range$2(1, 1, 1, 1), null);
      } else {
        builder.addEditOperation(new Range$2(lineNumber, 1, lineNumber, 1), model.getLineContent(otherLineNumber));
        builder.addEditOperation(new Range$2(otherLineNumber, 1, otherLineNumber, model.getLineMaxColumn(otherLineNumber)), null);
      }
      s = new Selection$1(otherLineNumber, 1, otherLineNumber, 1);
    } else {
      let movingLineNumber;
      let movingLineText;
      if (this._isMovingDown) {
        movingLineNumber = s.endLineNumber + 1;
        movingLineText = model.getLineContent(movingLineNumber);
        builder.addEditOperation(new Range$2(movingLineNumber - 1, model.getLineMaxColumn(movingLineNumber - 1), movingLineNumber, model.getLineMaxColumn(movingLineNumber)), null);
        let insertingText = movingLineText;
        if (this.shouldAutoIndent(model, s)) {
          const movingLineMatchResult = this.matchEnterRule(model, indentConverter, tabSize, movingLineNumber, s.startLineNumber - 1);
          if (movingLineMatchResult !== null) {
            const oldIndentation = getLeadingWhitespace(model.getLineContent(movingLineNumber));
            const newSpaceCnt = movingLineMatchResult + getSpaceCnt(oldIndentation, tabSize);
            const newIndentation = generateIndent(newSpaceCnt, tabSize, insertSpaces);
            insertingText = newIndentation + this.trimLeft(movingLineText);
          } else {
            virtualModel.getLineContent = (lineNumber) => {
              if (lineNumber === s.startLineNumber) {
                return model.getLineContent(movingLineNumber);
              } else {
                return model.getLineContent(lineNumber);
              }
            };
            const indentOfMovingLine = getGoodIndentForLine(this._autoIndent, virtualModel, model.getLanguageIdAtPosition(movingLineNumber, 1), s.startLineNumber, indentConverter, this._languageConfigurationService);
            if (indentOfMovingLine !== null) {
              const oldIndentation = getLeadingWhitespace(model.getLineContent(movingLineNumber));
              const newSpaceCnt = getSpaceCnt(indentOfMovingLine, tabSize);
              const oldSpaceCnt = getSpaceCnt(oldIndentation, tabSize);
              if (newSpaceCnt !== oldSpaceCnt) {
                const newIndentation = generateIndent(newSpaceCnt, tabSize, insertSpaces);
                insertingText = newIndentation + this.trimLeft(movingLineText);
              }
            }
          }
          builder.addEditOperation(new Range$2(s.startLineNumber, 1, s.startLineNumber, 1), insertingText + "\n");
          const ret = this.matchEnterRuleMovingDown(model, indentConverter, tabSize, s.startLineNumber, movingLineNumber, insertingText);
          if (ret !== null) {
            if (ret !== 0) {
              this.getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, ret);
            }
          } else {
            virtualModel.getLineContent = (lineNumber) => {
              if (lineNumber === s.startLineNumber) {
                return insertingText;
              } else if (lineNumber >= s.startLineNumber + 1 && lineNumber <= s.endLineNumber + 1) {
                return model.getLineContent(lineNumber - 1);
              } else {
                return model.getLineContent(lineNumber);
              }
            };
            const newIndentatOfMovingBlock = getGoodIndentForLine(this._autoIndent, virtualModel, model.getLanguageIdAtPosition(movingLineNumber, 1), s.startLineNumber + 1, indentConverter, this._languageConfigurationService);
            if (newIndentatOfMovingBlock !== null) {
              const oldIndentation = getLeadingWhitespace(model.getLineContent(s.startLineNumber));
              const newSpaceCnt = getSpaceCnt(newIndentatOfMovingBlock, tabSize);
              const oldSpaceCnt = getSpaceCnt(oldIndentation, tabSize);
              if (newSpaceCnt !== oldSpaceCnt) {
                const spaceCntOffset = newSpaceCnt - oldSpaceCnt;
                this.getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, spaceCntOffset);
              }
            }
          }
        } else {
          builder.addEditOperation(new Range$2(s.startLineNumber, 1, s.startLineNumber, 1), insertingText + "\n");
        }
      } else {
        movingLineNumber = s.startLineNumber - 1;
        movingLineText = model.getLineContent(movingLineNumber);
        builder.addEditOperation(new Range$2(movingLineNumber, 1, movingLineNumber + 1, 1), null);
        builder.addEditOperation(new Range$2(s.endLineNumber, model.getLineMaxColumn(s.endLineNumber), s.endLineNumber, model.getLineMaxColumn(s.endLineNumber)), "\n" + movingLineText);
        if (this.shouldAutoIndent(model, s)) {
          virtualModel.getLineContent = (lineNumber) => {
            if (lineNumber === movingLineNumber) {
              return model.getLineContent(s.startLineNumber);
            } else {
              return model.getLineContent(lineNumber);
            }
          };
          const ret = this.matchEnterRule(model, indentConverter, tabSize, s.startLineNumber, s.startLineNumber - 2);
          if (ret !== null) {
            if (ret !== 0) {
              this.getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, ret);
            }
          } else {
            const indentOfFirstLine = getGoodIndentForLine(this._autoIndent, virtualModel, model.getLanguageIdAtPosition(s.startLineNumber, 1), movingLineNumber, indentConverter, this._languageConfigurationService);
            if (indentOfFirstLine !== null) {
              const oldIndent = getLeadingWhitespace(model.getLineContent(s.startLineNumber));
              const newSpaceCnt = getSpaceCnt(indentOfFirstLine, tabSize);
              const oldSpaceCnt = getSpaceCnt(oldIndent, tabSize);
              if (newSpaceCnt !== oldSpaceCnt) {
                const spaceCntOffset = newSpaceCnt - oldSpaceCnt;
                this.getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, spaceCntOffset);
              }
            }
          }
        }
      }
    }
    this._selectionId = builder.trackSelection(s);
  }
  buildIndentConverter(tabSize, indentSize, insertSpaces) {
    return {
      shiftIndent: (indentation) => {
        return ShiftCommand.shiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces);
      },
      unshiftIndent: (indentation) => {
        return ShiftCommand.unshiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces);
      }
    };
  }
  parseEnterResult(model, indentConverter, tabSize, line, enter) {
    if (enter) {
      let enterPrefix = enter.indentation;
      if (enter.indentAction === IndentAction$1.None) {
        enterPrefix = enter.indentation + enter.appendText;
      } else if (enter.indentAction === IndentAction$1.Indent) {
        enterPrefix = enter.indentation + enter.appendText;
      } else if (enter.indentAction === IndentAction$1.IndentOutdent) {
        enterPrefix = enter.indentation;
      } else if (enter.indentAction === IndentAction$1.Outdent) {
        enterPrefix = indentConverter.unshiftIndent(enter.indentation) + enter.appendText;
      }
      const movingLineText = model.getLineContent(line);
      if (this.trimLeft(movingLineText).indexOf(this.trimLeft(enterPrefix)) >= 0) {
        const oldIndentation = getLeadingWhitespace(model.getLineContent(line));
        let newIndentation = getLeadingWhitespace(enterPrefix);
        const indentMetadataOfMovelingLine = getIndentMetadata(model, line, this._languageConfigurationService);
        if (indentMetadataOfMovelingLine !== null && indentMetadataOfMovelingLine & 2) {
          newIndentation = indentConverter.unshiftIndent(newIndentation);
        }
        const newSpaceCnt = getSpaceCnt(newIndentation, tabSize);
        const oldSpaceCnt = getSpaceCnt(oldIndentation, tabSize);
        return newSpaceCnt - oldSpaceCnt;
      }
    }
    return null;
  }
  /**
   *
   * @param model
   * @param indentConverter
   * @param tabSize
   * @param line the line moving down
   * @param futureAboveLineNumber the line which will be at the `line` position
   * @param futureAboveLineText
   */
  matchEnterRuleMovingDown(model, indentConverter, tabSize, line, futureAboveLineNumber, futureAboveLineText) {
    if (lastNonWhitespaceIndex(futureAboveLineText) >= 0) {
      const maxColumn = model.getLineMaxColumn(futureAboveLineNumber);
      const enter = getEnterAction(this._autoIndent, model, new Range$2(futureAboveLineNumber, maxColumn, futureAboveLineNumber, maxColumn), this._languageConfigurationService);
      return this.parseEnterResult(model, indentConverter, tabSize, line, enter);
    } else {
      let validPrecedingLine = line - 1;
      while (validPrecedingLine >= 1) {
        const lineContent = model.getLineContent(validPrecedingLine);
        const nonWhitespaceIdx = lastNonWhitespaceIndex(lineContent);
        if (nonWhitespaceIdx >= 0) {
          break;
        }
        validPrecedingLine--;
      }
      if (validPrecedingLine < 1 || line > model.getLineCount()) {
        return null;
      }
      const maxColumn = model.getLineMaxColumn(validPrecedingLine);
      const enter = getEnterAction(this._autoIndent, model, new Range$2(validPrecedingLine, maxColumn, validPrecedingLine, maxColumn), this._languageConfigurationService);
      return this.parseEnterResult(model, indentConverter, tabSize, line, enter);
    }
  }
  matchEnterRule(model, indentConverter, tabSize, line, oneLineAbove, previousLineText) {
    let validPrecedingLine = oneLineAbove;
    while (validPrecedingLine >= 1) {
      let lineContent;
      if (validPrecedingLine === oneLineAbove && previousLineText !== void 0) {
        lineContent = previousLineText;
      } else {
        lineContent = model.getLineContent(validPrecedingLine);
      }
      const nonWhitespaceIdx = lastNonWhitespaceIndex(lineContent);
      if (nonWhitespaceIdx >= 0) {
        break;
      }
      validPrecedingLine--;
    }
    if (validPrecedingLine < 1 || line > model.getLineCount()) {
      return null;
    }
    const maxColumn = model.getLineMaxColumn(validPrecedingLine);
    const enter = getEnterAction(this._autoIndent, model, new Range$2(validPrecedingLine, maxColumn, validPrecedingLine, maxColumn), this._languageConfigurationService);
    return this.parseEnterResult(model, indentConverter, tabSize, line, enter);
  }
  trimLeft(str2) {
    return str2.replace(/^\s+/, "");
  }
  shouldAutoIndent(model, selection) {
    if (this._autoIndent < 4) {
      return false;
    }
    if (!model.tokenization.isCheapToTokenize(selection.startLineNumber)) {
      return false;
    }
    const languageAtSelectionStart = model.getLanguageIdAtPosition(selection.startLineNumber, 1);
    const languageAtSelectionEnd = model.getLanguageIdAtPosition(selection.endLineNumber, 1);
    if (languageAtSelectionStart !== languageAtSelectionEnd) {
      return false;
    }
    if (this._languageConfigurationService.getLanguageConfiguration(languageAtSelectionStart).indentRulesSupport === null) {
      return false;
    }
    return true;
  }
  getIndentEditsOfMovingBlock(model, builder, s, tabSize, insertSpaces, offset) {
    for (let i = s.startLineNumber; i <= s.endLineNumber; i++) {
      const lineContent = model.getLineContent(i);
      const originalIndent = getLeadingWhitespace(lineContent);
      const originalSpacesCnt = getSpaceCnt(originalIndent, tabSize);
      const newSpacesCnt = originalSpacesCnt + offset;
      const newIndent = generateIndent(newSpacesCnt, tabSize, insertSpaces);
      if (newIndent !== originalIndent) {
        builder.addEditOperation(new Range$2(i, 1, i, originalIndent.length + 1), newIndent);
        if (i === s.endLineNumber && s.endColumn <= originalIndent.length + 1 && newIndent === "") {
          this._moveEndLineSelectionShrink = true;
        }
      }
    }
  }
  computeCursorState(model, helper) {
    let result2 = helper.getTrackedSelection(this._selectionId);
    if (this._moveEndPositionDown) {
      result2 = result2.setEndPosition(result2.endLineNumber + 1, 1);
    }
    if (this._moveEndLineSelectionShrink && result2.startLineNumber < result2.endLineNumber) {
      result2 = result2.setEndPosition(result2.endLineNumber, 2);
    }
    return result2;
  }
};
MoveLinesCommand = __decorate$T([
  __param$R(3, ILanguageConfigurationService)
], MoveLinesCommand);
class SortLinesCommand {
  static getCollator() {
    if (!SortLinesCommand._COLLATOR) {
      SortLinesCommand._COLLATOR = new Intl.Collator();
    }
    return SortLinesCommand._COLLATOR;
  }
  constructor(selection, descending) {
    this.selection = selection;
    this.descending = descending;
    this.selectionId = null;
  }
  getEditOperations(model, builder) {
    const op = sortLines(model, this.selection, this.descending);
    if (op) {
      builder.addEditOperation(op.range, op.text);
    }
    this.selectionId = builder.trackSelection(this.selection);
  }
  computeCursorState(model, helper) {
    return helper.getTrackedSelection(this.selectionId);
  }
  static canRun(model, selection, descending) {
    if (model === null) {
      return false;
    }
    const data = getSortData(model, selection, descending);
    if (!data) {
      return false;
    }
    for (let i = 0, len = data.before.length; i < len; i++) {
      if (data.before[i] !== data.after[i]) {
        return true;
      }
    }
    return false;
  }
}
SortLinesCommand._COLLATOR = null;
function getSortData(model, selection, descending) {
  const startLineNumber = selection.startLineNumber;
  let endLineNumber = selection.endLineNumber;
  if (selection.endColumn === 1) {
    endLineNumber--;
  }
  if (startLineNumber >= endLineNumber) {
    return null;
  }
  const linesToSort = [];
  for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
    linesToSort.push(model.getLineContent(lineNumber));
  }
  let sorted = linesToSort.slice(0);
  sorted.sort(SortLinesCommand.getCollator().compare);
  if (descending === true) {
    sorted = sorted.reverse();
  }
  return {
    startLineNumber,
    endLineNumber,
    before: linesToSort,
    after: sorted
  };
}
function sortLines(model, selection, descending) {
  const data = getSortData(model, selection, descending);
  if (!data) {
    return null;
  }
  return EditOperation.replace(new Range$2(data.startLineNumber, 1, data.endLineNumber, model.getLineMaxColumn(data.endLineNumber)), data.after.join("\n"));
}
class AbstractCopyLinesAction extends EditorAction {
  constructor(down, opts) {
    super(opts);
    this.down = down;
  }
  run(_accessor, editor2) {
    if (!editor2.hasModel()) {
      return;
    }
    const selections2 = editor2.getSelections().map((selection, index) => ({ selection, index, ignore: false }));
    selections2.sort((a, b) => Range$2.compareRangesUsingStarts(a.selection, b.selection));
    let prev = selections2[0];
    for (let i = 1; i < selections2.length; i++) {
      const curr = selections2[i];
      if (prev.selection.endLineNumber === curr.selection.startLineNumber) {
        if (prev.index < curr.index) {
          curr.ignore = true;
        } else {
          prev.ignore = true;
          prev = curr;
        }
      }
    }
    const commands = [];
    for (const selection of selections2) {
      commands.push(new CopyLinesCommand(selection.selection, this.down, selection.ignore));
    }
    editor2.pushUndoStop();
    editor2.executeCommands(this.id, commands);
    editor2.pushUndoStop();
  }
}
class CopyLinesUpAction extends AbstractCopyLinesAction {
  constructor() {
    super(false, {
      id: "editor.action.copyLinesUpAction",
      label: localize("lines.copyUp", "Copy Line Up"),
      alias: "Copy Line Up",
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 512 | 1024 | 16,
        linux: {
          primary: 2048 | 512 | 1024 | 16
          /* KeyCode.UpArrow */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: MenuId.MenubarSelectionMenu,
        group: "2_line",
        title: localize({ key: "miCopyLinesUp", comment: ["&& denotes a mnemonic"] }, "&&Copy Line Up"),
        order: 1
      }
    });
  }
}
class CopyLinesDownAction extends AbstractCopyLinesAction {
  constructor() {
    super(true, {
      id: "editor.action.copyLinesDownAction",
      label: localize("lines.copyDown", "Copy Line Down"),
      alias: "Copy Line Down",
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 512 | 1024 | 18,
        linux: {
          primary: 2048 | 512 | 1024 | 18
          /* KeyCode.DownArrow */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: MenuId.MenubarSelectionMenu,
        group: "2_line",
        title: localize({ key: "miCopyLinesDown", comment: ["&& denotes a mnemonic"] }, "Co&&py Line Down"),
        order: 2
      }
    });
  }
}
class DuplicateSelectionAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.duplicateSelection",
      label: localize("duplicateSelection", "Duplicate Selection"),
      alias: "Duplicate Selection",
      precondition: EditorContextKeys.writable,
      menuOpts: {
        menuId: MenuId.MenubarSelectionMenu,
        group: "2_line",
        title: localize({ key: "miDuplicateSelection", comment: ["&& denotes a mnemonic"] }, "&&Duplicate Selection"),
        order: 5
      }
    });
  }
  run(accessor, editor2, args) {
    if (!editor2.hasModel()) {
      return;
    }
    const commands = [];
    const selections2 = editor2.getSelections();
    const model = editor2.getModel();
    for (const selection of selections2) {
      if (selection.isEmpty()) {
        commands.push(new CopyLinesCommand(selection, true));
      } else {
        const insertSelection = new Selection$1(selection.endLineNumber, selection.endColumn, selection.endLineNumber, selection.endColumn);
        commands.push(new ReplaceCommandThatSelectsText(insertSelection, model.getValueInRange(selection)));
      }
    }
    editor2.pushUndoStop();
    editor2.executeCommands(this.id, commands);
    editor2.pushUndoStop();
  }
}
class AbstractMoveLinesAction extends EditorAction {
  constructor(down, opts) {
    super(opts);
    this.down = down;
  }
  run(accessor, editor2) {
    const languageConfigurationService = accessor.get(ILanguageConfigurationService);
    const commands = [];
    const selections2 = editor2.getSelections() || [];
    const autoIndent = editor2.getOption(
      11
      /* EditorOption.autoIndent */
    );
    for (const selection of selections2) {
      commands.push(new MoveLinesCommand(selection, this.down, autoIndent, languageConfigurationService));
    }
    editor2.pushUndoStop();
    editor2.executeCommands(this.id, commands);
    editor2.pushUndoStop();
  }
}
class MoveLinesUpAction extends AbstractMoveLinesAction {
  constructor() {
    super(false, {
      id: "editor.action.moveLinesUpAction",
      label: localize("lines.moveUp", "Move Line Up"),
      alias: "Move Line Up",
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 512 | 16,
        linux: {
          primary: 512 | 16
          /* KeyCode.UpArrow */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: MenuId.MenubarSelectionMenu,
        group: "2_line",
        title: localize({ key: "miMoveLinesUp", comment: ["&& denotes a mnemonic"] }, "Mo&&ve Line Up"),
        order: 3
      }
    });
  }
}
class MoveLinesDownAction extends AbstractMoveLinesAction {
  constructor() {
    super(true, {
      id: "editor.action.moveLinesDownAction",
      label: localize("lines.moveDown", "Move Line Down"),
      alias: "Move Line Down",
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 512 | 18,
        linux: {
          primary: 512 | 18
          /* KeyCode.DownArrow */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: MenuId.MenubarSelectionMenu,
        group: "2_line",
        title: localize({ key: "miMoveLinesDown", comment: ["&& denotes a mnemonic"] }, "Move &&Line Down"),
        order: 4
      }
    });
  }
}
class AbstractSortLinesAction extends EditorAction {
  constructor(descending, opts) {
    super(opts);
    this.descending = descending;
  }
  run(_accessor, editor2) {
    const selections2 = editor2.getSelections() || [];
    for (const selection of selections2) {
      if (!SortLinesCommand.canRun(editor2.getModel(), selection, this.descending)) {
        return;
      }
    }
    const commands = [];
    for (let i = 0, len = selections2.length; i < len; i++) {
      commands[i] = new SortLinesCommand(selections2[i], this.descending);
    }
    editor2.pushUndoStop();
    editor2.executeCommands(this.id, commands);
    editor2.pushUndoStop();
  }
}
class SortLinesAscendingAction extends AbstractSortLinesAction {
  constructor() {
    super(false, {
      id: "editor.action.sortLinesAscending",
      label: localize("lines.sortAscending", "Sort Lines Ascending"),
      alias: "Sort Lines Ascending",
      precondition: EditorContextKeys.writable
    });
  }
}
class SortLinesDescendingAction extends AbstractSortLinesAction {
  constructor() {
    super(true, {
      id: "editor.action.sortLinesDescending",
      label: localize("lines.sortDescending", "Sort Lines Descending"),
      alias: "Sort Lines Descending",
      precondition: EditorContextKeys.writable
    });
  }
}
class DeleteDuplicateLinesAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.removeDuplicateLines",
      label: localize("lines.deleteDuplicates", "Delete Duplicate Lines"),
      alias: "Delete Duplicate Lines",
      precondition: EditorContextKeys.writable
    });
  }
  run(_accessor, editor2) {
    if (!editor2.hasModel()) {
      return;
    }
    const model = editor2.getModel();
    if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) {
      return;
    }
    const edits = [];
    const endCursorState = [];
    let linesDeleted = 0;
    for (const selection of editor2.getSelections()) {
      const uniqueLines = /* @__PURE__ */ new Set();
      const lines = [];
      for (let i = selection.startLineNumber; i <= selection.endLineNumber; i++) {
        const line = model.getLineContent(i);
        if (uniqueLines.has(line)) {
          continue;
        }
        lines.push(line);
        uniqueLines.add(line);
      }
      const selectionToReplace = new Selection$1(selection.startLineNumber, 1, selection.endLineNumber, model.getLineMaxColumn(selection.endLineNumber));
      const adjustedSelectionStart = selection.startLineNumber - linesDeleted;
      const finalSelection = new Selection$1(adjustedSelectionStart, 1, adjustedSelectionStart + lines.length - 1, lines[lines.length - 1].length);
      edits.push(EditOperation.replace(selectionToReplace, lines.join("\n")));
      endCursorState.push(finalSelection);
      linesDeleted += selection.endLineNumber - selection.startLineNumber + 1 - lines.length;
    }
    editor2.pushUndoStop();
    editor2.executeEdits(this.id, edits, endCursorState);
    editor2.pushUndoStop();
  }
}
class TrimTrailingWhitespaceAction extends EditorAction {
  constructor() {
    super({
      id: TrimTrailingWhitespaceAction.ID,
      label: localize("lines.trimTrailingWhitespace", "Trim Trailing Whitespace"),
      alias: "Trim Trailing Whitespace",
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: KeyChord(
          2048 | 41,
          2048 | 54
          /* KeyCode.KeyX */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(_accessor, editor2, args) {
    let cursors = [];
    if (args.reason === "auto-save") {
      cursors = (editor2.getSelections() || []).map((s) => new Position$2(s.positionLineNumber, s.positionColumn));
    }
    const selection = editor2.getSelection();
    if (selection === null) {
      return;
    }
    const command = new TrimTrailingWhitespaceCommand(selection, cursors);
    editor2.pushUndoStop();
    editor2.executeCommands(this.id, [command]);
    editor2.pushUndoStop();
  }
}
TrimTrailingWhitespaceAction.ID = "editor.action.trimTrailingWhitespace";
class DeleteLinesAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.deleteLines",
      label: localize("lines.delete", "Delete Line"),
      alias: "Delete Line",
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 2048 | 1024 | 41,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(_accessor, editor2) {
    if (!editor2.hasModel()) {
      return;
    }
    const ops = this._getLinesToRemove(editor2);
    const model = editor2.getModel();
    if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) {
      return;
    }
    let linesDeleted = 0;
    const edits = [];
    const cursorState = [];
    for (let i = 0, len = ops.length; i < len; i++) {
      const op = ops[i];
      let startLineNumber = op.startLineNumber;
      let endLineNumber = op.endLineNumber;
      let startColumn = 1;
      let endColumn = model.getLineMaxColumn(endLineNumber);
      if (endLineNumber < model.getLineCount()) {
        endLineNumber += 1;
        endColumn = 1;
      } else if (startLineNumber > 1) {
        startLineNumber -= 1;
        startColumn = model.getLineMaxColumn(startLineNumber);
      }
      edits.push(EditOperation.replace(new Selection$1(startLineNumber, startColumn, endLineNumber, endColumn), ""));
      cursorState.push(new Selection$1(startLineNumber - linesDeleted, op.positionColumn, startLineNumber - linesDeleted, op.positionColumn));
      linesDeleted += op.endLineNumber - op.startLineNumber + 1;
    }
    editor2.pushUndoStop();
    editor2.executeEdits(this.id, edits, cursorState);
    editor2.pushUndoStop();
  }
  _getLinesToRemove(editor2) {
    const operations = editor2.getSelections().map((s) => {
      let endLineNumber = s.endLineNumber;
      if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) {
        endLineNumber -= 1;
      }
      return {
        startLineNumber: s.startLineNumber,
        selectionStartColumn: s.selectionStartColumn,
        endLineNumber,
        positionColumn: s.positionColumn
      };
    });
    operations.sort((a, b) => {
      if (a.startLineNumber === b.startLineNumber) {
        return a.endLineNumber - b.endLineNumber;
      }
      return a.startLineNumber - b.startLineNumber;
    });
    const mergedOperations = [];
    let previousOperation = operations[0];
    for (let i = 1; i < operations.length; i++) {
      if (previousOperation.endLineNumber + 1 >= operations[i].startLineNumber) {
        previousOperation.endLineNumber = operations[i].endLineNumber;
      } else {
        mergedOperations.push(previousOperation);
        previousOperation = operations[i];
      }
    }
    mergedOperations.push(previousOperation);
    return mergedOperations;
  }
}
class IndentLinesAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.indentLines",
      label: localize("lines.indent", "Indent Line"),
      alias: "Indent Line",
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 94,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(_accessor, editor2) {
    const viewModel = editor2._getViewModel();
    if (!viewModel) {
      return;
    }
    editor2.pushUndoStop();
    editor2.executeCommands(this.id, TypeOperations.indent(viewModel.cursorConfig, editor2.getModel(), editor2.getSelections()));
    editor2.pushUndoStop();
  }
}
class OutdentLinesAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.outdentLines",
      label: localize("lines.outdent", "Outdent Line"),
      alias: "Outdent Line",
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 92,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(_accessor, editor2) {
    CoreEditingCommands.Outdent.runEditorCommand(_accessor, editor2, null);
  }
}
class InsertLineBeforeAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.insertLineBefore",
      label: localize("lines.insertBefore", "Insert Line Above"),
      alias: "Insert Line Above",
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 1024 | 3,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(_accessor, editor2) {
    const viewModel = editor2._getViewModel();
    if (!viewModel) {
      return;
    }
    editor2.pushUndoStop();
    editor2.executeCommands(this.id, TypeOperations.lineInsertBefore(viewModel.cursorConfig, editor2.getModel(), editor2.getSelections()));
  }
}
class InsertLineAfterAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.insertLineAfter",
      label: localize("lines.insertAfter", "Insert Line Below"),
      alias: "Insert Line Below",
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 3,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(_accessor, editor2) {
    const viewModel = editor2._getViewModel();
    if (!viewModel) {
      return;
    }
    editor2.pushUndoStop();
    editor2.executeCommands(this.id, TypeOperations.lineInsertAfter(viewModel.cursorConfig, editor2.getModel(), editor2.getSelections()));
  }
}
class AbstractDeleteAllToBoundaryAction extends EditorAction {
  run(_accessor, editor2) {
    if (!editor2.hasModel()) {
      return;
    }
    const primaryCursor = editor2.getSelection();
    const rangesToDelete = this._getRangesToDelete(editor2);
    const effectiveRanges = [];
    for (let i = 0, count = rangesToDelete.length - 1; i < count; i++) {
      const range2 = rangesToDelete[i];
      const nextRange = rangesToDelete[i + 1];
      if (Range$2.intersectRanges(range2, nextRange) === null) {
        effectiveRanges.push(range2);
      } else {
        rangesToDelete[i + 1] = Range$2.plusRange(range2, nextRange);
      }
    }
    effectiveRanges.push(rangesToDelete[rangesToDelete.length - 1]);
    const endCursorState = this._getEndCursorState(primaryCursor, effectiveRanges);
    const edits = effectiveRanges.map((range2) => {
      return EditOperation.replace(range2, "");
    });
    editor2.pushUndoStop();
    editor2.executeEdits(this.id, edits, endCursorState);
    editor2.pushUndoStop();
  }
}
class DeleteAllLeftAction extends AbstractDeleteAllToBoundaryAction {
  constructor() {
    super({
      id: "deleteAllLeft",
      label: localize("lines.deleteAllLeft", "Delete All Left"),
      alias: "Delete All Left",
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 0,
        mac: {
          primary: 2048 | 1
          /* KeyCode.Backspace */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  _getEndCursorState(primaryCursor, rangesToDelete) {
    let endPrimaryCursor = null;
    const endCursorState = [];
    let deletedLines = 0;
    rangesToDelete.forEach((range2) => {
      let endCursor;
      if (range2.endColumn === 1 && deletedLines > 0) {
        const newStartLine = range2.startLineNumber - deletedLines;
        endCursor = new Selection$1(newStartLine, range2.startColumn, newStartLine, range2.startColumn);
      } else {
        endCursor = new Selection$1(range2.startLineNumber, range2.startColumn, range2.startLineNumber, range2.startColumn);
      }
      deletedLines += range2.endLineNumber - range2.startLineNumber;
      if (range2.intersectRanges(primaryCursor)) {
        endPrimaryCursor = endCursor;
      } else {
        endCursorState.push(endCursor);
      }
    });
    if (endPrimaryCursor) {
      endCursorState.unshift(endPrimaryCursor);
    }
    return endCursorState;
  }
  _getRangesToDelete(editor2) {
    const selections2 = editor2.getSelections();
    if (selections2 === null) {
      return [];
    }
    let rangesToDelete = selections2;
    const model = editor2.getModel();
    if (model === null) {
      return [];
    }
    rangesToDelete.sort(Range$2.compareRangesUsingStarts);
    rangesToDelete = rangesToDelete.map((selection) => {
      if (selection.isEmpty()) {
        if (selection.startColumn === 1) {
          const deleteFromLine = Math.max(1, selection.startLineNumber - 1);
          const deleteFromColumn = selection.startLineNumber === 1 ? 1 : model.getLineContent(deleteFromLine).length + 1;
          return new Range$2(deleteFromLine, deleteFromColumn, selection.startLineNumber, 1);
        } else {
          return new Range$2(selection.startLineNumber, 1, selection.startLineNumber, selection.startColumn);
        }
      } else {
        return new Range$2(selection.startLineNumber, 1, selection.endLineNumber, selection.endColumn);
      }
    });
    return rangesToDelete;
  }
}
class DeleteAllRightAction extends AbstractDeleteAllToBoundaryAction {
  constructor() {
    super({
      id: "deleteAllRight",
      label: localize("lines.deleteAllRight", "Delete All Right"),
      alias: "Delete All Right",
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 0,
        mac: { primary: 256 | 41, secondary: [
          2048 | 20
          /* KeyCode.Delete */
        ] },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  _getEndCursorState(primaryCursor, rangesToDelete) {
    let endPrimaryCursor = null;
    const endCursorState = [];
    for (let i = 0, len = rangesToDelete.length, offset = 0; i < len; i++) {
      const range2 = rangesToDelete[i];
      const endCursor = new Selection$1(range2.startLineNumber - offset, range2.startColumn, range2.startLineNumber - offset, range2.startColumn);
      if (range2.intersectRanges(primaryCursor)) {
        endPrimaryCursor = endCursor;
      } else {
        endCursorState.push(endCursor);
      }
    }
    if (endPrimaryCursor) {
      endCursorState.unshift(endPrimaryCursor);
    }
    return endCursorState;
  }
  _getRangesToDelete(editor2) {
    const model = editor2.getModel();
    if (model === null) {
      return [];
    }
    const selections2 = editor2.getSelections();
    if (selections2 === null) {
      return [];
    }
    const rangesToDelete = selections2.map((sel) => {
      if (sel.isEmpty()) {
        const maxColumn = model.getLineMaxColumn(sel.startLineNumber);
        if (sel.startColumn === maxColumn) {
          return new Range$2(sel.startLineNumber, sel.startColumn, sel.startLineNumber + 1, 1);
        } else {
          return new Range$2(sel.startLineNumber, sel.startColumn, sel.startLineNumber, maxColumn);
        }
      }
      return sel;
    });
    rangesToDelete.sort(Range$2.compareRangesUsingStarts);
    return rangesToDelete;
  }
}
class JoinLinesAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.joinLines",
      label: localize("lines.joinLines", "Join Lines"),
      alias: "Join Lines",
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 0,
        mac: {
          primary: 256 | 40
          /* KeyCode.KeyJ */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(_accessor, editor2) {
    const selections2 = editor2.getSelections();
    if (selections2 === null) {
      return;
    }
    let primaryCursor = editor2.getSelection();
    if (primaryCursor === null) {
      return;
    }
    selections2.sort(Range$2.compareRangesUsingStarts);
    const reducedSelections = [];
    const lastSelection = selections2.reduce((previousValue, currentValue) => {
      if (previousValue.isEmpty()) {
        if (previousValue.endLineNumber === currentValue.startLineNumber) {
          if (primaryCursor.equalsSelection(previousValue)) {
            primaryCursor = currentValue;
          }
          return currentValue;
        }
        if (currentValue.startLineNumber > previousValue.endLineNumber + 1) {
          reducedSelections.push(previousValue);
          return currentValue;
        } else {
          return new Selection$1(previousValue.startLineNumber, previousValue.startColumn, currentValue.endLineNumber, currentValue.endColumn);
        }
      } else {
        if (currentValue.startLineNumber > previousValue.endLineNumber) {
          reducedSelections.push(previousValue);
          return currentValue;
        } else {
          return new Selection$1(previousValue.startLineNumber, previousValue.startColumn, currentValue.endLineNumber, currentValue.endColumn);
        }
      }
    });
    reducedSelections.push(lastSelection);
    const model = editor2.getModel();
    if (model === null) {
      return;
    }
    const edits = [];
    const endCursorState = [];
    let endPrimaryCursor = primaryCursor;
    let lineOffset = 0;
    for (let i = 0, len = reducedSelections.length; i < len; i++) {
      const selection = reducedSelections[i];
      const startLineNumber = selection.startLineNumber;
      const startColumn = 1;
      let columnDeltaOffset = 0;
      let endLineNumber, endColumn;
      const selectionEndPositionOffset = model.getLineContent(selection.endLineNumber).length - selection.endColumn;
      if (selection.isEmpty() || selection.startLineNumber === selection.endLineNumber) {
        const position = selection.getStartPosition();
        if (position.lineNumber < model.getLineCount()) {
          endLineNumber = startLineNumber + 1;
          endColumn = model.getLineMaxColumn(endLineNumber);
        } else {
          endLineNumber = position.lineNumber;
          endColumn = model.getLineMaxColumn(position.lineNumber);
        }
      } else {
        endLineNumber = selection.endLineNumber;
        endColumn = model.getLineMaxColumn(endLineNumber);
      }
      let trimmedLinesContent = model.getLineContent(startLineNumber);
      for (let i2 = startLineNumber + 1; i2 <= endLineNumber; i2++) {
        const lineText = model.getLineContent(i2);
        const firstNonWhitespaceIdx = model.getLineFirstNonWhitespaceColumn(i2);
        if (firstNonWhitespaceIdx >= 1) {
          let insertSpace = true;
          if (trimmedLinesContent === "") {
            insertSpace = false;
          }
          if (insertSpace && (trimmedLinesContent.charAt(trimmedLinesContent.length - 1) === " " || trimmedLinesContent.charAt(trimmedLinesContent.length - 1) === "	")) {
            insertSpace = false;
            trimmedLinesContent = trimmedLinesContent.replace(/[\s\uFEFF\xA0]+$/g, " ");
          }
          const lineTextWithoutIndent = lineText.substr(firstNonWhitespaceIdx - 1);
          trimmedLinesContent += (insertSpace ? " " : "") + lineTextWithoutIndent;
          if (insertSpace) {
            columnDeltaOffset = lineTextWithoutIndent.length + 1;
          } else {
            columnDeltaOffset = lineTextWithoutIndent.length;
          }
        } else {
          columnDeltaOffset = 0;
        }
      }
      const deleteSelection = new Range$2(startLineNumber, startColumn, endLineNumber, endColumn);
      if (!deleteSelection.isEmpty()) {
        let resultSelection;
        if (selection.isEmpty()) {
          edits.push(EditOperation.replace(deleteSelection, trimmedLinesContent));
          resultSelection = new Selection$1(deleteSelection.startLineNumber - lineOffset, trimmedLinesContent.length - columnDeltaOffset + 1, startLineNumber - lineOffset, trimmedLinesContent.length - columnDeltaOffset + 1);
        } else {
          if (selection.startLineNumber === selection.endLineNumber) {
            edits.push(EditOperation.replace(deleteSelection, trimmedLinesContent));
            resultSelection = new Selection$1(selection.startLineNumber - lineOffset, selection.startColumn, selection.endLineNumber - lineOffset, selection.endColumn);
          } else {
            edits.push(EditOperation.replace(deleteSelection, trimmedLinesContent));
            resultSelection = new Selection$1(selection.startLineNumber - lineOffset, selection.startColumn, selection.startLineNumber - lineOffset, trimmedLinesContent.length - selectionEndPositionOffset);
          }
        }
        if (Range$2.intersectRanges(deleteSelection, primaryCursor) !== null) {
          endPrimaryCursor = resultSelection;
        } else {
          endCursorState.push(resultSelection);
        }
      }
      lineOffset += deleteSelection.endLineNumber - deleteSelection.startLineNumber;
    }
    endCursorState.unshift(endPrimaryCursor);
    editor2.pushUndoStop();
    editor2.executeEdits(this.id, edits, endCursorState);
    editor2.pushUndoStop();
  }
}
class TransposeAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.transpose",
      label: localize("editor.transpose", "Transpose characters around the cursor"),
      alias: "Transpose characters around the cursor",
      precondition: EditorContextKeys.writable
    });
  }
  run(_accessor, editor2) {
    const selections2 = editor2.getSelections();
    if (selections2 === null) {
      return;
    }
    const model = editor2.getModel();
    if (model === null) {
      return;
    }
    const commands = [];
    for (let i = 0, len = selections2.length; i < len; i++) {
      const selection = selections2[i];
      if (!selection.isEmpty()) {
        continue;
      }
      const cursor = selection.getStartPosition();
      const maxColumn = model.getLineMaxColumn(cursor.lineNumber);
      if (cursor.column >= maxColumn) {
        if (cursor.lineNumber === model.getLineCount()) {
          continue;
        }
        const deleteSelection = new Range$2(cursor.lineNumber, Math.max(1, cursor.column - 1), cursor.lineNumber + 1, 1);
        const chars2 = model.getValueInRange(deleteSelection).split("").reverse().join("");
        commands.push(new ReplaceCommand(new Selection$1(cursor.lineNumber, Math.max(1, cursor.column - 1), cursor.lineNumber + 1, 1), chars2));
      } else {
        const deleteSelection = new Range$2(cursor.lineNumber, Math.max(1, cursor.column - 1), cursor.lineNumber, cursor.column + 1);
        const chars2 = model.getValueInRange(deleteSelection).split("").reverse().join("");
        commands.push(new ReplaceCommandThatPreservesSelection(deleteSelection, chars2, new Selection$1(cursor.lineNumber, cursor.column + 1, cursor.lineNumber, cursor.column + 1)));
      }
    }
    editor2.pushUndoStop();
    editor2.executeCommands(this.id, commands);
    editor2.pushUndoStop();
  }
}
class AbstractCaseAction extends EditorAction {
  run(_accessor, editor2) {
    const selections2 = editor2.getSelections();
    if (selections2 === null) {
      return;
    }
    const model = editor2.getModel();
    if (model === null) {
      return;
    }
    const wordSeparators2 = editor2.getOption(
      128
      /* EditorOption.wordSeparators */
    );
    const textEdits = [];
    for (const selection of selections2) {
      if (selection.isEmpty()) {
        const cursor = selection.getStartPosition();
        const word2 = editor2.getConfiguredWordAtPosition(cursor);
        if (!word2) {
          continue;
        }
        const wordRange = new Range$2(cursor.lineNumber, word2.startColumn, cursor.lineNumber, word2.endColumn);
        const text2 = model.getValueInRange(wordRange);
        textEdits.push(EditOperation.replace(wordRange, this._modifyText(text2, wordSeparators2)));
      } else {
        const text2 = model.getValueInRange(selection);
        textEdits.push(EditOperation.replace(selection, this._modifyText(text2, wordSeparators2)));
      }
    }
    editor2.pushUndoStop();
    editor2.executeEdits(this.id, textEdits);
    editor2.pushUndoStop();
  }
}
class UpperCaseAction extends AbstractCaseAction {
  constructor() {
    super({
      id: "editor.action.transformToUppercase",
      label: localize("editor.transformToUppercase", "Transform to Uppercase"),
      alias: "Transform to Uppercase",
      precondition: EditorContextKeys.writable
    });
  }
  _modifyText(text2, wordSeparators2) {
    return text2.toLocaleUpperCase();
  }
}
class LowerCaseAction extends AbstractCaseAction {
  constructor() {
    super({
      id: "editor.action.transformToLowercase",
      label: localize("editor.transformToLowercase", "Transform to Lowercase"),
      alias: "Transform to Lowercase",
      precondition: EditorContextKeys.writable
    });
  }
  _modifyText(text2, wordSeparators2) {
    return text2.toLocaleLowerCase();
  }
}
class BackwardsCompatibleRegExp {
  constructor(_pattern, _flags) {
    this._pattern = _pattern;
    this._flags = _flags;
    this._actual = null;
    this._evaluated = false;
  }
  get() {
    if (!this._evaluated) {
      this._evaluated = true;
      try {
        this._actual = new RegExp(this._pattern, this._flags);
      } catch (err) {
      }
    }
    return this._actual;
  }
  isSupported() {
    return this.get() !== null;
  }
}
class TitleCaseAction extends AbstractCaseAction {
  constructor() {
    super({
      id: "editor.action.transformToTitlecase",
      label: localize("editor.transformToTitlecase", "Transform to Title Case"),
      alias: "Transform to Title Case",
      precondition: EditorContextKeys.writable
    });
  }
  _modifyText(text2, wordSeparators2) {
    const titleBoundary = TitleCaseAction.titleBoundary.get();
    if (!titleBoundary) {
      return text2;
    }
    return text2.toLocaleLowerCase().replace(titleBoundary, (b) => b.toLocaleUpperCase());
  }
}
TitleCaseAction.titleBoundary = new BackwardsCompatibleRegExp("(^|[^\\p{L}\\p{N}']|((^|\\P{L})'))\\p{L}", "gmu");
class SnakeCaseAction extends AbstractCaseAction {
  constructor() {
    super({
      id: "editor.action.transformToSnakecase",
      label: localize("editor.transformToSnakecase", "Transform to Snake Case"),
      alias: "Transform to Snake Case",
      precondition: EditorContextKeys.writable
    });
  }
  _modifyText(text2, wordSeparators2) {
    const caseBoundary = SnakeCaseAction.caseBoundary.get();
    const singleLetters = SnakeCaseAction.singleLetters.get();
    if (!caseBoundary || !singleLetters) {
      return text2;
    }
    return text2.replace(caseBoundary, "$1_$2").replace(singleLetters, "$1_$2$3").toLocaleLowerCase();
  }
}
SnakeCaseAction.caseBoundary = new BackwardsCompatibleRegExp("(\\p{Ll})(\\p{Lu})", "gmu");
SnakeCaseAction.singleLetters = new BackwardsCompatibleRegExp("(\\p{Lu}|\\p{N})(\\p{Lu})(\\p{Ll})", "gmu");
class CamelCaseAction extends AbstractCaseAction {
  constructor() {
    super({
      id: "editor.action.transformToCamelcase",
      label: localize("editor.transformToCamelcase", "Transform to Camel Case"),
      alias: "Transform to Camel Case",
      precondition: EditorContextKeys.writable
    });
  }
  _modifyText(text2, wordSeparators2) {
    const wordBoundary = CamelCaseAction.wordBoundary.get();
    if (!wordBoundary) {
      return text2;
    }
    const words = text2.split(wordBoundary);
    const firstWord = words.shift();
    return firstWord + words.map((word2) => word2.substring(0, 1).toLocaleUpperCase() + word2.substring(1)).join("");
  }
}
CamelCaseAction.wordBoundary = new BackwardsCompatibleRegExp("[_\\s-]", "gm");
class KebabCaseAction extends AbstractCaseAction {
  static isSupported() {
    const areAllRegexpsSupported = [
      this.caseBoundary,
      this.singleLetters,
      this.underscoreBoundary
    ].every((regexp) => regexp.isSupported());
    return areAllRegexpsSupported;
  }
  constructor() {
    super({
      id: "editor.action.transformToKebabcase",
      label: localize("editor.transformToKebabcase", "Transform to Kebab Case"),
      alias: "Transform to Kebab Case",
      precondition: EditorContextKeys.writable
    });
  }
  _modifyText(text2, _) {
    const caseBoundary = KebabCaseAction.caseBoundary.get();
    const singleLetters = KebabCaseAction.singleLetters.get();
    const underscoreBoundary = KebabCaseAction.underscoreBoundary.get();
    if (!caseBoundary || !singleLetters || !underscoreBoundary) {
      return text2;
    }
    return text2.replace(underscoreBoundary, "$1-$3").replace(caseBoundary, "$1-$2").replace(singleLetters, "$1-$2").toLocaleLowerCase();
  }
}
KebabCaseAction.caseBoundary = new BackwardsCompatibleRegExp("(\\p{Ll})(\\p{Lu})", "gmu");
KebabCaseAction.singleLetters = new BackwardsCompatibleRegExp("(\\p{Lu}|\\p{N})(\\p{Lu}\\p{Ll})", "gmu");
KebabCaseAction.underscoreBoundary = new BackwardsCompatibleRegExp("(\\S)(_)(\\S)", "gm");
registerEditorAction(CopyLinesUpAction);
registerEditorAction(CopyLinesDownAction);
registerEditorAction(DuplicateSelectionAction);
registerEditorAction(MoveLinesUpAction);
registerEditorAction(MoveLinesDownAction);
registerEditorAction(SortLinesAscendingAction);
registerEditorAction(SortLinesDescendingAction);
registerEditorAction(DeleteDuplicateLinesAction);
registerEditorAction(TrimTrailingWhitespaceAction);
registerEditorAction(DeleteLinesAction);
registerEditorAction(IndentLinesAction);
registerEditorAction(OutdentLinesAction);
registerEditorAction(InsertLineBeforeAction);
registerEditorAction(InsertLineAfterAction);
registerEditorAction(DeleteAllLeftAction);
registerEditorAction(DeleteAllRightAction);
registerEditorAction(JoinLinesAction);
registerEditorAction(TransposeAction);
registerEditorAction(UpperCaseAction);
registerEditorAction(LowerCaseAction);
if (SnakeCaseAction.caseBoundary.isSupported() && SnakeCaseAction.singleLetters.isSupported()) {
  registerEditorAction(SnakeCaseAction);
}
if (CamelCaseAction.wordBoundary.isSupported()) {
  registerEditorAction(CamelCaseAction);
}
if (TitleCaseAction.titleBoundary.isSupported()) {
  registerEditorAction(TitleCaseAction);
}
if (KebabCaseAction.isSupported()) {
  registerEditorAction(KebabCaseAction);
}
const linkedEditing = "";
var __decorate$S = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$Q = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$x = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
const CONTEXT_ONTYPE_RENAME_INPUT_VISIBLE = new RawContextKey("LinkedEditingInputVisible", false);
const DECORATION_CLASS_NAME = "linked-editing-decoration";
let LinkedEditingContribution = class LinkedEditingContribution2 extends Disposable {
  static get(editor2) {
    return editor2.getContribution(LinkedEditingContribution2.ID);
  }
  constructor(editor2, contextKeyService, languageFeaturesService, languageConfigurationService, languageFeatureDebounceService) {
    super();
    this.languageConfigurationService = languageConfigurationService;
    this._syncRangesToken = 0;
    this._localToDispose = this._register(new DisposableStore());
    this._editor = editor2;
    this._providers = languageFeaturesService.linkedEditingRangeProvider;
    this._enabled = false;
    this._visibleContextKey = CONTEXT_ONTYPE_RENAME_INPUT_VISIBLE.bindTo(contextKeyService);
    this._debounceInformation = languageFeatureDebounceService.for(this._providers, "Linked Editing", { max: 200 });
    this._currentDecorations = this._editor.createDecorationsCollection();
    this._languageWordPattern = null;
    this._currentWordPattern = null;
    this._ignoreChangeEvent = false;
    this._localToDispose = this._register(new DisposableStore());
    this._rangeUpdateTriggerPromise = null;
    this._rangeSyncTriggerPromise = null;
    this._currentRequest = null;
    this._currentRequestPosition = null;
    this._currentRequestModelVersion = null;
    this._register(this._editor.onDidChangeModel(() => this.reinitialize(true)));
    this._register(this._editor.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        68
        /* EditorOption.linkedEditing */
      ) || e.hasChanged(
        91
        /* EditorOption.renameOnType */
      )) {
        this.reinitialize(false);
      }
    }));
    this._register(this._providers.onDidChange(() => this.reinitialize(false)));
    this._register(this._editor.onDidChangeModelLanguage(() => this.reinitialize(true)));
    this.reinitialize(true);
  }
  reinitialize(forceRefresh) {
    const model = this._editor.getModel();
    const isEnabled = model !== null && (this._editor.getOption(
      68
      /* EditorOption.linkedEditing */
    ) || this._editor.getOption(
      91
      /* EditorOption.renameOnType */
    )) && this._providers.has(model);
    if (isEnabled === this._enabled && !forceRefresh) {
      return;
    }
    this._enabled = isEnabled;
    this.clearRanges();
    this._localToDispose.clear();
    if (!isEnabled || model === null) {
      return;
    }
    this._localToDispose.add(Event$1.runAndSubscribe(model.onDidChangeLanguageConfiguration, () => {
      this._languageWordPattern = this.languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).getWordDefinition();
    }));
    const rangeUpdateScheduler = new Delayer(this._debounceInformation.get(model));
    const triggerRangeUpdate = () => {
      var _a2;
      this._rangeUpdateTriggerPromise = rangeUpdateScheduler.trigger(() => this.updateRanges(), (_a2 = this._debounceDuration) !== null && _a2 !== void 0 ? _a2 : this._debounceInformation.get(model));
    };
    const rangeSyncScheduler = new Delayer(0);
    const triggerRangeSync = (token) => {
      this._rangeSyncTriggerPromise = rangeSyncScheduler.trigger(() => this._syncRanges(token));
    };
    this._localToDispose.add(this._editor.onDidChangeCursorPosition(() => {
      triggerRangeUpdate();
    }));
    this._localToDispose.add(this._editor.onDidChangeModelContent((e) => {
      if (!this._ignoreChangeEvent) {
        if (this._currentDecorations.length > 0) {
          const referenceRange = this._currentDecorations.getRange(0);
          if (referenceRange && e.changes.every((c) => referenceRange.intersectRanges(c.range))) {
            triggerRangeSync(this._syncRangesToken);
            return;
          }
        }
      }
      triggerRangeUpdate();
    }));
    this._localToDispose.add({
      dispose: () => {
        rangeUpdateScheduler.dispose();
        rangeSyncScheduler.dispose();
      }
    });
    this.updateRanges();
  }
  _syncRanges(token) {
    if (!this._editor.hasModel() || token !== this._syncRangesToken || this._currentDecorations.length === 0) {
      return;
    }
    const model = this._editor.getModel();
    const referenceRange = this._currentDecorations.getRange(0);
    if (!referenceRange || referenceRange.startLineNumber !== referenceRange.endLineNumber) {
      return this.clearRanges();
    }
    const referenceValue = model.getValueInRange(referenceRange);
    if (this._currentWordPattern) {
      const match2 = referenceValue.match(this._currentWordPattern);
      const matchLength = match2 ? match2[0].length : 0;
      if (matchLength !== referenceValue.length) {
        return this.clearRanges();
      }
    }
    const edits = [];
    for (let i = 1, len = this._currentDecorations.length; i < len; i++) {
      const mirrorRange = this._currentDecorations.getRange(i);
      if (!mirrorRange) {
        continue;
      }
      if (mirrorRange.startLineNumber !== mirrorRange.endLineNumber) {
        edits.push({
          range: mirrorRange,
          text: referenceValue
        });
      } else {
        let oldValue = model.getValueInRange(mirrorRange);
        let newValue = referenceValue;
        let rangeStartColumn = mirrorRange.startColumn;
        let rangeEndColumn = mirrorRange.endColumn;
        const commonPrefixLength$1 = commonPrefixLength(oldValue, newValue);
        rangeStartColumn += commonPrefixLength$1;
        oldValue = oldValue.substr(commonPrefixLength$1);
        newValue = newValue.substr(commonPrefixLength$1);
        const commonSuffixLength$1 = commonSuffixLength(oldValue, newValue);
        rangeEndColumn -= commonSuffixLength$1;
        oldValue = oldValue.substr(0, oldValue.length - commonSuffixLength$1);
        newValue = newValue.substr(0, newValue.length - commonSuffixLength$1);
        if (rangeStartColumn !== rangeEndColumn || newValue.length !== 0) {
          edits.push({
            range: new Range$2(mirrorRange.startLineNumber, rangeStartColumn, mirrorRange.endLineNumber, rangeEndColumn),
            text: newValue
          });
        }
      }
    }
    if (edits.length === 0) {
      return;
    }
    try {
      this._editor.popUndoStop();
      this._ignoreChangeEvent = true;
      const prevEditOperationType = this._editor._getViewModel().getPrevEditOperationType();
      this._editor.executeEdits("linkedEditing", edits);
      this._editor._getViewModel().setPrevEditOperationType(prevEditOperationType);
    } finally {
      this._ignoreChangeEvent = false;
    }
  }
  dispose() {
    this.clearRanges();
    super.dispose();
  }
  clearRanges() {
    this._visibleContextKey.set(false);
    this._currentDecorations.clear();
    if (this._currentRequest) {
      this._currentRequest.cancel();
      this._currentRequest = null;
      this._currentRequestPosition = null;
    }
  }
  updateRanges(force = false) {
    return __awaiter$x(this, void 0, void 0, function* () {
      if (!this._editor.hasModel()) {
        this.clearRanges();
        return;
      }
      const position = this._editor.getPosition();
      if (!this._enabled && !force || this._editor.getSelections().length > 1) {
        this.clearRanges();
        return;
      }
      const model = this._editor.getModel();
      const modelVersionId = model.getVersionId();
      if (this._currentRequestPosition && this._currentRequestModelVersion === modelVersionId) {
        if (position.equals(this._currentRequestPosition)) {
          return;
        }
        if (this._currentDecorations.length > 0) {
          const range2 = this._currentDecorations.getRange(0);
          if (range2 && range2.containsPosition(position)) {
            return;
          }
        }
      }
      this.clearRanges();
      this._currentRequestPosition = position;
      this._currentRequestModelVersion = modelVersionId;
      const request = createCancelablePromise((token) => __awaiter$x(this, void 0, void 0, function* () {
        try {
          const sw = new StopWatch(false);
          const response = yield getLinkedEditingRanges(this._providers, model, position, token);
          this._debounceInformation.update(model, sw.elapsed());
          if (request !== this._currentRequest) {
            return;
          }
          this._currentRequest = null;
          if (modelVersionId !== model.getVersionId()) {
            return;
          }
          let ranges = [];
          if (response === null || response === void 0 ? void 0 : response.ranges) {
            ranges = response.ranges;
          }
          this._currentWordPattern = (response === null || response === void 0 ? void 0 : response.wordPattern) || this._languageWordPattern;
          let foundReferenceRange = false;
          for (let i = 0, len = ranges.length; i < len; i++) {
            if (Range$2.containsPosition(ranges[i], position)) {
              foundReferenceRange = true;
              if (i !== 0) {
                const referenceRange = ranges[i];
                ranges.splice(i, 1);
                ranges.unshift(referenceRange);
              }
              break;
            }
          }
          if (!foundReferenceRange) {
            this.clearRanges();
            return;
          }
          const decorations2 = ranges.map((range2) => ({ range: range2, options: LinkedEditingContribution2.DECORATION }));
          this._visibleContextKey.set(true);
          this._currentDecorations.set(decorations2);
          this._syncRangesToken++;
        } catch (err) {
          if (!isCancellationError(err)) {
            onUnexpectedError(err);
          }
          if (this._currentRequest === request || !this._currentRequest) {
            this.clearRanges();
          }
        }
      }));
      this._currentRequest = request;
      return request;
    });
  }
};
LinkedEditingContribution.ID = "editor.contrib.linkedEditing";
LinkedEditingContribution.DECORATION = ModelDecorationOptions.register({
  description: "linked-editing",
  stickiness: 0,
  className: DECORATION_CLASS_NAME
});
LinkedEditingContribution = __decorate$S([
  __param$Q(1, IContextKeyService),
  __param$Q(2, ILanguageFeaturesService),
  __param$Q(3, ILanguageConfigurationService),
  __param$Q(4, ILanguageFeatureDebounceService)
], LinkedEditingContribution);
class LinkedEditingAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.linkedEditing",
      label: localize("linkedEditing.label", "Start Linked Editing"),
      alias: "Start Linked Editing",
      precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasRenameProvider),
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 1024 | 60,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  runCommand(accessor, args) {
    const editorService = accessor.get(ICodeEditorService);
    const [uri, pos] = Array.isArray(args) && args || [void 0, void 0];
    if (URI.isUri(uri) && Position$2.isIPosition(pos)) {
      return editorService.openCodeEditor({ resource: uri }, editorService.getActiveCodeEditor()).then((editor2) => {
        if (!editor2) {
          return;
        }
        editor2.setPosition(pos);
        editor2.invokeWithinContext((accessor2) => {
          this.reportTelemetry(accessor2, editor2);
          return this.run(accessor2, editor2);
        });
      }, onUnexpectedError);
    }
    return super.runCommand(accessor, args);
  }
  run(_accessor, editor2) {
    const controller = LinkedEditingContribution.get(editor2);
    if (controller) {
      return Promise.resolve(controller.updateRanges(true));
    }
    return Promise.resolve();
  }
}
const LinkedEditingCommand = EditorCommand.bindToContribution(LinkedEditingContribution.get);
registerEditorCommand(new LinkedEditingCommand({
  id: "cancelLinkedEditingInput",
  precondition: CONTEXT_ONTYPE_RENAME_INPUT_VISIBLE,
  handler: (x) => x.clearRanges(),
  kbOpts: {
    kbExpr: EditorContextKeys.editorTextFocus,
    weight: 100 + 99,
    primary: 9,
    secondary: [
      1024 | 9
      /* KeyCode.Escape */
    ]
  }
}));
function getLinkedEditingRanges(providers, model, position, token) {
  const orderedByScore = providers.ordered(model);
  return first(orderedByScore.map((provider) => () => __awaiter$x(this, void 0, void 0, function* () {
    try {
      return yield provider.provideLinkedEditingRanges(model, position, token);
    } catch (e) {
      onUnexpectedExternalError(e);
      return void 0;
    }
  })), (result2) => !!result2 && isNonEmptyArray(result2 === null || result2 === void 0 ? void 0 : result2.ranges));
}
registerColor("editor.linkedEditingBackground", { dark: Color.fromHex("#f00").transparent(0.3), light: Color.fromHex("#f00").transparent(0.3), hcDark: Color.fromHex("#f00").transparent(0.3), hcLight: Color.white }, localize("editorLinkedEditingBackground", "Background color when the editor auto renames on type."));
registerModelAndPositionCommand("_executeLinkedEditingProvider", (_accessor, model, position) => {
  const { linkedEditingRangeProvider } = _accessor.get(ILanguageFeaturesService);
  return getLinkedEditingRanges(linkedEditingRangeProvider, model, position, CancellationToken.None);
});
registerEditorContribution(
  LinkedEditingContribution.ID,
  LinkedEditingContribution,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
registerEditorAction(LinkedEditingAction);
const links = "";
var __awaiter$w = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
let Link$1 = class Link {
  constructor(link2, provider) {
    this._link = link2;
    this._provider = provider;
  }
  toJSON() {
    return {
      range: this.range,
      url: this.url,
      tooltip: this.tooltip
    };
  }
  get range() {
    return this._link.range;
  }
  get url() {
    return this._link.url;
  }
  get tooltip() {
    return this._link.tooltip;
  }
  resolve(token) {
    return __awaiter$w(this, void 0, void 0, function* () {
      if (this._link.url) {
        return this._link.url;
      }
      if (typeof this._provider.resolveLink === "function") {
        return Promise.resolve(this._provider.resolveLink(this._link, token)).then((value) => {
          this._link = value || this._link;
          if (this._link.url) {
            return this.resolve(token);
          }
          return Promise.reject(new Error("missing"));
        });
      }
      return Promise.reject(new Error("missing"));
    });
  }
};
class LinksList {
  constructor(tuples) {
    this._disposables = new DisposableStore();
    let links2 = [];
    for (const [list2, provider] of tuples) {
      const newLinks = list2.links.map((link2) => new Link$1(link2, provider));
      links2 = LinksList._union(links2, newLinks);
      if (isDisposable(list2)) {
        this._disposables.add(list2);
      }
    }
    this.links = links2;
  }
  dispose() {
    this._disposables.dispose();
    this.links.length = 0;
  }
  static _union(oldLinks, newLinks) {
    const result2 = [];
    let oldIndex;
    let oldLen;
    let newIndex;
    let newLen;
    for (oldIndex = 0, newIndex = 0, oldLen = oldLinks.length, newLen = newLinks.length; oldIndex < oldLen && newIndex < newLen; ) {
      const oldLink = oldLinks[oldIndex];
      const newLink = newLinks[newIndex];
      if (Range$2.areIntersectingOrTouching(oldLink.range, newLink.range)) {
        oldIndex++;
        continue;
      }
      const comparisonResult = Range$2.compareRangesUsingStarts(oldLink.range, newLink.range);
      if (comparisonResult < 0) {
        result2.push(oldLink);
        oldIndex++;
      } else {
        result2.push(newLink);
        newIndex++;
      }
    }
    for (; oldIndex < oldLen; oldIndex++) {
      result2.push(oldLinks[oldIndex]);
    }
    for (; newIndex < newLen; newIndex++) {
      result2.push(newLinks[newIndex]);
    }
    return result2;
  }
}
function getLinks(providers, model, token) {
  const lists = [];
  const promises = providers.ordered(model).reverse().map((provider, i) => {
    return Promise.resolve(provider.provideLinks(model, token)).then((result2) => {
      if (result2) {
        lists[i] = [result2, provider];
      }
    }, onUnexpectedExternalError);
  });
  return Promise.all(promises).then(() => {
    const result2 = new LinksList(coalesce(lists));
    if (!token.isCancellationRequested) {
      return result2;
    }
    result2.dispose();
    return new LinksList([]);
  });
}
CommandsRegistry.registerCommand("_executeLinkProvider", (accessor, ...args) => __awaiter$w(void 0, void 0, void 0, function* () {
  let [uri, resolveCount] = args;
  assertType(uri instanceof URI);
  if (typeof resolveCount !== "number") {
    resolveCount = 0;
  }
  const { linkProvider } = accessor.get(ILanguageFeaturesService);
  const model = accessor.get(IModelService).getModel(uri);
  if (!model) {
    return [];
  }
  const list2 = yield getLinks(linkProvider, model, CancellationToken.None);
  if (!list2) {
    return [];
  }
  for (let i = 0; i < Math.min(resolveCount, list2.links.length); i++) {
    yield list2.links[i].resolve(CancellationToken.None);
  }
  const result2 = list2.links.slice(0);
  list2.dispose();
  return result2;
}));
var __decorate$R = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$P = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$v = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
let LinkDetector = class LinkDetector2 extends Disposable {
  static get(editor2) {
    return editor2.getContribution(LinkDetector2.ID);
  }
  constructor(editor2, openerService, notificationService, languageFeaturesService, languageFeatureDebounceService) {
    super();
    this.editor = editor2;
    this.openerService = openerService;
    this.notificationService = notificationService;
    this.languageFeaturesService = languageFeaturesService;
    this.providers = this.languageFeaturesService.linkProvider;
    this.debounceInformation = languageFeatureDebounceService.for(this.providers, "Links", { min: 1e3, max: 4e3 });
    this.computeLinks = this._register(new RunOnceScheduler(() => this.computeLinksNow(), 1e3));
    this.computePromise = null;
    this.activeLinksList = null;
    this.currentOccurrences = {};
    this.activeLinkDecorationId = null;
    const clickLinkGesture = this._register(new ClickLinkGesture(editor2));
    this._register(clickLinkGesture.onMouseMoveOrRelevantKeyDown(([mouseEvent, keyboardEvent]) => {
      this._onEditorMouseMove(mouseEvent, keyboardEvent);
    }));
    this._register(clickLinkGesture.onExecute((e) => {
      this.onEditorMouseUp(e);
    }));
    this._register(clickLinkGesture.onCancel((e) => {
      this.cleanUpActiveLinkDecoration();
    }));
    this._register(editor2.onDidChangeConfiguration((e) => {
      if (!e.hasChanged(
        69
        /* EditorOption.links */
      )) {
        return;
      }
      this.updateDecorations([]);
      this.stop();
      this.computeLinks.schedule(0);
    }));
    this._register(editor2.onDidChangeModelContent((e) => {
      if (!this.editor.hasModel()) {
        return;
      }
      this.computeLinks.schedule(this.debounceInformation.get(this.editor.getModel()));
    }));
    this._register(editor2.onDidChangeModel((e) => {
      this.currentOccurrences = {};
      this.activeLinkDecorationId = null;
      this.stop();
      this.computeLinks.schedule(0);
    }));
    this._register(editor2.onDidChangeModelLanguage((e) => {
      this.stop();
      this.computeLinks.schedule(0);
    }));
    this._register(this.providers.onDidChange((e) => {
      this.stop();
      this.computeLinks.schedule(0);
    }));
    this.computeLinks.schedule(0);
  }
  computeLinksNow() {
    return __awaiter$v(this, void 0, void 0, function* () {
      if (!this.editor.hasModel() || !this.editor.getOption(
        69
        /* EditorOption.links */
      )) {
        return;
      }
      const model = this.editor.getModel();
      if (!this.providers.has(model)) {
        return;
      }
      if (this.activeLinksList) {
        this.activeLinksList.dispose();
        this.activeLinksList = null;
      }
      this.computePromise = createCancelablePromise((token) => getLinks(this.providers, model, token));
      try {
        const sw = new StopWatch(false);
        this.activeLinksList = yield this.computePromise;
        this.debounceInformation.update(model, sw.elapsed());
        if (model.isDisposed()) {
          return;
        }
        this.updateDecorations(this.activeLinksList.links);
      } catch (err) {
        onUnexpectedError(err);
      } finally {
        this.computePromise = null;
      }
    });
  }
  updateDecorations(links2) {
    const useMetaKey = this.editor.getOption(
      76
      /* EditorOption.multiCursorModifier */
    ) === "altKey";
    const oldDecorations = [];
    const keys = Object.keys(this.currentOccurrences);
    for (const decorationId of keys) {
      const occurence = this.currentOccurrences[decorationId];
      oldDecorations.push(occurence.decorationId);
    }
    const newDecorations = [];
    if (links2) {
      for (const link2 of links2) {
        newDecorations.push(LinkOccurrence.decoration(link2, useMetaKey));
      }
    }
    this.editor.changeDecorations((changeAccessor) => {
      const decorations2 = changeAccessor.deltaDecorations(oldDecorations, newDecorations);
      this.currentOccurrences = {};
      this.activeLinkDecorationId = null;
      for (let i = 0, len = decorations2.length; i < len; i++) {
        const occurence = new LinkOccurrence(links2[i], decorations2[i]);
        this.currentOccurrences[occurence.decorationId] = occurence;
      }
    });
  }
  _onEditorMouseMove(mouseEvent, withKey) {
    const useMetaKey = this.editor.getOption(
      76
      /* EditorOption.multiCursorModifier */
    ) === "altKey";
    if (this.isEnabled(mouseEvent, withKey)) {
      this.cleanUpActiveLinkDecoration();
      const occurrence = this.getLinkOccurrence(mouseEvent.target.position);
      if (occurrence) {
        this.editor.changeDecorations((changeAccessor) => {
          occurrence.activate(changeAccessor, useMetaKey);
          this.activeLinkDecorationId = occurrence.decorationId;
        });
      }
    } else {
      this.cleanUpActiveLinkDecoration();
    }
  }
  cleanUpActiveLinkDecoration() {
    const useMetaKey = this.editor.getOption(
      76
      /* EditorOption.multiCursorModifier */
    ) === "altKey";
    if (this.activeLinkDecorationId) {
      const occurrence = this.currentOccurrences[this.activeLinkDecorationId];
      if (occurrence) {
        this.editor.changeDecorations((changeAccessor) => {
          occurrence.deactivate(changeAccessor, useMetaKey);
        });
      }
      this.activeLinkDecorationId = null;
    }
  }
  onEditorMouseUp(mouseEvent) {
    if (!this.isEnabled(mouseEvent)) {
      return;
    }
    const occurrence = this.getLinkOccurrence(mouseEvent.target.position);
    if (!occurrence) {
      return;
    }
    this.openLinkOccurrence(
      occurrence,
      mouseEvent.hasSideBySideModifier,
      true
      /* from user gesture */
    );
  }
  openLinkOccurrence(occurrence, openToSide, fromUserGesture = false) {
    if (!this.openerService) {
      return;
    }
    const { link: link2 } = occurrence;
    link2.resolve(CancellationToken.None).then((uri) => {
      if (typeof uri === "string" && this.editor.hasModel()) {
        const modelUri = this.editor.getModel().uri;
        if (modelUri.scheme === Schemas.file && uri.startsWith(`${Schemas.file}:`)) {
          const parsedUri = URI.parse(uri);
          if (parsedUri.scheme === Schemas.file) {
            const fsPath = originalFSPath(parsedUri);
            let relativePath2 = null;
            if (fsPath.startsWith("/./")) {
              relativePath2 = `.${fsPath.substr(1)}`;
            } else if (fsPath.startsWith("//./")) {
              relativePath2 = `.${fsPath.substr(2)}`;
            }
            if (relativePath2) {
              uri = joinPath(modelUri, relativePath2);
            }
          }
        }
      }
      return this.openerService.open(uri, { openToSide, fromUserGesture, allowContributedOpeners: true, allowCommands: true, fromWorkspace: true });
    }, (err) => {
      const messageOrError = err instanceof Error ? err.message : err;
      if (messageOrError === "invalid") {
        this.notificationService.warn(localize("invalid.url", "Failed to open this link because it is not well-formed: {0}", link2.url.toString()));
      } else if (messageOrError === "missing") {
        this.notificationService.warn(localize("missing.url", "Failed to open this link because its target is missing."));
      } else {
        onUnexpectedError(err);
      }
    });
  }
  getLinkOccurrence(position) {
    if (!this.editor.hasModel() || !position) {
      return null;
    }
    const decorations2 = this.editor.getModel().getDecorationsInRange({
      startLineNumber: position.lineNumber,
      startColumn: position.column,
      endLineNumber: position.lineNumber,
      endColumn: position.column
    }, 0, true);
    for (const decoration2 of decorations2) {
      const currentOccurrence = this.currentOccurrences[decoration2.id];
      if (currentOccurrence) {
        return currentOccurrence;
      }
    }
    return null;
  }
  isEnabled(mouseEvent, withKey) {
    return Boolean(mouseEvent.target.type === 6 && (mouseEvent.hasTriggerModifier || withKey && withKey.keyCodeIsTriggerKey));
  }
  stop() {
    var _a2;
    this.computeLinks.cancel();
    if (this.activeLinksList) {
      (_a2 = this.activeLinksList) === null || _a2 === void 0 ? void 0 : _a2.dispose();
      this.activeLinksList = null;
    }
    if (this.computePromise) {
      this.computePromise.cancel();
      this.computePromise = null;
    }
  }
  dispose() {
    super.dispose();
    this.stop();
  }
};
LinkDetector.ID = "editor.linkDetector";
LinkDetector = __decorate$R([
  __param$P(1, IOpenerService),
  __param$P(2, INotificationService),
  __param$P(3, ILanguageFeaturesService),
  __param$P(4, ILanguageFeatureDebounceService)
], LinkDetector);
const decoration = {
  general: ModelDecorationOptions.register({
    description: "detected-link",
    stickiness: 1,
    collapseOnReplaceEdit: true,
    inlineClassName: "detected-link"
  }),
  active: ModelDecorationOptions.register({
    description: "detected-link-active",
    stickiness: 1,
    collapseOnReplaceEdit: true,
    inlineClassName: "detected-link-active"
  })
};
class LinkOccurrence {
  static decoration(link2, useMetaKey) {
    return {
      range: link2.range,
      options: LinkOccurrence._getOptions(link2, useMetaKey, false)
    };
  }
  static _getOptions(link2, useMetaKey, isActive) {
    const options = Object.assign({}, isActive ? decoration.active : decoration.general);
    options.hoverMessage = getHoverMessage(link2, useMetaKey);
    return options;
  }
  constructor(link2, decorationId) {
    this.link = link2;
    this.decorationId = decorationId;
  }
  activate(changeAccessor, useMetaKey) {
    changeAccessor.changeDecorationOptions(this.decorationId, LinkOccurrence._getOptions(this.link, useMetaKey, true));
  }
  deactivate(changeAccessor, useMetaKey) {
    changeAccessor.changeDecorationOptions(this.decorationId, LinkOccurrence._getOptions(this.link, useMetaKey, false));
  }
}
function getHoverMessage(link2, useMetaKey) {
  const executeCmd = link2.url && /^command:/i.test(link2.url.toString());
  const label = link2.tooltip ? link2.tooltip : executeCmd ? localize("links.navigate.executeCmd", "Execute command") : localize("links.navigate.follow", "Follow link");
  const kb = useMetaKey ? isMacintosh ? localize("links.navigate.kb.meta.mac", "cmd + click") : localize("links.navigate.kb.meta", "ctrl + click") : isMacintosh ? localize("links.navigate.kb.alt.mac", "option + click") : localize("links.navigate.kb.alt", "alt + click");
  if (link2.url) {
    let nativeLabel = "";
    if (/^command:/i.test(link2.url.toString())) {
      const match2 = link2.url.toString().match(/^command:([^?#]+)/);
      if (match2) {
        const commandId = match2[1];
        nativeLabel = localize("tooltip.explanation", "Execute command {0}", commandId);
      }
    }
    const hoverMessage = new MarkdownString("", true).appendLink(link2.url.toString(true).replace(/ /g, "%20"), label, nativeLabel).appendMarkdown(` (${kb})`);
    return hoverMessage;
  } else {
    return new MarkdownString().appendText(`${label} (${kb})`);
  }
}
class OpenLinkAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.openLink",
      label: localize("label", "Open Link"),
      alias: "Open Link",
      precondition: void 0
    });
  }
  run(accessor, editor2) {
    const linkDetector = LinkDetector.get(editor2);
    if (!linkDetector) {
      return;
    }
    if (!editor2.hasModel()) {
      return;
    }
    const selections2 = editor2.getSelections();
    for (const sel of selections2) {
      const link2 = linkDetector.getLinkOccurrence(sel.getEndPosition());
      if (link2) {
        linkDetector.openLinkOccurrence(link2, false);
      }
    }
  }
}
registerEditorContribution(
  LinkDetector.ID,
  LinkDetector,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
registerEditorAction(OpenLinkAction);
class LongLinesHelper extends Disposable {
  constructor(_editor) {
    super();
    this._editor = _editor;
    this._register(this._editor.onMouseDown((e) => {
      const stopRenderingLineAfter = this._editor.getOption(
        115
        /* EditorOption.stopRenderingLineAfter */
      );
      if (stopRenderingLineAfter >= 0 && e.target.type === 6 && e.target.position.column >= stopRenderingLineAfter) {
        this._editor.updateOptions({
          stopRenderingLineAfter: -1
        });
      }
    }));
  }
}
LongLinesHelper.ID = "editor.contrib.longLinesHelper";
registerEditorContribution(
  LongLinesHelper.ID,
  LongLinesHelper,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);
const highlightDecorations = "";
const wordHighlightBackground = registerColor("editor.wordHighlightBackground", { dark: "#575757B8", light: "#57575740", hcDark: null, hcLight: null }, localize("wordHighlight", "Background color of a symbol during read-access, like reading a variable. The color must not be opaque so as not to hide underlying decorations."), true);
registerColor("editor.wordHighlightStrongBackground", { dark: "#004972B8", light: "#0e639c40", hcDark: null, hcLight: null }, localize("wordHighlightStrong", "Background color of a symbol during write-access, like writing to a variable. The color must not be opaque so as not to hide underlying decorations."), true);
registerColor("editor.wordHighlightTextBackground", { light: wordHighlightBackground, dark: wordHighlightBackground, hcDark: wordHighlightBackground, hcLight: wordHighlightBackground }, localize("wordHighlightText", "Background color of a textual occurrence for a symbol. The color must not be opaque so as not to hide underlying decorations."), true);
const wordHighlightBorder = registerColor("editor.wordHighlightBorder", { light: null, dark: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize("wordHighlightBorder", "Border color of a symbol during read-access, like reading a variable."));
registerColor("editor.wordHighlightStrongBorder", { light: null, dark: null, hcDark: activeContrastBorder, hcLight: activeContrastBorder }, localize("wordHighlightStrongBorder", "Border color of a symbol during write-access, like writing to a variable."));
registerColor("editor.wordHighlightTextBorder", { light: wordHighlightBorder, dark: wordHighlightBorder, hcDark: wordHighlightBorder, hcLight: wordHighlightBorder }, localize("wordHighlightTextBorder", "Border color of a textual occurrence for a symbol."));
const overviewRulerWordHighlightForeground = registerColor("editorOverviewRuler.wordHighlightForeground", { dark: "#A0A0A0CC", light: "#A0A0A0CC", hcDark: "#A0A0A0CC", hcLight: "#A0A0A0CC" }, localize("overviewRulerWordHighlightForeground", "Overview ruler marker color for symbol highlights. The color must not be opaque so as not to hide underlying decorations."), true);
const overviewRulerWordHighlightStrongForeground = registerColor("editorOverviewRuler.wordHighlightStrongForeground", { dark: "#C0A0C0CC", light: "#C0A0C0CC", hcDark: "#C0A0C0CC", hcLight: "#C0A0C0CC" }, localize("overviewRulerWordHighlightStrongForeground", "Overview ruler marker color for write-access symbol highlights. The color must not be opaque so as not to hide underlying decorations."), true);
const overviewRulerWordHighlightTextForeground = registerColor("editorOverviewRuler.wordHighlightTextForeground", { dark: overviewRulerSelectionHighlightForeground, light: overviewRulerSelectionHighlightForeground, hcDark: overviewRulerSelectionHighlightForeground, hcLight: overviewRulerSelectionHighlightForeground }, localize("overviewRulerWordHighlightTextForeground", "Overview ruler marker color of a textual occurrence for a symbol. The color must not be opaque so as not to hide underlying decorations."), true);
const _WRITE_OPTIONS = ModelDecorationOptions.register({
  description: "word-highlight-strong",
  stickiness: 1,
  className: "wordHighlightStrong",
  overviewRuler: {
    color: themeColorFromId(overviewRulerWordHighlightStrongForeground),
    position: OverviewRulerLane$1.Center
  },
  minimap: {
    color: themeColorFromId(minimapSelectionOccurrenceHighlight),
    position: MinimapPosition$1.Inline
  }
});
const _TEXT_OPTIONS = ModelDecorationOptions.register({
  description: "word-highlight-text",
  stickiness: 1,
  className: "wordHighlightText",
  overviewRuler: {
    color: themeColorFromId(overviewRulerWordHighlightTextForeground),
    position: OverviewRulerLane$1.Center
  },
  minimap: {
    color: themeColorFromId(minimapSelectionOccurrenceHighlight),
    position: MinimapPosition$1.Inline
  }
});
const _SELECTION_HIGHLIGHT_OPTIONS = ModelDecorationOptions.register({
  description: "selection-highlight-overview",
  stickiness: 1,
  className: "selectionHighlight",
  overviewRuler: {
    color: themeColorFromId(overviewRulerSelectionHighlightForeground),
    position: OverviewRulerLane$1.Center
  },
  minimap: {
    color: themeColorFromId(minimapSelectionOccurrenceHighlight),
    position: MinimapPosition$1.Inline
  }
});
const _SELECTION_HIGHLIGHT_OPTIONS_NO_OVERVIEW = ModelDecorationOptions.register({
  description: "selection-highlight",
  stickiness: 1,
  className: "selectionHighlight"
});
const _REGULAR_OPTIONS = ModelDecorationOptions.register({
  description: "word-highlight",
  stickiness: 1,
  className: "wordHighlight",
  overviewRuler: {
    color: themeColorFromId(overviewRulerWordHighlightForeground),
    position: OverviewRulerLane$1.Center
  },
  minimap: {
    color: themeColorFromId(minimapSelectionOccurrenceHighlight),
    position: MinimapPosition$1.Inline
  }
});
function getHighlightDecorationOptions(kind) {
  if (kind === DocumentHighlightKind$1.Write) {
    return _WRITE_OPTIONS;
  } else if (kind === DocumentHighlightKind$1.Text) {
    return _TEXT_OPTIONS;
  } else {
    return _REGULAR_OPTIONS;
  }
}
function getSelectionHighlightDecorationOptions(hasSemanticHighlights) {
  return hasSemanticHighlights ? _SELECTION_HIGHLIGHT_OPTIONS_NO_OVERVIEW : _SELECTION_HIGHLIGHT_OPTIONS;
}
registerThemingParticipant((theme, collector) => {
  const selectionHighlight = theme.getColor(editorSelectionHighlight);
  if (selectionHighlight) {
    collector.addRule(`.monaco-editor .selectionHighlight { background-color: ${selectionHighlight.transparent(0.5)}; }`);
  }
});
var __decorate$Q = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$O = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
function announceCursorChange(previousCursorState, cursorState) {
  const cursorDiff = cursorState.filter((cs) => !previousCursorState.find((pcs) => pcs.equals(cs)));
  if (cursorDiff.length >= 1) {
    const cursorPositions = cursorDiff.map((cs) => `line ${cs.viewState.position.lineNumber} column ${cs.viewState.position.column}`).join(", ");
    const msg = cursorDiff.length === 1 ? localize("cursorAdded", "Cursor added: {0}", cursorPositions) : localize("cursorsAdded", "Cursors added: {0}", cursorPositions);
    status(msg);
  }
}
class InsertCursorAbove extends EditorAction {
  constructor() {
    super({
      id: "editor.action.insertCursorAbove",
      label: localize("mutlicursor.insertAbove", "Add Cursor Above"),
      alias: "Add Cursor Above",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 512 | 16,
        linux: {
          primary: 1024 | 512 | 16,
          secondary: [
            2048 | 1024 | 16
            /* KeyCode.UpArrow */
          ]
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: MenuId.MenubarSelectionMenu,
        group: "3_multi",
        title: localize({ key: "miInsertCursorAbove", comment: ["&& denotes a mnemonic"] }, "&&Add Cursor Above"),
        order: 2
      }
    });
  }
  run(accessor, editor2, args) {
    if (!editor2.hasModel()) {
      return;
    }
    let useLogicalLine = true;
    if (args && args.logicalLine === false) {
      useLogicalLine = false;
    }
    const viewModel = editor2._getViewModel();
    if (viewModel.cursorConfig.readOnly) {
      return;
    }
    viewModel.model.pushStackElement();
    const previousCursorState = viewModel.getCursorStates();
    viewModel.setCursorStates(args.source, 3, CursorMoveCommands.addCursorUp(viewModel, previousCursorState, useLogicalLine));
    viewModel.revealTopMostCursor(args.source);
    announceCursorChange(previousCursorState, viewModel.getCursorStates());
  }
}
class InsertCursorBelow extends EditorAction {
  constructor() {
    super({
      id: "editor.action.insertCursorBelow",
      label: localize("mutlicursor.insertBelow", "Add Cursor Below"),
      alias: "Add Cursor Below",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 512 | 18,
        linux: {
          primary: 1024 | 512 | 18,
          secondary: [
            2048 | 1024 | 18
            /* KeyCode.DownArrow */
          ]
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: MenuId.MenubarSelectionMenu,
        group: "3_multi",
        title: localize({ key: "miInsertCursorBelow", comment: ["&& denotes a mnemonic"] }, "A&&dd Cursor Below"),
        order: 3
      }
    });
  }
  run(accessor, editor2, args) {
    if (!editor2.hasModel()) {
      return;
    }
    let useLogicalLine = true;
    if (args && args.logicalLine === false) {
      useLogicalLine = false;
    }
    const viewModel = editor2._getViewModel();
    if (viewModel.cursorConfig.readOnly) {
      return;
    }
    viewModel.model.pushStackElement();
    const previousCursorState = viewModel.getCursorStates();
    viewModel.setCursorStates(args.source, 3, CursorMoveCommands.addCursorDown(viewModel, previousCursorState, useLogicalLine));
    viewModel.revealBottomMostCursor(args.source);
    announceCursorChange(previousCursorState, viewModel.getCursorStates());
  }
}
class InsertCursorAtEndOfEachLineSelected extends EditorAction {
  constructor() {
    super({
      id: "editor.action.insertCursorAtEndOfEachLineSelected",
      label: localize("mutlicursor.insertAtEndOfEachLineSelected", "Add Cursors to Line Ends"),
      alias: "Add Cursors to Line Ends",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 1024 | 512 | 39,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: MenuId.MenubarSelectionMenu,
        group: "3_multi",
        title: localize({ key: "miInsertCursorAtEndOfEachLineSelected", comment: ["&& denotes a mnemonic"] }, "Add C&&ursors to Line Ends"),
        order: 4
      }
    });
  }
  getCursorsForSelection(selection, model, result2) {
    if (selection.isEmpty()) {
      return;
    }
    for (let i = selection.startLineNumber; i < selection.endLineNumber; i++) {
      const currentLineMaxColumn = model.getLineMaxColumn(i);
      result2.push(new Selection$1(i, currentLineMaxColumn, i, currentLineMaxColumn));
    }
    if (selection.endColumn > 1) {
      result2.push(new Selection$1(selection.endLineNumber, selection.endColumn, selection.endLineNumber, selection.endColumn));
    }
  }
  run(accessor, editor2) {
    if (!editor2.hasModel()) {
      return;
    }
    const model = editor2.getModel();
    const selections2 = editor2.getSelections();
    const viewModel = editor2._getViewModel();
    const previousCursorState = viewModel.getCursorStates();
    const newSelections = [];
    selections2.forEach((sel) => this.getCursorsForSelection(sel, model, newSelections));
    if (newSelections.length > 0) {
      editor2.setSelections(newSelections);
    }
    announceCursorChange(previousCursorState, viewModel.getCursorStates());
  }
}
class InsertCursorAtEndOfLineSelected extends EditorAction {
  constructor() {
    super({
      id: "editor.action.addCursorsToBottom",
      label: localize("mutlicursor.addCursorsToBottom", "Add Cursors To Bottom"),
      alias: "Add Cursors To Bottom",
      precondition: void 0
    });
  }
  run(accessor, editor2) {
    if (!editor2.hasModel()) {
      return;
    }
    const selections2 = editor2.getSelections();
    const lineCount = editor2.getModel().getLineCount();
    const newSelections = [];
    for (let i = selections2[0].startLineNumber; i <= lineCount; i++) {
      newSelections.push(new Selection$1(i, selections2[0].startColumn, i, selections2[0].endColumn));
    }
    const viewModel = editor2._getViewModel();
    const previousCursorState = viewModel.getCursorStates();
    if (newSelections.length > 0) {
      editor2.setSelections(newSelections);
    }
    announceCursorChange(previousCursorState, viewModel.getCursorStates());
  }
}
class InsertCursorAtTopOfLineSelected extends EditorAction {
  constructor() {
    super({
      id: "editor.action.addCursorsToTop",
      label: localize("mutlicursor.addCursorsToTop", "Add Cursors To Top"),
      alias: "Add Cursors To Top",
      precondition: void 0
    });
  }
  run(accessor, editor2) {
    if (!editor2.hasModel()) {
      return;
    }
    const selections2 = editor2.getSelections();
    const newSelections = [];
    for (let i = selections2[0].startLineNumber; i >= 1; i--) {
      newSelections.push(new Selection$1(i, selections2[0].startColumn, i, selections2[0].endColumn));
    }
    const viewModel = editor2._getViewModel();
    const previousCursorState = viewModel.getCursorStates();
    if (newSelections.length > 0) {
      editor2.setSelections(newSelections);
    }
    announceCursorChange(previousCursorState, viewModel.getCursorStates());
  }
}
class MultiCursorSessionResult {
  constructor(selections2, revealRange, revealScrollType) {
    this.selections = selections2;
    this.revealRange = revealRange;
    this.revealScrollType = revealScrollType;
  }
}
class MultiCursorSession {
  static create(editor2, findController) {
    if (!editor2.hasModel()) {
      return null;
    }
    const findState = findController.getState();
    if (!editor2.hasTextFocus() && findState.isRevealed && findState.searchString.length > 0) {
      return new MultiCursorSession(editor2, findController, false, findState.searchString, findState.wholeWord, findState.matchCase, null);
    }
    let isDisconnectedFromFindController = false;
    let wholeWord;
    let matchCase;
    const selections2 = editor2.getSelections();
    if (selections2.length === 1 && selections2[0].isEmpty()) {
      isDisconnectedFromFindController = true;
      wholeWord = true;
      matchCase = true;
    } else {
      wholeWord = findState.wholeWord;
      matchCase = findState.matchCase;
    }
    const s = editor2.getSelection();
    let searchText;
    let currentMatch = null;
    if (s.isEmpty()) {
      const word2 = editor2.getConfiguredWordAtPosition(s.getStartPosition());
      if (!word2) {
        return null;
      }
      searchText = word2.word;
      currentMatch = new Selection$1(s.startLineNumber, word2.startColumn, s.startLineNumber, word2.endColumn);
    } else {
      searchText = editor2.getModel().getValueInRange(s).replace(/\r\n/g, "\n");
    }
    return new MultiCursorSession(editor2, findController, isDisconnectedFromFindController, searchText, wholeWord, matchCase, currentMatch);
  }
  constructor(_editor, findController, isDisconnectedFromFindController, searchText, wholeWord, matchCase, currentMatch) {
    this._editor = _editor;
    this.findController = findController;
    this.isDisconnectedFromFindController = isDisconnectedFromFindController;
    this.searchText = searchText;
    this.wholeWord = wholeWord;
    this.matchCase = matchCase;
    this.currentMatch = currentMatch;
  }
  addSelectionToNextFindMatch() {
    if (!this._editor.hasModel()) {
      return null;
    }
    const nextMatch = this._getNextMatch();
    if (!nextMatch) {
      return null;
    }
    const allSelections = this._editor.getSelections();
    return new MultiCursorSessionResult(
      allSelections.concat(nextMatch),
      nextMatch,
      0
      /* ScrollType.Smooth */
    );
  }
  moveSelectionToNextFindMatch() {
    if (!this._editor.hasModel()) {
      return null;
    }
    const nextMatch = this._getNextMatch();
    if (!nextMatch) {
      return null;
    }
    const allSelections = this._editor.getSelections();
    return new MultiCursorSessionResult(
      allSelections.slice(0, allSelections.length - 1).concat(nextMatch),
      nextMatch,
      0
      /* ScrollType.Smooth */
    );
  }
  _getNextMatch() {
    if (!this._editor.hasModel()) {
      return null;
    }
    if (this.currentMatch) {
      const result2 = this.currentMatch;
      this.currentMatch = null;
      return result2;
    }
    this.findController.highlightFindOptions();
    const allSelections = this._editor.getSelections();
    const lastAddedSelection = allSelections[allSelections.length - 1];
    const nextMatch = this._editor.getModel().findNextMatch(this.searchText, lastAddedSelection.getEndPosition(), false, this.matchCase, this.wholeWord ? this._editor.getOption(
      128
      /* EditorOption.wordSeparators */
    ) : null, false);
    if (!nextMatch) {
      return null;
    }
    return new Selection$1(nextMatch.range.startLineNumber, nextMatch.range.startColumn, nextMatch.range.endLineNumber, nextMatch.range.endColumn);
  }
  addSelectionToPreviousFindMatch() {
    if (!this._editor.hasModel()) {
      return null;
    }
    const previousMatch = this._getPreviousMatch();
    if (!previousMatch) {
      return null;
    }
    const allSelections = this._editor.getSelections();
    return new MultiCursorSessionResult(
      allSelections.concat(previousMatch),
      previousMatch,
      0
      /* ScrollType.Smooth */
    );
  }
  moveSelectionToPreviousFindMatch() {
    if (!this._editor.hasModel()) {
      return null;
    }
    const previousMatch = this._getPreviousMatch();
    if (!previousMatch) {
      return null;
    }
    const allSelections = this._editor.getSelections();
    return new MultiCursorSessionResult(
      allSelections.slice(0, allSelections.length - 1).concat(previousMatch),
      previousMatch,
      0
      /* ScrollType.Smooth */
    );
  }
  _getPreviousMatch() {
    if (!this._editor.hasModel()) {
      return null;
    }
    if (this.currentMatch) {
      const result2 = this.currentMatch;
      this.currentMatch = null;
      return result2;
    }
    this.findController.highlightFindOptions();
    const allSelections = this._editor.getSelections();
    const lastAddedSelection = allSelections[allSelections.length - 1];
    const previousMatch = this._editor.getModel().findPreviousMatch(this.searchText, lastAddedSelection.getStartPosition(), false, this.matchCase, this.wholeWord ? this._editor.getOption(
      128
      /* EditorOption.wordSeparators */
    ) : null, false);
    if (!previousMatch) {
      return null;
    }
    return new Selection$1(previousMatch.range.startLineNumber, previousMatch.range.startColumn, previousMatch.range.endLineNumber, previousMatch.range.endColumn);
  }
  selectAll(searchScope) {
    if (!this._editor.hasModel()) {
      return [];
    }
    this.findController.highlightFindOptions();
    const editorModel = this._editor.getModel();
    if (searchScope) {
      return editorModel.findMatches(
        this.searchText,
        searchScope,
        false,
        this.matchCase,
        this.wholeWord ? this._editor.getOption(
          128
          /* EditorOption.wordSeparators */
        ) : null,
        false,
        1073741824
        /* Constants.MAX_SAFE_SMALL_INTEGER */
      );
    }
    return editorModel.findMatches(
      this.searchText,
      true,
      false,
      this.matchCase,
      this.wholeWord ? this._editor.getOption(
        128
        /* EditorOption.wordSeparators */
      ) : null,
      false,
      1073741824
      /* Constants.MAX_SAFE_SMALL_INTEGER */
    );
  }
}
class MultiCursorSelectionController extends Disposable {
  static get(editor2) {
    return editor2.getContribution(MultiCursorSelectionController.ID);
  }
  constructor(editor2) {
    super();
    this._sessionDispose = this._register(new DisposableStore());
    this._editor = editor2;
    this._ignoreSelectionChange = false;
    this._session = null;
  }
  dispose() {
    this._endSession();
    super.dispose();
  }
  _beginSessionIfNeeded(findController) {
    if (!this._session) {
      const session = MultiCursorSession.create(this._editor, findController);
      if (!session) {
        return;
      }
      this._session = session;
      const newState = { searchString: this._session.searchText };
      if (this._session.isDisconnectedFromFindController) {
        newState.wholeWordOverride = 1;
        newState.matchCaseOverride = 1;
        newState.isRegexOverride = 2;
      }
      findController.getState().change(newState, false);
      this._sessionDispose.add(this._editor.onDidChangeCursorSelection((e) => {
        if (this._ignoreSelectionChange) {
          return;
        }
        this._endSession();
      }));
      this._sessionDispose.add(this._editor.onDidBlurEditorText(() => {
        this._endSession();
      }));
      this._sessionDispose.add(findController.getState().onFindReplaceStateChange((e) => {
        if (e.matchCase || e.wholeWord) {
          this._endSession();
        }
      }));
    }
  }
  _endSession() {
    this._sessionDispose.clear();
    if (this._session && this._session.isDisconnectedFromFindController) {
      const newState = {
        wholeWordOverride: 0,
        matchCaseOverride: 0,
        isRegexOverride: 0
      };
      this._session.findController.getState().change(newState, false);
    }
    this._session = null;
  }
  _setSelections(selections2) {
    this._ignoreSelectionChange = true;
    this._editor.setSelections(selections2);
    this._ignoreSelectionChange = false;
  }
  _expandEmptyToWord(model, selection) {
    if (!selection.isEmpty()) {
      return selection;
    }
    const word2 = this._editor.getConfiguredWordAtPosition(selection.getStartPosition());
    if (!word2) {
      return selection;
    }
    return new Selection$1(selection.startLineNumber, word2.startColumn, selection.startLineNumber, word2.endColumn);
  }
  _applySessionResult(result2) {
    if (!result2) {
      return;
    }
    this._setSelections(result2.selections);
    if (result2.revealRange) {
      this._editor.revealRangeInCenterIfOutsideViewport(result2.revealRange, result2.revealScrollType);
    }
  }
  getSession(findController) {
    return this._session;
  }
  addSelectionToNextFindMatch(findController) {
    if (!this._editor.hasModel()) {
      return;
    }
    if (!this._session) {
      const allSelections = this._editor.getSelections();
      if (allSelections.length > 1) {
        const findState = findController.getState();
        const matchCase = findState.matchCase;
        const selectionsContainSameText = modelRangesContainSameText(this._editor.getModel(), allSelections, matchCase);
        if (!selectionsContainSameText) {
          const model = this._editor.getModel();
          const resultingSelections = [];
          for (let i = 0, len = allSelections.length; i < len; i++) {
            resultingSelections[i] = this._expandEmptyToWord(model, allSelections[i]);
          }
          this._editor.setSelections(resultingSelections);
          return;
        }
      }
    }
    this._beginSessionIfNeeded(findController);
    if (this._session) {
      this._applySessionResult(this._session.addSelectionToNextFindMatch());
    }
  }
  addSelectionToPreviousFindMatch(findController) {
    this._beginSessionIfNeeded(findController);
    if (this._session) {
      this._applySessionResult(this._session.addSelectionToPreviousFindMatch());
    }
  }
  moveSelectionToNextFindMatch(findController) {
    this._beginSessionIfNeeded(findController);
    if (this._session) {
      this._applySessionResult(this._session.moveSelectionToNextFindMatch());
    }
  }
  moveSelectionToPreviousFindMatch(findController) {
    this._beginSessionIfNeeded(findController);
    if (this._session) {
      this._applySessionResult(this._session.moveSelectionToPreviousFindMatch());
    }
  }
  selectAll(findController) {
    if (!this._editor.hasModel()) {
      return;
    }
    let matches = null;
    const findState = findController.getState();
    if (findState.isRevealed && findState.searchString.length > 0 && findState.isRegex) {
      const editorModel = this._editor.getModel();
      if (findState.searchScope) {
        matches = editorModel.findMatches(
          findState.searchString,
          findState.searchScope,
          findState.isRegex,
          findState.matchCase,
          findState.wholeWord ? this._editor.getOption(
            128
            /* EditorOption.wordSeparators */
          ) : null,
          false,
          1073741824
          /* Constants.MAX_SAFE_SMALL_INTEGER */
        );
      } else {
        matches = editorModel.findMatches(
          findState.searchString,
          true,
          findState.isRegex,
          findState.matchCase,
          findState.wholeWord ? this._editor.getOption(
            128
            /* EditorOption.wordSeparators */
          ) : null,
          false,
          1073741824
          /* Constants.MAX_SAFE_SMALL_INTEGER */
        );
      }
    } else {
      this._beginSessionIfNeeded(findController);
      if (!this._session) {
        return;
      }
      matches = this._session.selectAll(findState.searchScope);
    }
    if (matches.length > 0) {
      const editorSelection = this._editor.getSelection();
      for (let i = 0, len = matches.length; i < len; i++) {
        const match2 = matches[i];
        const intersection = match2.range.intersectRanges(editorSelection);
        if (intersection) {
          matches[i] = matches[0];
          matches[0] = match2;
          break;
        }
      }
      this._setSelections(matches.map((m) => new Selection$1(m.range.startLineNumber, m.range.startColumn, m.range.endLineNumber, m.range.endColumn)));
    }
  }
}
MultiCursorSelectionController.ID = "editor.contrib.multiCursorController";
class MultiCursorSelectionControllerAction extends EditorAction {
  run(accessor, editor2) {
    const multiCursorController = MultiCursorSelectionController.get(editor2);
    if (!multiCursorController) {
      return;
    }
    const viewModel = editor2._getViewModel();
    if (viewModel) {
      const previousCursorState = viewModel.getCursorStates();
      const findController = CommonFindController.get(editor2);
      if (findController) {
        this._run(multiCursorController, findController);
      } else {
        const newFindController = accessor.get(IInstantiationService).createInstance(CommonFindController, editor2);
        this._run(multiCursorController, newFindController);
        newFindController.dispose();
      }
      announceCursorChange(previousCursorState, viewModel.getCursorStates());
    }
  }
}
class AddSelectionToNextFindMatchAction extends MultiCursorSelectionControllerAction {
  constructor() {
    super({
      id: "editor.action.addSelectionToNextFindMatch",
      label: localize("addSelectionToNextFindMatch", "Add Selection To Next Find Match"),
      alias: "Add Selection To Next Find Match",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.focus,
        primary: 2048 | 34,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: MenuId.MenubarSelectionMenu,
        group: "3_multi",
        title: localize({ key: "miAddSelectionToNextFindMatch", comment: ["&& denotes a mnemonic"] }, "Add &&Next Occurrence"),
        order: 5
      }
    });
  }
  _run(multiCursorController, findController) {
    multiCursorController.addSelectionToNextFindMatch(findController);
  }
}
class AddSelectionToPreviousFindMatchAction extends MultiCursorSelectionControllerAction {
  constructor() {
    super({
      id: "editor.action.addSelectionToPreviousFindMatch",
      label: localize("addSelectionToPreviousFindMatch", "Add Selection To Previous Find Match"),
      alias: "Add Selection To Previous Find Match",
      precondition: void 0,
      menuOpts: {
        menuId: MenuId.MenubarSelectionMenu,
        group: "3_multi",
        title: localize({ key: "miAddSelectionToPreviousFindMatch", comment: ["&& denotes a mnemonic"] }, "Add P&&revious Occurrence"),
        order: 6
      }
    });
  }
  _run(multiCursorController, findController) {
    multiCursorController.addSelectionToPreviousFindMatch(findController);
  }
}
class MoveSelectionToNextFindMatchAction extends MultiCursorSelectionControllerAction {
  constructor() {
    super({
      id: "editor.action.moveSelectionToNextFindMatch",
      label: localize("moveSelectionToNextFindMatch", "Move Last Selection To Next Find Match"),
      alias: "Move Last Selection To Next Find Match",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.focus,
        primary: KeyChord(
          2048 | 41,
          2048 | 34
          /* KeyCode.KeyD */
        ),
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  _run(multiCursorController, findController) {
    multiCursorController.moveSelectionToNextFindMatch(findController);
  }
}
class MoveSelectionToPreviousFindMatchAction extends MultiCursorSelectionControllerAction {
  constructor() {
    super({
      id: "editor.action.moveSelectionToPreviousFindMatch",
      label: localize("moveSelectionToPreviousFindMatch", "Move Last Selection To Previous Find Match"),
      alias: "Move Last Selection To Previous Find Match",
      precondition: void 0
    });
  }
  _run(multiCursorController, findController) {
    multiCursorController.moveSelectionToPreviousFindMatch(findController);
  }
}
class SelectHighlightsAction extends MultiCursorSelectionControllerAction {
  constructor() {
    super({
      id: "editor.action.selectHighlights",
      label: localize("selectAllOccurrencesOfFindMatch", "Select All Occurrences of Find Match"),
      alias: "Select All Occurrences of Find Match",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.focus,
        primary: 2048 | 1024 | 42,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: MenuId.MenubarSelectionMenu,
        group: "3_multi",
        title: localize({ key: "miSelectHighlights", comment: ["&& denotes a mnemonic"] }, "Select All &&Occurrences"),
        order: 7
      }
    });
  }
  _run(multiCursorController, findController) {
    multiCursorController.selectAll(findController);
  }
}
class CompatChangeAll extends MultiCursorSelectionControllerAction {
  constructor() {
    super({
      id: "editor.action.changeAll",
      label: localize("changeAll.label", "Change All Occurrences"),
      alias: "Change All Occurrences",
      precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.editorTextFocus),
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 60,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      contextMenuOpts: {
        group: "1_modification",
        order: 1.2
      }
    });
  }
  _run(multiCursorController, findController) {
    multiCursorController.selectAll(findController);
  }
}
class SelectionHighlighterState {
  constructor(_model, _searchText, _matchCase, _wordSeparators, prevState) {
    this._model = _model;
    this._searchText = _searchText;
    this._matchCase = _matchCase;
    this._wordSeparators = _wordSeparators;
    this._modelVersionId = this._model.getVersionId();
    this._cachedFindMatches = null;
    if (prevState && this._model === prevState._model && this._searchText === prevState._searchText && this._matchCase === prevState._matchCase && this._wordSeparators === prevState._wordSeparators && this._modelVersionId === prevState._modelVersionId) {
      this._cachedFindMatches = prevState._cachedFindMatches;
    }
  }
  findMatches() {
    if (this._cachedFindMatches === null) {
      this._cachedFindMatches = this._model.findMatches(this._searchText, true, false, this._matchCase, this._wordSeparators, false).map((m) => m.range);
      this._cachedFindMatches.sort(Range$2.compareRangesUsingStarts);
    }
    return this._cachedFindMatches;
  }
}
let SelectionHighlighter = class SelectionHighlighter2 extends Disposable {
  constructor(editor2, _languageFeaturesService) {
    super();
    this._languageFeaturesService = _languageFeaturesService;
    this.editor = editor2;
    this._isEnabled = editor2.getOption(
      106
      /* EditorOption.selectionHighlight */
    );
    this._decorations = editor2.createDecorationsCollection();
    this.updateSoon = this._register(new RunOnceScheduler(() => this._update(), 300));
    this.state = null;
    this._register(editor2.onDidChangeConfiguration((e) => {
      this._isEnabled = editor2.getOption(
        106
        /* EditorOption.selectionHighlight */
      );
    }));
    this._register(editor2.onDidChangeCursorSelection((e) => {
      if (!this._isEnabled) {
        return;
      }
      if (e.selection.isEmpty()) {
        if (e.reason === 3) {
          if (this.state) {
            this._setState(null);
          }
          this.updateSoon.schedule();
        } else {
          this._setState(null);
        }
      } else {
        this._update();
      }
    }));
    this._register(editor2.onDidChangeModel((e) => {
      this._setState(null);
    }));
    this._register(editor2.onDidChangeModelContent((e) => {
      if (this._isEnabled) {
        this.updateSoon.schedule();
      }
    }));
    const findController = CommonFindController.get(editor2);
    if (findController) {
      this._register(findController.getState().onFindReplaceStateChange((e) => {
        this._update();
      }));
    }
    this.updateSoon.schedule();
  }
  _update() {
    this._setState(SelectionHighlighter2._createState(this.state, this._isEnabled, this.editor));
  }
  static _createState(oldState, isEnabled, editor2) {
    if (!isEnabled) {
      return null;
    }
    if (!editor2.hasModel()) {
      return null;
    }
    const s = editor2.getSelection();
    if (s.startLineNumber !== s.endLineNumber) {
      return null;
    }
    const multiCursorController = MultiCursorSelectionController.get(editor2);
    if (!multiCursorController) {
      return null;
    }
    const findController = CommonFindController.get(editor2);
    if (!findController) {
      return null;
    }
    let r = multiCursorController.getSession(findController);
    if (!r) {
      const allSelections = editor2.getSelections();
      if (allSelections.length > 1) {
        const findState2 = findController.getState();
        const matchCase = findState2.matchCase;
        const selectionsContainSameText = modelRangesContainSameText(editor2.getModel(), allSelections, matchCase);
        if (!selectionsContainSameText) {
          return null;
        }
      }
      r = MultiCursorSession.create(editor2, findController);
    }
    if (!r) {
      return null;
    }
    if (r.currentMatch) {
      return null;
    }
    if (/^[ \t]+$/.test(r.searchText)) {
      return null;
    }
    if (r.searchText.length > 200) {
      return null;
    }
    const findState = findController.getState();
    const caseSensitive = findState.matchCase;
    if (findState.isRevealed) {
      let findStateSearchString = findState.searchString;
      if (!caseSensitive) {
        findStateSearchString = findStateSearchString.toLowerCase();
      }
      let mySearchString = r.searchText;
      if (!caseSensitive) {
        mySearchString = mySearchString.toLowerCase();
      }
      if (findStateSearchString === mySearchString && r.matchCase === findState.matchCase && r.wholeWord === findState.wholeWord && !findState.isRegex) {
        return null;
      }
    }
    return new SelectionHighlighterState(editor2.getModel(), r.searchText, r.matchCase, r.wholeWord ? editor2.getOption(
      128
      /* EditorOption.wordSeparators */
    ) : null, oldState);
  }
  _setState(newState) {
    this.state = newState;
    if (!this.state) {
      this._decorations.clear();
      return;
    }
    if (!this.editor.hasModel()) {
      return;
    }
    const model = this.editor.getModel();
    if (model.isTooLargeForTokenization()) {
      return;
    }
    const allMatches = this.state.findMatches();
    const selections2 = this.editor.getSelections();
    selections2.sort(Range$2.compareRangesUsingStarts);
    const matches = [];
    for (let i = 0, j = 0, len = allMatches.length, lenJ = selections2.length; i < len; ) {
      const match2 = allMatches[i];
      if (j >= lenJ) {
        matches.push(match2);
        i++;
      } else {
        const cmp3 = Range$2.compareRangesUsingStarts(match2, selections2[j]);
        if (cmp3 < 0) {
          if (selections2[j].isEmpty() || !Range$2.areIntersecting(match2, selections2[j])) {
            matches.push(match2);
          }
          i++;
        } else if (cmp3 > 0) {
          j++;
        } else {
          i++;
          j++;
        }
      }
    }
    const hasSemanticHighlights = this._languageFeaturesService.documentHighlightProvider.has(model) && this.editor.getOption(
      79
      /* EditorOption.occurrencesHighlight */
    );
    const decorations2 = matches.map((r) => {
      return {
        range: r,
        options: getSelectionHighlightDecorationOptions(hasSemanticHighlights)
      };
    });
    this._decorations.set(decorations2);
  }
  dispose() {
    this._setState(null);
    super.dispose();
  }
};
SelectionHighlighter.ID = "editor.contrib.selectionHighlighter";
SelectionHighlighter = __decorate$Q([
  __param$O(1, ILanguageFeaturesService)
], SelectionHighlighter);
function modelRangesContainSameText(model, ranges, matchCase) {
  const selectedText = getValueInRange(model, ranges[0], !matchCase);
  for (let i = 1, len = ranges.length; i < len; i++) {
    const range2 = ranges[i];
    if (range2.isEmpty()) {
      return false;
    }
    const thisSelectedText = getValueInRange(model, range2, !matchCase);
    if (selectedText !== thisSelectedText) {
      return false;
    }
  }
  return true;
}
function getValueInRange(model, range2, toLowerCase) {
  const text2 = model.getValueInRange(range2);
  return toLowerCase ? text2.toLowerCase() : text2;
}
class FocusNextCursor extends EditorAction {
  constructor() {
    super({
      id: "editor.action.focusNextCursor",
      label: localize("mutlicursor.focusNextCursor", "Focus Next Cursor"),
      description: {
        description: localize("mutlicursor.focusNextCursor.description", "Focuses the next cursor"),
        args: []
      },
      alias: "Focus Next Cursor",
      precondition: void 0
    });
  }
  run(accessor, editor2, args) {
    if (!editor2.hasModel()) {
      return;
    }
    const viewModel = editor2._getViewModel();
    if (viewModel.cursorConfig.readOnly) {
      return;
    }
    viewModel.model.pushStackElement();
    const previousCursorState = Array.from(viewModel.getCursorStates());
    const firstCursor = previousCursorState.shift();
    if (!firstCursor) {
      return;
    }
    previousCursorState.push(firstCursor);
    viewModel.setCursorStates(args.source, 3, previousCursorState);
    viewModel.revealPrimaryCursor(args.source, true);
    announceCursorChange(previousCursorState, viewModel.getCursorStates());
  }
}
class FocusPreviousCursor extends EditorAction {
  constructor() {
    super({
      id: "editor.action.focusPreviousCursor",
      label: localize("mutlicursor.focusPreviousCursor", "Focus Previous Cursor"),
      description: {
        description: localize("mutlicursor.focusPreviousCursor.description", "Focuses the previous cursor"),
        args: []
      },
      alias: "Focus Previous Cursor",
      precondition: void 0
    });
  }
  run(accessor, editor2, args) {
    if (!editor2.hasModel()) {
      return;
    }
    const viewModel = editor2._getViewModel();
    if (viewModel.cursorConfig.readOnly) {
      return;
    }
    viewModel.model.pushStackElement();
    const previousCursorState = Array.from(viewModel.getCursorStates());
    const firstCursor = previousCursorState.pop();
    if (!firstCursor) {
      return;
    }
    previousCursorState.unshift(firstCursor);
    viewModel.setCursorStates(args.source, 3, previousCursorState);
    viewModel.revealPrimaryCursor(args.source, true);
    announceCursorChange(previousCursorState, viewModel.getCursorStates());
  }
}
registerEditorContribution(
  MultiCursorSelectionController.ID,
  MultiCursorSelectionController,
  4
  /* EditorContributionInstantiation.Lazy */
);
registerEditorContribution(
  SelectionHighlighter.ID,
  SelectionHighlighter,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
registerEditorAction(InsertCursorAbove);
registerEditorAction(InsertCursorBelow);
registerEditorAction(InsertCursorAtEndOfEachLineSelected);
registerEditorAction(AddSelectionToNextFindMatchAction);
registerEditorAction(AddSelectionToPreviousFindMatchAction);
registerEditorAction(MoveSelectionToNextFindMatchAction);
registerEditorAction(MoveSelectionToPreviousFindMatchAction);
registerEditorAction(SelectHighlightsAction);
registerEditorAction(CompatChangeAll);
registerEditorAction(InsertCursorAtEndOfLineSelected);
registerEditorAction(InsertCursorAtTopOfLineSelected);
registerEditorAction(FocusNextCursor);
registerEditorAction(FocusPreviousCursor);
var __awaiter$u = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
const Context$1 = {
  Visible: new RawContextKey("parameterHintsVisible", false),
  MultipleSignatures: new RawContextKey("parameterHintsMultipleSignatures", false)
};
function provideSignatureHelp(registry, model, position, context, token) {
  return __awaiter$u(this, void 0, void 0, function* () {
    const supports = registry.ordered(model);
    for (const support of supports) {
      try {
        const result2 = yield support.provideSignatureHelp(model, position, token, context);
        if (result2) {
          return result2;
        }
      } catch (err) {
        onUnexpectedExternalError(err);
      }
    }
    return void 0;
  });
}
CommandsRegistry.registerCommand("_executeSignatureHelpProvider", (accessor, ...args) => __awaiter$u(void 0, void 0, void 0, function* () {
  const [uri, position, triggerCharacter] = args;
  assertType(URI.isUri(uri));
  assertType(Position$2.isIPosition(position));
  assertType(typeof triggerCharacter === "string" || !triggerCharacter);
  const languageFeaturesService = accessor.get(ILanguageFeaturesService);
  const ref2 = yield accessor.get(ITextModelService).createModelReference(uri);
  try {
    const result2 = yield provideSignatureHelp(languageFeaturesService.signatureHelpProvider, ref2.object.textEditorModel, Position$2.lift(position), {
      triggerKind: SignatureHelpTriggerKind$1.Invoke,
      isRetrigger: false,
      triggerCharacter
    }, CancellationToken.None);
    if (!result2) {
      return void 0;
    }
    setTimeout(() => result2.dispose(), 0);
    return result2.value;
  } finally {
    ref2.dispose();
  }
}));
var __awaiter$t = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var ParameterHintState;
(function(ParameterHintState2) {
  ParameterHintState2.Default = {
    type: 0
    /* Type.Default */
  };
  class Pending {
    constructor(request, previouslyActiveHints) {
      this.request = request;
      this.previouslyActiveHints = previouslyActiveHints;
      this.type = 2;
    }
  }
  ParameterHintState2.Pending = Pending;
  class Active {
    constructor(hints) {
      this.hints = hints;
      this.type = 1;
    }
  }
  ParameterHintState2.Active = Active;
})(ParameterHintState || (ParameterHintState = {}));
class ParameterHintsModel extends Disposable {
  constructor(editor2, providers, delay = ParameterHintsModel.DEFAULT_DELAY) {
    super();
    this._onChangedHints = this._register(new Emitter$1());
    this.onChangedHints = this._onChangedHints.event;
    this.triggerOnType = false;
    this._state = ParameterHintState.Default;
    this._pendingTriggers = [];
    this._lastSignatureHelpResult = this._register(new MutableDisposable());
    this.triggerChars = new CharacterSet();
    this.retriggerChars = new CharacterSet();
    this.triggerId = 0;
    this.editor = editor2;
    this.providers = providers;
    this.throttledDelayer = new Delayer(delay);
    this._register(this.editor.onDidBlurEditorWidget(() => this.cancel()));
    this._register(this.editor.onDidChangeConfiguration(() => this.onEditorConfigurationChange()));
    this._register(this.editor.onDidChangeModel((e) => this.onModelChanged()));
    this._register(this.editor.onDidChangeModelLanguage((_) => this.onModelChanged()));
    this._register(this.editor.onDidChangeCursorSelection((e) => this.onCursorChange(e)));
    this._register(this.editor.onDidChangeModelContent((e) => this.onModelContentChange()));
    this._register(this.providers.onDidChange(this.onModelChanged, this));
    this._register(this.editor.onDidType((text2) => this.onDidType(text2)));
    this.onEditorConfigurationChange();
    this.onModelChanged();
  }
  get state() {
    return this._state;
  }
  set state(value) {
    if (this._state.type === 2) {
      this._state.request.cancel();
    }
    this._state = value;
  }
  cancel(silent = false) {
    this.state = ParameterHintState.Default;
    this.throttledDelayer.cancel();
    if (!silent) {
      this._onChangedHints.fire(void 0);
    }
  }
  trigger(context, delay) {
    const model = this.editor.getModel();
    if (!model || !this.providers.has(model)) {
      return;
    }
    const triggerId = ++this.triggerId;
    this._pendingTriggers.push(context);
    this.throttledDelayer.trigger(() => {
      return this.doTrigger(triggerId);
    }, delay).catch(onUnexpectedError);
  }
  next() {
    if (this.state.type !== 1) {
      return;
    }
    const length2 = this.state.hints.signatures.length;
    const activeSignature = this.state.hints.activeSignature;
    const last2 = activeSignature % length2 === length2 - 1;
    const cycle = this.editor.getOption(
      84
      /* EditorOption.parameterHints */
    ).cycle;
    if ((length2 < 2 || last2) && !cycle) {
      this.cancel();
      return;
    }
    this.updateActiveSignature(last2 && cycle ? 0 : activeSignature + 1);
  }
  previous() {
    if (this.state.type !== 1) {
      return;
    }
    const length2 = this.state.hints.signatures.length;
    const activeSignature = this.state.hints.activeSignature;
    const first2 = activeSignature === 0;
    const cycle = this.editor.getOption(
      84
      /* EditorOption.parameterHints */
    ).cycle;
    if ((length2 < 2 || first2) && !cycle) {
      this.cancel();
      return;
    }
    this.updateActiveSignature(first2 && cycle ? length2 - 1 : activeSignature - 1);
  }
  updateActiveSignature(activeSignature) {
    if (this.state.type !== 1) {
      return;
    }
    this.state = new ParameterHintState.Active(Object.assign(Object.assign({}, this.state.hints), { activeSignature }));
    this._onChangedHints.fire(this.state.hints);
  }
  doTrigger(triggerId) {
    return __awaiter$t(this, void 0, void 0, function* () {
      const isRetrigger = this.state.type === 1 || this.state.type === 2;
      const activeSignatureHelp = this.getLastActiveHints();
      this.cancel(true);
      if (this._pendingTriggers.length === 0) {
        return false;
      }
      const context = this._pendingTriggers.reduce(mergeTriggerContexts);
      this._pendingTriggers = [];
      const triggerContext = {
        triggerKind: context.triggerKind,
        triggerCharacter: context.triggerCharacter,
        isRetrigger,
        activeSignatureHelp
      };
      if (!this.editor.hasModel()) {
        return false;
      }
      const model = this.editor.getModel();
      const position = this.editor.getPosition();
      this.state = new ParameterHintState.Pending(createCancelablePromise((token) => provideSignatureHelp(this.providers, model, position, triggerContext, token)), activeSignatureHelp);
      try {
        const result2 = yield this.state.request;
        if (triggerId !== this.triggerId) {
          result2 === null || result2 === void 0 ? void 0 : result2.dispose();
          return false;
        }
        if (!result2 || !result2.value.signatures || result2.value.signatures.length === 0) {
          result2 === null || result2 === void 0 ? void 0 : result2.dispose();
          this._lastSignatureHelpResult.clear();
          this.cancel();
          return false;
        } else {
          this.state = new ParameterHintState.Active(result2.value);
          this._lastSignatureHelpResult.value = result2;
          this._onChangedHints.fire(this.state.hints);
          return true;
        }
      } catch (error2) {
        if (triggerId === this.triggerId) {
          this.state = ParameterHintState.Default;
        }
        onUnexpectedError(error2);
        return false;
      }
    });
  }
  getLastActiveHints() {
    switch (this.state.type) {
      case 1:
        return this.state.hints;
      case 2:
        return this.state.previouslyActiveHints;
      default:
        return void 0;
    }
  }
  get isTriggered() {
    return this.state.type === 1 || this.state.type === 2 || this.throttledDelayer.isTriggered();
  }
  onModelChanged() {
    this.cancel();
    this.triggerChars.clear();
    this.retriggerChars.clear();
    const model = this.editor.getModel();
    if (!model) {
      return;
    }
    for (const support of this.providers.ordered(model)) {
      for (const ch of support.signatureHelpTriggerCharacters || []) {
        if (ch.length) {
          const charCode = ch.charCodeAt(0);
          this.triggerChars.add(charCode);
          this.retriggerChars.add(charCode);
        }
      }
      for (const ch of support.signatureHelpRetriggerCharacters || []) {
        if (ch.length) {
          this.retriggerChars.add(ch.charCodeAt(0));
        }
      }
    }
  }
  onDidType(text2) {
    if (!this.triggerOnType) {
      return;
    }
    const lastCharIndex = text2.length - 1;
    const triggerCharCode = text2.charCodeAt(lastCharIndex);
    if (this.triggerChars.has(triggerCharCode) || this.isTriggered && this.retriggerChars.has(triggerCharCode)) {
      this.trigger({
        triggerKind: SignatureHelpTriggerKind$1.TriggerCharacter,
        triggerCharacter: text2.charAt(lastCharIndex)
      });
    }
  }
  onCursorChange(e) {
    if (e.source === "mouse") {
      this.cancel();
    } else if (this.isTriggered) {
      this.trigger({ triggerKind: SignatureHelpTriggerKind$1.ContentChange });
    }
  }
  onModelContentChange() {
    if (this.isTriggered) {
      this.trigger({ triggerKind: SignatureHelpTriggerKind$1.ContentChange });
    }
  }
  onEditorConfigurationChange() {
    this.triggerOnType = this.editor.getOption(
      84
      /* EditorOption.parameterHints */
    ).enabled;
    if (!this.triggerOnType) {
      this.cancel();
    }
  }
  dispose() {
    this.cancel(true);
    super.dispose();
  }
}
ParameterHintsModel.DEFAULT_DELAY = 120;
function mergeTriggerContexts(previous, current) {
  switch (current.triggerKind) {
    case SignatureHelpTriggerKind$1.Invoke:
      return current;
    case SignatureHelpTriggerKind$1.ContentChange:
      return previous;
    case SignatureHelpTriggerKind$1.TriggerCharacter:
    default:
      return current;
  }
}
const parameterHints = "";
var __decorate$P = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$N = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
const $$3 = $$d;
const parameterHintsNextIcon = registerIcon("parameter-hints-next", Codicon.chevronDown, localize("parameterHintsNextIcon", "Icon for show next parameter hint."));
const parameterHintsPreviousIcon = registerIcon("parameter-hints-previous", Codicon.chevronUp, localize("parameterHintsPreviousIcon", "Icon for show previous parameter hint."));
let ParameterHintsWidget = class ParameterHintsWidget2 extends Disposable {
  constructor(editor2, model, contextKeyService, openerService, languageService) {
    super();
    this.editor = editor2;
    this.model = model;
    this.renderDisposeables = this._register(new DisposableStore());
    this.visible = false;
    this.announcedLabel = null;
    this.allowEditorOverflow = true;
    this.markdownRenderer = this._register(new MarkdownRenderer({ editor: editor2 }, languageService, openerService));
    this.keyVisible = Context$1.Visible.bindTo(contextKeyService);
    this.keyMultipleSignatures = Context$1.MultipleSignatures.bindTo(contextKeyService);
  }
  createParameterHintDOMNodes() {
    const element = $$3(".editor-widget.parameter-hints-widget");
    const wrapper = append$1(element, $$3(".phwrapper"));
    wrapper.tabIndex = -1;
    const controls = append$1(wrapper, $$3(".controls"));
    const previous = append$1(controls, $$3(".button" + ThemeIcon.asCSSSelector(parameterHintsPreviousIcon)));
    const overloads = append$1(controls, $$3(".overloads"));
    const next = append$1(controls, $$3(".button" + ThemeIcon.asCSSSelector(parameterHintsNextIcon)));
    this._register(addDisposableListener(previous, "click", (e) => {
      EventHelper.stop(e);
      this.previous();
    }));
    this._register(addDisposableListener(next, "click", (e) => {
      EventHelper.stop(e);
      this.next();
    }));
    const body = $$3(".body");
    const scrollbar = new DomScrollableElement(body, {
      alwaysConsumeMouseWheel: true
    });
    this._register(scrollbar);
    wrapper.appendChild(scrollbar.getDomNode());
    const signature = append$1(body, $$3(".signature"));
    const docs = append$1(body, $$3(".docs"));
    element.style.userSelect = "text";
    this.domNodes = {
      element,
      signature,
      overloads,
      docs,
      scrollbar
    };
    this.editor.addContentWidget(this);
    this.hide();
    this._register(this.editor.onDidChangeCursorSelection((e) => {
      if (this.visible) {
        this.editor.layoutContentWidget(this);
      }
    }));
    const updateFont = () => {
      if (!this.domNodes) {
        return;
      }
      const fontInfo = this.editor.getOption(
        49
        /* EditorOption.fontInfo */
      );
      this.domNodes.element.style.fontSize = `${fontInfo.fontSize}px`;
      this.domNodes.element.style.lineHeight = `${fontInfo.lineHeight / fontInfo.fontSize}`;
    };
    updateFont();
    this._register(Event$1.chain(this.editor.onDidChangeConfiguration.bind(this.editor)).filter((e) => e.hasChanged(
      49
      /* EditorOption.fontInfo */
    )).on(updateFont, null));
    this._register(this.editor.onDidLayoutChange((e) => this.updateMaxHeight()));
    this.updateMaxHeight();
  }
  show() {
    if (this.visible) {
      return;
    }
    if (!this.domNodes) {
      this.createParameterHintDOMNodes();
    }
    this.keyVisible.set(true);
    this.visible = true;
    setTimeout(() => {
      var _a2;
      (_a2 = this.domNodes) === null || _a2 === void 0 ? void 0 : _a2.element.classList.add("visible");
    }, 100);
    this.editor.layoutContentWidget(this);
  }
  hide() {
    var _a2;
    this.renderDisposeables.clear();
    if (!this.visible) {
      return;
    }
    this.keyVisible.reset();
    this.visible = false;
    this.announcedLabel = null;
    (_a2 = this.domNodes) === null || _a2 === void 0 ? void 0 : _a2.element.classList.remove("visible");
    this.editor.layoutContentWidget(this);
  }
  getPosition() {
    if (this.visible) {
      return {
        position: this.editor.getPosition(),
        preference: [
          1,
          2
          /* ContentWidgetPositionPreference.BELOW */
        ]
      };
    }
    return null;
  }
  render(hints) {
    var _a2;
    this.renderDisposeables.clear();
    if (!this.domNodes) {
      return;
    }
    const multiple = hints.signatures.length > 1;
    this.domNodes.element.classList.toggle("multiple", multiple);
    this.keyMultipleSignatures.set(multiple);
    this.domNodes.signature.innerText = "";
    this.domNodes.docs.innerText = "";
    const signature = hints.signatures[hints.activeSignature];
    if (!signature) {
      return;
    }
    const code = append$1(this.domNodes.signature, $$3(".code"));
    const fontInfo = this.editor.getOption(
      49
      /* EditorOption.fontInfo */
    );
    code.style.fontSize = `${fontInfo.fontSize}px`;
    code.style.fontFamily = fontInfo.fontFamily;
    const hasParameters = signature.parameters.length > 0;
    const activeParameterIndex = (_a2 = signature.activeParameter) !== null && _a2 !== void 0 ? _a2 : hints.activeParameter;
    if (!hasParameters) {
      const label = append$1(code, $$3("span"));
      label.textContent = signature.label;
    } else {
      this.renderParameters(code, signature, activeParameterIndex);
    }
    const activeParameter = signature.parameters[activeParameterIndex];
    if (activeParameter === null || activeParameter === void 0 ? void 0 : activeParameter.documentation) {
      const documentation = $$3("span.documentation");
      if (typeof activeParameter.documentation === "string") {
        documentation.textContent = activeParameter.documentation;
      } else {
        const renderedContents = this.renderMarkdownDocs(activeParameter.documentation);
        documentation.appendChild(renderedContents.element);
      }
      append$1(this.domNodes.docs, $$3("p", {}, documentation));
    }
    if (signature.documentation === void 0)
      ;
    else if (typeof signature.documentation === "string") {
      append$1(this.domNodes.docs, $$3("p", {}, signature.documentation));
    } else {
      const renderedContents = this.renderMarkdownDocs(signature.documentation);
      append$1(this.domNodes.docs, renderedContents.element);
    }
    const hasDocs = this.hasDocs(signature, activeParameter);
    this.domNodes.signature.classList.toggle("has-docs", hasDocs);
    this.domNodes.docs.classList.toggle("empty", !hasDocs);
    this.domNodes.overloads.textContent = String(hints.activeSignature + 1).padStart(hints.signatures.length.toString().length, "0") + "/" + hints.signatures.length;
    if (activeParameter) {
      let labelToAnnounce = "";
      const param = signature.parameters[activeParameterIndex];
      if (Array.isArray(param.label)) {
        labelToAnnounce = signature.label.substring(param.label[0], param.label[1]);
      } else {
        labelToAnnounce = param.label;
      }
      if (param.documentation) {
        labelToAnnounce += typeof param.documentation === "string" ? `, ${param.documentation}` : `, ${param.documentation.value}`;
      }
      if (signature.documentation) {
        labelToAnnounce += typeof signature.documentation === "string" ? `, ${signature.documentation}` : `, ${signature.documentation.value}`;
      }
      if (this.announcedLabel !== labelToAnnounce) {
        alert(localize("hint", "{0}, hint", labelToAnnounce));
        this.announcedLabel = labelToAnnounce;
      }
    }
    this.editor.layoutContentWidget(this);
    this.domNodes.scrollbar.scanDomNode();
  }
  renderMarkdownDocs(markdown) {
    const renderedContents = this.renderDisposeables.add(this.markdownRenderer.render(markdown, {
      asyncRenderCallback: () => {
        var _a2;
        (_a2 = this.domNodes) === null || _a2 === void 0 ? void 0 : _a2.scrollbar.scanDomNode();
      }
    }));
    renderedContents.element.classList.add("markdown-docs");
    return renderedContents;
  }
  hasDocs(signature, activeParameter) {
    if (activeParameter && typeof activeParameter.documentation === "string" && assertIsDefined(activeParameter.documentation).length > 0) {
      return true;
    }
    if (activeParameter && typeof activeParameter.documentation === "object" && assertIsDefined(activeParameter.documentation).value.length > 0) {
      return true;
    }
    if (signature.documentation && typeof signature.documentation === "string" && assertIsDefined(signature.documentation).length > 0) {
      return true;
    }
    if (signature.documentation && typeof signature.documentation === "object" && assertIsDefined(signature.documentation.value).length > 0) {
      return true;
    }
    return false;
  }
  renderParameters(parent, signature, activeParameterIndex) {
    const [start, end] = this.getParameterLabelOffsets(signature, activeParameterIndex);
    const beforeSpan = document.createElement("span");
    beforeSpan.textContent = signature.label.substring(0, start);
    const paramSpan = document.createElement("span");
    paramSpan.textContent = signature.label.substring(start, end);
    paramSpan.className = "parameter active";
    const afterSpan = document.createElement("span");
    afterSpan.textContent = signature.label.substring(end);
    append$1(parent, beforeSpan, paramSpan, afterSpan);
  }
  getParameterLabelOffsets(signature, paramIdx) {
    const param = signature.parameters[paramIdx];
    if (!param) {
      return [0, 0];
    } else if (Array.isArray(param.label)) {
      return param.label;
    } else if (!param.label.length) {
      return [0, 0];
    } else {
      const regex = new RegExp(`(\\W|^)${escapeRegExpCharacters(param.label)}(?=\\W|$)`, "g");
      regex.test(signature.label);
      const idx = regex.lastIndex - param.label.length;
      return idx >= 0 ? [idx, regex.lastIndex] : [0, 0];
    }
  }
  next() {
    this.editor.focus();
    this.model.next();
  }
  previous() {
    this.editor.focus();
    this.model.previous();
  }
  getDomNode() {
    if (!this.domNodes) {
      this.createParameterHintDOMNodes();
    }
    return this.domNodes.element;
  }
  getId() {
    return ParameterHintsWidget2.ID;
  }
  updateMaxHeight() {
    if (!this.domNodes) {
      return;
    }
    const height = Math.max(this.editor.getLayoutInfo().height / 4, 250);
    const maxHeight = `${height}px`;
    this.domNodes.element.style.maxHeight = maxHeight;
    const wrapper = this.domNodes.element.getElementsByClassName("phwrapper");
    if (wrapper.length) {
      wrapper[0].style.maxHeight = maxHeight;
    }
  }
};
ParameterHintsWidget.ID = "editor.widget.parameterHintsWidget";
ParameterHintsWidget = __decorate$P([
  __param$N(2, IContextKeyService),
  __param$N(3, IOpenerService),
  __param$N(4, ILanguageService)
], ParameterHintsWidget);
registerColor("editorHoverWidget.highlightForeground", { dark: listHighlightForeground, light: listHighlightForeground, hcDark: listHighlightForeground, hcLight: listHighlightForeground }, localize("editorHoverWidgetHighlightForeground", "Foreground color of the active item in the parameter hint."));
var __decorate$O = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$M = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let ParameterHintsController = class ParameterHintsController2 extends Disposable {
  static get(editor2) {
    return editor2.getContribution(ParameterHintsController2.ID);
  }
  constructor(editor2, instantiationService, languageFeaturesService) {
    super();
    this.editor = editor2;
    this.model = this._register(new ParameterHintsModel(editor2, languageFeaturesService.signatureHelpProvider));
    this._register(this.model.onChangedHints((newParameterHints) => {
      var _a2;
      if (newParameterHints) {
        this.widget.value.show();
        this.widget.value.render(newParameterHints);
      } else {
        (_a2 = this.widget.rawValue) === null || _a2 === void 0 ? void 0 : _a2.hide();
      }
    }));
    this.widget = new Lazy(() => this._register(instantiationService.createInstance(ParameterHintsWidget, this.editor, this.model)));
  }
  cancel() {
    this.model.cancel();
  }
  previous() {
    var _a2;
    (_a2 = this.widget.rawValue) === null || _a2 === void 0 ? void 0 : _a2.previous();
  }
  next() {
    var _a2;
    (_a2 = this.widget.rawValue) === null || _a2 === void 0 ? void 0 : _a2.next();
  }
  trigger(context) {
    this.model.trigger(context, 0);
  }
};
ParameterHintsController.ID = "editor.controller.parameterHints";
ParameterHintsController = __decorate$O([
  __param$M(1, IInstantiationService),
  __param$M(2, ILanguageFeaturesService)
], ParameterHintsController);
class TriggerParameterHintsAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.triggerParameterHints",
      label: localize("parameterHints.trigger.label", "Trigger Parameter Hints"),
      alias: "Trigger Parameter Hints",
      precondition: EditorContextKeys.hasSignatureHelpProvider,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 2048 | 1024 | 10,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor2) {
    const controller = ParameterHintsController.get(editor2);
    controller === null || controller === void 0 ? void 0 : controller.trigger({
      triggerKind: SignatureHelpTriggerKind$1.Invoke
    });
  }
}
registerEditorContribution(
  ParameterHintsController.ID,
  ParameterHintsController,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);
registerEditorAction(TriggerParameterHintsAction);
const weight$1 = 100 + 75;
const ParameterHintsCommand = EditorCommand.bindToContribution(ParameterHintsController.get);
registerEditorCommand(new ParameterHintsCommand({
  id: "closeParameterHints",
  precondition: Context$1.Visible,
  handler: (x) => x.cancel(),
  kbOpts: {
    weight: weight$1,
    kbExpr: EditorContextKeys.focus,
    primary: 9,
    secondary: [
      1024 | 9
      /* KeyCode.Escape */
    ]
  }
}));
registerEditorCommand(new ParameterHintsCommand({
  id: "showPrevParameterHint",
  precondition: ContextKeyExpr.and(Context$1.Visible, Context$1.MultipleSignatures),
  handler: (x) => x.previous(),
  kbOpts: {
    weight: weight$1,
    kbExpr: EditorContextKeys.focus,
    primary: 16,
    secondary: [
      512 | 16
      /* KeyCode.UpArrow */
    ],
    mac: { primary: 16, secondary: [
      512 | 16,
      256 | 46
      /* KeyCode.KeyP */
    ] }
  }
}));
registerEditorCommand(new ParameterHintsCommand({
  id: "showNextParameterHint",
  precondition: ContextKeyExpr.and(Context$1.Visible, Context$1.MultipleSignatures),
  handler: (x) => x.next(),
  kbOpts: {
    weight: weight$1,
    kbExpr: EditorContextKeys.focus,
    primary: 18,
    secondary: [
      512 | 18
      /* KeyCode.DownArrow */
    ],
    mac: { primary: 18, secondary: [
      512 | 18,
      256 | 44
      /* KeyCode.KeyN */
    ] }
  }
}));
const renameInputField = "";
var __decorate$N = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$L = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
const CONTEXT_RENAME_INPUT_VISIBLE = new RawContextKey("renameInputVisible", false, localize("renameInputVisible", "Whether the rename input widget is visible"));
let RenameInputField = class RenameInputField2 {
  constructor(_editor, _acceptKeybindings, _themeService, _keybindingService, contextKeyService) {
    this._editor = _editor;
    this._acceptKeybindings = _acceptKeybindings;
    this._themeService = _themeService;
    this._keybindingService = _keybindingService;
    this._disposables = new DisposableStore();
    this.allowEditorOverflow = true;
    this._visibleContextKey = CONTEXT_RENAME_INPUT_VISIBLE.bindTo(contextKeyService);
    this._editor.addContentWidget(this);
    this._disposables.add(this._editor.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        49
        /* EditorOption.fontInfo */
      )) {
        this._updateFont();
      }
    }));
    this._disposables.add(_themeService.onDidColorThemeChange(this._updateStyles, this));
  }
  dispose() {
    this._disposables.dispose();
    this._editor.removeContentWidget(this);
  }
  getId() {
    return "__renameInputWidget";
  }
  getDomNode() {
    if (!this._domNode) {
      this._domNode = document.createElement("div");
      this._domNode.className = "monaco-editor rename-box";
      this._input = document.createElement("input");
      this._input.className = "rename-input";
      this._input.type = "text";
      this._input.setAttribute("aria-label", localize("renameAriaLabel", "Rename input. Type new name and press Enter to commit."));
      this._domNode.appendChild(this._input);
      this._label = document.createElement("div");
      this._label.className = "rename-label";
      this._domNode.appendChild(this._label);
      this._updateFont();
      this._updateStyles(this._themeService.getColorTheme());
    }
    return this._domNode;
  }
  _updateStyles(theme) {
    var _a2, _b2, _c2, _d2;
    if (!this._input || !this._domNode) {
      return;
    }
    const widgetShadowColor = theme.getColor(widgetShadow);
    const widgetBorderColor = theme.getColor(widgetBorder);
    this._domNode.style.backgroundColor = String((_a2 = theme.getColor(editorWidgetBackground)) !== null && _a2 !== void 0 ? _a2 : "");
    this._domNode.style.boxShadow = widgetShadowColor ? ` 0 0 8px 2px ${widgetShadowColor}` : "";
    this._domNode.style.border = widgetBorderColor ? `1px solid ${widgetBorderColor}` : "";
    this._domNode.style.color = String((_b2 = theme.getColor(inputForeground)) !== null && _b2 !== void 0 ? _b2 : "");
    this._input.style.backgroundColor = String((_c2 = theme.getColor(inputBackground)) !== null && _c2 !== void 0 ? _c2 : "");
    const border = theme.getColor(inputBorder);
    this._input.style.borderWidth = border ? "1px" : "0px";
    this._input.style.borderStyle = border ? "solid" : "none";
    this._input.style.borderColor = (_d2 = border === null || border === void 0 ? void 0 : border.toString()) !== null && _d2 !== void 0 ? _d2 : "none";
  }
  _updateFont() {
    if (!this._input || !this._label) {
      return;
    }
    const fontInfo = this._editor.getOption(
      49
      /* EditorOption.fontInfo */
    );
    this._input.style.fontFamily = fontInfo.fontFamily;
    this._input.style.fontWeight = fontInfo.fontWeight;
    this._input.style.fontSize = `${fontInfo.fontSize}px`;
    this._label.style.fontSize = `${fontInfo.fontSize * 0.8}px`;
  }
  getPosition() {
    if (!this._visible) {
      return null;
    }
    return {
      position: this._position,
      preference: [
        2,
        1
        /* ContentWidgetPositionPreference.ABOVE */
      ]
    };
  }
  beforeRender() {
    var _a2, _b2;
    const [accept, preview] = this._acceptKeybindings;
    this._label.innerText = localize({ key: "label", comment: ['placeholders are keybindings, e.g "F2 to Rename, Shift+F2 to Preview"'] }, "{0} to Rename, {1} to Preview", (_a2 = this._keybindingService.lookupKeybinding(accept)) === null || _a2 === void 0 ? void 0 : _a2.getLabel(), (_b2 = this._keybindingService.lookupKeybinding(preview)) === null || _b2 === void 0 ? void 0 : _b2.getLabel());
    return null;
  }
  afterRender(position) {
    if (!position) {
      this.cancelInput(true);
    }
  }
  acceptInput(wantsPreview) {
    var _a2;
    (_a2 = this._currentAcceptInput) === null || _a2 === void 0 ? void 0 : _a2.call(this, wantsPreview);
  }
  cancelInput(focusEditor) {
    var _a2;
    (_a2 = this._currentCancelInput) === null || _a2 === void 0 ? void 0 : _a2.call(this, focusEditor);
  }
  getInput(where, value, selectionStart, selectionEnd, supportPreview, token) {
    this._domNode.classList.toggle("preview", supportPreview);
    this._position = new Position$2(where.startLineNumber, where.startColumn);
    this._input.value = value;
    this._input.setAttribute("selectionStart", selectionStart.toString());
    this._input.setAttribute("selectionEnd", selectionEnd.toString());
    this._input.size = Math.max((where.endColumn - where.startColumn) * 1.1, 20);
    const disposeOnDone = new DisposableStore();
    return new Promise((resolve2) => {
      this._currentCancelInput = (focusEditor) => {
        this._currentAcceptInput = void 0;
        this._currentCancelInput = void 0;
        resolve2(focusEditor);
        return true;
      };
      this._currentAcceptInput = (wantsPreview) => {
        if (this._input.value.trim().length === 0 || this._input.value === value) {
          this.cancelInput(true);
          return;
        }
        this._currentAcceptInput = void 0;
        this._currentCancelInput = void 0;
        resolve2({
          newName: this._input.value,
          wantsPreview: supportPreview && wantsPreview
        });
      };
      disposeOnDone.add(token.onCancellationRequested(() => this.cancelInput(true)));
      disposeOnDone.add(this._editor.onDidBlurEditorWidget(() => this.cancelInput(!document.hasFocus())));
      this._show();
    }).finally(() => {
      disposeOnDone.dispose();
      this._hide();
    });
  }
  _show() {
    this._editor.revealLineInCenterIfOutsideViewport(
      this._position.lineNumber,
      0
      /* ScrollType.Smooth */
    );
    this._visible = true;
    this._visibleContextKey.set(true);
    this._editor.layoutContentWidget(this);
    setTimeout(() => {
      this._input.focus();
      this._input.setSelectionRange(parseInt(this._input.getAttribute("selectionStart")), parseInt(this._input.getAttribute("selectionEnd")));
    }, 100);
  }
  _hide() {
    this._visible = false;
    this._visibleContextKey.reset();
    this._editor.layoutContentWidget(this);
  }
};
RenameInputField = __decorate$N([
  __param$L(2, IThemeService),
  __param$L(3, IKeybindingService),
  __param$L(4, IContextKeyService)
], RenameInputField);
var __decorate$M = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$K = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$s = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class RenameSkeleton {
  constructor(model, position, registry) {
    this.model = model;
    this.position = position;
    this._providerRenameIdx = 0;
    this._providers = registry.ordered(model);
  }
  hasProvider() {
    return this._providers.length > 0;
  }
  resolveRenameLocation(token) {
    return __awaiter$s(this, void 0, void 0, function* () {
      const rejects = [];
      for (this._providerRenameIdx = 0; this._providerRenameIdx < this._providers.length; this._providerRenameIdx++) {
        const provider = this._providers[this._providerRenameIdx];
        if (!provider.resolveRenameLocation) {
          break;
        }
        const res = yield provider.resolveRenameLocation(this.model, this.position, token);
        if (!res) {
          continue;
        }
        if (res.rejectReason) {
          rejects.push(res.rejectReason);
          continue;
        }
        return res;
      }
      const word2 = this.model.getWordAtPosition(this.position);
      if (!word2) {
        return {
          range: Range$2.fromPositions(this.position),
          text: "",
          rejectReason: rejects.length > 0 ? rejects.join("\n") : void 0
        };
      }
      return {
        range: new Range$2(this.position.lineNumber, word2.startColumn, this.position.lineNumber, word2.endColumn),
        text: word2.word,
        rejectReason: rejects.length > 0 ? rejects.join("\n") : void 0
      };
    });
  }
  provideRenameEdits(newName, token) {
    return __awaiter$s(this, void 0, void 0, function* () {
      return this._provideRenameEdits(newName, this._providerRenameIdx, [], token);
    });
  }
  _provideRenameEdits(newName, i, rejects, token) {
    return __awaiter$s(this, void 0, void 0, function* () {
      const provider = this._providers[i];
      if (!provider) {
        return {
          edits: [],
          rejectReason: rejects.join("\n")
        };
      }
      const result2 = yield provider.provideRenameEdits(this.model, this.position, newName, token);
      if (!result2) {
        return this._provideRenameEdits(newName, i + 1, rejects.concat(localize("no result", "No result.")), token);
      } else if (result2.rejectReason) {
        return this._provideRenameEdits(newName, i + 1, rejects.concat(result2.rejectReason), token);
      }
      return result2;
    });
  }
}
function rename(registry, model, position, newName) {
  return __awaiter$s(this, void 0, void 0, function* () {
    const skeleton = new RenameSkeleton(model, position, registry);
    const loc = yield skeleton.resolveRenameLocation(CancellationToken.None);
    if (loc === null || loc === void 0 ? void 0 : loc.rejectReason) {
      return { edits: [], rejectReason: loc.rejectReason };
    }
    return skeleton.provideRenameEdits(newName, CancellationToken.None);
  });
}
let RenameController = class RenameController2 {
  static get(editor2) {
    return editor2.getContribution(RenameController2.ID);
  }
  constructor(editor2, _instaService, _notificationService, _bulkEditService, _progressService, _logService, _configService, _languageFeaturesService) {
    this.editor = editor2;
    this._instaService = _instaService;
    this._notificationService = _notificationService;
    this._bulkEditService = _bulkEditService;
    this._progressService = _progressService;
    this._logService = _logService;
    this._configService = _configService;
    this._languageFeaturesService = _languageFeaturesService;
    this._disposableStore = new DisposableStore();
    this._cts = new CancellationTokenSource$1();
    this._renameInputField = this._disposableStore.add(this._instaService.createInstance(RenameInputField, this.editor, ["acceptRenameInput", "acceptRenameInputWithPreview"]));
  }
  dispose() {
    this._disposableStore.dispose();
    this._cts.dispose(true);
  }
  run() {
    var _a2, _b2;
    return __awaiter$s(this, void 0, void 0, function* () {
      this._cts.dispose(true);
      this._cts = new CancellationTokenSource$1();
      if (!this.editor.hasModel()) {
        return void 0;
      }
      const position = this.editor.getPosition();
      const skeleton = new RenameSkeleton(this.editor.getModel(), position, this._languageFeaturesService.renameProvider);
      if (!skeleton.hasProvider()) {
        return void 0;
      }
      const cts1 = new EditorStateCancellationTokenSource(this.editor, 4 | 1, void 0, this._cts.token);
      let loc;
      try {
        const resolveLocationOperation = skeleton.resolveRenameLocation(cts1.token);
        this._progressService.showWhile(resolveLocationOperation, 250);
        loc = yield resolveLocationOperation;
      } catch (e) {
        (_a2 = MessageController.get(this.editor)) === null || _a2 === void 0 ? void 0 : _a2.showMessage(e || localize("resolveRenameLocationFailed", "An unknown error occurred while resolving rename location"), position);
        return void 0;
      } finally {
        cts1.dispose();
      }
      if (!loc) {
        return void 0;
      }
      if (loc.rejectReason) {
        (_b2 = MessageController.get(this.editor)) === null || _b2 === void 0 ? void 0 : _b2.showMessage(loc.rejectReason, position);
        return void 0;
      }
      if (cts1.token.isCancellationRequested) {
        return void 0;
      }
      const cts2 = new EditorStateCancellationTokenSource(this.editor, 4 | 1, loc.range, this._cts.token);
      const selection = this.editor.getSelection();
      let selectionStart = 0;
      let selectionEnd = loc.text.length;
      if (!Range$2.isEmpty(selection) && !Range$2.spansMultipleLines(selection) && Range$2.containsRange(loc.range, selection)) {
        selectionStart = Math.max(0, selection.startColumn - loc.range.startColumn);
        selectionEnd = Math.min(loc.range.endColumn, selection.endColumn) - loc.range.startColumn;
      }
      const supportPreview = this._bulkEditService.hasPreviewHandler() && this._configService.getValue(this.editor.getModel().uri, "editor.rename.enablePreview");
      const inputFieldResult = yield this._renameInputField.getInput(loc.range, loc.text, selectionStart, selectionEnd, supportPreview, cts2.token);
      if (typeof inputFieldResult === "boolean") {
        if (inputFieldResult) {
          this.editor.focus();
        }
        cts2.dispose();
        return void 0;
      }
      this.editor.focus();
      const renameOperation = raceCancellation(skeleton.provideRenameEdits(inputFieldResult.newName, cts2.token), cts2.token).then((renameResult) => __awaiter$s(this, void 0, void 0, function* () {
        if (!renameResult || !this.editor.hasModel()) {
          return;
        }
        if (renameResult.rejectReason) {
          this._notificationService.info(renameResult.rejectReason);
          return;
        }
        this.editor.setSelection(Range$2.fromPositions(this.editor.getSelection().getPosition()));
        this._bulkEditService.apply(renameResult, {
          editor: this.editor,
          showPreview: inputFieldResult.wantsPreview,
          label: localize("label", "Renaming '{0}' to '{1}'", loc === null || loc === void 0 ? void 0 : loc.text, inputFieldResult.newName),
          code: "undoredo.rename",
          quotableLabel: localize("quotableLabel", "Renaming {0} to {1}", loc === null || loc === void 0 ? void 0 : loc.text, inputFieldResult.newName),
          respectAutoSaveConfig: true
        }).then((result2) => {
          if (result2.ariaSummary) {
            alert(localize("aria", "Successfully renamed '{0}' to '{1}'. Summary: {2}", loc.text, inputFieldResult.newName, result2.ariaSummary));
          }
        }).catch((err) => {
          this._notificationService.error(localize("rename.failedApply", "Rename failed to apply edits"));
          this._logService.error(err);
        });
      }), (err) => {
        this._notificationService.error(localize("rename.failed", "Rename failed to compute edits"));
        this._logService.error(err);
      }).finally(() => {
        cts2.dispose();
      });
      this._progressService.showWhile(renameOperation, 250);
      return renameOperation;
    });
  }
  acceptRenameInput(wantsPreview) {
    this._renameInputField.acceptInput(wantsPreview);
  }
  cancelRenameInput() {
    this._renameInputField.cancelInput(true);
  }
};
RenameController.ID = "editor.contrib.renameController";
RenameController = __decorate$M([
  __param$K(1, IInstantiationService),
  __param$K(2, INotificationService),
  __param$K(3, IBulkEditService),
  __param$K(4, IEditorProgressService),
  __param$K(5, ILogService),
  __param$K(6, ITextResourceConfigurationService),
  __param$K(7, ILanguageFeaturesService)
], RenameController);
class RenameAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.rename",
      label: localize("rename.label", "Rename Symbol"),
      alias: "Rename Symbol",
      precondition: ContextKeyExpr.and(EditorContextKeys.writable, EditorContextKeys.hasRenameProvider),
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 60,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      contextMenuOpts: {
        group: "1_modification",
        order: 1.1
      }
    });
  }
  runCommand(accessor, args) {
    const editorService = accessor.get(ICodeEditorService);
    const [uri, pos] = Array.isArray(args) && args || [void 0, void 0];
    if (URI.isUri(uri) && Position$2.isIPosition(pos)) {
      return editorService.openCodeEditor({ resource: uri }, editorService.getActiveCodeEditor()).then((editor2) => {
        if (!editor2) {
          return;
        }
        editor2.setPosition(pos);
        editor2.invokeWithinContext((accessor2) => {
          this.reportTelemetry(accessor2, editor2);
          return this.run(accessor2, editor2);
        });
      }, onUnexpectedError);
    }
    return super.runCommand(accessor, args);
  }
  run(accessor, editor2) {
    const controller = RenameController.get(editor2);
    if (controller) {
      return controller.run();
    }
    return Promise.resolve();
  }
}
registerEditorContribution(
  RenameController.ID,
  RenameController,
  4
  /* EditorContributionInstantiation.Lazy */
);
registerEditorAction(RenameAction);
const RenameCommand = EditorCommand.bindToContribution(RenameController.get);
registerEditorCommand(new RenameCommand({
  id: "acceptRenameInput",
  precondition: CONTEXT_RENAME_INPUT_VISIBLE,
  handler: (x) => x.acceptRenameInput(false),
  kbOpts: {
    weight: 100 + 99,
    kbExpr: ContextKeyExpr.and(EditorContextKeys.focus, ContextKeyExpr.not("isComposing")),
    primary: 3
    /* KeyCode.Enter */
  }
}));
registerEditorCommand(new RenameCommand({
  id: "acceptRenameInputWithPreview",
  precondition: ContextKeyExpr.and(CONTEXT_RENAME_INPUT_VISIBLE, ContextKeyExpr.has("config.editor.rename.enablePreview")),
  handler: (x) => x.acceptRenameInput(true),
  kbOpts: {
    weight: 100 + 99,
    kbExpr: ContextKeyExpr.and(EditorContextKeys.focus, ContextKeyExpr.not("isComposing")),
    primary: 1024 + 3
    /* KeyCode.Enter */
  }
}));
registerEditorCommand(new RenameCommand({
  id: "cancelRenameInput",
  precondition: CONTEXT_RENAME_INPUT_VISIBLE,
  handler: (x) => x.cancelRenameInput(),
  kbOpts: {
    weight: 100 + 99,
    kbExpr: EditorContextKeys.focus,
    primary: 9,
    secondary: [
      1024 | 9
      /* KeyCode.Escape */
    ]
  }
}));
registerModelAndPositionCommand("_executeDocumentRenameProvider", function(accessor, model, position, ...args) {
  const [newName] = args;
  assertType(typeof newName === "string");
  const { renameProvider } = accessor.get(ILanguageFeaturesService);
  return rename(renameProvider, model, position, newName);
});
registerModelAndPositionCommand("_executePrepareRename", function(accessor, model, position) {
  return __awaiter$s(this, void 0, void 0, function* () {
    const { renameProvider } = accessor.get(ILanguageFeaturesService);
    const skeleton = new RenameSkeleton(model, position, renameProvider);
    const loc = yield skeleton.resolveRenameLocation(CancellationToken.None);
    if (loc === null || loc === void 0 ? void 0 : loc.rejectReason) {
      throw new Error(loc.rejectReason);
    }
    return loc;
  });
});
Registry.as(Extensions$6.Configuration).registerConfiguration({
  id: "editor",
  properties: {
    "editor.rename.enablePreview": {
      scope: 5,
      description: localize("enablePreview", "Enable/disable the ability to preview changes before renaming"),
      default: true,
      type: "boolean"
    }
  }
});
class SparseMultilineTokens {
  static create(startLineNumber, tokens) {
    return new SparseMultilineTokens(startLineNumber, new SparseMultilineTokensStorage(tokens));
  }
  /**
   * (Inclusive) start line number for these tokens.
   */
  get startLineNumber() {
    return this._startLineNumber;
  }
  /**
   * (Inclusive) end line number for these tokens.
   */
  get endLineNumber() {
    return this._endLineNumber;
  }
  constructor(startLineNumber, tokens) {
    this._startLineNumber = startLineNumber;
    this._tokens = tokens;
    this._endLineNumber = this._startLineNumber + this._tokens.getMaxDeltaLine();
  }
  toString() {
    return this._tokens.toString(this._startLineNumber);
  }
  _updateEndLineNumber() {
    this._endLineNumber = this._startLineNumber + this._tokens.getMaxDeltaLine();
  }
  isEmpty() {
    return this._tokens.isEmpty();
  }
  getLineTokens(lineNumber) {
    if (this._startLineNumber <= lineNumber && lineNumber <= this._endLineNumber) {
      return this._tokens.getLineTokens(lineNumber - this._startLineNumber);
    }
    return null;
  }
  getRange() {
    const deltaRange = this._tokens.getRange();
    if (!deltaRange) {
      return deltaRange;
    }
    return new Range$2(this._startLineNumber + deltaRange.startLineNumber, deltaRange.startColumn, this._startLineNumber + deltaRange.endLineNumber, deltaRange.endColumn);
  }
  removeTokens(range2) {
    const startLineIndex = range2.startLineNumber - this._startLineNumber;
    const endLineIndex = range2.endLineNumber - this._startLineNumber;
    this._startLineNumber += this._tokens.removeTokens(startLineIndex, range2.startColumn - 1, endLineIndex, range2.endColumn - 1);
    this._updateEndLineNumber();
  }
  split(range2) {
    const startLineIndex = range2.startLineNumber - this._startLineNumber;
    const endLineIndex = range2.endLineNumber - this._startLineNumber;
    const [a, b, bDeltaLine] = this._tokens.split(startLineIndex, range2.startColumn - 1, endLineIndex, range2.endColumn - 1);
    return [new SparseMultilineTokens(this._startLineNumber, a), new SparseMultilineTokens(this._startLineNumber + bDeltaLine, b)];
  }
  applyEdit(range2, text2) {
    const [eolCount, firstLineLength, lastLineLength2] = countEOL(text2);
    this.acceptEdit(
      range2,
      eolCount,
      firstLineLength,
      lastLineLength2,
      text2.length > 0 ? text2.charCodeAt(0) : 0
      /* CharCode.Null */
    );
  }
  acceptEdit(range2, eolCount, firstLineLength, lastLineLength2, firstCharCode) {
    this._acceptDeleteRange(range2);
    this._acceptInsertText(new Position$2(range2.startLineNumber, range2.startColumn), eolCount, firstLineLength, lastLineLength2, firstCharCode);
    this._updateEndLineNumber();
  }
  _acceptDeleteRange(range2) {
    if (range2.startLineNumber === range2.endLineNumber && range2.startColumn === range2.endColumn) {
      return;
    }
    const firstLineIndex = range2.startLineNumber - this._startLineNumber;
    const lastLineIndex = range2.endLineNumber - this._startLineNumber;
    if (lastLineIndex < 0) {
      const deletedLinesCount = lastLineIndex - firstLineIndex;
      this._startLineNumber -= deletedLinesCount;
      return;
    }
    const tokenMaxDeltaLine = this._tokens.getMaxDeltaLine();
    if (firstLineIndex >= tokenMaxDeltaLine + 1) {
      return;
    }
    if (firstLineIndex < 0 && lastLineIndex >= tokenMaxDeltaLine + 1) {
      this._startLineNumber = 0;
      this._tokens.clear();
      return;
    }
    if (firstLineIndex < 0) {
      const deletedBefore = -firstLineIndex;
      this._startLineNumber -= deletedBefore;
      this._tokens.acceptDeleteRange(range2.startColumn - 1, 0, 0, lastLineIndex, range2.endColumn - 1);
    } else {
      this._tokens.acceptDeleteRange(0, firstLineIndex, range2.startColumn - 1, lastLineIndex, range2.endColumn - 1);
    }
  }
  _acceptInsertText(position, eolCount, firstLineLength, lastLineLength2, firstCharCode) {
    if (eolCount === 0 && firstLineLength === 0) {
      return;
    }
    const lineIndex = position.lineNumber - this._startLineNumber;
    if (lineIndex < 0) {
      this._startLineNumber += eolCount;
      return;
    }
    const tokenMaxDeltaLine = this._tokens.getMaxDeltaLine();
    if (lineIndex >= tokenMaxDeltaLine + 1) {
      return;
    }
    this._tokens.acceptInsertText(lineIndex, position.column - 1, eolCount, firstLineLength, lastLineLength2, firstCharCode);
  }
}
class SparseMultilineTokensStorage {
  constructor(tokens) {
    this._tokens = tokens;
    this._tokenCount = tokens.length / 4;
  }
  toString(startLineNumber) {
    const pieces = [];
    for (let i = 0; i < this._tokenCount; i++) {
      pieces.push(`(${this._getDeltaLine(i) + startLineNumber},${this._getStartCharacter(i)}-${this._getEndCharacter(i)})`);
    }
    return `[${pieces.join(",")}]`;
  }
  getMaxDeltaLine() {
    const tokenCount = this._getTokenCount();
    if (tokenCount === 0) {
      return -1;
    }
    return this._getDeltaLine(tokenCount - 1);
  }
  getRange() {
    const tokenCount = this._getTokenCount();
    if (tokenCount === 0) {
      return null;
    }
    const startChar = this._getStartCharacter(0);
    const maxDeltaLine = this._getDeltaLine(tokenCount - 1);
    const endChar = this._getEndCharacter(tokenCount - 1);
    return new Range$2(0, startChar + 1, maxDeltaLine, endChar + 1);
  }
  _getTokenCount() {
    return this._tokenCount;
  }
  _getDeltaLine(tokenIndex) {
    return this._tokens[4 * tokenIndex];
  }
  _getStartCharacter(tokenIndex) {
    return this._tokens[4 * tokenIndex + 1];
  }
  _getEndCharacter(tokenIndex) {
    return this._tokens[4 * tokenIndex + 2];
  }
  isEmpty() {
    return this._getTokenCount() === 0;
  }
  getLineTokens(deltaLine) {
    let low = 0;
    let high = this._getTokenCount() - 1;
    while (low < high) {
      const mid = low + Math.floor((high - low) / 2);
      const midDeltaLine = this._getDeltaLine(mid);
      if (midDeltaLine < deltaLine) {
        low = mid + 1;
      } else if (midDeltaLine > deltaLine) {
        high = mid - 1;
      } else {
        let min = mid;
        while (min > low && this._getDeltaLine(min - 1) === deltaLine) {
          min--;
        }
        let max = mid;
        while (max < high && this._getDeltaLine(max + 1) === deltaLine) {
          max++;
        }
        return new SparseLineTokens(this._tokens.subarray(4 * min, 4 * max + 4));
      }
    }
    if (this._getDeltaLine(low) === deltaLine) {
      return new SparseLineTokens(this._tokens.subarray(4 * low, 4 * low + 4));
    }
    return null;
  }
  clear() {
    this._tokenCount = 0;
  }
  removeTokens(startDeltaLine, startChar, endDeltaLine, endChar) {
    const tokens = this._tokens;
    const tokenCount = this._tokenCount;
    let newTokenCount = 0;
    let hasDeletedTokens = false;
    let firstDeltaLine = 0;
    for (let i = 0; i < tokenCount; i++) {
      const srcOffset = 4 * i;
      const tokenDeltaLine = tokens[srcOffset];
      const tokenStartCharacter = tokens[srcOffset + 1];
      const tokenEndCharacter = tokens[srcOffset + 2];
      const tokenMetadata = tokens[srcOffset + 3];
      if ((tokenDeltaLine > startDeltaLine || tokenDeltaLine === startDeltaLine && tokenEndCharacter >= startChar) && (tokenDeltaLine < endDeltaLine || tokenDeltaLine === endDeltaLine && tokenStartCharacter <= endChar)) {
        hasDeletedTokens = true;
      } else {
        if (newTokenCount === 0) {
          firstDeltaLine = tokenDeltaLine;
        }
        if (hasDeletedTokens) {
          const destOffset = 4 * newTokenCount;
          tokens[destOffset] = tokenDeltaLine - firstDeltaLine;
          tokens[destOffset + 1] = tokenStartCharacter;
          tokens[destOffset + 2] = tokenEndCharacter;
          tokens[destOffset + 3] = tokenMetadata;
        }
        newTokenCount++;
      }
    }
    this._tokenCount = newTokenCount;
    return firstDeltaLine;
  }
  split(startDeltaLine, startChar, endDeltaLine, endChar) {
    const tokens = this._tokens;
    const tokenCount = this._tokenCount;
    const aTokens = [];
    const bTokens = [];
    let destTokens = aTokens;
    let destOffset = 0;
    let destFirstDeltaLine = 0;
    for (let i = 0; i < tokenCount; i++) {
      const srcOffset = 4 * i;
      const tokenDeltaLine = tokens[srcOffset];
      const tokenStartCharacter = tokens[srcOffset + 1];
      const tokenEndCharacter = tokens[srcOffset + 2];
      const tokenMetadata = tokens[srcOffset + 3];
      if (tokenDeltaLine > startDeltaLine || tokenDeltaLine === startDeltaLine && tokenEndCharacter >= startChar) {
        if (tokenDeltaLine < endDeltaLine || tokenDeltaLine === endDeltaLine && tokenStartCharacter <= endChar) {
          continue;
        } else {
          if (destTokens !== bTokens) {
            destTokens = bTokens;
            destOffset = 0;
            destFirstDeltaLine = tokenDeltaLine;
          }
        }
      }
      destTokens[destOffset++] = tokenDeltaLine - destFirstDeltaLine;
      destTokens[destOffset++] = tokenStartCharacter;
      destTokens[destOffset++] = tokenEndCharacter;
      destTokens[destOffset++] = tokenMetadata;
    }
    return [new SparseMultilineTokensStorage(new Uint32Array(aTokens)), new SparseMultilineTokensStorage(new Uint32Array(bTokens)), destFirstDeltaLine];
  }
  acceptDeleteRange(horizontalShiftForFirstLineTokens, startDeltaLine, startCharacter, endDeltaLine, endCharacter) {
    const tokens = this._tokens;
    const tokenCount = this._tokenCount;
    const deletedLineCount = endDeltaLine - startDeltaLine;
    let newTokenCount = 0;
    let hasDeletedTokens = false;
    for (let i = 0; i < tokenCount; i++) {
      const srcOffset = 4 * i;
      let tokenDeltaLine = tokens[srcOffset];
      let tokenStartCharacter = tokens[srcOffset + 1];
      let tokenEndCharacter = tokens[srcOffset + 2];
      const tokenMetadata = tokens[srcOffset + 3];
      if (tokenDeltaLine < startDeltaLine || tokenDeltaLine === startDeltaLine && tokenEndCharacter <= startCharacter) {
        newTokenCount++;
        continue;
      } else if (tokenDeltaLine === startDeltaLine && tokenStartCharacter < startCharacter) {
        if (tokenDeltaLine === endDeltaLine && tokenEndCharacter > endCharacter) {
          tokenEndCharacter -= endCharacter - startCharacter;
        } else {
          tokenEndCharacter = startCharacter;
        }
      } else if (tokenDeltaLine === startDeltaLine && tokenStartCharacter === startCharacter) {
        if (tokenDeltaLine === endDeltaLine && tokenEndCharacter > endCharacter) {
          tokenEndCharacter -= endCharacter - startCharacter;
        } else {
          hasDeletedTokens = true;
          continue;
        }
      } else if (tokenDeltaLine < endDeltaLine || tokenDeltaLine === endDeltaLine && tokenStartCharacter < endCharacter) {
        if (tokenDeltaLine === endDeltaLine && tokenEndCharacter > endCharacter) {
          tokenDeltaLine = startDeltaLine;
          tokenStartCharacter = startCharacter;
          tokenEndCharacter = tokenStartCharacter + (tokenEndCharacter - endCharacter);
        } else {
          hasDeletedTokens = true;
          continue;
        }
      } else if (tokenDeltaLine > endDeltaLine) {
        if (deletedLineCount === 0 && !hasDeletedTokens) {
          newTokenCount = tokenCount;
          break;
        }
        tokenDeltaLine -= deletedLineCount;
      } else if (tokenDeltaLine === endDeltaLine && tokenStartCharacter >= endCharacter) {
        if (horizontalShiftForFirstLineTokens && tokenDeltaLine === 0) {
          tokenStartCharacter += horizontalShiftForFirstLineTokens;
          tokenEndCharacter += horizontalShiftForFirstLineTokens;
        }
        tokenDeltaLine -= deletedLineCount;
        tokenStartCharacter -= endCharacter - startCharacter;
        tokenEndCharacter -= endCharacter - startCharacter;
      } else {
        throw new Error(`Not possible!`);
      }
      const destOffset = 4 * newTokenCount;
      tokens[destOffset] = tokenDeltaLine;
      tokens[destOffset + 1] = tokenStartCharacter;
      tokens[destOffset + 2] = tokenEndCharacter;
      tokens[destOffset + 3] = tokenMetadata;
      newTokenCount++;
    }
    this._tokenCount = newTokenCount;
  }
  acceptInsertText(deltaLine, character, eolCount, firstLineLength, lastLineLength2, firstCharCode) {
    const isInsertingPreciselyOneWordCharacter = eolCount === 0 && firstLineLength === 1 && (firstCharCode >= 48 && firstCharCode <= 57 || firstCharCode >= 65 && firstCharCode <= 90 || firstCharCode >= 97 && firstCharCode <= 122);
    const tokens = this._tokens;
    const tokenCount = this._tokenCount;
    for (let i = 0; i < tokenCount; i++) {
      const offset = 4 * i;
      let tokenDeltaLine = tokens[offset];
      let tokenStartCharacter = tokens[offset + 1];
      let tokenEndCharacter = tokens[offset + 2];
      if (tokenDeltaLine < deltaLine || tokenDeltaLine === deltaLine && tokenEndCharacter < character) {
        continue;
      } else if (tokenDeltaLine === deltaLine && tokenEndCharacter === character) {
        if (isInsertingPreciselyOneWordCharacter) {
          tokenEndCharacter += 1;
        } else {
          continue;
        }
      } else if (tokenDeltaLine === deltaLine && tokenStartCharacter < character && character < tokenEndCharacter) {
        if (eolCount === 0) {
          tokenEndCharacter += firstLineLength;
        } else {
          tokenEndCharacter = character;
        }
      } else {
        if (tokenDeltaLine === deltaLine && tokenStartCharacter === character) {
          if (isInsertingPreciselyOneWordCharacter) {
            continue;
          }
        }
        if (tokenDeltaLine === deltaLine) {
          tokenDeltaLine += eolCount;
          if (eolCount === 0) {
            tokenStartCharacter += firstLineLength;
            tokenEndCharacter += firstLineLength;
          } else {
            const tokenLength = tokenEndCharacter - tokenStartCharacter;
            tokenStartCharacter = lastLineLength2 + (tokenStartCharacter - character);
            tokenEndCharacter = tokenStartCharacter + tokenLength;
          }
        } else {
          tokenDeltaLine += eolCount;
        }
      }
      tokens[offset] = tokenDeltaLine;
      tokens[offset + 1] = tokenStartCharacter;
      tokens[offset + 2] = tokenEndCharacter;
    }
  }
}
class SparseLineTokens {
  constructor(tokens) {
    this._tokens = tokens;
  }
  getCount() {
    return this._tokens.length / 4;
  }
  getStartCharacter(tokenIndex) {
    return this._tokens[4 * tokenIndex + 1];
  }
  getEndCharacter(tokenIndex) {
    return this._tokens[4 * tokenIndex + 2];
  }
  getMetadata(tokenIndex) {
    return this._tokens[4 * tokenIndex + 3];
  }
}
var __decorate$L = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$J = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let SemanticTokensProviderStyling = class SemanticTokensProviderStyling2 {
  constructor(_legend, _themeService, _languageService, _logService) {
    this._legend = _legend;
    this._themeService = _themeService;
    this._languageService = _languageService;
    this._logService = _logService;
    this._hasWarnedOverlappingTokens = false;
    this._hasWarnedInvalidLengthTokens = false;
    this._hasWarnedInvalidEditStart = false;
    this._hashTable = new HashTable();
  }
  getMetadata(tokenTypeIndex, tokenModifierSet, languageId) {
    const encodedLanguageId = this._languageService.languageIdCodec.encodeLanguageId(languageId);
    const entry = this._hashTable.get(tokenTypeIndex, tokenModifierSet, encodedLanguageId);
    let metadata;
    if (entry) {
      metadata = entry.metadata;
      if (this._logService.getLevel() === LogLevel.Trace) {
        this._logService.trace(`SemanticTokensProviderStyling [CACHED] ${tokenTypeIndex} / ${tokenModifierSet}: foreground ${TokenMetadata.getForeground(metadata)}, fontStyle ${TokenMetadata.getFontStyle(metadata).toString(2)}`);
      }
    } else {
      let tokenType = this._legend.tokenTypes[tokenTypeIndex];
      const tokenModifiers = [];
      if (tokenType) {
        let modifierSet = tokenModifierSet;
        for (let modifierIndex = 0; modifierSet > 0 && modifierIndex < this._legend.tokenModifiers.length; modifierIndex++) {
          if (modifierSet & 1) {
            tokenModifiers.push(this._legend.tokenModifiers[modifierIndex]);
          }
          modifierSet = modifierSet >> 1;
        }
        if (modifierSet > 0 && this._logService.getLevel() === LogLevel.Trace) {
          this._logService.trace(`SemanticTokensProviderStyling: unknown token modifier index: ${tokenModifierSet.toString(2)} for legend: ${JSON.stringify(this._legend.tokenModifiers)}`);
          tokenModifiers.push("not-in-legend");
        }
        const tokenStyle = this._themeService.getColorTheme().getTokenStyleMetadata(tokenType, tokenModifiers, languageId);
        if (typeof tokenStyle === "undefined") {
          metadata = 2147483647;
        } else {
          metadata = 0;
          if (typeof tokenStyle.italic !== "undefined") {
            const italicBit = (tokenStyle.italic ? 1 : 0) << 11;
            metadata |= italicBit | 1;
          }
          if (typeof tokenStyle.bold !== "undefined") {
            const boldBit = (tokenStyle.bold ? 2 : 0) << 11;
            metadata |= boldBit | 2;
          }
          if (typeof tokenStyle.underline !== "undefined") {
            const underlineBit = (tokenStyle.underline ? 4 : 0) << 11;
            metadata |= underlineBit | 4;
          }
          if (typeof tokenStyle.strikethrough !== "undefined") {
            const strikethroughBit = (tokenStyle.strikethrough ? 8 : 0) << 11;
            metadata |= strikethroughBit | 8;
          }
          if (tokenStyle.foreground) {
            const foregroundBits = tokenStyle.foreground << 15;
            metadata |= foregroundBits | 16;
          }
          if (metadata === 0) {
            metadata = 2147483647;
          }
        }
      } else {
        if (this._logService.getLevel() === LogLevel.Trace) {
          this._logService.trace(`SemanticTokensProviderStyling: unknown token type index: ${tokenTypeIndex} for legend: ${JSON.stringify(this._legend.tokenTypes)}`);
        }
        metadata = 2147483647;
        tokenType = "not-in-legend";
      }
      this._hashTable.add(tokenTypeIndex, tokenModifierSet, encodedLanguageId, metadata);
      if (this._logService.getLevel() === LogLevel.Trace) {
        this._logService.trace(`SemanticTokensProviderStyling ${tokenTypeIndex} (${tokenType}) / ${tokenModifierSet} (${tokenModifiers.join(" ")}): foreground ${TokenMetadata.getForeground(metadata)}, fontStyle ${TokenMetadata.getFontStyle(metadata).toString(2)}`);
      }
    }
    return metadata;
  }
  warnOverlappingSemanticTokens(lineNumber, startColumn) {
    if (!this._hasWarnedOverlappingTokens) {
      this._hasWarnedOverlappingTokens = true;
      console.warn(`Overlapping semantic tokens detected at lineNumber ${lineNumber}, column ${startColumn}`);
    }
  }
  warnInvalidLengthSemanticTokens(lineNumber, startColumn) {
    if (!this._hasWarnedInvalidLengthTokens) {
      this._hasWarnedInvalidLengthTokens = true;
      console.warn(`Semantic token with invalid length detected at lineNumber ${lineNumber}, column ${startColumn}`);
    }
  }
  warnInvalidEditStart(previousResultId, resultId, editIndex, editStart, maxExpectedStart) {
    if (!this._hasWarnedInvalidEditStart) {
      this._hasWarnedInvalidEditStart = true;
      console.warn(`Invalid semantic tokens edit detected (previousResultId: ${previousResultId}, resultId: ${resultId}) at edit #${editIndex}: The provided start offset ${editStart} is outside the previous data (length ${maxExpectedStart}).`);
    }
  }
};
SemanticTokensProviderStyling = __decorate$L([
  __param$J(1, IThemeService),
  __param$J(2, ILanguageService),
  __param$J(3, ILogService)
], SemanticTokensProviderStyling);
function toMultilineTokens2(tokens, styling, languageId) {
  const srcData = tokens.data;
  const tokenCount = tokens.data.length / 5 | 0;
  const tokensPerArea = Math.max(
    Math.ceil(
      tokenCount / 1024
      /* SemanticColoringConstants.DesiredMaxAreas */
    ),
    400
    /* SemanticColoringConstants.DesiredTokensPerArea */
  );
  const result2 = [];
  let tokenIndex = 0;
  let lastLineNumber = 1;
  let lastStartCharacter = 0;
  while (tokenIndex < tokenCount) {
    const tokenStartIndex = tokenIndex;
    let tokenEndIndex = Math.min(tokenStartIndex + tokensPerArea, tokenCount);
    if (tokenEndIndex < tokenCount) {
      let smallTokenEndIndex = tokenEndIndex;
      while (smallTokenEndIndex - 1 > tokenStartIndex && srcData[5 * smallTokenEndIndex] === 0) {
        smallTokenEndIndex--;
      }
      if (smallTokenEndIndex - 1 === tokenStartIndex) {
        let bigTokenEndIndex = tokenEndIndex;
        while (bigTokenEndIndex + 1 < tokenCount && srcData[5 * bigTokenEndIndex] === 0) {
          bigTokenEndIndex++;
        }
        tokenEndIndex = bigTokenEndIndex;
      } else {
        tokenEndIndex = smallTokenEndIndex;
      }
    }
    let destData = new Uint32Array((tokenEndIndex - tokenStartIndex) * 4);
    let destOffset = 0;
    let areaLine = 0;
    let prevLineNumber = 0;
    let prevEndCharacter = 0;
    while (tokenIndex < tokenEndIndex) {
      const srcOffset = 5 * tokenIndex;
      const deltaLine = srcData[srcOffset];
      const deltaCharacter = srcData[srcOffset + 1];
      const lineNumber = lastLineNumber + deltaLine | 0;
      const startCharacter = deltaLine === 0 ? lastStartCharacter + deltaCharacter | 0 : deltaCharacter;
      const length2 = srcData[srcOffset + 2];
      const endCharacter = startCharacter + length2 | 0;
      const tokenTypeIndex = srcData[srcOffset + 3];
      const tokenModifierSet = srcData[srcOffset + 4];
      if (endCharacter <= startCharacter) {
        styling.warnInvalidLengthSemanticTokens(lineNumber, startCharacter + 1);
      } else if (prevLineNumber === lineNumber && prevEndCharacter > startCharacter) {
        styling.warnOverlappingSemanticTokens(lineNumber, startCharacter + 1);
      } else {
        const metadata = styling.getMetadata(tokenTypeIndex, tokenModifierSet, languageId);
        if (metadata !== 2147483647) {
          if (areaLine === 0) {
            areaLine = lineNumber;
          }
          destData[destOffset] = lineNumber - areaLine;
          destData[destOffset + 1] = startCharacter;
          destData[destOffset + 2] = endCharacter;
          destData[destOffset + 3] = metadata;
          destOffset += 4;
          prevLineNumber = lineNumber;
          prevEndCharacter = endCharacter;
        }
      }
      lastLineNumber = lineNumber;
      lastStartCharacter = startCharacter;
      tokenIndex++;
    }
    if (destOffset !== destData.length) {
      destData = destData.subarray(0, destOffset);
    }
    const tokens2 = SparseMultilineTokens.create(areaLine, destData);
    result2.push(tokens2);
  }
  return result2;
}
class HashTableEntry {
  constructor(tokenTypeIndex, tokenModifierSet, languageId, metadata) {
    this.tokenTypeIndex = tokenTypeIndex;
    this.tokenModifierSet = tokenModifierSet;
    this.languageId = languageId;
    this.metadata = metadata;
    this.next = null;
  }
}
class HashTable {
  constructor() {
    this._elementsCount = 0;
    this._currentLengthIndex = 0;
    this._currentLength = HashTable._SIZES[this._currentLengthIndex];
    this._growCount = Math.round(this._currentLengthIndex + 1 < HashTable._SIZES.length ? 2 / 3 * this._currentLength : 0);
    this._elements = [];
    HashTable._nullOutEntries(this._elements, this._currentLength);
  }
  static _nullOutEntries(entries, length2) {
    for (let i = 0; i < length2; i++) {
      entries[i] = null;
    }
  }
  _hash2(n1, n2) {
    return (n1 << 5) - n1 + n2 | 0;
  }
  _hashFunc(tokenTypeIndex, tokenModifierSet, languageId) {
    return this._hash2(this._hash2(tokenTypeIndex, tokenModifierSet), languageId) % this._currentLength;
  }
  get(tokenTypeIndex, tokenModifierSet, languageId) {
    const hash2 = this._hashFunc(tokenTypeIndex, tokenModifierSet, languageId);
    let p2 = this._elements[hash2];
    while (p2) {
      if (p2.tokenTypeIndex === tokenTypeIndex && p2.tokenModifierSet === tokenModifierSet && p2.languageId === languageId) {
        return p2;
      }
      p2 = p2.next;
    }
    return null;
  }
  add(tokenTypeIndex, tokenModifierSet, languageId, metadata) {
    this._elementsCount++;
    if (this._growCount !== 0 && this._elementsCount >= this._growCount) {
      const oldElements = this._elements;
      this._currentLengthIndex++;
      this._currentLength = HashTable._SIZES[this._currentLengthIndex];
      this._growCount = Math.round(this._currentLengthIndex + 1 < HashTable._SIZES.length ? 2 / 3 * this._currentLength : 0);
      this._elements = [];
      HashTable._nullOutEntries(this._elements, this._currentLength);
      for (const first2 of oldElements) {
        let p2 = first2;
        while (p2) {
          const oldNext = p2.next;
          p2.next = null;
          this._add(p2);
          p2 = oldNext;
        }
      }
    }
    this._add(new HashTableEntry(tokenTypeIndex, tokenModifierSet, languageId, metadata));
  }
  _add(element) {
    const hash2 = this._hashFunc(element.tokenTypeIndex, element.tokenModifierSet, element.languageId);
    element.next = this._elements[hash2];
    this._elements[hash2] = element;
  }
}
HashTable._SIZES = [3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143];
function reverseEndianness(arr) {
  for (let i = 0, len = arr.length; i < len; i += 4) {
    const b0 = arr[i + 0];
    const b1 = arr[i + 1];
    const b2 = arr[i + 2];
    const b3 = arr[i + 3];
    arr[i + 0] = b3;
    arr[i + 1] = b2;
    arr[i + 2] = b1;
    arr[i + 3] = b0;
  }
}
function toLittleEndianBuffer(arr) {
  const uint8Arr = new Uint8Array(arr.buffer, arr.byteOffset, arr.length * 4);
  if (!isLittleEndian()) {
    reverseEndianness(uint8Arr);
  }
  return VSBuffer.wrap(uint8Arr);
}
function encodeSemanticTokensDto(semanticTokens) {
  const dest = new Uint32Array(encodeSemanticTokensDtoSize(semanticTokens));
  let offset = 0;
  dest[offset++] = semanticTokens.id;
  if (semanticTokens.type === "full") {
    dest[offset++] = 1;
    dest[offset++] = semanticTokens.data.length;
    dest.set(semanticTokens.data, offset);
    offset += semanticTokens.data.length;
  } else {
    dest[offset++] = 2;
    dest[offset++] = semanticTokens.deltas.length;
    for (const delta of semanticTokens.deltas) {
      dest[offset++] = delta.start;
      dest[offset++] = delta.deleteCount;
      if (delta.data) {
        dest[offset++] = delta.data.length;
        dest.set(delta.data, offset);
        offset += delta.data.length;
      } else {
        dest[offset++] = 0;
      }
    }
  }
  return toLittleEndianBuffer(dest);
}
function encodeSemanticTokensDtoSize(semanticTokens) {
  let result2 = 0;
  result2 += 1 + 1;
  if (semanticTokens.type === "full") {
    result2 += 1 + semanticTokens.data.length;
  } else {
    result2 += 1;
    result2 += (1 + 1 + 1) * semanticTokens.deltas.length;
    for (const delta of semanticTokens.deltas) {
      if (delta.data) {
        result2 += delta.data.length;
      }
    }
  }
  return result2;
}
var __awaiter$r = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
function isSemanticTokens(v) {
  return v && !!v.data;
}
function isSemanticTokensEdits(v) {
  return v && Array.isArray(v.edits);
}
class DocumentSemanticTokensResult {
  constructor(provider, tokens, error2) {
    this.provider = provider;
    this.tokens = tokens;
    this.error = error2;
  }
}
function hasDocumentSemanticTokensProvider(registry, model) {
  return registry.has(model);
}
function getDocumentSemanticTokensProviders(registry, model) {
  const groups = registry.orderedGroups(model);
  return groups.length > 0 ? groups[0] : [];
}
function getDocumentSemanticTokens(registry, model, lastProvider, lastResultId, token) {
  return __awaiter$r(this, void 0, void 0, function* () {
    const providers = getDocumentSemanticTokensProviders(registry, model);
    const results = yield Promise.all(providers.map((provider) => __awaiter$r(this, void 0, void 0, function* () {
      let result2;
      let error2 = null;
      try {
        result2 = yield provider.provideDocumentSemanticTokens(model, provider === lastProvider ? lastResultId : null, token);
      } catch (err) {
        error2 = err;
        result2 = null;
      }
      if (!result2 || !isSemanticTokens(result2) && !isSemanticTokensEdits(result2)) {
        result2 = null;
      }
      return new DocumentSemanticTokensResult(provider, result2, error2);
    })));
    for (const result2 of results) {
      if (result2.error) {
        throw result2.error;
      }
      if (result2.tokens) {
        return result2;
      }
    }
    if (results.length > 0) {
      return results[0];
    }
    return null;
  });
}
function _getDocumentSemanticTokensProviderHighestGroup(registry, model) {
  const result2 = registry.orderedGroups(model);
  return result2.length > 0 ? result2[0] : null;
}
class DocumentRangeSemanticTokensResult {
  constructor(provider, tokens) {
    this.provider = provider;
    this.tokens = tokens;
  }
}
function hasDocumentRangeSemanticTokensProvider(providers, model) {
  return providers.has(model);
}
function getDocumentRangeSemanticTokensProviders(providers, model) {
  const groups = providers.orderedGroups(model);
  return groups.length > 0 ? groups[0] : [];
}
function getDocumentRangeSemanticTokens(registry, model, range2, token) {
  return __awaiter$r(this, void 0, void 0, function* () {
    const providers = getDocumentRangeSemanticTokensProviders(registry, model);
    const results = yield Promise.all(providers.map((provider) => __awaiter$r(this, void 0, void 0, function* () {
      let result2;
      try {
        result2 = yield provider.provideDocumentRangeSemanticTokens(model, range2, token);
      } catch (err) {
        onUnexpectedExternalError(err);
        result2 = null;
      }
      if (!result2 || !isSemanticTokens(result2)) {
        result2 = null;
      }
      return new DocumentRangeSemanticTokensResult(provider, result2);
    })));
    for (const result2 of results) {
      if (result2.tokens) {
        return result2;
      }
    }
    if (results.length > 0) {
      return results[0];
    }
    return null;
  });
}
CommandsRegistry.registerCommand("_provideDocumentSemanticTokensLegend", (accessor, ...args) => __awaiter$r(void 0, void 0, void 0, function* () {
  const [uri] = args;
  assertType(uri instanceof URI);
  const model = accessor.get(IModelService).getModel(uri);
  if (!model) {
    return void 0;
  }
  const { documentSemanticTokensProvider } = accessor.get(ILanguageFeaturesService);
  const providers = _getDocumentSemanticTokensProviderHighestGroup(documentSemanticTokensProvider, model);
  if (!providers) {
    return accessor.get(ICommandService).executeCommand("_provideDocumentRangeSemanticTokensLegend", uri);
  }
  return providers[0].getLegend();
}));
CommandsRegistry.registerCommand("_provideDocumentSemanticTokens", (accessor, ...args) => __awaiter$r(void 0, void 0, void 0, function* () {
  const [uri] = args;
  assertType(uri instanceof URI);
  const model = accessor.get(IModelService).getModel(uri);
  if (!model) {
    return void 0;
  }
  const { documentSemanticTokensProvider } = accessor.get(ILanguageFeaturesService);
  if (!hasDocumentSemanticTokensProvider(documentSemanticTokensProvider, model)) {
    return accessor.get(ICommandService).executeCommand("_provideDocumentRangeSemanticTokens", uri, model.getFullModelRange());
  }
  const r = yield getDocumentSemanticTokens(documentSemanticTokensProvider, model, null, null, CancellationToken.None);
  if (!r) {
    return void 0;
  }
  const { provider, tokens } = r;
  if (!tokens || !isSemanticTokens(tokens)) {
    return void 0;
  }
  const buff = encodeSemanticTokensDto({
    id: 0,
    type: "full",
    data: tokens.data
  });
  if (tokens.resultId) {
    provider.releaseDocumentSemanticTokens(tokens.resultId);
  }
  return buff;
}));
CommandsRegistry.registerCommand("_provideDocumentRangeSemanticTokensLegend", (accessor, ...args) => __awaiter$r(void 0, void 0, void 0, function* () {
  const [uri, range2] = args;
  assertType(uri instanceof URI);
  const model = accessor.get(IModelService).getModel(uri);
  if (!model) {
    return void 0;
  }
  const { documentRangeSemanticTokensProvider } = accessor.get(ILanguageFeaturesService);
  const providers = getDocumentRangeSemanticTokensProviders(documentRangeSemanticTokensProvider, model);
  if (providers.length === 0) {
    return void 0;
  }
  if (providers.length === 1) {
    return providers[0].getLegend();
  }
  if (!range2 || !Range$2.isIRange(range2)) {
    console.warn(`provideDocumentRangeSemanticTokensLegend might be out-of-sync with provideDocumentRangeSemanticTokens unless a range argument is passed in`);
    return providers[0].getLegend();
  }
  const result2 = yield getDocumentRangeSemanticTokens(documentRangeSemanticTokensProvider, model, Range$2.lift(range2), CancellationToken.None);
  if (!result2) {
    return void 0;
  }
  return result2.provider.getLegend();
}));
CommandsRegistry.registerCommand("_provideDocumentRangeSemanticTokens", (accessor, ...args) => __awaiter$r(void 0, void 0, void 0, function* () {
  const [uri, range2] = args;
  assertType(uri instanceof URI);
  assertType(Range$2.isIRange(range2));
  const model = accessor.get(IModelService).getModel(uri);
  if (!model) {
    return void 0;
  }
  const { documentRangeSemanticTokensProvider } = accessor.get(ILanguageFeaturesService);
  const result2 = yield getDocumentRangeSemanticTokens(documentRangeSemanticTokensProvider, model, Range$2.lift(range2), CancellationToken.None);
  if (!result2 || !result2.tokens) {
    return void 0;
  }
  return encodeSemanticTokensDto({
    id: 0,
    type: "full",
    data: result2.tokens.data
  });
}));
const ISemanticTokensStylingService = createDecorator("semanticTokensStylingService");
const SEMANTIC_HIGHLIGHTING_SETTING_ID = "editor.semanticHighlighting";
function isSemanticColoringEnabled(model, themeService, configurationService) {
  var _a2;
  const setting = (_a2 = configurationService.getValue(SEMANTIC_HIGHLIGHTING_SETTING_ID, { overrideIdentifier: model.getLanguageId(), resource: model.uri })) === null || _a2 === void 0 ? void 0 : _a2.enabled;
  if (typeof setting === "boolean") {
    return setting;
  }
  return themeService.getColorTheme().semanticHighlighting;
}
var __decorate$K = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$I = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let DocumentSemanticTokensFeature = class DocumentSemanticTokensFeature2 extends Disposable {
  constructor(semanticTokensStylingService, modelService, themeService, configurationService, languageFeatureDebounceService, languageFeaturesService) {
    super();
    this._watchers = /* @__PURE__ */ Object.create(null);
    const register2 = (model) => {
      this._watchers[model.uri.toString()] = new ModelSemanticColoring(model, semanticTokensStylingService, themeService, languageFeatureDebounceService, languageFeaturesService);
    };
    const deregister = (model, modelSemanticColoring) => {
      modelSemanticColoring.dispose();
      delete this._watchers[model.uri.toString()];
    };
    const handleSettingOrThemeChange = () => {
      for (const model of modelService.getModels()) {
        const curr = this._watchers[model.uri.toString()];
        if (isSemanticColoringEnabled(model, themeService, configurationService)) {
          if (!curr) {
            register2(model);
          }
        } else {
          if (curr) {
            deregister(model, curr);
          }
        }
      }
    };
    this._register(modelService.onModelAdded((model) => {
      if (isSemanticColoringEnabled(model, themeService, configurationService)) {
        register2(model);
      }
    }));
    this._register(modelService.onModelRemoved((model) => {
      const curr = this._watchers[model.uri.toString()];
      if (curr) {
        deregister(model, curr);
      }
    }));
    this._register(configurationService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(SEMANTIC_HIGHLIGHTING_SETTING_ID)) {
        handleSettingOrThemeChange();
      }
    }));
    this._register(themeService.onDidColorThemeChange(handleSettingOrThemeChange));
  }
  dispose() {
    for (const watcher of Object.values(this._watchers)) {
      watcher.dispose();
    }
    super.dispose();
  }
};
DocumentSemanticTokensFeature = __decorate$K([
  __param$I(0, ISemanticTokensStylingService),
  __param$I(1, IModelService),
  __param$I(2, IThemeService),
  __param$I(3, IConfigurationService),
  __param$I(4, ILanguageFeatureDebounceService),
  __param$I(5, ILanguageFeaturesService)
], DocumentSemanticTokensFeature);
let ModelSemanticColoring = class ModelSemanticColoring2 extends Disposable {
  constructor(model, _semanticTokensStylingService, themeService, languageFeatureDebounceService, languageFeaturesService) {
    super();
    this._semanticTokensStylingService = _semanticTokensStylingService;
    this._isDisposed = false;
    this._model = model;
    this._provider = languageFeaturesService.documentSemanticTokensProvider;
    this._debounceInformation = languageFeatureDebounceService.for(this._provider, "DocumentSemanticTokens", { min: ModelSemanticColoring2.REQUEST_MIN_DELAY, max: ModelSemanticColoring2.REQUEST_MAX_DELAY });
    this._fetchDocumentSemanticTokens = this._register(new RunOnceScheduler(() => this._fetchDocumentSemanticTokensNow(), ModelSemanticColoring2.REQUEST_MIN_DELAY));
    this._currentDocumentResponse = null;
    this._currentDocumentRequestCancellationTokenSource = null;
    this._documentProvidersChangeListeners = [];
    this._providersChangedDuringRequest = false;
    this._register(this._model.onDidChangeContent(() => {
      if (!this._fetchDocumentSemanticTokens.isScheduled()) {
        this._fetchDocumentSemanticTokens.schedule(this._debounceInformation.get(this._model));
      }
    }));
    this._register(this._model.onDidChangeAttached(() => {
      if (!this._fetchDocumentSemanticTokens.isScheduled()) {
        this._fetchDocumentSemanticTokens.schedule(this._debounceInformation.get(this._model));
      }
    }));
    this._register(this._model.onDidChangeLanguage(() => {
      if (this._currentDocumentResponse) {
        this._currentDocumentResponse.dispose();
        this._currentDocumentResponse = null;
      }
      if (this._currentDocumentRequestCancellationTokenSource) {
        this._currentDocumentRequestCancellationTokenSource.cancel();
        this._currentDocumentRequestCancellationTokenSource = null;
      }
      this._setDocumentSemanticTokens(null, null, null, []);
      this._fetchDocumentSemanticTokens.schedule(0);
    }));
    const bindDocumentChangeListeners = () => {
      dispose(this._documentProvidersChangeListeners);
      this._documentProvidersChangeListeners = [];
      for (const provider of this._provider.all(model)) {
        if (typeof provider.onDidChange === "function") {
          this._documentProvidersChangeListeners.push(provider.onDidChange(() => {
            if (this._currentDocumentRequestCancellationTokenSource) {
              this._providersChangedDuringRequest = true;
              return;
            }
            this._fetchDocumentSemanticTokens.schedule(0);
          }));
        }
      }
    };
    bindDocumentChangeListeners();
    this._register(this._provider.onDidChange(() => {
      bindDocumentChangeListeners();
      this._fetchDocumentSemanticTokens.schedule(this._debounceInformation.get(this._model));
    }));
    this._register(themeService.onDidColorThemeChange((_) => {
      this._setDocumentSemanticTokens(null, null, null, []);
      this._fetchDocumentSemanticTokens.schedule(this._debounceInformation.get(this._model));
    }));
    this._fetchDocumentSemanticTokens.schedule(0);
  }
  dispose() {
    if (this._currentDocumentResponse) {
      this._currentDocumentResponse.dispose();
      this._currentDocumentResponse = null;
    }
    if (this._currentDocumentRequestCancellationTokenSource) {
      this._currentDocumentRequestCancellationTokenSource.cancel();
      this._currentDocumentRequestCancellationTokenSource = null;
    }
    dispose(this._documentProvidersChangeListeners);
    this._documentProvidersChangeListeners = [];
    this._setDocumentSemanticTokens(null, null, null, []);
    this._isDisposed = true;
    super.dispose();
  }
  _fetchDocumentSemanticTokensNow() {
    if (this._currentDocumentRequestCancellationTokenSource) {
      return;
    }
    if (!hasDocumentSemanticTokensProvider(this._provider, this._model)) {
      if (this._currentDocumentResponse) {
        this._model.tokenization.setSemanticTokens(null, false);
      }
      return;
    }
    if (!this._model.isAttachedToEditor()) {
      return;
    }
    const cancellationTokenSource = new CancellationTokenSource$1();
    const lastProvider = this._currentDocumentResponse ? this._currentDocumentResponse.provider : null;
    const lastResultId = this._currentDocumentResponse ? this._currentDocumentResponse.resultId || null : null;
    const request = getDocumentSemanticTokens(this._provider, this._model, lastProvider, lastResultId, cancellationTokenSource.token);
    this._currentDocumentRequestCancellationTokenSource = cancellationTokenSource;
    this._providersChangedDuringRequest = false;
    const pendingChanges = [];
    const contentChangeListener = this._model.onDidChangeContent((e) => {
      pendingChanges.push(e);
    });
    const sw = new StopWatch(false);
    request.then((res) => {
      this._debounceInformation.update(this._model, sw.elapsed());
      this._currentDocumentRequestCancellationTokenSource = null;
      contentChangeListener.dispose();
      if (!res) {
        this._setDocumentSemanticTokens(null, null, null, pendingChanges);
      } else {
        const { provider, tokens } = res;
        const styling = this._semanticTokensStylingService.getStyling(provider);
        this._setDocumentSemanticTokens(provider, tokens || null, styling, pendingChanges);
      }
    }, (err) => {
      const isExpectedError = err && (isCancellationError(err) || typeof err.message === "string" && err.message.indexOf("busy") !== -1);
      if (!isExpectedError) {
        onUnexpectedError(err);
      }
      this._currentDocumentRequestCancellationTokenSource = null;
      contentChangeListener.dispose();
      if (pendingChanges.length > 0 || this._providersChangedDuringRequest) {
        if (!this._fetchDocumentSemanticTokens.isScheduled()) {
          this._fetchDocumentSemanticTokens.schedule(this._debounceInformation.get(this._model));
        }
      }
    });
  }
  static _copy(src, srcOffset, dest, destOffset, length2) {
    length2 = Math.min(length2, dest.length - destOffset, src.length - srcOffset);
    for (let i = 0; i < length2; i++) {
      dest[destOffset + i] = src[srcOffset + i];
    }
  }
  _setDocumentSemanticTokens(provider, tokens, styling, pendingChanges) {
    const currentResponse = this._currentDocumentResponse;
    const rescheduleIfNeeded = () => {
      if ((pendingChanges.length > 0 || this._providersChangedDuringRequest) && !this._fetchDocumentSemanticTokens.isScheduled()) {
        this._fetchDocumentSemanticTokens.schedule(this._debounceInformation.get(this._model));
      }
    };
    if (this._currentDocumentResponse) {
      this._currentDocumentResponse.dispose();
      this._currentDocumentResponse = null;
    }
    if (this._isDisposed) {
      if (provider && tokens) {
        provider.releaseDocumentSemanticTokens(tokens.resultId);
      }
      return;
    }
    if (!provider || !styling) {
      this._model.tokenization.setSemanticTokens(null, false);
      return;
    }
    if (!tokens) {
      this._model.tokenization.setSemanticTokens(null, true);
      rescheduleIfNeeded();
      return;
    }
    if (isSemanticTokensEdits(tokens)) {
      if (!currentResponse) {
        this._model.tokenization.setSemanticTokens(null, true);
        return;
      }
      if (tokens.edits.length === 0) {
        tokens = {
          resultId: tokens.resultId,
          data: currentResponse.data
        };
      } else {
        let deltaLength = 0;
        for (const edit of tokens.edits) {
          deltaLength += (edit.data ? edit.data.length : 0) - edit.deleteCount;
        }
        const srcData = currentResponse.data;
        const destData = new Uint32Array(srcData.length + deltaLength);
        let srcLastStart = srcData.length;
        let destLastStart = destData.length;
        for (let i = tokens.edits.length - 1; i >= 0; i--) {
          const edit = tokens.edits[i];
          if (edit.start > srcData.length) {
            styling.warnInvalidEditStart(currentResponse.resultId, tokens.resultId, i, edit.start, srcData.length);
            this._model.tokenization.setSemanticTokens(null, true);
            return;
          }
          const copyCount = srcLastStart - (edit.start + edit.deleteCount);
          if (copyCount > 0) {
            ModelSemanticColoring2._copy(srcData, srcLastStart - copyCount, destData, destLastStart - copyCount, copyCount);
            destLastStart -= copyCount;
          }
          if (edit.data) {
            ModelSemanticColoring2._copy(edit.data, 0, destData, destLastStart - edit.data.length, edit.data.length);
            destLastStart -= edit.data.length;
          }
          srcLastStart = edit.start;
        }
        if (srcLastStart > 0) {
          ModelSemanticColoring2._copy(srcData, 0, destData, 0, srcLastStart);
        }
        tokens = {
          resultId: tokens.resultId,
          data: destData
        };
      }
    }
    if (isSemanticTokens(tokens)) {
      this._currentDocumentResponse = new SemanticTokensResponse(provider, tokens.resultId, tokens.data);
      const result2 = toMultilineTokens2(tokens, styling, this._model.getLanguageId());
      if (pendingChanges.length > 0) {
        for (const change of pendingChanges) {
          for (const area of result2) {
            for (const singleChange of change.changes) {
              area.applyEdit(singleChange.range, singleChange.text);
            }
          }
        }
      }
      this._model.tokenization.setSemanticTokens(result2, true);
    } else {
      this._model.tokenization.setSemanticTokens(null, true);
    }
    rescheduleIfNeeded();
  }
};
ModelSemanticColoring.REQUEST_MIN_DELAY = 300;
ModelSemanticColoring.REQUEST_MAX_DELAY = 2e3;
ModelSemanticColoring = __decorate$K([
  __param$I(1, ISemanticTokensStylingService),
  __param$I(2, IThemeService),
  __param$I(3, ILanguageFeatureDebounceService),
  __param$I(4, ILanguageFeaturesService)
], ModelSemanticColoring);
class SemanticTokensResponse {
  constructor(provider, resultId, data) {
    this.provider = provider;
    this.resultId = resultId;
    this.data = data;
  }
  dispose() {
    this.provider.releaseDocumentSemanticTokens(this.resultId);
  }
}
registerEditorFeature(DocumentSemanticTokensFeature);
var __decorate$J = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$H = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let ViewportSemanticTokensContribution = class ViewportSemanticTokensContribution2 extends Disposable {
  constructor(editor2, _semanticTokensStylingService, _themeService, _configurationService, languageFeatureDebounceService, languageFeaturesService) {
    super();
    this._semanticTokensStylingService = _semanticTokensStylingService;
    this._themeService = _themeService;
    this._configurationService = _configurationService;
    this._editor = editor2;
    this._provider = languageFeaturesService.documentRangeSemanticTokensProvider;
    this._debounceInformation = languageFeatureDebounceService.for(this._provider, "DocumentRangeSemanticTokens", { min: 100, max: 500 });
    this._tokenizeViewport = this._register(new RunOnceScheduler(() => this._tokenizeViewportNow(), 100));
    this._outstandingRequests = [];
    const scheduleTokenizeViewport = () => {
      if (this._editor.hasModel()) {
        this._tokenizeViewport.schedule(this._debounceInformation.get(this._editor.getModel()));
      }
    };
    this._register(this._editor.onDidScrollChange(() => {
      scheduleTokenizeViewport();
    }));
    this._register(this._editor.onDidChangeModel(() => {
      this._cancelAll();
      scheduleTokenizeViewport();
    }));
    this._register(this._editor.onDidChangeModelContent((e) => {
      this._cancelAll();
      scheduleTokenizeViewport();
    }));
    this._register(this._provider.onDidChange(() => {
      this._cancelAll();
      scheduleTokenizeViewport();
    }));
    this._register(this._configurationService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration(SEMANTIC_HIGHLIGHTING_SETTING_ID)) {
        this._cancelAll();
        scheduleTokenizeViewport();
      }
    }));
    this._register(this._themeService.onDidColorThemeChange(() => {
      this._cancelAll();
      scheduleTokenizeViewport();
    }));
    scheduleTokenizeViewport();
  }
  _cancelAll() {
    for (const request of this._outstandingRequests) {
      request.cancel();
    }
    this._outstandingRequests = [];
  }
  _removeOutstandingRequest(req) {
    for (let i = 0, len = this._outstandingRequests.length; i < len; i++) {
      if (this._outstandingRequests[i] === req) {
        this._outstandingRequests.splice(i, 1);
        return;
      }
    }
  }
  _tokenizeViewportNow() {
    if (!this._editor.hasModel()) {
      return;
    }
    const model = this._editor.getModel();
    if (model.tokenization.hasCompleteSemanticTokens()) {
      return;
    }
    if (!isSemanticColoringEnabled(model, this._themeService, this._configurationService)) {
      if (model.tokenization.hasSomeSemanticTokens()) {
        model.tokenization.setSemanticTokens(null, false);
      }
      return;
    }
    if (!hasDocumentRangeSemanticTokensProvider(this._provider, model)) {
      if (model.tokenization.hasSomeSemanticTokens()) {
        model.tokenization.setSemanticTokens(null, false);
      }
      return;
    }
    const visibleRanges = this._editor.getVisibleRangesPlusViewportAboveBelow();
    this._outstandingRequests = this._outstandingRequests.concat(visibleRanges.map((range2) => this._requestRange(model, range2)));
  }
  _requestRange(model, range2) {
    const requestVersionId = model.getVersionId();
    const request = createCancelablePromise((token) => Promise.resolve(getDocumentRangeSemanticTokens(this._provider, model, range2, token)));
    const sw = new StopWatch(false);
    request.then((r) => {
      this._debounceInformation.update(model, sw.elapsed());
      if (!r || !r.tokens || model.isDisposed() || model.getVersionId() !== requestVersionId) {
        return;
      }
      const { provider, tokens: result2 } = r;
      const styling = this._semanticTokensStylingService.getStyling(provider);
      model.tokenization.setPartialSemanticTokens(range2, toMultilineTokens2(result2, styling, model.getLanguageId()));
    }).then(() => this._removeOutstandingRequest(request), () => this._removeOutstandingRequest(request));
    return request;
  }
};
ViewportSemanticTokensContribution.ID = "editor.contrib.viewportSemanticTokens";
ViewportSemanticTokensContribution = __decorate$J([
  __param$H(1, ISemanticTokensStylingService),
  __param$H(2, IThemeService),
  __param$H(3, IConfigurationService),
  __param$H(4, ILanguageFeatureDebounceService),
  __param$H(5, ILanguageFeaturesService)
], ViewportSemanticTokensContribution);
registerEditorContribution(
  ViewportSemanticTokensContribution.ID,
  ViewportSemanticTokensContribution,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
class WordSelectionRangeProvider {
  constructor(selectSubwords = true) {
    this.selectSubwords = selectSubwords;
  }
  provideSelectionRanges(model, positions) {
    const result2 = [];
    for (const position of positions) {
      const bucket = [];
      result2.push(bucket);
      if (this.selectSubwords) {
        this._addInWordRanges(bucket, model, position);
      }
      this._addWordRanges(bucket, model, position);
      this._addWhitespaceLine(bucket, model, position);
      bucket.push({ range: model.getFullModelRange() });
    }
    return result2;
  }
  _addInWordRanges(bucket, model, pos) {
    const obj = model.getWordAtPosition(pos);
    if (!obj) {
      return;
    }
    const { word: word2, startColumn } = obj;
    const offset = pos.column - startColumn;
    let start = offset;
    let end = offset;
    let lastCh = 0;
    for (; start >= 0; start--) {
      const ch = word2.charCodeAt(start);
      if (start !== offset && (ch === 95 || ch === 45)) {
        break;
      } else if (isLowerAsciiLetter(ch) && isUpperAsciiLetter(lastCh)) {
        break;
      }
      lastCh = ch;
    }
    start += 1;
    for (; end < word2.length; end++) {
      const ch = word2.charCodeAt(end);
      if (isUpperAsciiLetter(ch) && isLowerAsciiLetter(lastCh)) {
        break;
      } else if (ch === 95 || ch === 45) {
        break;
      }
      lastCh = ch;
    }
    if (start < end) {
      bucket.push({ range: new Range$2(pos.lineNumber, startColumn + start, pos.lineNumber, startColumn + end) });
    }
  }
  _addWordRanges(bucket, model, pos) {
    const word2 = model.getWordAtPosition(pos);
    if (word2) {
      bucket.push({ range: new Range$2(pos.lineNumber, word2.startColumn, pos.lineNumber, word2.endColumn) });
    }
  }
  _addWhitespaceLine(bucket, model, pos) {
    if (model.getLineLength(pos.lineNumber) > 0 && model.getLineFirstNonWhitespaceColumn(pos.lineNumber) === 0 && model.getLineLastNonWhitespaceColumn(pos.lineNumber) === 0) {
      bucket.push({ range: new Range$2(pos.lineNumber, 1, pos.lineNumber, model.getLineMaxColumn(pos.lineNumber)) });
    }
  }
}
var __decorate$I = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$G = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$q = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class SelectionRanges {
  constructor(index, ranges) {
    this.index = index;
    this.ranges = ranges;
  }
  mov(fwd) {
    const index = this.index + (fwd ? 1 : -1);
    if (index < 0 || index >= this.ranges.length) {
      return this;
    }
    const res = new SelectionRanges(index, this.ranges);
    if (res.ranges[index].equalsRange(this.ranges[this.index])) {
      return res.mov(fwd);
    }
    return res;
  }
}
let SmartSelectController = class SmartSelectController2 {
  static get(editor2) {
    return editor2.getContribution(SmartSelectController2.ID);
  }
  constructor(_editor, _languageFeaturesService) {
    this._editor = _editor;
    this._languageFeaturesService = _languageFeaturesService;
    this._ignoreSelection = false;
  }
  dispose() {
    var _a2;
    (_a2 = this._selectionListener) === null || _a2 === void 0 ? void 0 : _a2.dispose();
  }
  run(forward) {
    return __awaiter$q(this, void 0, void 0, function* () {
      if (!this._editor.hasModel()) {
        return;
      }
      const selections2 = this._editor.getSelections();
      const model = this._editor.getModel();
      if (!this._state) {
        yield provideSelectionRanges(this._languageFeaturesService.selectionRangeProvider, model, selections2.map((s) => s.getPosition()), this._editor.getOption(
          111
          /* EditorOption.smartSelect */
        ), CancellationToken.None).then((ranges) => {
          var _a2;
          if (!isNonEmptyArray(ranges) || ranges.length !== selections2.length) {
            return;
          }
          if (!this._editor.hasModel() || !equals$3(this._editor.getSelections(), selections2, (a, b) => a.equalsSelection(b))) {
            return;
          }
          for (let i = 0; i < ranges.length; i++) {
            ranges[i] = ranges[i].filter((range2) => {
              return range2.containsPosition(selections2[i].getStartPosition()) && range2.containsPosition(selections2[i].getEndPosition());
            });
            ranges[i].unshift(selections2[i]);
          }
          this._state = ranges.map((ranges2) => new SelectionRanges(0, ranges2));
          (_a2 = this._selectionListener) === null || _a2 === void 0 ? void 0 : _a2.dispose();
          this._selectionListener = this._editor.onDidChangeCursorPosition(() => {
            var _a3;
            if (!this._ignoreSelection) {
              (_a3 = this._selectionListener) === null || _a3 === void 0 ? void 0 : _a3.dispose();
              this._state = void 0;
            }
          });
        });
      }
      if (!this._state) {
        return;
      }
      this._state = this._state.map((state) => state.mov(forward));
      const newSelections = this._state.map((state) => Selection$1.fromPositions(state.ranges[state.index].getStartPosition(), state.ranges[state.index].getEndPosition()));
      this._ignoreSelection = true;
      try {
        this._editor.setSelections(newSelections);
      } finally {
        this._ignoreSelection = false;
      }
    });
  }
};
SmartSelectController.ID = "editor.contrib.smartSelectController";
SmartSelectController = __decorate$I([
  __param$G(1, ILanguageFeaturesService)
], SmartSelectController);
class AbstractSmartSelect extends EditorAction {
  constructor(forward, opts) {
    super(opts);
    this._forward = forward;
  }
  run(_accessor, editor2) {
    return __awaiter$q(this, void 0, void 0, function* () {
      const controller = SmartSelectController.get(editor2);
      if (controller) {
        yield controller.run(this._forward);
      }
    });
  }
}
class GrowSelectionAction extends AbstractSmartSelect {
  constructor() {
    super(true, {
      id: "editor.action.smartSelect.expand",
      label: localize("smartSelect.expand", "Expand Selection"),
      alias: "Expand Selection",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 1024 | 512 | 17,
        mac: {
          primary: 2048 | 256 | 1024 | 17,
          secondary: [
            256 | 1024 | 17
            /* KeyCode.RightArrow */
          ]
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: MenuId.MenubarSelectionMenu,
        group: "1_basic",
        title: localize({ key: "miSmartSelectGrow", comment: ["&& denotes a mnemonic"] }, "&&Expand Selection"),
        order: 2
      }
    });
  }
}
CommandsRegistry.registerCommandAlias("editor.action.smartSelect.grow", "editor.action.smartSelect.expand");
class ShrinkSelectionAction extends AbstractSmartSelect {
  constructor() {
    super(false, {
      id: "editor.action.smartSelect.shrink",
      label: localize("smartSelect.shrink", "Shrink Selection"),
      alias: "Shrink Selection",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 1024 | 512 | 15,
        mac: {
          primary: 2048 | 256 | 1024 | 15,
          secondary: [
            256 | 1024 | 15
            /* KeyCode.LeftArrow */
          ]
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      menuOpts: {
        menuId: MenuId.MenubarSelectionMenu,
        group: "1_basic",
        title: localize({ key: "miSmartSelectShrink", comment: ["&& denotes a mnemonic"] }, "&&Shrink Selection"),
        order: 3
      }
    });
  }
}
registerEditorContribution(
  SmartSelectController.ID,
  SmartSelectController,
  4
  /* EditorContributionInstantiation.Lazy */
);
registerEditorAction(GrowSelectionAction);
registerEditorAction(ShrinkSelectionAction);
function provideSelectionRanges(registry, model, positions, options, token) {
  return __awaiter$q(this, void 0, void 0, function* () {
    const providers = registry.all(model).concat(new WordSelectionRangeProvider(options.selectSubwords));
    if (providers.length === 1) {
      providers.unshift(new BracketSelectionRangeProvider());
    }
    const work = [];
    const allRawRanges = [];
    for (const provider of providers) {
      work.push(Promise.resolve(provider.provideSelectionRanges(model, positions, token)).then((allProviderRanges) => {
        if (isNonEmptyArray(allProviderRanges) && allProviderRanges.length === positions.length) {
          for (let i = 0; i < positions.length; i++) {
            if (!allRawRanges[i]) {
              allRawRanges[i] = [];
            }
            for (const oneProviderRanges of allProviderRanges[i]) {
              if (Range$2.isIRange(oneProviderRanges.range) && Range$2.containsPosition(oneProviderRanges.range, positions[i])) {
                allRawRanges[i].push(Range$2.lift(oneProviderRanges.range));
              }
            }
          }
        }
      }, onUnexpectedExternalError));
    }
    yield Promise.all(work);
    return allRawRanges.map((oneRawRanges) => {
      if (oneRawRanges.length === 0) {
        return [];
      }
      oneRawRanges.sort((a, b) => {
        if (Position$2.isBefore(a.getStartPosition(), b.getStartPosition())) {
          return 1;
        } else if (Position$2.isBefore(b.getStartPosition(), a.getStartPosition())) {
          return -1;
        } else if (Position$2.isBefore(a.getEndPosition(), b.getEndPosition())) {
          return -1;
        } else if (Position$2.isBefore(b.getEndPosition(), a.getEndPosition())) {
          return 1;
        } else {
          return 0;
        }
      });
      const oneRanges = [];
      let last2;
      for (const range2 of oneRawRanges) {
        if (!last2 || Range$2.containsRange(range2, last2) && !Range$2.equalsRange(range2, last2)) {
          oneRanges.push(range2);
          last2 = range2;
        }
      }
      if (!options.selectLeadingAndTrailingWhitespace) {
        return oneRanges;
      }
      const oneRangesWithTrivia = [oneRanges[0]];
      for (let i = 1; i < oneRanges.length; i++) {
        const prev = oneRanges[i - 1];
        const cur = oneRanges[i];
        if (cur.startLineNumber !== prev.startLineNumber || cur.endLineNumber !== prev.endLineNumber) {
          const rangeNoWhitespace = new Range$2(prev.startLineNumber, model.getLineFirstNonWhitespaceColumn(prev.startLineNumber), prev.endLineNumber, model.getLineLastNonWhitespaceColumn(prev.endLineNumber));
          if (rangeNoWhitespace.containsRange(prev) && !rangeNoWhitespace.equalsRange(prev) && cur.containsRange(rangeNoWhitespace) && !cur.equalsRange(rangeNoWhitespace)) {
            oneRangesWithTrivia.push(rangeNoWhitespace);
          }
          const rangeFull = new Range$2(prev.startLineNumber, 1, prev.endLineNumber, model.getLineMaxColumn(prev.endLineNumber));
          if (rangeFull.containsRange(prev) && !rangeFull.equalsRange(rangeNoWhitespace) && cur.containsRange(rangeFull) && !cur.equalsRange(rangeFull)) {
            oneRangesWithTrivia.push(rangeFull);
          }
        }
        oneRangesWithTrivia.push(cur);
      }
      return oneRangesWithTrivia;
    });
  });
}
CommandsRegistry.registerCommand("_executeSelectionRangeProvider", function(accessor, ...args) {
  return __awaiter$q(this, void 0, void 0, function* () {
    const [resource, positions] = args;
    assertType(URI.isUri(resource));
    const registry = accessor.get(ILanguageFeaturesService).selectionRangeProvider;
    const reference = yield accessor.get(ITextModelService).createModelReference(resource);
    try {
      return provideSelectionRanges(registry, reference.object.textEditorModel, positions, { selectLeadingAndTrailingWhitespace: true, selectSubwords: true }, CancellationToken.None);
    } finally {
      reference.dispose();
    }
  });
});
const Categories = Object.freeze({
  View: { value: localize("view", "View"), original: "View" },
  Help: { value: localize("help", "Help"), original: "Help" },
  Test: { value: localize("test", "Test"), original: "Test" },
  File: { value: localize("file", "File"), original: "File" },
  Preferences: { value: localize("preferences", "Preferences"), original: "Preferences" },
  Developer: { value: localize({ key: "developer", comment: ["A developer on Code itself or someone diagnosing issues in Code"] }, "Developer"), original: "Developer" }
});
const stickyScroll = "";
class StickyScrollWidgetState {
  constructor(lineNumbers2, lastLineRelativePosition) {
    this.lineNumbers = lineNumbers2;
    this.lastLineRelativePosition = lastLineRelativePosition;
  }
}
const _ttPolicy = createTrustedTypesPolicy("stickyScrollViewLayer", { createHTML: (value) => value });
class StickyScrollWidget extends Disposable {
  constructor(_editor) {
    super();
    this._editor = _editor;
    this._rootDomNode = document.createElement("div");
    this._disposableStore = this._register(new DisposableStore());
    this._lineNumbers = [];
    this._lastLineRelativePosition = 0;
    this._hoverOnLine = -1;
    this._hoverOnColumn = -1;
    this._layoutInfo = this._editor.getLayoutInfo();
    this._rootDomNode = document.createElement("div");
    this._rootDomNode.className = "sticky-widget";
    this._rootDomNode.classList.toggle("peek", _editor instanceof EmbeddedCodeEditorWidget);
    this._rootDomNode.style.width = `${this._layoutInfo.width - this._layoutInfo.minimap.minimapCanvasOuterWidth - this._layoutInfo.verticalScrollbarWidth}px`;
  }
  get hoverOnLine() {
    return this._hoverOnLine;
  }
  get hoverOnColumn() {
    return this._hoverOnColumn;
  }
  get lineNumbers() {
    return this._lineNumbers;
  }
  getCurrentLines() {
    return this._lineNumbers;
  }
  setState(state) {
    clearNode(this._rootDomNode);
    this._disposableStore.clear();
    this._lineNumbers.length = 0;
    const editorLineHeight = this._editor.getOption(
      65
      /* EditorOption.lineHeight */
    );
    const futureWidgetHeight = state.lineNumbers.length * editorLineHeight + state.lastLineRelativePosition;
    if (futureWidgetHeight > 0) {
      this._lastLineRelativePosition = state.lastLineRelativePosition;
      this._lineNumbers = state.lineNumbers;
    } else {
      this._lastLineRelativePosition = 0;
      this._lineNumbers = [];
    }
    this._renderRootNode();
  }
  _renderRootNode() {
    if (!this._editor._getViewModel()) {
      return;
    }
    for (const [index, line] of this._lineNumbers.entries()) {
      const childNode = this._renderChildNode(index, line);
      this._rootDomNode.appendChild(childNode);
    }
    const editorLineHeight = this._editor.getOption(
      65
      /* EditorOption.lineHeight */
    );
    const widgetHeight = this._lineNumbers.length * editorLineHeight + this._lastLineRelativePosition;
    this._rootDomNode.style.display = widgetHeight > 0 ? "block" : "none";
    this._rootDomNode.style.height = widgetHeight.toString() + "px";
    this._rootDomNode.setAttribute("role", "list");
    const minimapSide = this._editor.getOption(
      71
      /* EditorOption.minimap */
    ).side;
    if (minimapSide === "left") {
      this._rootDomNode.style.marginLeft = this._editor.getLayoutInfo().minimap.minimapCanvasOuterWidth + "px";
    }
  }
  _renderChildNode(index, line) {
    const child = document.createElement("div");
    const viewModel = this._editor._getViewModel();
    const viewLineNumber = viewModel.coordinatesConverter.convertModelPositionToViewPosition(new Position$2(line, 1)).lineNumber;
    const lineRenderingData = viewModel.getViewLineRenderingData(viewLineNumber);
    const layoutInfo = this._editor.getLayoutInfo();
    const width = layoutInfo.width - layoutInfo.minimap.minimapCanvasOuterWidth - layoutInfo.verticalScrollbarWidth;
    const minimapSide = this._editor.getOption(
      71
      /* EditorOption.minimap */
    ).side;
    const lineHeight = this._editor.getOption(
      65
      /* EditorOption.lineHeight */
    );
    const lineNumberOption = this._editor.getOption(
      66
      /* EditorOption.lineNumbers */
    );
    let actualInlineDecorations;
    try {
      actualInlineDecorations = LineDecoration.filter(lineRenderingData.inlineDecorations, viewLineNumber, lineRenderingData.minColumn, lineRenderingData.maxColumn);
    } catch (err) {
      actualInlineDecorations = [];
    }
    const renderLineInput = new RenderLineInput(true, true, lineRenderingData.content, lineRenderingData.continuesWithWrappedLine, lineRenderingData.isBasicASCII, lineRenderingData.containsRTL, 0, lineRenderingData.tokens, actualInlineDecorations, lineRenderingData.tabSize, lineRenderingData.startVisibleColumn, 1, 1, 1, 500, "none", true, true, null);
    const sb = new StringBuilder(2e3);
    renderViewLine(renderLineInput, sb);
    let newLine;
    if (_ttPolicy) {
      newLine = _ttPolicy.createHTML(sb.build());
    } else {
      newLine = sb.build();
    }
    const lineHTMLNode = document.createElement("span");
    lineHTMLNode.className = "sticky-line";
    lineHTMLNode.classList.add(`stickyLine${line}`);
    lineHTMLNode.style.lineHeight = `${lineHeight}px`;
    lineHTMLNode.innerHTML = newLine;
    const lineNumberHTMLNode = document.createElement("span");
    lineNumberHTMLNode.className = "sticky-line";
    lineNumberHTMLNode.style.lineHeight = `${lineHeight}px`;
    if (minimapSide === "left") {
      lineNumberHTMLNode.style.width = `${layoutInfo.contentLeft - layoutInfo.minimap.minimapCanvasOuterWidth}px`;
    } else if (minimapSide === "right") {
      lineNumberHTMLNode.style.width = `${layoutInfo.contentLeft}px`;
    }
    const innerLineNumberHTML = document.createElement("span");
    if (lineNumberOption.renderType === 1 || lineNumberOption.renderType === 3 && line % 10 === 0) {
      innerLineNumberHTML.innerText = line.toString();
    } else if (lineNumberOption.renderType === 2) {
      innerLineNumberHTML.innerText = Math.abs(line - this._editor.getPosition().lineNumber).toString();
    }
    innerLineNumberHTML.className = "sticky-line-number";
    innerLineNumberHTML.style.lineHeight = `${lineHeight}px`;
    innerLineNumberHTML.style.width = `${layoutInfo.lineNumbersWidth}px`;
    if (minimapSide === "left") {
      innerLineNumberHTML.style.paddingLeft = `${layoutInfo.lineNumbersLeft - layoutInfo.minimap.minimapCanvasOuterWidth}px`;
    } else if (minimapSide === "right") {
      innerLineNumberHTML.style.paddingLeft = `${layoutInfo.lineNumbersLeft}px`;
    }
    lineNumberHTMLNode.appendChild(innerLineNumberHTML);
    this._editor.applyFontInfo(lineHTMLNode);
    this._editor.applyFontInfo(innerLineNumberHTML);
    child.appendChild(lineNumberHTMLNode);
    child.appendChild(lineHTMLNode);
    child.className = "sticky-line-root";
    child.setAttribute("role", "listitem");
    child.tabIndex = 0;
    child.style.lineHeight = `${lineHeight}px`;
    child.style.width = `${width}px`;
    child.style.height = `${lineHeight}px`;
    child.style.zIndex = "0";
    if (index === this._lineNumbers.length - 1) {
      child.style.position = "relative";
      child.style.zIndex = "-1";
      child.style.top = this._lastLineRelativePosition + "px";
    }
    this._disposableStore.add(addDisposableListener(child, "mouseover", (e) => {
      if (this._editor.hasModel()) {
        const mouseOverEvent = new StandardMouseEvent(e);
        const text2 = mouseOverEvent.target.innerText;
        this._hoverOnLine = line;
        this._hoverOnColumn = this._editor.getModel().getLineContent(line).indexOf(text2) + 1 || -1;
      }
    }));
    return child;
  }
  getId() {
    return "editor.contrib.stickyScrollWidget";
  }
  getDomNode() {
    return this._rootDomNode;
  }
  getPosition() {
    return {
      preference: null
    };
  }
}
class StickyRange {
  constructor(startLineNumber, endLineNumber) {
    this.startLineNumber = startLineNumber;
    this.endLineNumber = endLineNumber;
  }
}
class StickyElement {
  constructor(range2, children, parent) {
    this.range = range2;
    this.children = children;
    this.parent = parent;
  }
}
class StickyModel {
  constructor(uri, version2, element, outlineProviderId) {
    this.uri = uri;
    this.version = version2;
    this.element = element;
    this.outlineProviderId = outlineProviderId;
  }
}
var __decorate$H = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$F = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$p = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var ModelProvider;
(function(ModelProvider2) {
  ModelProvider2["OUTLINE_MODEL"] = "outlineModel";
  ModelProvider2["FOLDING_PROVIDER_MODEL"] = "foldingProviderModel";
  ModelProvider2["INDENTATION_MODEL"] = "indentationModel";
})(ModelProvider || (ModelProvider = {}));
var Status;
(function(Status2) {
  Status2[Status2["VALID"] = 0] = "VALID";
  Status2[Status2["INVALID"] = 1] = "INVALID";
  Status2[Status2["CANCELED"] = 2] = "CANCELED";
})(Status || (Status = {}));
let StickyModelProvider = class StickyModelProvider2 {
  constructor(_editor, _languageConfigurationService, _languageFeaturesService, defaultModel) {
    this._editor = _editor;
    this._languageConfigurationService = _languageConfigurationService;
    this._languageFeaturesService = _languageFeaturesService;
    this._modelProviders = [];
    this._modelPromise = null;
    this._updateScheduler = new Delayer(300);
    const stickyModelFromCandidateOutlineProvider = new StickyModelFromCandidateOutlineProvider(_languageFeaturesService);
    const stickyModelFromSyntaxFoldingProvider = new StickyModelFromCandidateSyntaxFoldingProvider(this._editor, _languageFeaturesService);
    const stickyModelFromIndentationFoldingProvider = new StickyModelFromCandidateIndentationFoldingProvider(this._editor, _languageConfigurationService);
    switch (defaultModel) {
      case ModelProvider.OUTLINE_MODEL:
        this._modelProviders.push(stickyModelFromCandidateOutlineProvider);
        this._modelProviders.push(stickyModelFromSyntaxFoldingProvider);
        this._modelProviders.push(stickyModelFromIndentationFoldingProvider);
        break;
      case ModelProvider.FOLDING_PROVIDER_MODEL:
        this._modelProviders.push(stickyModelFromSyntaxFoldingProvider);
        this._modelProviders.push(stickyModelFromIndentationFoldingProvider);
        break;
      case ModelProvider.INDENTATION_MODEL:
        this._modelProviders.push(stickyModelFromIndentationFoldingProvider);
        break;
    }
    this._store = new DisposableStore();
  }
  _cancelModelPromise() {
    if (this._modelPromise) {
      this._modelPromise.cancel();
      this._modelPromise = null;
    }
  }
  update(textModel, textModelVersionId, token) {
    return __awaiter$p(this, void 0, void 0, function* () {
      this._store.clear();
      this._store.add({
        dispose: () => {
          var _a2;
          this._cancelModelPromise();
          (_a2 = this._updateScheduler) === null || _a2 === void 0 ? void 0 : _a2.cancel();
        }
      });
      this._cancelModelPromise();
      return yield this._updateScheduler.trigger(() => __awaiter$p(this, void 0, void 0, function* () {
        for (const modelProvider of this._modelProviders) {
          const { statusPromise, modelPromise } = modelProvider.computeStickyModel(textModel, textModelVersionId, token);
          this._modelPromise = modelPromise;
          const status2 = yield statusPromise;
          if (this._modelPromise !== modelPromise) {
            return null;
          }
          switch (status2) {
            case Status.CANCELED:
              this._store.clear();
              return null;
            case Status.VALID:
              return modelProvider.stickyModel;
          }
        }
        return null;
      }));
    });
  }
};
StickyModelProvider = __decorate$H([
  __param$F(1, ILanguageConfigurationService),
  __param$F(2, ILanguageFeaturesService)
], StickyModelProvider);
class StickyModelCandidateProvider {
  constructor() {
    this._stickyModel = null;
  }
  get stickyModel() {
    return this._stickyModel;
  }
  _invalid() {
    this._stickyModel = null;
    return Status.INVALID;
  }
  computeStickyModel(textModel, modelVersionId, token) {
    if (token.isCancellationRequested || !this.isProviderValid(textModel)) {
      return { statusPromise: this._invalid(), modelPromise: null };
    }
    const providerModelPromise = createCancelablePromise((token2) => this.createModelFromProvider(textModel, modelVersionId, token2));
    return {
      statusPromise: providerModelPromise.then((providerModel) => {
        if (!this.isModelValid(providerModel)) {
          return this._invalid();
        }
        if (token.isCancellationRequested) {
          return Status.CANCELED;
        }
        this._stickyModel = this.createStickyModel(textModel, modelVersionId, token, providerModel);
        return Status.VALID;
      }).then(void 0, (err) => {
        onUnexpectedError(err);
        return Status.CANCELED;
      }),
      modelPromise: providerModelPromise
    };
  }
  /**
   * Method which checks whether the model returned by the provider is valid and can be used to compute a sticky model.
   * This method by default returns true.
   * @param model model returned by the provider
   * @returns boolean indicating whether the model is valid
   */
  isModelValid(model) {
    return true;
  }
  /**
   * Method which checks whether the provider is valid before applying it to find the provider model.
   * This method by default returns true.
   * @param textModel text-model of the editor
   * @returns boolean indicating whether the provider is valid
   */
  isProviderValid(textModel) {
    return true;
  }
}
let StickyModelFromCandidateOutlineProvider = class StickyModelFromCandidateOutlineProvider2 extends StickyModelCandidateProvider {
  constructor(_languageFeaturesService) {
    super();
    this._languageFeaturesService = _languageFeaturesService;
  }
  createModelFromProvider(textModel, modelVersionId, token) {
    return OutlineModel.create(this._languageFeaturesService.documentSymbolProvider, textModel, token);
  }
  createStickyModel(textModel, modelVersionId, token, model) {
    var _a2;
    const { stickyOutlineElement, providerID } = this._stickyModelFromOutlineModel(model, (_a2 = this._stickyModel) === null || _a2 === void 0 ? void 0 : _a2.outlineProviderId);
    return new StickyModel(textModel.uri, modelVersionId, stickyOutlineElement, providerID);
  }
  isModelValid(model) {
    return model && model.children.size > 0;
  }
  _stickyModelFromOutlineModel(outlineModel, preferredProvider) {
    let outlineElements;
    if (Iterable.first(outlineModel.children.values()) instanceof OutlineGroup) {
      const provider = Iterable.find(outlineModel.children.values(), (outlineGroupOfModel) => outlineGroupOfModel.id === preferredProvider);
      if (provider) {
        outlineElements = provider.children;
      } else {
        let tempID = "";
        let maxTotalSumOfRanges = -1;
        let optimalOutlineGroup = void 0;
        for (const [_key, outlineGroup] of outlineModel.children.entries()) {
          const totalSumRanges = this._findSumOfRangesOfGroup(outlineGroup);
          if (totalSumRanges > maxTotalSumOfRanges) {
            optimalOutlineGroup = outlineGroup;
            maxTotalSumOfRanges = totalSumRanges;
            tempID = outlineGroup.id;
          }
        }
        preferredProvider = tempID;
        outlineElements = optimalOutlineGroup.children;
      }
    } else {
      outlineElements = outlineModel.children;
    }
    const stickyChildren = [];
    const outlineElementsArray = Array.from(outlineElements.values()).sort((element1, element2) => {
      const range1 = new StickyRange(element1.symbol.range.startLineNumber, element1.symbol.range.endLineNumber);
      const range2 = new StickyRange(element2.symbol.range.startLineNumber, element2.symbol.range.endLineNumber);
      return this._comparator(range1, range2);
    });
    for (const outlineElement of outlineElementsArray) {
      stickyChildren.push(this._stickyModelFromOutlineElement(outlineElement, outlineElement.symbol.selectionRange.startLineNumber));
    }
    const stickyOutlineElement = new StickyElement(void 0, stickyChildren, void 0);
    return {
      stickyOutlineElement,
      providerID: preferredProvider
    };
  }
  _stickyModelFromOutlineElement(outlineElement, previousStartLine) {
    const children = [];
    for (const child of outlineElement.children.values()) {
      if (child.symbol.selectionRange.startLineNumber !== child.symbol.range.endLineNumber) {
        if (child.symbol.selectionRange.startLineNumber !== previousStartLine) {
          children.push(this._stickyModelFromOutlineElement(child, child.symbol.selectionRange.startLineNumber));
        } else {
          for (const subchild of child.children.values()) {
            children.push(this._stickyModelFromOutlineElement(subchild, child.symbol.selectionRange.startLineNumber));
          }
        }
      }
    }
    children.sort((child1, child2) => this._comparator(child1.range, child2.range));
    const range2 = new StickyRange(outlineElement.symbol.selectionRange.startLineNumber, outlineElement.symbol.range.endLineNumber);
    return new StickyElement(range2, children, void 0);
  }
  _comparator(range1, range2) {
    if (range1.startLineNumber !== range2.startLineNumber) {
      return range1.startLineNumber - range2.startLineNumber;
    } else {
      return range2.endLineNumber - range1.endLineNumber;
    }
  }
  _findSumOfRangesOfGroup(outline) {
    let res = 0;
    for (const child of outline.children.values()) {
      res += this._findSumOfRangesOfGroup(child);
    }
    if (outline instanceof OutlineElement) {
      return res + outline.symbol.range.endLineNumber - outline.symbol.selectionRange.startLineNumber;
    } else {
      return res;
    }
  }
};
StickyModelFromCandidateOutlineProvider = __decorate$H([
  __param$F(0, ILanguageFeaturesService)
], StickyModelFromCandidateOutlineProvider);
class StickyModelFromCandidateFoldingProvider extends StickyModelCandidateProvider {
  constructor(editor2) {
    super();
    this._foldingLimitReporter = new RangesLimitReporter(editor2);
  }
  createStickyModel(textModel, modelVersionId, token, model) {
    const foldingElement = this._fromFoldingRegions(model);
    return new StickyModel(textModel.uri, modelVersionId, foldingElement, void 0);
  }
  isModelValid(model) {
    return model !== null;
  }
  _fromFoldingRegions(foldingRegions) {
    const length2 = foldingRegions.length;
    const orderedStickyElements = [];
    const stickyOutlineElement = new StickyElement(void 0, [], void 0);
    for (let i = 0; i < length2; i++) {
      const parentIndex = foldingRegions.getParentIndex(i);
      let parentNode;
      if (parentIndex !== -1) {
        parentNode = orderedStickyElements[parentIndex];
      } else {
        parentNode = stickyOutlineElement;
      }
      const child = new StickyElement(new StickyRange(foldingRegions.getStartLineNumber(i), foldingRegions.getEndLineNumber(i) + 1), [], parentNode);
      parentNode.children.push(child);
      orderedStickyElements.push(child);
    }
    return stickyOutlineElement;
  }
}
let StickyModelFromCandidateIndentationFoldingProvider = class StickyModelFromCandidateIndentationFoldingProvider2 extends StickyModelFromCandidateFoldingProvider {
  constructor(editor2, _languageConfigurationService) {
    super(editor2);
    this._languageConfigurationService = _languageConfigurationService;
  }
  createModelFromProvider(textModel, modelVersionId, token) {
    const provider = new IndentRangeProvider(textModel, this._languageConfigurationService, this._foldingLimitReporter);
    return provider.compute(token);
  }
};
StickyModelFromCandidateIndentationFoldingProvider = __decorate$H([
  __param$F(1, ILanguageConfigurationService)
], StickyModelFromCandidateIndentationFoldingProvider);
let StickyModelFromCandidateSyntaxFoldingProvider = class StickyModelFromCandidateSyntaxFoldingProvider2 extends StickyModelFromCandidateFoldingProvider {
  constructor(editor2, _languageFeaturesService) {
    super(editor2);
    this._languageFeaturesService = _languageFeaturesService;
  }
  isProviderValid(textModel) {
    const selectedProviders = FoldingController.getFoldingRangeProviders(this._languageFeaturesService, textModel);
    return selectedProviders.length > 0;
  }
  createModelFromProvider(textModel, modelVersionId, token) {
    const selectedProviders = FoldingController.getFoldingRangeProviders(this._languageFeaturesService, textModel);
    const provider = new SyntaxRangeProvider(textModel, selectedProviders, () => this.createModelFromProvider(textModel, modelVersionId, token), this._foldingLimitReporter, void 0);
    return provider.compute(token);
  }
};
StickyModelFromCandidateSyntaxFoldingProvider = __decorate$H([
  __param$F(1, ILanguageFeaturesService)
], StickyModelFromCandidateSyntaxFoldingProvider);
var __decorate$G = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$E = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$o = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class StickyLineCandidate {
  constructor(startLineNumber, endLineNumber, nestingDepth) {
    this.startLineNumber = startLineNumber;
    this.endLineNumber = endLineNumber;
    this.nestingDepth = nestingDepth;
  }
}
let StickyLineCandidateProvider = class StickyLineCandidateProvider2 extends Disposable {
  constructor(editor2, _languageFeaturesService, _languageConfigurationService) {
    super();
    this._languageFeaturesService = _languageFeaturesService;
    this._languageConfigurationService = _languageConfigurationService;
    this._onDidChangeStickyScroll = this._store.add(new Emitter$1());
    this.onDidChangeStickyScroll = this._onDidChangeStickyScroll.event;
    this._options = null;
    this._model = null;
    this._cts = null;
    this._stickyModelProvider = null;
    this._editor = editor2;
    this._sessionStore = new DisposableStore();
    this._updateSoon = this._register(new RunOnceScheduler(() => this.update(), 50));
    this._register(this._editor.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        113
        /* EditorOption.stickyScroll */
      )) {
        this.readConfiguration();
      }
    }));
    this.readConfiguration();
  }
  dispose() {
    super.dispose();
    this._sessionStore.dispose();
  }
  readConfiguration() {
    this._options = this._editor.getOption(
      113
      /* EditorOption.stickyScroll */
    );
    if (!this._options.enabled) {
      this._sessionStore.clear();
      return;
    }
    this._stickyModelProvider = new StickyModelProvider(this._editor, this._languageConfigurationService, this._languageFeaturesService, this._options.defaultModel);
    this._sessionStore.add(this._editor.onDidChangeModel(() => this.update()));
    this._sessionStore.add(this._editor.onDidChangeHiddenAreas(() => this.update()));
    this._sessionStore.add(this._editor.onDidChangeModelContent(() => this._updateSoon.schedule()));
    this._sessionStore.add(this._languageFeaturesService.documentSymbolProvider.onDidChange(() => this.update()));
    this.update();
  }
  getVersionId() {
    var _a2;
    return (_a2 = this._model) === null || _a2 === void 0 ? void 0 : _a2.version;
  }
  update() {
    var _a2;
    return __awaiter$o(this, void 0, void 0, function* () {
      (_a2 = this._cts) === null || _a2 === void 0 ? void 0 : _a2.dispose(true);
      this._cts = new CancellationTokenSource$1();
      yield this.updateStickyModel(this._cts.token);
      this._onDidChangeStickyScroll.fire();
    });
  }
  updateStickyModel(token) {
    return __awaiter$o(this, void 0, void 0, function* () {
      if (!this._editor.hasModel() || !this._stickyModelProvider) {
        return;
      }
      const textModel = this._editor.getModel();
      const modelVersionId = textModel.getVersionId();
      const isDifferentModel = this._model ? !isEqual(this._model.uri, textModel.uri) : false;
      const resetHandle = isDifferentModel ? setTimeout(() => {
        if (!token.isCancellationRequested) {
          this._model = new StickyModel(textModel.uri, textModel.getVersionId(), void 0, void 0);
          this._onDidChangeStickyScroll.fire();
        }
      }, 75) : void 0;
      this._model = yield this._stickyModelProvider.update(textModel, modelVersionId, token);
      clearTimeout(resetHandle);
    });
  }
  updateIndex(index) {
    if (index === -1) {
      index = 0;
    } else if (index < 0) {
      index = -index - 2;
    }
    return index;
  }
  getCandidateStickyLinesIntersectingFromStickyModel(range2, outlineModel, result2, depth, lastStartLineNumber) {
    if (outlineModel.children.length === 0) {
      return;
    }
    let lastLine = lastStartLineNumber;
    const childrenStartLines = [];
    for (let i = 0; i < outlineModel.children.length; i++) {
      const child = outlineModel.children[i];
      if (child.range) {
        childrenStartLines.push(child.range.startLineNumber);
      }
    }
    const lowerBound = this.updateIndex(binarySearch$4(childrenStartLines, range2.startLineNumber, (a, b) => {
      return a - b;
    }));
    const upperBound = this.updateIndex(binarySearch$4(childrenStartLines, range2.startLineNumber + depth, (a, b) => {
      return a - b;
    }));
    for (let i = lowerBound; i <= upperBound; i++) {
      const child = outlineModel.children[i];
      if (!child) {
        return;
      }
      if (child.range) {
        const childStartLine = child.range.startLineNumber;
        const childEndLine = child.range.endLineNumber;
        if (range2.startLineNumber <= childEndLine + 1 && childStartLine - 1 <= range2.endLineNumber && childStartLine !== lastLine) {
          lastLine = childStartLine;
          result2.push(new StickyLineCandidate(childStartLine, childEndLine - 1, depth + 1));
          this.getCandidateStickyLinesIntersectingFromStickyModel(range2, child, result2, depth + 1, childStartLine);
        }
      } else {
        this.getCandidateStickyLinesIntersectingFromStickyModel(range2, child, result2, depth, lastStartLineNumber);
      }
    }
  }
  getCandidateStickyLinesIntersecting(range2) {
    var _a2, _b2;
    if (!((_a2 = this._model) === null || _a2 === void 0 ? void 0 : _a2.element)) {
      return [];
    }
    let stickyLineCandidates = [];
    this.getCandidateStickyLinesIntersectingFromStickyModel(range2, this._model.element, stickyLineCandidates, 0, -1);
    const hiddenRanges = (_b2 = this._editor._getViewModel()) === null || _b2 === void 0 ? void 0 : _b2.getHiddenAreas();
    if (hiddenRanges) {
      for (const hiddenRange of hiddenRanges) {
        stickyLineCandidates = stickyLineCandidates.filter((stickyLine) => !(stickyLine.startLineNumber >= hiddenRange.startLineNumber && stickyLine.endLineNumber <= hiddenRange.endLineNumber + 1));
      }
    }
    return stickyLineCandidates;
  }
};
StickyLineCandidateProvider = __decorate$G([
  __param$E(1, ILanguageFeaturesService),
  __param$E(2, ILanguageConfigurationService)
], StickyLineCandidateProvider);
var __decorate$F = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$D = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$n = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
let StickyScrollController = class StickyScrollController2 extends Disposable {
  constructor(_editor, _contextMenuService, _languageFeaturesService, _instaService, _languageConfigurationService, _languageFeatureDebounceService, _contextKeyService) {
    super();
    this._editor = _editor;
    this._contextMenuService = _contextMenuService;
    this._languageFeaturesService = _languageFeaturesService;
    this._instaService = _instaService;
    this._contextKeyService = _contextKeyService;
    this._sessionStore = new DisposableStore();
    this._maxStickyLines = Number.MAX_SAFE_INTEGER;
    this._candidateDefinitionsLength = -1;
    this._focusedStickyElementIndex = -1;
    this._enabled = false;
    this._focused = false;
    this._positionRevealed = false;
    this._onMouseDown = false;
    this._stickyScrollWidget = new StickyScrollWidget(this._editor);
    this._stickyLineCandidateProvider = new StickyLineCandidateProvider(this._editor, _languageFeaturesService, _languageConfigurationService);
    this._register(this._stickyScrollWidget);
    this._register(this._stickyLineCandidateProvider);
    this._widgetState = new StickyScrollWidgetState([], 0);
    this._readConfiguration();
    this._register(this._editor.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        113
        /* EditorOption.stickyScroll */
      )) {
        this._readConfiguration();
      }
    }));
    this._register(addDisposableListener(this._stickyScrollWidget.getDomNode(), EventType$1.CONTEXT_MENU, (event) => __awaiter$n(this, void 0, void 0, function* () {
      this._onContextMenu(event);
    })));
    this._stickyScrollFocusedContextKey = EditorContextKeys.stickyScrollFocused.bindTo(this._contextKeyService);
    this._stickyScrollVisibleContextKey = EditorContextKeys.stickyScrollVisible.bindTo(this._contextKeyService);
    const focusTracker = this._register(trackFocus(this._stickyScrollWidget.getDomNode()));
    this._register(focusTracker.onDidBlur((_) => {
      const height = this._stickyScrollWidget.getDomNode().clientHeight;
      if (this._positionRevealed === false && height === 0) {
        this._focusedStickyElementIndex = -1;
        this.focus();
      } else {
        this._disposeFocusStickyScrollStore();
      }
    }));
    this._register(focusTracker.onDidFocus((_) => {
      this.focus();
    }));
    this._register(this._createClickLinkGesture());
    this._register(addDisposableListener(this._stickyScrollWidget.getDomNode(), EventType$1.MOUSE_DOWN, (e) => {
      this._onMouseDown = true;
    }));
  }
  static get(editor2) {
    return editor2.getContribution(StickyScrollController2.ID);
  }
  _disposeFocusStickyScrollStore() {
    var _a2;
    this._stickyScrollFocusedContextKey.set(false);
    (_a2 = this._focusDisposableStore) === null || _a2 === void 0 ? void 0 : _a2.dispose();
    this._focused = false;
    this._positionRevealed = false;
    this._onMouseDown = false;
  }
  focus() {
    if (this._onMouseDown) {
      this._onMouseDown = false;
      this._editor.focus();
      return;
    }
    const focusState = this._stickyScrollFocusedContextKey.get();
    if (focusState === true) {
      return;
    }
    this._focused = true;
    this._focusDisposableStore = new DisposableStore();
    this._stickyScrollFocusedContextKey.set(true);
    const rootNode = this._stickyScrollWidget.getDomNode();
    rootNode.lastElementChild.focus();
    this._stickyElements = rootNode.children;
    this._focusedStickyElementIndex = this._stickyScrollWidget.lineNumbers.length - 1;
  }
  focusNext() {
    if (this._focusedStickyElementIndex < this._stickyElements.length - 1) {
      this._focusNav(true);
    }
  }
  focusPrevious() {
    if (this._focusedStickyElementIndex > 0) {
      this._focusNav(false);
    }
  }
  selectEditor() {
    this._editor.focus();
  }
  // True is next, false is previous
  _focusNav(direction) {
    this._focusedStickyElementIndex = direction ? this._focusedStickyElementIndex + 1 : this._focusedStickyElementIndex - 1;
    this._stickyElements.item(this._focusedStickyElementIndex).focus();
  }
  goToFocused() {
    const lineNumbers2 = this._stickyScrollWidget.lineNumbers;
    this._disposeFocusStickyScrollStore();
    this._revealPosition({ lineNumber: lineNumbers2[this._focusedStickyElementIndex], column: 1 });
  }
  _revealPosition(position) {
    this._positionRevealed = true;
    this._editor.revealPosition(position);
    this._editor.setSelection(Range$2.fromPositions(position));
    this._editor.focus();
  }
  _createClickLinkGesture() {
    const linkGestureStore = new DisposableStore();
    const sessionStore = new DisposableStore();
    linkGestureStore.add(sessionStore);
    const gesture = new ClickLinkGesture(this._editor, true);
    linkGestureStore.add(gesture);
    linkGestureStore.add(gesture.onMouseMoveOrRelevantKeyDown(([mouseEvent, _keyboardEvent]) => {
      if (!this._editor.hasModel() || !mouseEvent.hasTriggerModifier) {
        sessionStore.clear();
        return;
      }
      const targetMouseEvent = mouseEvent.target;
      if (targetMouseEvent.detail === this._stickyScrollWidget.getId() && targetMouseEvent.element.innerText === targetMouseEvent.element.innerHTML) {
        const text2 = targetMouseEvent.element.innerText;
        if (this._stickyScrollWidget.hoverOnColumn === -1) {
          return;
        }
        const lineNumber = this._stickyScrollWidget.hoverOnLine;
        const column = this._stickyScrollWidget.hoverOnColumn;
        const stickyPositionProjectedOnEditor = new Range$2(lineNumber, column, lineNumber, column + text2.length);
        if (!stickyPositionProjectedOnEditor.equalsRange(this._stickyRangeProjectedOnEditor)) {
          this._stickyRangeProjectedOnEditor = stickyPositionProjectedOnEditor;
          sessionStore.clear();
        } else if (targetMouseEvent.element.style.textDecoration === "underline") {
          return;
        }
        const cancellationToken = new CancellationTokenSource$1();
        sessionStore.add(toDisposable(() => cancellationToken.dispose(true)));
        let currentHTMLChild;
        getDefinitionsAtPosition(this._languageFeaturesService.definitionProvider, this._editor.getModel(), new Position$2(lineNumber, column + 1), cancellationToken.token).then((candidateDefinitions) => {
          if (cancellationToken.token.isCancellationRequested) {
            return;
          }
          if (candidateDefinitions.length !== 0) {
            this._candidateDefinitionsLength = candidateDefinitions.length;
            const childHTML = targetMouseEvent.element;
            if (currentHTMLChild !== childHTML) {
              sessionStore.clear();
              currentHTMLChild = childHTML;
              currentHTMLChild.style.textDecoration = "underline";
              sessionStore.add(toDisposable(() => {
                currentHTMLChild.style.textDecoration = "none";
              }));
            } else if (!currentHTMLChild) {
              currentHTMLChild = childHTML;
              currentHTMLChild.style.textDecoration = "underline";
              sessionStore.add(toDisposable(() => {
                currentHTMLChild.style.textDecoration = "none";
              }));
            }
          } else {
            sessionStore.clear();
          }
        });
      } else {
        sessionStore.clear();
      }
    }));
    linkGestureStore.add(gesture.onCancel(() => {
      sessionStore.clear();
    }));
    linkGestureStore.add(gesture.onExecute((e) => __awaiter$n(this, void 0, void 0, function* () {
      if (e.target.detail !== this._stickyScrollWidget.getId()) {
        return;
      }
      if (e.hasTriggerModifier) {
        if (this._candidateDefinitionsLength > 1) {
          if (this._focused) {
            this._disposeFocusStickyScrollStore();
          }
          this._revealPosition({ lineNumber: this._stickyScrollWidget.hoverOnLine, column: 1 });
        }
        this._instaService.invokeFunction(goToDefinitionWithLocation, e, this._editor, { uri: this._editor.getModel().uri, range: this._stickyRangeProjectedOnEditor });
      } else if (!e.isRightClick) {
        if (this._focused) {
          this._disposeFocusStickyScrollStore();
        }
        this._revealPosition({ lineNumber: this._stickyScrollWidget.hoverOnLine, column: this._stickyScrollWidget.hoverOnColumn });
      }
    })));
    return linkGestureStore;
  }
  _onContextMenu(e) {
    const event = new StandardMouseEvent(e);
    this._contextMenuService.showContextMenu({
      menuId: MenuId.StickyScrollContext,
      getAnchor: () => event
    });
  }
  _readConfiguration() {
    const options = this._editor.getOption(
      113
      /* EditorOption.stickyScroll */
    );
    if (options.enabled === false) {
      this._editor.removeOverlayWidget(this._stickyScrollWidget);
      this._sessionStore.clear();
      this._enabled = false;
      return;
    } else if (options.enabled && !this._enabled) {
      this._editor.addOverlayWidget(this._stickyScrollWidget);
      this._sessionStore.add(this._editor.onDidScrollChange(() => this._renderStickyScroll()));
      this._sessionStore.add(this._editor.onDidLayoutChange(() => this._onDidResize()));
      this._sessionStore.add(this._editor.onDidChangeModelTokens((e) => this._onTokensChange(e)));
      this._sessionStore.add(this._stickyLineCandidateProvider.onDidChangeStickyScroll(() => this._renderStickyScroll()));
      this._enabled = true;
    }
    const lineNumberOption = this._editor.getOption(
      66
      /* EditorOption.lineNumbers */
    );
    if (lineNumberOption.renderType === 2) {
      this._sessionStore.add(this._editor.onDidChangeCursorPosition(() => this._renderStickyScroll()));
    }
  }
  _needsUpdate(event) {
    const stickyLineNumbers = this._stickyScrollWidget.getCurrentLines();
    for (const stickyLineNumber of stickyLineNumbers) {
      for (const range2 of event.ranges) {
        if (stickyLineNumber >= range2.fromLineNumber && stickyLineNumber <= range2.toLineNumber) {
          return true;
        }
      }
    }
    return false;
  }
  _onTokensChange(event) {
    if (this._needsUpdate(event)) {
      this._renderStickyScroll();
    }
  }
  _onDidResize() {
    const layoutInfo = this._editor.getLayoutInfo();
    const width = layoutInfo.width - layoutInfo.minimap.minimapCanvasOuterWidth - layoutInfo.verticalScrollbarWidth;
    this._stickyScrollWidget.getDomNode().style.width = `${width}px`;
    const theoreticalLines = layoutInfo.height / this._editor.getOption(
      65
      /* EditorOption.lineHeight */
    );
    this._maxStickyLines = Math.round(theoreticalLines * 0.25);
  }
  _renderStickyScroll() {
    if (!this._editor.hasModel()) {
      return;
    }
    const model = this._editor.getModel();
    const stickyLineVersion = this._stickyLineCandidateProvider.getVersionId();
    if (stickyLineVersion === void 0 || stickyLineVersion === model.getVersionId()) {
      this._widgetState = this.findScrollWidgetState();
      this._stickyScrollVisibleContextKey.set(!(this._widgetState.lineNumbers.length === 0));
      if (!this._focused) {
        this._stickyScrollWidget.setState(this._widgetState);
      } else {
        this._stickyElements = this._stickyScrollWidget.getDomNode().children;
        if (this._focusedStickyElementIndex === -1) {
          this._stickyScrollWidget.setState(this._widgetState);
          this._focusedStickyElementIndex = this._stickyElements.length - 1;
          if (this._focusedStickyElementIndex !== -1) {
            this._stickyElements.item(this._focusedStickyElementIndex).focus();
          }
        } else {
          const focusedStickyElementLineNumber = this._stickyScrollWidget.lineNumbers[this._focusedStickyElementIndex];
          this._stickyScrollWidget.setState(this._widgetState);
          if (this._stickyElements.length === 0) {
            this._focusedStickyElementIndex = -1;
          } else {
            const previousFocusedLineNumberExists = this._stickyScrollWidget.lineNumbers.includes(focusedStickyElementLineNumber);
            if (!previousFocusedLineNumberExists) {
              this._focusedStickyElementIndex = this._stickyElements.length - 1;
            }
            this._stickyElements.item(this._focusedStickyElementIndex).focus();
          }
        }
      }
    }
  }
  findScrollWidgetState() {
    const lineHeight = this._editor.getOption(
      65
      /* EditorOption.lineHeight */
    );
    const maxNumberStickyLines = Math.min(this._maxStickyLines, this._editor.getOption(
      113
      /* EditorOption.stickyScroll */
    ).maxLineCount);
    const scrollTop = this._editor.getScrollTop();
    let lastLineRelativePosition = 0;
    const lineNumbers2 = [];
    const arrayVisibleRanges = this._editor.getVisibleRanges();
    if (arrayVisibleRanges.length !== 0) {
      const fullVisibleRange = new StickyRange(arrayVisibleRanges[0].startLineNumber, arrayVisibleRanges[arrayVisibleRanges.length - 1].endLineNumber);
      const candidateRanges = this._stickyLineCandidateProvider.getCandidateStickyLinesIntersecting(fullVisibleRange);
      for (const range2 of candidateRanges) {
        const start = range2.startLineNumber;
        const end = range2.endLineNumber;
        const depth = range2.nestingDepth;
        if (end - start > 0) {
          const topOfElementAtDepth = (depth - 1) * lineHeight;
          const bottomOfElementAtDepth = depth * lineHeight;
          const bottomOfBeginningLine = this._editor.getBottomForLineNumber(start) - scrollTop;
          const topOfEndLine = this._editor.getTopForLineNumber(end) - scrollTop;
          const bottomOfEndLine = this._editor.getBottomForLineNumber(end) - scrollTop;
          if (topOfElementAtDepth > topOfEndLine && topOfElementAtDepth <= bottomOfEndLine) {
            lineNumbers2.push(start);
            lastLineRelativePosition = bottomOfEndLine - bottomOfElementAtDepth;
            break;
          } else if (bottomOfElementAtDepth > bottomOfBeginningLine && bottomOfElementAtDepth <= bottomOfEndLine) {
            lineNumbers2.push(start);
          }
          if (lineNumbers2.length === maxNumberStickyLines) {
            break;
          }
        }
      }
    }
    return new StickyScrollWidgetState(lineNumbers2, lastLineRelativePosition);
  }
  dispose() {
    super.dispose();
    this._sessionStore.dispose();
  }
};
StickyScrollController.ID = "store.contrib.stickyScrollController";
StickyScrollController = __decorate$F([
  __param$D(1, IContextMenuService),
  __param$D(2, ILanguageFeaturesService),
  __param$D(3, IInstantiationService),
  __param$D(4, ILanguageConfigurationService),
  __param$D(5, ILanguageFeatureDebounceService),
  __param$D(6, IContextKeyService)
], StickyScrollController);
var __awaiter$m = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class ToggleStickyScroll extends Action2 {
  constructor() {
    super({
      id: "editor.action.toggleStickyScroll",
      title: {
        value: localize("toggleStickyScroll", "Toggle Sticky Scroll"),
        mnemonicTitle: localize({ key: "mitoggleStickyScroll", comment: ["&& denotes a mnemonic"] }, "&&Toggle Sticky Scroll"),
        original: "Toggle Sticky Scroll"
      },
      category: Categories.View,
      toggled: {
        condition: ContextKeyExpr.equals("config.editor.stickyScroll.enabled", true),
        title: localize("stickyScroll", "Sticky Scroll"),
        mnemonicTitle: localize({ key: "miStickyScroll", comment: ["&& denotes a mnemonic"] }, "&&Sticky Scroll")
      },
      menu: [
        { id: MenuId.CommandPalette },
        { id: MenuId.MenubarViewMenu, group: "5_editor", order: 2 },
        { id: MenuId.StickyScrollContext }
      ]
    });
  }
  run(accessor) {
    return __awaiter$m(this, void 0, void 0, function* () {
      const configurationService = accessor.get(IConfigurationService);
      const newValue = !configurationService.getValue("editor.stickyScroll.enabled");
      return configurationService.updateValue("editor.stickyScroll.enabled", newValue);
    });
  }
}
const weight = 100;
class FocusStickyScroll extends EditorAction2 {
  constructor() {
    super({
      id: "editor.action.focusStickyScroll",
      title: {
        value: localize("focusStickyScroll", "Focus Sticky Scroll"),
        mnemonicTitle: localize({ key: "mifocusStickyScroll", comment: ["&& denotes a mnemonic"] }, "&&Focus Sticky Scroll"),
        original: "Focus Sticky Scroll"
      },
      precondition: ContextKeyExpr.and(ContextKeyExpr.has("config.editor.stickyScroll.enabled"), EditorContextKeys.stickyScrollVisible),
      menu: [
        { id: MenuId.CommandPalette }
      ]
    });
  }
  runEditorCommand(_accessor, editor2) {
    var _a2;
    (_a2 = StickyScrollController.get(editor2)) === null || _a2 === void 0 ? void 0 : _a2.focus();
  }
}
class SelectNextStickyScrollLine extends EditorAction2 {
  constructor() {
    super({
      id: "editor.action.selectNextStickyScrollLine",
      title: {
        value: localize("selectNextStickyScrollLine.title", "Select next sticky scroll line"),
        original: "Select next sticky scroll line"
      },
      precondition: EditorContextKeys.stickyScrollFocused.isEqualTo(true),
      keybinding: {
        weight,
        primary: 18
        /* KeyCode.DownArrow */
      }
    });
  }
  runEditorCommand(_accessor, editor2) {
    var _a2;
    (_a2 = StickyScrollController.get(editor2)) === null || _a2 === void 0 ? void 0 : _a2.focusNext();
  }
}
class SelectPreviousStickyScrollLine extends EditorAction2 {
  constructor() {
    super({
      id: "editor.action.selectPreviousStickyScrollLine",
      title: {
        value: localize("selectPreviousStickyScrollLine.title", "Select previous sticky scroll line"),
        original: "Select previous sticky scroll line"
      },
      precondition: EditorContextKeys.stickyScrollFocused.isEqualTo(true),
      keybinding: {
        weight,
        primary: 16
        /* KeyCode.UpArrow */
      }
    });
  }
  runEditorCommand(_accessor, editor2) {
    var _a2;
    (_a2 = StickyScrollController.get(editor2)) === null || _a2 === void 0 ? void 0 : _a2.focusPrevious();
  }
}
class GoToStickyScrollLine extends EditorAction2 {
  constructor() {
    super({
      id: "editor.action.goToFocusedStickyScrollLine",
      title: {
        value: localize("goToFocusedStickyScrollLine.title", "Go to focused sticky scroll line"),
        original: "Go to focused sticky scroll line"
      },
      precondition: EditorContextKeys.stickyScrollFocused.isEqualTo(true),
      keybinding: {
        weight,
        primary: 3
        /* KeyCode.Enter */
      }
    });
  }
  runEditorCommand(_accessor, editor2) {
    var _a2;
    (_a2 = StickyScrollController.get(editor2)) === null || _a2 === void 0 ? void 0 : _a2.goToFocused();
  }
}
class SelectEditor extends EditorAction2 {
  constructor() {
    super({
      id: "editor.action.selectEditor",
      title: {
        value: localize("selectEditor.title", "Select Editor"),
        original: "Select Editor"
      },
      precondition: EditorContextKeys.stickyScrollFocused.isEqualTo(true),
      keybinding: {
        weight,
        primary: 9
        /* KeyCode.Escape */
      }
    });
  }
  runEditorCommand(_accessor, editor2) {
    var _a2;
    (_a2 = StickyScrollController.get(editor2)) === null || _a2 === void 0 ? void 0 : _a2.selectEditor();
  }
}
registerEditorContribution(
  StickyScrollController.ID,
  StickyScrollController,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
registerAction2(ToggleStickyScroll);
registerAction2(FocusStickyScroll);
registerAction2(SelectPreviousStickyScrollLine);
registerAction2(SelectNextStickyScrollLine);
registerAction2(GoToStickyScrollLine);
registerAction2(SelectEditor);
var __decorate$E = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$C = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$l = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class SuggestInlineCompletion {
  constructor(range2, insertText, filterText, additionalTextEdits, command, completion) {
    this.range = range2;
    this.insertText = insertText;
    this.filterText = filterText;
    this.additionalTextEdits = additionalTextEdits;
    this.command = command;
    this.completion = completion;
  }
}
let InlineCompletionResults = class InlineCompletionResults2 extends RefCountedDisposable {
  constructor(model, line, word2, completionModel, completions, _suggestMemoryService) {
    super(completions.disposable);
    this.model = model;
    this.line = line;
    this.word = word2;
    this.completionModel = completionModel;
    this._suggestMemoryService = _suggestMemoryService;
  }
  canBeReused(model, line, word2) {
    return this.model === model && this.line === line && this.word.word.length > 0 && this.word.startColumn === word2.startColumn && this.word.endColumn < word2.endColumn && this.completionModel.getIncompleteProvider().size === 0;
  }
  get items() {
    var _a2;
    const result2 = [];
    const { items } = this.completionModel;
    const selectedIndex = this._suggestMemoryService.select(this.model, { lineNumber: this.line, column: this.word.endColumn + this.completionModel.lineContext.characterCountDelta }, items);
    const first2 = Iterable.slice(items, selectedIndex);
    const second = Iterable.slice(items, 0, selectedIndex);
    let resolveCount = 5;
    for (const item of Iterable.concat(first2, second)) {
      if (item.score === FuzzyScore.Default) {
        continue;
      }
      const range2 = new Range$2(
        item.editStart.lineNumber,
        item.editStart.column,
        item.editInsertEnd.lineNumber,
        item.editInsertEnd.column + this.completionModel.lineContext.characterCountDelta
        // end PLUS character delta
      );
      const insertText = item.completion.insertTextRules && item.completion.insertTextRules & 4 ? { snippet: item.completion.insertText } : item.completion.insertText;
      result2.push(new SuggestInlineCompletion(range2, insertText, (_a2 = item.filterTextLow) !== null && _a2 !== void 0 ? _a2 : item.labelLow, item.completion.additionalTextEdits, item.completion.command, item));
      if (resolveCount-- >= 0) {
        item.resolve(CancellationToken.None);
      }
    }
    return result2;
  }
};
InlineCompletionResults = __decorate$E([
  __param$C(5, ISuggestMemoryService)
], InlineCompletionResults);
let SuggestInlineCompletions = class SuggestInlineCompletions2 {
  constructor(_getEditorOption, _languageFeatureService, _clipboardService, _suggestMemoryService) {
    this._getEditorOption = _getEditorOption;
    this._languageFeatureService = _languageFeatureService;
    this._clipboardService = _clipboardService;
    this._suggestMemoryService = _suggestMemoryService;
  }
  provideInlineCompletions(model, position, context, token) {
    var _a2;
    return __awaiter$l(this, void 0, void 0, function* () {
      if (context.selectedSuggestionInfo) {
        return;
      }
      const config2 = this._getEditorOption(87, model);
      if (QuickSuggestionsOptions.isAllOff(config2)) {
        return;
      }
      model.tokenization.tokenizeIfCheap(position.lineNumber);
      const lineTokens = model.tokenization.getLineTokens(position.lineNumber);
      const tokenType = lineTokens.getStandardTokenType(lineTokens.findTokenIndexAtOffset(Math.max(position.column - 1 - 1, 0)));
      if (QuickSuggestionsOptions.valueFor(config2, tokenType) !== "inline") {
        return void 0;
      }
      let wordInfo = model.getWordAtPosition(position);
      let triggerCharacterInfo;
      if (!(wordInfo === null || wordInfo === void 0 ? void 0 : wordInfo.word)) {
        triggerCharacterInfo = this._getTriggerCharacterInfo(model, position);
      }
      if (!(wordInfo === null || wordInfo === void 0 ? void 0 : wordInfo.word) && !triggerCharacterInfo) {
        return;
      }
      if (!wordInfo) {
        wordInfo = model.getWordUntilPosition(position);
      }
      if (wordInfo.endColumn !== position.column) {
        return;
      }
      let result2;
      const leadingLineContents = model.getValueInRange(new Range$2(position.lineNumber, 1, position.lineNumber, position.column));
      if (!triggerCharacterInfo && ((_a2 = this._lastResult) === null || _a2 === void 0 ? void 0 : _a2.canBeReused(model, position.lineNumber, wordInfo))) {
        const newLineContext = new LineContext$1(leadingLineContents, position.column - this._lastResult.word.endColumn);
        this._lastResult.completionModel.lineContext = newLineContext;
        this._lastResult.acquire();
        result2 = this._lastResult;
      } else {
        const completions = yield provideSuggestionItems(this._languageFeatureService.completionProvider, model, position, new CompletionOptions(void 0, void 0, triggerCharacterInfo === null || triggerCharacterInfo === void 0 ? void 0 : triggerCharacterInfo.providers), triggerCharacterInfo && { triggerKind: 1, triggerCharacter: triggerCharacterInfo.ch }, token);
        let clipboardText;
        if (completions.needsClipboard) {
          clipboardText = yield this._clipboardService.readText();
        }
        const completionModel = new CompletionModel(completions.items, position.column, new LineContext$1(leadingLineContents, 0), WordDistance.None, this._getEditorOption(116, model), this._getEditorOption(110, model), { boostFullMatch: false, firstMatchCanBeWeak: false }, clipboardText);
        result2 = new InlineCompletionResults(model, position.lineNumber, wordInfo, completionModel, completions, this._suggestMemoryService);
      }
      this._lastResult = result2;
      return result2;
    });
  }
  handleItemDidShow(_completions, item) {
    item.completion.resolve(CancellationToken.None);
  }
  freeInlineCompletions(result2) {
    result2.release();
  }
  _getTriggerCharacterInfo(model, position) {
    var _a2;
    const ch = model.getValueInRange(Range$2.fromPositions({ lineNumber: position.lineNumber, column: position.column - 1 }, position));
    const providers = /* @__PURE__ */ new Set();
    for (const provider of this._languageFeatureService.completionProvider.all(model)) {
      if ((_a2 = provider.triggerCharacters) === null || _a2 === void 0 ? void 0 : _a2.includes(ch)) {
        providers.add(provider);
      }
    }
    if (providers.size === 0) {
      return void 0;
    }
    return { providers, ch };
  }
};
SuggestInlineCompletions = __decorate$E([
  __param$C(1, ILanguageFeaturesService),
  __param$C(2, IClipboardService),
  __param$C(3, ISuggestMemoryService)
], SuggestInlineCompletions);
let EditorContribution = class EditorContribution2 {
  constructor(_editor, languageFeatureService, editorService, instaService) {
    if (++EditorContribution2._counter === 1) {
      const provider = instaService.createInstance(SuggestInlineCompletions, (id3, model) => {
        var _a2;
        const editor2 = (_a2 = editorService.listCodeEditors().find((editor3) => editor3.getModel() === model)) !== null && _a2 !== void 0 ? _a2 : _editor;
        return editor2.getOption(id3);
      });
      EditorContribution2._disposable = languageFeatureService.inlineCompletionsProvider.register("*", provider);
    }
  }
  dispose() {
    var _a2;
    if (--EditorContribution2._counter === 0) {
      (_a2 = EditorContribution2._disposable) === null || _a2 === void 0 ? void 0 : _a2.dispose();
      EditorContribution2._disposable = void 0;
    }
  }
};
EditorContribution._counter = 0;
EditorContribution = __decorate$E([
  __param$C(1, ILanguageFeaturesService),
  __param$C(2, ICodeEditorService),
  __param$C(3, IInstantiationService)
], EditorContribution);
registerEditorContribution(
  "suggest.inlineCompletionsProvider",
  EditorContribution,
  0
  /* EditorContributionInstantiation.Eager */
);
class ForceRetokenizeAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.forceRetokenize",
      label: localize("forceRetokenize", "Developer: Force Retokenize"),
      alias: "Developer: Force Retokenize",
      precondition: void 0
    });
  }
  run(accessor, editor2) {
    if (!editor2.hasModel()) {
      return;
    }
    const model = editor2.getModel();
    model.tokenization.resetTokenization();
    const sw = new StopWatch();
    model.tokenization.forceTokenization(model.getLineCount());
    sw.stop();
    console.log(`tokenization took ${sw.elapsed()}`);
  }
}
registerEditorAction(ForceRetokenizeAction);
class ToggleTabFocusModeAction extends Action2 {
  constructor() {
    super({
      id: ToggleTabFocusModeAction.ID,
      title: { value: localize({ key: "toggle.tabMovesFocus", comment: ["Turn on/off use of tab key for moving focus around VS Code"] }, "Toggle Tab Key Moves Focus"), original: "Toggle Tab Key Moves Focus" },
      precondition: void 0,
      keybinding: {
        primary: 2048 | 43,
        mac: {
          primary: 256 | 1024 | 43
          /* KeyCode.KeyM */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      f1: true
    });
  }
  run(accessor) {
    const context = accessor.get(IContextKeyService).getContextKeyValue("focusedView") === "terminal" ? "terminalFocus" : "editorFocus";
    const oldValue = TabFocus.getTabFocusMode(context);
    const newValue = !oldValue;
    TabFocus.setTabFocusMode(newValue, context);
    if (newValue) {
      alert(localize("toggle.tabMovesFocus.on", "Pressing Tab will now move focus to the next focusable element"));
    } else {
      alert(localize("toggle.tabMovesFocus.off", "Pressing Tab will now insert the tab character"));
    }
  }
}
ToggleTabFocusModeAction.ID = "editor.action.toggleTabFocusMode";
registerAction2(ToggleTabFocusModeAction);
const unicodeHighlighter = "";
const bannerController = "";
const link = "";
var __decorate$D = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$B = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let Link2 = class Link3 extends Disposable {
  get enabled() {
    return this._enabled;
  }
  set enabled(enabled) {
    if (enabled) {
      this.el.setAttribute("aria-disabled", "false");
      this.el.tabIndex = 0;
      this.el.style.pointerEvents = "auto";
      this.el.style.opacity = "1";
      this.el.style.cursor = "pointer";
      this._enabled = false;
    } else {
      this.el.setAttribute("aria-disabled", "true");
      this.el.tabIndex = -1;
      this.el.style.pointerEvents = "none";
      this.el.style.opacity = "0.4";
      this.el.style.cursor = "default";
      this._enabled = true;
    }
    this._enabled = enabled;
  }
  constructor(container2, _link, options = {}, openerService) {
    var _a2;
    super();
    this._link = _link;
    this._enabled = true;
    this.el = append$1(container2, $$d("a.monaco-link", {
      tabIndex: (_a2 = _link.tabIndex) !== null && _a2 !== void 0 ? _a2 : 0,
      href: _link.href,
      title: _link.title
    }, _link.label));
    this.el.setAttribute("role", "button");
    const onClickEmitter = this._register(new DomEmitter(this.el, "click"));
    const onKeyPress = this._register(new DomEmitter(this.el, "keypress"));
    const onEnterPress = Event$1.chain(onKeyPress.event).map((e) => new StandardKeyboardEvent(e)).filter(
      (e) => e.keyCode === 3
      /* KeyCode.Enter */
    ).event;
    const onTap = this._register(new DomEmitter(this.el, EventType.Tap)).event;
    this._register(Gesture.addTarget(this.el));
    const onOpen = Event$1.any(onClickEmitter.event, onEnterPress, onTap);
    this._register(onOpen((e) => {
      if (!this.enabled) {
        return;
      }
      EventHelper.stop(e, true);
      if (options === null || options === void 0 ? void 0 : options.opener) {
        options.opener(this._link.href);
      } else {
        openerService.open(this._link.href, { allowCommands: true });
      }
    }));
    this.enabled = true;
  }
};
Link2 = __decorate$D([
  __param$B(3, IOpenerService)
], Link2);
var __decorate$C = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$A = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
const BANNER_ELEMENT_HEIGHT = 26;
let BannerController = class BannerController2 extends Disposable {
  constructor(_editor, instantiationService) {
    super();
    this._editor = _editor;
    this.instantiationService = instantiationService;
    this.banner = this._register(this.instantiationService.createInstance(Banner));
  }
  hide() {
    this._editor.setBanner(null, 0);
    this.banner.clear();
  }
  show(item) {
    this.banner.show(Object.assign(Object.assign({}, item), { onClose: () => {
      var _a2;
      this.hide();
      (_a2 = item.onClose) === null || _a2 === void 0 ? void 0 : _a2.call(item);
    } }));
    this._editor.setBanner(this.banner.element, BANNER_ELEMENT_HEIGHT);
  }
};
BannerController = __decorate$C([
  __param$A(1, IInstantiationService)
], BannerController);
let Banner = class Banner2 extends Disposable {
  constructor(instantiationService) {
    super();
    this.instantiationService = instantiationService;
    this.markdownRenderer = this.instantiationService.createInstance(MarkdownRenderer, {});
    this.element = $$d("div.editor-banner");
    this.element.tabIndex = 0;
  }
  getAriaLabel(item) {
    if (item.ariaLabel) {
      return item.ariaLabel;
    }
    if (typeof item.message === "string") {
      return item.message;
    }
    return void 0;
  }
  getBannerMessage(message) {
    if (typeof message === "string") {
      const element = $$d("span");
      element.innerText = message;
      return element;
    }
    return this.markdownRenderer.render(message).element;
  }
  clear() {
    clearNode(this.element);
  }
  show(item) {
    clearNode(this.element);
    const ariaLabel = this.getAriaLabel(item);
    if (ariaLabel) {
      this.element.setAttribute("aria-label", ariaLabel);
    }
    const iconContainer = append$1(this.element, $$d("div.icon-container"));
    iconContainer.setAttribute("aria-hidden", "true");
    if (item.icon) {
      iconContainer.appendChild($$d(`div${ThemeIcon.asCSSSelector(item.icon)}`));
    }
    const messageContainer = append$1(this.element, $$d("div.message-container"));
    messageContainer.setAttribute("aria-hidden", "true");
    messageContainer.appendChild(this.getBannerMessage(item.message));
    this.messageActionsContainer = append$1(this.element, $$d("div.message-actions-container"));
    if (item.actions) {
      for (const action of item.actions) {
        this._register(this.instantiationService.createInstance(Link2, this.messageActionsContainer, Object.assign(Object.assign({}, action), { tabIndex: -1 }), {}));
      }
    }
    const actionBarContainer = append$1(this.element, $$d("div.action-container"));
    this.actionBar = this._register(new ActionBar(actionBarContainer));
    this.actionBar.push(this._register(new Action("banner.close", "Close Banner", ThemeIcon.asClassName(widgetClose), true, () => {
      if (typeof item.onClose === "function") {
        item.onClose();
      }
    })), { icon: true, label: false });
    this.actionBar.setFocusable(false);
  }
};
Banner = __decorate$C([
  __param$A(0, IInstantiationService)
], Banner);
const IWorkspaceTrustManagementService = createDecorator("workspaceTrustManagementService");
var __decorate$B = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$z = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$k = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
const warningIcon = registerIcon("extensions-warning-message", Codicon.warning, localize("warningIcon", "Icon shown with a warning message in the extensions editor."));
let UnicodeHighlighter = class UnicodeHighlighter2 extends Disposable {
  constructor(_editor, _editorWorkerService, _workspaceTrustService, instantiationService) {
    super();
    this._editor = _editor;
    this._editorWorkerService = _editorWorkerService;
    this._workspaceTrustService = _workspaceTrustService;
    this._highlighter = null;
    this._bannerClosed = false;
    this._updateState = (state) => {
      if (state && state.hasMore) {
        if (this._bannerClosed) {
          return;
        }
        const max = Math.max(state.ambiguousCharacterCount, state.nonBasicAsciiCharacterCount, state.invisibleCharacterCount);
        let data;
        if (state.nonBasicAsciiCharacterCount >= max) {
          data = {
            message: localize("unicodeHighlighting.thisDocumentHasManyNonBasicAsciiUnicodeCharacters", "This document contains many non-basic ASCII unicode characters"),
            command: new DisableHighlightingOfNonBasicAsciiCharactersAction()
          };
        } else if (state.ambiguousCharacterCount >= max) {
          data = {
            message: localize("unicodeHighlighting.thisDocumentHasManyAmbiguousUnicodeCharacters", "This document contains many ambiguous unicode characters"),
            command: new DisableHighlightingOfAmbiguousCharactersAction()
          };
        } else if (state.invisibleCharacterCount >= max) {
          data = {
            message: localize("unicodeHighlighting.thisDocumentHasManyInvisibleUnicodeCharacters", "This document contains many invisible unicode characters"),
            command: new DisableHighlightingOfInvisibleCharactersAction()
          };
        } else {
          throw new Error("Unreachable");
        }
        this._bannerController.show({
          id: "unicodeHighlightBanner",
          message: data.message,
          icon: warningIcon,
          actions: [
            {
              label: data.command.shortLabel,
              href: `command:${data.command.id}`
            }
          ],
          onClose: () => {
            this._bannerClosed = true;
          }
        });
      } else {
        this._bannerController.hide();
      }
    };
    this._bannerController = this._register(instantiationService.createInstance(BannerController, _editor));
    this._register(this._editor.onDidChangeModel(() => {
      this._bannerClosed = false;
      this._updateHighlighter();
    }));
    this._options = _editor.getOption(
      123
      /* EditorOption.unicodeHighlighting */
    );
    this._register(_workspaceTrustService.onDidChangeTrust((e) => {
      this._updateHighlighter();
    }));
    this._register(_editor.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        123
        /* EditorOption.unicodeHighlighting */
      )) {
        this._options = _editor.getOption(
          123
          /* EditorOption.unicodeHighlighting */
        );
        this._updateHighlighter();
      }
    }));
    this._updateHighlighter();
  }
  dispose() {
    if (this._highlighter) {
      this._highlighter.dispose();
      this._highlighter = null;
    }
    super.dispose();
  }
  _updateHighlighter() {
    this._updateState(null);
    if (this._highlighter) {
      this._highlighter.dispose();
      this._highlighter = null;
    }
    if (!this._editor.hasModel()) {
      return;
    }
    const options = resolveOptions(this._workspaceTrustService.isWorkspaceTrusted(), this._options);
    if ([
      options.nonBasicASCII,
      options.ambiguousCharacters,
      options.invisibleCharacters
    ].every((option) => option === false)) {
      return;
    }
    const highlightOptions = {
      nonBasicASCII: options.nonBasicASCII,
      ambiguousCharacters: options.ambiguousCharacters,
      invisibleCharacters: options.invisibleCharacters,
      includeComments: options.includeComments,
      includeStrings: options.includeStrings,
      allowedCodePoints: Object.keys(options.allowedCharacters).map((c) => c.codePointAt(0)),
      allowedLocales: Object.keys(options.allowedLocales).map((locale) => {
        if (locale === "_os") {
          const osLocale = new Intl.NumberFormat().resolvedOptions().locale;
          return osLocale;
        } else if (locale === "_vscode") {
          return language;
        }
        return locale;
      })
    };
    if (this._editorWorkerService.canComputeUnicodeHighlights(this._editor.getModel().uri)) {
      this._highlighter = new DocumentUnicodeHighlighter(this._editor, highlightOptions, this._updateState, this._editorWorkerService);
    } else {
      this._highlighter = new ViewportUnicodeHighlighter(this._editor, highlightOptions, this._updateState);
    }
  }
  getDecorationInfo(decoration2) {
    if (this._highlighter) {
      return this._highlighter.getDecorationInfo(decoration2);
    }
    return null;
  }
};
UnicodeHighlighter.ID = "editor.contrib.unicodeHighlighter";
UnicodeHighlighter = __decorate$B([
  __param$z(1, IEditorWorkerService),
  __param$z(2, IWorkspaceTrustManagementService),
  __param$z(3, IInstantiationService)
], UnicodeHighlighter);
function resolveOptions(trusted, options) {
  return {
    nonBasicASCII: options.nonBasicASCII === inUntrustedWorkspace ? !trusted : options.nonBasicASCII,
    ambiguousCharacters: options.ambiguousCharacters,
    invisibleCharacters: options.invisibleCharacters,
    includeComments: options.includeComments === inUntrustedWorkspace ? !trusted : options.includeComments,
    includeStrings: options.includeStrings === inUntrustedWorkspace ? !trusted : options.includeStrings,
    allowedCharacters: options.allowedCharacters,
    allowedLocales: options.allowedLocales
  };
}
let DocumentUnicodeHighlighter = class DocumentUnicodeHighlighter2 extends Disposable {
  constructor(_editor, _options, _updateState, _editorWorkerService) {
    super();
    this._editor = _editor;
    this._options = _options;
    this._updateState = _updateState;
    this._editorWorkerService = _editorWorkerService;
    this._model = this._editor.getModel();
    this._decorations = this._editor.createDecorationsCollection();
    this._updateSoon = this._register(new RunOnceScheduler(() => this._update(), 250));
    this._register(this._editor.onDidChangeModelContent(() => {
      this._updateSoon.schedule();
    }));
    this._updateSoon.schedule();
  }
  dispose() {
    this._decorations.clear();
    super.dispose();
  }
  _update() {
    if (this._model.isDisposed()) {
      return;
    }
    if (!this._model.mightContainNonBasicASCII()) {
      this._decorations.clear();
      return;
    }
    const modelVersionId = this._model.getVersionId();
    this._editorWorkerService.computedUnicodeHighlights(this._model.uri, this._options).then((info) => {
      if (this._model.isDisposed()) {
        return;
      }
      if (this._model.getVersionId() !== modelVersionId) {
        return;
      }
      this._updateState(info);
      const decorations2 = [];
      if (!info.hasMore) {
        for (const range2 of info.ranges) {
          decorations2.push({
            range: range2,
            options: Decorations.instance.getDecorationFromOptions(this._options)
          });
        }
      }
      this._decorations.set(decorations2);
    });
  }
  getDecorationInfo(decoration2) {
    if (!this._decorations.has(decoration2)) {
      return null;
    }
    const model = this._editor.getModel();
    if (!isModelDecorationVisible(model, decoration2)) {
      return null;
    }
    const text2 = model.getValueInRange(decoration2.range);
    return {
      reason: computeReason(text2, this._options),
      inComment: isModelDecorationInComment(model, decoration2),
      inString: isModelDecorationInString(model, decoration2)
    };
  }
};
DocumentUnicodeHighlighter = __decorate$B([
  __param$z(3, IEditorWorkerService)
], DocumentUnicodeHighlighter);
class ViewportUnicodeHighlighter extends Disposable {
  constructor(_editor, _options, _updateState) {
    super();
    this._editor = _editor;
    this._options = _options;
    this._updateState = _updateState;
    this._model = this._editor.getModel();
    this._decorations = this._editor.createDecorationsCollection();
    this._updateSoon = this._register(new RunOnceScheduler(() => this._update(), 250));
    this._register(this._editor.onDidLayoutChange(() => {
      this._updateSoon.schedule();
    }));
    this._register(this._editor.onDidScrollChange(() => {
      this._updateSoon.schedule();
    }));
    this._register(this._editor.onDidChangeHiddenAreas(() => {
      this._updateSoon.schedule();
    }));
    this._register(this._editor.onDidChangeModelContent(() => {
      this._updateSoon.schedule();
    }));
    this._updateSoon.schedule();
  }
  dispose() {
    this._decorations.clear();
    super.dispose();
  }
  _update() {
    if (this._model.isDisposed()) {
      return;
    }
    if (!this._model.mightContainNonBasicASCII()) {
      this._decorations.clear();
      return;
    }
    const ranges = this._editor.getVisibleRanges();
    const decorations2 = [];
    const totalResult = {
      ranges: [],
      ambiguousCharacterCount: 0,
      invisibleCharacterCount: 0,
      nonBasicAsciiCharacterCount: 0,
      hasMore: false
    };
    for (const range2 of ranges) {
      const result2 = UnicodeTextModelHighlighter.computeUnicodeHighlights(this._model, this._options, range2);
      for (const r of result2.ranges) {
        totalResult.ranges.push(r);
      }
      totalResult.ambiguousCharacterCount += totalResult.ambiguousCharacterCount;
      totalResult.invisibleCharacterCount += totalResult.invisibleCharacterCount;
      totalResult.nonBasicAsciiCharacterCount += totalResult.nonBasicAsciiCharacterCount;
      totalResult.hasMore = totalResult.hasMore || result2.hasMore;
    }
    if (!totalResult.hasMore) {
      for (const range2 of totalResult.ranges) {
        decorations2.push({ range: range2, options: Decorations.instance.getDecorationFromOptions(this._options) });
      }
    }
    this._updateState(totalResult);
    this._decorations.set(decorations2);
  }
  getDecorationInfo(decoration2) {
    if (!this._decorations.has(decoration2)) {
      return null;
    }
    const model = this._editor.getModel();
    const text2 = model.getValueInRange(decoration2.range);
    if (!isModelDecorationVisible(model, decoration2)) {
      return null;
    }
    return {
      reason: computeReason(text2, this._options),
      inComment: isModelDecorationInComment(model, decoration2),
      inString: isModelDecorationInString(model, decoration2)
    };
  }
}
let UnicodeHighlighterHoverParticipant = class UnicodeHighlighterHoverParticipant2 {
  constructor(_editor, _languageService, _openerService) {
    this._editor = _editor;
    this._languageService = _languageService;
    this._openerService = _openerService;
    this.hoverOrdinal = 5;
  }
  computeSync(anchor, lineDecorations) {
    if (!this._editor.hasModel() || anchor.type !== 1) {
      return [];
    }
    const model = this._editor.getModel();
    const unicodeHighlighter2 = this._editor.getContribution(UnicodeHighlighter.ID);
    if (!unicodeHighlighter2) {
      return [];
    }
    const result2 = [];
    const existedReason = /* @__PURE__ */ new Set();
    let index = 300;
    for (const d of lineDecorations) {
      const highlightInfo = unicodeHighlighter2.getDecorationInfo(d);
      if (!highlightInfo) {
        continue;
      }
      const char = model.getValueInRange(d.range);
      const codePoint = char.codePointAt(0);
      const codePointStr = formatCodePointMarkdown(codePoint);
      let reason;
      switch (highlightInfo.reason.kind) {
        case 0: {
          if (isBasicASCII(highlightInfo.reason.confusableWith)) {
            reason = localize("unicodeHighlight.characterIsAmbiguousASCII", "The character {0} could be confused with the ASCII character {1}, which is more common in source code.", codePointStr, formatCodePointMarkdown(highlightInfo.reason.confusableWith.codePointAt(0)));
          } else {
            reason = localize("unicodeHighlight.characterIsAmbiguous", "The character {0} could be confused with the character {1}, which is more common in source code.", codePointStr, formatCodePointMarkdown(highlightInfo.reason.confusableWith.codePointAt(0)));
          }
          break;
        }
        case 1:
          reason = localize("unicodeHighlight.characterIsInvisible", "The character {0} is invisible.", codePointStr);
          break;
        case 2:
          reason = localize("unicodeHighlight.characterIsNonBasicAscii", "The character {0} is not a basic ASCII character.", codePointStr);
          break;
      }
      if (existedReason.has(reason)) {
        continue;
      }
      existedReason.add(reason);
      const adjustSettingsArgs = {
        codePoint,
        reason: highlightInfo.reason,
        inComment: highlightInfo.inComment,
        inString: highlightInfo.inString
      };
      const adjustSettings = localize("unicodeHighlight.adjustSettings", "Adjust settings");
      const uri = `command:${ShowExcludeOptions.ID}?${encodeURIComponent(JSON.stringify(adjustSettingsArgs))}`;
      const markdown = new MarkdownString("", true).appendMarkdown(reason).appendText(" ").appendLink(uri, adjustSettings);
      result2.push(new MarkdownHover(this, d.range, [markdown], false, index++));
    }
    return result2;
  }
  renderHoverParts(context, hoverParts) {
    return renderMarkdownHovers(context, hoverParts, this._editor, this._languageService, this._openerService);
  }
};
UnicodeHighlighterHoverParticipant = __decorate$B([
  __param$z(1, ILanguageService),
  __param$z(2, IOpenerService)
], UnicodeHighlighterHoverParticipant);
function codePointToHex(codePoint) {
  return `U+${codePoint.toString(16).padStart(4, "0")}`;
}
function formatCodePointMarkdown(codePoint) {
  let value = `\`${codePointToHex(codePoint)}\``;
  if (!InvisibleCharacters.isInvisibleCharacter(codePoint)) {
    value += ` "${`${renderCodePointAsInlineCode(codePoint)}`}"`;
  }
  return value;
}
function renderCodePointAsInlineCode(codePoint) {
  if (codePoint === 96) {
    return "`` ` ``";
  }
  return "`" + String.fromCodePoint(codePoint) + "`";
}
function computeReason(char, options) {
  return UnicodeTextModelHighlighter.computeUnicodeHighlightReason(char, options);
}
class Decorations {
  constructor() {
    this.map = /* @__PURE__ */ new Map();
  }
  getDecorationFromOptions(options) {
    return this.getDecoration(!options.includeComments, !options.includeStrings);
  }
  getDecoration(hideInComments, hideInStrings) {
    const key = `${hideInComments}${hideInStrings}`;
    let options = this.map.get(key);
    if (!options) {
      options = ModelDecorationOptions.createDynamic({
        description: "unicode-highlight",
        stickiness: 1,
        className: "unicode-highlight",
        showIfCollapsed: true,
        overviewRuler: null,
        minimap: null,
        hideInCommentTokens: hideInComments,
        hideInStringTokens: hideInStrings
      });
      this.map.set(key, options);
    }
    return options;
  }
}
Decorations.instance = new Decorations();
class DisableHighlightingInCommentsAction extends EditorAction {
  constructor() {
    super({
      id: DisableHighlightingOfAmbiguousCharactersAction.ID,
      label: localize("action.unicodeHighlight.disableHighlightingInComments", "Disable highlighting of characters in comments"),
      alias: "Disable highlighting of characters in comments",
      precondition: void 0
    });
    this.shortLabel = localize("unicodeHighlight.disableHighlightingInComments.shortLabel", "Disable Highlight In Comments");
  }
  run(accessor, editor2, args) {
    return __awaiter$k(this, void 0, void 0, function* () {
      const configurationService = accessor === null || accessor === void 0 ? void 0 : accessor.get(IConfigurationService);
      if (configurationService) {
        this.runAction(configurationService);
      }
    });
  }
  runAction(configurationService) {
    return __awaiter$k(this, void 0, void 0, function* () {
      yield configurationService.updateValue(
        unicodeHighlightConfigKeys.includeComments,
        false,
        2
        /* ConfigurationTarget.USER */
      );
    });
  }
}
class DisableHighlightingInStringsAction extends EditorAction {
  constructor() {
    super({
      id: DisableHighlightingOfAmbiguousCharactersAction.ID,
      label: localize("action.unicodeHighlight.disableHighlightingInStrings", "Disable highlighting of characters in strings"),
      alias: "Disable highlighting of characters in strings",
      precondition: void 0
    });
    this.shortLabel = localize("unicodeHighlight.disableHighlightingInStrings.shortLabel", "Disable Highlight In Strings");
  }
  run(accessor, editor2, args) {
    return __awaiter$k(this, void 0, void 0, function* () {
      const configurationService = accessor === null || accessor === void 0 ? void 0 : accessor.get(IConfigurationService);
      if (configurationService) {
        this.runAction(configurationService);
      }
    });
  }
  runAction(configurationService) {
    return __awaiter$k(this, void 0, void 0, function* () {
      yield configurationService.updateValue(
        unicodeHighlightConfigKeys.includeStrings,
        false,
        2
        /* ConfigurationTarget.USER */
      );
    });
  }
}
class DisableHighlightingOfAmbiguousCharactersAction extends EditorAction {
  constructor() {
    super({
      id: DisableHighlightingOfAmbiguousCharactersAction.ID,
      label: localize("action.unicodeHighlight.disableHighlightingOfAmbiguousCharacters", "Disable highlighting of ambiguous characters"),
      alias: "Disable highlighting of ambiguous characters",
      precondition: void 0
    });
    this.shortLabel = localize("unicodeHighlight.disableHighlightingOfAmbiguousCharacters.shortLabel", "Disable Ambiguous Highlight");
  }
  run(accessor, editor2, args) {
    return __awaiter$k(this, void 0, void 0, function* () {
      const configurationService = accessor === null || accessor === void 0 ? void 0 : accessor.get(IConfigurationService);
      if (configurationService) {
        this.runAction(configurationService);
      }
    });
  }
  runAction(configurationService) {
    return __awaiter$k(this, void 0, void 0, function* () {
      yield configurationService.updateValue(
        unicodeHighlightConfigKeys.ambiguousCharacters,
        false,
        2
        /* ConfigurationTarget.USER */
      );
    });
  }
}
DisableHighlightingOfAmbiguousCharactersAction.ID = "editor.action.unicodeHighlight.disableHighlightingOfAmbiguousCharacters";
class DisableHighlightingOfInvisibleCharactersAction extends EditorAction {
  constructor() {
    super({
      id: DisableHighlightingOfInvisibleCharactersAction.ID,
      label: localize("action.unicodeHighlight.disableHighlightingOfInvisibleCharacters", "Disable highlighting of invisible characters"),
      alias: "Disable highlighting of invisible characters",
      precondition: void 0
    });
    this.shortLabel = localize("unicodeHighlight.disableHighlightingOfInvisibleCharacters.shortLabel", "Disable Invisible Highlight");
  }
  run(accessor, editor2, args) {
    return __awaiter$k(this, void 0, void 0, function* () {
      const configurationService = accessor === null || accessor === void 0 ? void 0 : accessor.get(IConfigurationService);
      if (configurationService) {
        this.runAction(configurationService);
      }
    });
  }
  runAction(configurationService) {
    return __awaiter$k(this, void 0, void 0, function* () {
      yield configurationService.updateValue(
        unicodeHighlightConfigKeys.invisibleCharacters,
        false,
        2
        /* ConfigurationTarget.USER */
      );
    });
  }
}
DisableHighlightingOfInvisibleCharactersAction.ID = "editor.action.unicodeHighlight.disableHighlightingOfInvisibleCharacters";
class DisableHighlightingOfNonBasicAsciiCharactersAction extends EditorAction {
  constructor() {
    super({
      id: DisableHighlightingOfNonBasicAsciiCharactersAction.ID,
      label: localize("action.unicodeHighlight.disableHighlightingOfNonBasicAsciiCharacters", "Disable highlighting of non basic ASCII characters"),
      alias: "Disable highlighting of non basic ASCII characters",
      precondition: void 0
    });
    this.shortLabel = localize("unicodeHighlight.disableHighlightingOfNonBasicAsciiCharacters.shortLabel", "Disable Non ASCII Highlight");
  }
  run(accessor, editor2, args) {
    return __awaiter$k(this, void 0, void 0, function* () {
      const configurationService = accessor === null || accessor === void 0 ? void 0 : accessor.get(IConfigurationService);
      if (configurationService) {
        this.runAction(configurationService);
      }
    });
  }
  runAction(configurationService) {
    return __awaiter$k(this, void 0, void 0, function* () {
      yield configurationService.updateValue(
        unicodeHighlightConfigKeys.nonBasicASCII,
        false,
        2
        /* ConfigurationTarget.USER */
      );
    });
  }
}
DisableHighlightingOfNonBasicAsciiCharactersAction.ID = "editor.action.unicodeHighlight.disableHighlightingOfNonBasicAsciiCharacters";
class ShowExcludeOptions extends EditorAction {
  constructor() {
    super({
      id: ShowExcludeOptions.ID,
      label: localize("action.unicodeHighlight.showExcludeOptions", "Show Exclude Options"),
      alias: "Show Exclude Options",
      precondition: void 0
    });
  }
  run(accessor, editor2, args) {
    return __awaiter$k(this, void 0, void 0, function* () {
      const { codePoint, reason, inString, inComment } = args;
      const char = String.fromCodePoint(codePoint);
      const quickPickService = accessor.get(IQuickInputService);
      const configurationService = accessor.get(IConfigurationService);
      function getExcludeCharFromBeingHighlightedLabel(codePoint2) {
        if (InvisibleCharacters.isInvisibleCharacter(codePoint2)) {
          return localize("unicodeHighlight.excludeInvisibleCharFromBeingHighlighted", "Exclude {0} (invisible character) from being highlighted", codePointToHex(codePoint2));
        }
        return localize("unicodeHighlight.excludeCharFromBeingHighlighted", "Exclude {0} from being highlighted", `${codePointToHex(codePoint2)} "${char}"`);
      }
      const options = [];
      if (reason.kind === 0) {
        for (const locale of reason.notAmbiguousInLocales) {
          options.push({
            label: localize("unicodeHighlight.allowCommonCharactersInLanguage", 'Allow unicode characters that are more common in the language "{0}".', locale),
            run: () => __awaiter$k(this, void 0, void 0, function* () {
              excludeLocaleFromBeingHighlighted(configurationService, [locale]);
            })
          });
        }
      }
      options.push({
        label: getExcludeCharFromBeingHighlightedLabel(codePoint),
        run: () => excludeCharFromBeingHighlighted(configurationService, [codePoint])
      });
      if (inComment) {
        const action = new DisableHighlightingInCommentsAction();
        options.push({ label: action.label, run: () => __awaiter$k(this, void 0, void 0, function* () {
          return action.runAction(configurationService);
        }) });
      } else if (inString) {
        const action = new DisableHighlightingInStringsAction();
        options.push({ label: action.label, run: () => __awaiter$k(this, void 0, void 0, function* () {
          return action.runAction(configurationService);
        }) });
      }
      if (reason.kind === 0) {
        const action = new DisableHighlightingOfAmbiguousCharactersAction();
        options.push({ label: action.label, run: () => __awaiter$k(this, void 0, void 0, function* () {
          return action.runAction(configurationService);
        }) });
      } else if (reason.kind === 1) {
        const action = new DisableHighlightingOfInvisibleCharactersAction();
        options.push({ label: action.label, run: () => __awaiter$k(this, void 0, void 0, function* () {
          return action.runAction(configurationService);
        }) });
      } else if (reason.kind === 2) {
        const action = new DisableHighlightingOfNonBasicAsciiCharactersAction();
        options.push({ label: action.label, run: () => __awaiter$k(this, void 0, void 0, function* () {
          return action.runAction(configurationService);
        }) });
      } else {
        expectNever(reason);
      }
      const result2 = yield quickPickService.pick(options, { title: localize("unicodeHighlight.configureUnicodeHighlightOptions", "Configure Unicode Highlight Options") });
      if (result2) {
        yield result2.run();
      }
    });
  }
}
ShowExcludeOptions.ID = "editor.action.unicodeHighlight.showExcludeOptions";
function excludeCharFromBeingHighlighted(configurationService, charCodes) {
  return __awaiter$k(this, void 0, void 0, function* () {
    const existingValue = configurationService.getValue(unicodeHighlightConfigKeys.allowedCharacters);
    let value;
    if (typeof existingValue === "object" && existingValue) {
      value = existingValue;
    } else {
      value = {};
    }
    for (const charCode of charCodes) {
      value[String.fromCodePoint(charCode)] = true;
    }
    yield configurationService.updateValue(
      unicodeHighlightConfigKeys.allowedCharacters,
      value,
      2
      /* ConfigurationTarget.USER */
    );
  });
}
function excludeLocaleFromBeingHighlighted(configurationService, locales) {
  var _a2;
  return __awaiter$k(this, void 0, void 0, function* () {
    const existingValue = (_a2 = configurationService.inspect(unicodeHighlightConfigKeys.allowedLocales).user) === null || _a2 === void 0 ? void 0 : _a2.value;
    let value;
    if (typeof existingValue === "object" && existingValue) {
      value = Object.assign({}, existingValue);
    } else {
      value = {};
    }
    for (const locale of locales) {
      value[locale] = true;
    }
    yield configurationService.updateValue(
      unicodeHighlightConfigKeys.allowedLocales,
      value,
      2
      /* ConfigurationTarget.USER */
    );
  });
}
function expectNever(value) {
  throw new Error(`Unexpected value: ${value}`);
}
registerEditorAction(DisableHighlightingOfAmbiguousCharactersAction);
registerEditorAction(DisableHighlightingOfInvisibleCharactersAction);
registerEditorAction(DisableHighlightingOfNonBasicAsciiCharactersAction);
registerEditorAction(ShowExcludeOptions);
registerEditorContribution(
  UnicodeHighlighter.ID,
  UnicodeHighlighter,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
HoverParticipantRegistry.register(UnicodeHighlighterHoverParticipant);
const IDialogService = createDecorator("dialogService");
var __decorate$A = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$y = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$j = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
const ignoreUnusualLineTerminators = "ignoreUnusualLineTerminators";
function writeIgnoreState(codeEditorService, model, state) {
  codeEditorService.setModelProperty(model.uri, ignoreUnusualLineTerminators, state);
}
function readIgnoreState(codeEditorService, model) {
  return codeEditorService.getModelProperty(model.uri, ignoreUnusualLineTerminators);
}
let UnusualLineTerminatorsDetector = class UnusualLineTerminatorsDetector2 extends Disposable {
  constructor(_editor, _dialogService, _codeEditorService) {
    super();
    this._editor = _editor;
    this._dialogService = _dialogService;
    this._codeEditorService = _codeEditorService;
    this._isPresentingDialog = false;
    this._config = this._editor.getOption(
      124
      /* EditorOption.unusualLineTerminators */
    );
    this._register(this._editor.onDidChangeConfiguration((e) => {
      if (e.hasChanged(
        124
        /* EditorOption.unusualLineTerminators */
      )) {
        this._config = this._editor.getOption(
          124
          /* EditorOption.unusualLineTerminators */
        );
        this._checkForUnusualLineTerminators();
      }
    }));
    this._register(this._editor.onDidChangeModel(() => {
      this._checkForUnusualLineTerminators();
    }));
    this._register(this._editor.onDidChangeModelContent((e) => {
      if (e.isUndoing) {
        return;
      }
      this._checkForUnusualLineTerminators();
    }));
    this._checkForUnusualLineTerminators();
  }
  _checkForUnusualLineTerminators() {
    return __awaiter$j(this, void 0, void 0, function* () {
      if (this._config === "off") {
        return;
      }
      if (!this._editor.hasModel()) {
        return;
      }
      const model = this._editor.getModel();
      if (!model.mightContainUnusualLineTerminators()) {
        return;
      }
      const ignoreState = readIgnoreState(this._codeEditorService, model);
      if (ignoreState === true) {
        return;
      }
      if (this._editor.getOption(
        89
        /* EditorOption.readOnly */
      )) {
        return;
      }
      if (this._config === "auto") {
        model.removeUnusualLineTerminators(this._editor.getSelections());
        return;
      }
      if (this._isPresentingDialog) {
        return;
      }
      let result2;
      try {
        this._isPresentingDialog = true;
        result2 = yield this._dialogService.confirm({
          title: localize("unusualLineTerminators.title", "Unusual Line Terminators"),
          message: localize("unusualLineTerminators.message", "Detected unusual line terminators"),
          detail: localize("unusualLineTerminators.detail", "The file '{0}' contains one or more unusual line terminator characters, like Line Separator (LS) or Paragraph Separator (PS).\n\nIt is recommended to remove them from the file. This can be configured via `editor.unusualLineTerminators`.", basename$1(model.uri)),
          primaryButton: localize({ key: "unusualLineTerminators.fix", comment: ["&& denotes a mnemonic"] }, "&&Remove Unusual Line Terminators"),
          cancelButton: localize("unusualLineTerminators.ignore", "Ignore")
        });
      } finally {
        this._isPresentingDialog = false;
      }
      if (!result2.confirmed) {
        writeIgnoreState(this._codeEditorService, model, true);
        return;
      }
      model.removeUnusualLineTerminators(this._editor.getSelections());
    });
  }
};
UnusualLineTerminatorsDetector.ID = "editor.contrib.unusualLineTerminatorsDetector";
UnusualLineTerminatorsDetector = __decorate$A([
  __param$y(1, IDialogService),
  __param$y(2, ICodeEditorService)
], UnusualLineTerminatorsDetector);
registerEditorContribution(
  UnusualLineTerminatorsDetector.ID,
  UnusualLineTerminatorsDetector,
  1
  /* EditorContributionInstantiation.AfterFirstRender */
);
var __decorate$z = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$x = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
const ctxHasWordHighlights = new RawContextKey("hasWordHighlights", false);
function getOccurrencesAtPosition(registry, model, position, token) {
  const orderedByScore = registry.ordered(model);
  return first(orderedByScore.map((provider) => () => {
    return Promise.resolve(provider.provideDocumentHighlights(model, position, token)).then(void 0, onUnexpectedExternalError);
  }), isNonEmptyArray);
}
class OccurenceAtPositionRequest {
  constructor(_model, _selection, _wordSeparators) {
    this._model = _model;
    this._selection = _selection;
    this._wordSeparators = _wordSeparators;
    this._wordRange = this._getCurrentWordRange(_model, _selection);
    this._result = null;
  }
  get result() {
    if (!this._result) {
      this._result = createCancelablePromise((token) => this._compute(this._model, this._selection, this._wordSeparators, token));
    }
    return this._result;
  }
  _getCurrentWordRange(model, selection) {
    const word2 = model.getWordAtPosition(selection.getPosition());
    if (word2) {
      return new Range$2(selection.startLineNumber, word2.startColumn, selection.startLineNumber, word2.endColumn);
    }
    return null;
  }
  isValid(model, selection, decorations2) {
    const lineNumber = selection.startLineNumber;
    const startColumn = selection.startColumn;
    const endColumn = selection.endColumn;
    const currentWordRange = this._getCurrentWordRange(model, selection);
    let requestIsValid = Boolean(this._wordRange && this._wordRange.equalsRange(currentWordRange));
    for (let i = 0, len = decorations2.length; !requestIsValid && i < len; i++) {
      const range2 = decorations2.getRange(i);
      if (range2 && range2.startLineNumber === lineNumber) {
        if (range2.startColumn <= startColumn && range2.endColumn >= endColumn) {
          requestIsValid = true;
        }
      }
    }
    return requestIsValid;
  }
  cancel() {
    this.result.cancel();
  }
}
class SemanticOccurenceAtPositionRequest extends OccurenceAtPositionRequest {
  constructor(model, selection, wordSeparators2, providers) {
    super(model, selection, wordSeparators2);
    this._providers = providers;
  }
  _compute(model, selection, wordSeparators2, token) {
    return getOccurrencesAtPosition(this._providers, model, selection.getPosition(), token).then((value) => value || []);
  }
}
class TextualOccurenceAtPositionRequest extends OccurenceAtPositionRequest {
  constructor(model, selection, wordSeparators2) {
    super(model, selection, wordSeparators2);
    this._selectionIsEmpty = selection.isEmpty();
  }
  _compute(model, selection, wordSeparators2, token) {
    return timeout(250, token).then(() => {
      if (!selection.isEmpty()) {
        return [];
      }
      const word2 = model.getWordAtPosition(selection.getPosition());
      if (!word2 || word2.word.length > 1e3) {
        return [];
      }
      const matches = model.findMatches(word2.word, true, false, true, wordSeparators2, false);
      return matches.map((m) => {
        return {
          range: m.range,
          kind: DocumentHighlightKind$1.Text
        };
      });
    });
  }
  isValid(model, selection, decorations2) {
    const currentSelectionIsEmpty = selection.isEmpty();
    if (this._selectionIsEmpty !== currentSelectionIsEmpty) {
      return false;
    }
    return super.isValid(model, selection, decorations2);
  }
}
function computeOccurencesAtPosition(registry, model, selection, wordSeparators2) {
  if (registry.has(model)) {
    return new SemanticOccurenceAtPositionRequest(model, selection, wordSeparators2, registry);
  }
  return new TextualOccurenceAtPositionRequest(model, selection, wordSeparators2);
}
registerModelAndPositionCommand("_executeDocumentHighlights", (accessor, model, position) => {
  const languageFeaturesService = accessor.get(ILanguageFeaturesService);
  return getOccurrencesAtPosition(languageFeaturesService.documentHighlightProvider, model, position, CancellationToken.None);
});
class WordHighlighter {
  constructor(editor2, providers, linkedHighlighters, contextKeyService) {
    this.toUnhook = new DisposableStore();
    this.workerRequestTokenId = 0;
    this.workerRequestCompleted = false;
    this.workerRequestValue = [];
    this.lastCursorPositionChangeTime = 0;
    this.renderDecorationsTimer = -1;
    this.editor = editor2;
    this.providers = providers;
    this.linkedHighlighters = linkedHighlighters;
    this._hasWordHighlights = ctxHasWordHighlights.bindTo(contextKeyService);
    this._ignorePositionChangeEvent = false;
    this.occurrencesHighlight = this.editor.getOption(
      79
      /* EditorOption.occurrencesHighlight */
    );
    this.model = this.editor.getModel();
    this.toUnhook.add(editor2.onDidChangeCursorPosition((e) => {
      if (this._ignorePositionChangeEvent) {
        return;
      }
      if (!this.occurrencesHighlight) {
        return;
      }
      this._onPositionChanged(e);
    }));
    this.toUnhook.add(editor2.onDidChangeModelContent((e) => {
      this._stopAll();
    }));
    this.toUnhook.add(editor2.onDidChangeConfiguration((e) => {
      const newValue = this.editor.getOption(
        79
        /* EditorOption.occurrencesHighlight */
      );
      if (this.occurrencesHighlight !== newValue) {
        this.occurrencesHighlight = newValue;
        this._stopAll();
      }
    }));
    this.decorations = this.editor.createDecorationsCollection();
    this.workerRequestTokenId = 0;
    this.workerRequest = null;
    this.workerRequestCompleted = false;
    this.lastCursorPositionChangeTime = 0;
    this.renderDecorationsTimer = -1;
  }
  hasDecorations() {
    return this.decorations.length > 0;
  }
  restore() {
    if (!this.occurrencesHighlight) {
      return;
    }
    this._run();
  }
  _getSortedHighlights() {
    return this.decorations.getRanges().sort(Range$2.compareRangesUsingStarts);
  }
  moveNext() {
    const highlights = this._getSortedHighlights();
    const index = highlights.findIndex((range2) => range2.containsPosition(this.editor.getPosition()));
    const newIndex = (index + 1) % highlights.length;
    const dest = highlights[newIndex];
    try {
      this._ignorePositionChangeEvent = true;
      this.editor.setPosition(dest.getStartPosition());
      this.editor.revealRangeInCenterIfOutsideViewport(dest);
      const word2 = this._getWord();
      if (word2) {
        const lineContent = this.editor.getModel().getLineContent(dest.startLineNumber);
        alert(`${lineContent}, ${newIndex + 1} of ${highlights.length} for '${word2.word}'`);
      }
    } finally {
      this._ignorePositionChangeEvent = false;
    }
  }
  moveBack() {
    const highlights = this._getSortedHighlights();
    const index = highlights.findIndex((range2) => range2.containsPosition(this.editor.getPosition()));
    const newIndex = (index - 1 + highlights.length) % highlights.length;
    const dest = highlights[newIndex];
    try {
      this._ignorePositionChangeEvent = true;
      this.editor.setPosition(dest.getStartPosition());
      this.editor.revealRangeInCenterIfOutsideViewport(dest);
      const word2 = this._getWord();
      if (word2) {
        const lineContent = this.editor.getModel().getLineContent(dest.startLineNumber);
        alert(`${lineContent}, ${newIndex + 1} of ${highlights.length} for '${word2.word}'`);
      }
    } finally {
      this._ignorePositionChangeEvent = false;
    }
  }
  _removeDecorations() {
    if (this.decorations.length > 0) {
      this.decorations.clear();
      this._hasWordHighlights.set(false);
    }
  }
  _stopAll() {
    this._removeDecorations();
    if (this.renderDecorationsTimer !== -1) {
      clearTimeout(this.renderDecorationsTimer);
      this.renderDecorationsTimer = -1;
    }
    if (this.workerRequest !== null) {
      this.workerRequest.cancel();
      this.workerRequest = null;
    }
    if (!this.workerRequestCompleted) {
      this.workerRequestTokenId++;
      this.workerRequestCompleted = true;
    }
  }
  _onPositionChanged(e) {
    if (!this.occurrencesHighlight) {
      this._stopAll();
      return;
    }
    if (e.reason !== 3) {
      this._stopAll();
      return;
    }
    this._run();
  }
  _getWord() {
    const editorSelection = this.editor.getSelection();
    const lineNumber = editorSelection.startLineNumber;
    const startColumn = editorSelection.startColumn;
    return this.model.getWordAtPosition({
      lineNumber,
      column: startColumn
    });
  }
  _run() {
    const editorSelection = this.editor.getSelection();
    if (editorSelection.startLineNumber !== editorSelection.endLineNumber) {
      this._stopAll();
      return;
    }
    const startColumn = editorSelection.startColumn;
    const endColumn = editorSelection.endColumn;
    const word2 = this._getWord();
    if (!word2 || word2.startColumn > startColumn || word2.endColumn < endColumn) {
      this._stopAll();
      return;
    }
    const workerRequestIsValid = this.workerRequest && this.workerRequest.isValid(this.model, editorSelection, this.decorations);
    this.lastCursorPositionChangeTime = (/* @__PURE__ */ new Date()).getTime();
    if (workerRequestIsValid) {
      if (this.workerRequestCompleted && this.renderDecorationsTimer !== -1) {
        clearTimeout(this.renderDecorationsTimer);
        this.renderDecorationsTimer = -1;
        this._beginRenderDecorations();
      }
    } else {
      this._stopAll();
      const myRequestId = ++this.workerRequestTokenId;
      this.workerRequestCompleted = false;
      this.workerRequest = computeOccurencesAtPosition(this.providers, this.model, this.editor.getSelection(), this.editor.getOption(
        128
        /* EditorOption.wordSeparators */
      ));
      this.workerRequest.result.then((data) => {
        if (myRequestId === this.workerRequestTokenId) {
          this.workerRequestCompleted = true;
          this.workerRequestValue = data || [];
          this._beginRenderDecorations();
        }
      }, onUnexpectedError);
    }
  }
  _beginRenderDecorations() {
    const currentTime = (/* @__PURE__ */ new Date()).getTime();
    const minimumRenderTime = this.lastCursorPositionChangeTime + 250;
    if (currentTime >= minimumRenderTime) {
      this.renderDecorationsTimer = -1;
      this.renderDecorations();
    } else {
      this.renderDecorationsTimer = setTimeout(() => {
        this.renderDecorations();
      }, minimumRenderTime - currentTime);
    }
  }
  renderDecorations() {
    this.renderDecorationsTimer = -1;
    const decorations2 = [];
    for (const info of this.workerRequestValue) {
      if (info.range) {
        decorations2.push({
          range: info.range,
          options: getHighlightDecorationOptions(info.kind)
        });
      }
    }
    this.decorations.set(decorations2);
    this._hasWordHighlights.set(this.hasDecorations());
    for (const other of this.linkedHighlighters()) {
      if ((other === null || other === void 0 ? void 0 : other.editor.getModel()) === this.editor.getModel()) {
        other._stopAll();
        other.decorations.set(decorations2);
        other._hasWordHighlights.set(other.hasDecorations());
      }
    }
  }
  dispose() {
    this._stopAll();
    this.toUnhook.dispose();
  }
}
let WordHighlighterContribution = class WordHighlighterContribution2 extends Disposable {
  static get(editor2) {
    return editor2.getContribution(WordHighlighterContribution2.ID);
  }
  constructor(editor2, contextKeyService, languageFeaturesService) {
    super();
    this.wordHighlighter = null;
    this.linkedContributions = /* @__PURE__ */ new Set();
    const createWordHighlighterIfPossible = () => {
      if (editor2.hasModel()) {
        this.wordHighlighter = new WordHighlighter(editor2, languageFeaturesService.documentHighlightProvider, () => Iterable.map(this.linkedContributions, (c) => c.wordHighlighter), contextKeyService);
      }
    };
    this._register(editor2.onDidChangeModel((e) => {
      if (this.wordHighlighter) {
        this.wordHighlighter.dispose();
        this.wordHighlighter = null;
      }
      createWordHighlighterIfPossible();
    }));
    createWordHighlighterIfPossible();
  }
  saveViewState() {
    if (this.wordHighlighter && this.wordHighlighter.hasDecorations()) {
      return true;
    }
    return false;
  }
  moveNext() {
    var _a2;
    (_a2 = this.wordHighlighter) === null || _a2 === void 0 ? void 0 : _a2.moveNext();
  }
  moveBack() {
    var _a2;
    (_a2 = this.wordHighlighter) === null || _a2 === void 0 ? void 0 : _a2.moveBack();
  }
  restoreViewState(state) {
    if (this.wordHighlighter && state) {
      this.wordHighlighter.restore();
    }
  }
  dispose() {
    if (this.wordHighlighter) {
      this.wordHighlighter.dispose();
      this.wordHighlighter = null;
    }
    super.dispose();
  }
};
WordHighlighterContribution.ID = "editor.contrib.wordHighlighter";
WordHighlighterContribution = __decorate$z([
  __param$x(1, IContextKeyService),
  __param$x(2, ILanguageFeaturesService)
], WordHighlighterContribution);
class WordHighlightNavigationAction extends EditorAction {
  constructor(next, opts) {
    super(opts);
    this._isNext = next;
  }
  run(accessor, editor2) {
    const controller = WordHighlighterContribution.get(editor2);
    if (!controller) {
      return;
    }
    if (this._isNext) {
      controller.moveNext();
    } else {
      controller.moveBack();
    }
  }
}
class NextWordHighlightAction extends WordHighlightNavigationAction {
  constructor() {
    super(true, {
      id: "editor.action.wordHighlight.next",
      label: localize("wordHighlight.next.label", "Go to Next Symbol Highlight"),
      alias: "Go to Next Symbol Highlight",
      precondition: ctxHasWordHighlights,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 65,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
}
class PrevWordHighlightAction extends WordHighlightNavigationAction {
  constructor() {
    super(false, {
      id: "editor.action.wordHighlight.prev",
      label: localize("wordHighlight.previous.label", "Go to Previous Symbol Highlight"),
      alias: "Go to Previous Symbol Highlight",
      precondition: ctxHasWordHighlights,
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 1024 | 65,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
}
class TriggerWordHighlightAction extends EditorAction {
  constructor() {
    super({
      id: "editor.action.wordHighlight.trigger",
      label: localize("wordHighlight.trigger.label", "Trigger Symbol Highlight"),
      alias: "Trigger Symbol Highlight",
      precondition: ctxHasWordHighlights.toNegated(),
      kbOpts: {
        kbExpr: EditorContextKeys.editorTextFocus,
        primary: 0,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor, editor2, args) {
    const controller = WordHighlighterContribution.get(editor2);
    if (!controller) {
      return;
    }
    controller.restoreViewState(true);
  }
}
registerEditorContribution(
  WordHighlighterContribution.ID,
  WordHighlighterContribution,
  0
  /* EditorContributionInstantiation.Eager */
);
registerEditorAction(NextWordHighlightAction);
registerEditorAction(PrevWordHighlightAction);
registerEditorAction(TriggerWordHighlightAction);
class MoveWordCommand extends EditorCommand {
  constructor(opts) {
    super(opts);
    this._inSelectionMode = opts.inSelectionMode;
    this._wordNavigationType = opts.wordNavigationType;
  }
  runEditorCommand(accessor, editor2, args) {
    if (!editor2.hasModel()) {
      return;
    }
    const wordSeparators2 = getMapForWordSeparators(editor2.getOption(
      128
      /* EditorOption.wordSeparators */
    ));
    const model = editor2.getModel();
    const selections2 = editor2.getSelections();
    const result2 = selections2.map((sel) => {
      const inPosition = new Position$2(sel.positionLineNumber, sel.positionColumn);
      const outPosition = this._move(wordSeparators2, model, inPosition, this._wordNavigationType);
      return this._moveTo(sel, outPosition, this._inSelectionMode);
    });
    model.pushStackElement();
    editor2._getViewModel().setCursorStates("moveWordCommand", 3, result2.map((r) => CursorState$1.fromModelSelection(r)));
    if (result2.length === 1) {
      const pos = new Position$2(result2[0].positionLineNumber, result2[0].positionColumn);
      editor2.revealPosition(
        pos,
        0
        /* ScrollType.Smooth */
      );
    }
  }
  _moveTo(from2, to, inSelectionMode) {
    if (inSelectionMode) {
      return new Selection$1(from2.selectionStartLineNumber, from2.selectionStartColumn, to.lineNumber, to.column);
    } else {
      return new Selection$1(to.lineNumber, to.column, to.lineNumber, to.column);
    }
  }
}
class WordLeftCommand extends MoveWordCommand {
  _move(wordSeparators2, model, position, wordNavigationType) {
    return WordOperations.moveWordLeft(wordSeparators2, model, position, wordNavigationType);
  }
}
class WordRightCommand extends MoveWordCommand {
  _move(wordSeparators2, model, position, wordNavigationType) {
    return WordOperations.moveWordRight(wordSeparators2, model, position, wordNavigationType);
  }
}
class CursorWordStartLeft extends WordLeftCommand {
  constructor() {
    super({
      inSelectionMode: false,
      wordNavigationType: 0,
      id: "cursorWordStartLeft",
      precondition: void 0
    });
  }
}
class CursorWordEndLeft extends WordLeftCommand {
  constructor() {
    super({
      inSelectionMode: false,
      wordNavigationType: 2,
      id: "cursorWordEndLeft",
      precondition: void 0
    });
  }
}
class CursorWordLeft extends WordLeftCommand {
  constructor() {
    var _a2;
    super({
      inSelectionMode: false,
      wordNavigationType: 1,
      id: "cursorWordLeft",
      precondition: void 0,
      kbOpts: {
        kbExpr: ContextKeyExpr.and(EditorContextKeys.textInputFocus, (_a2 = ContextKeyExpr.and(CONTEXT_ACCESSIBILITY_MODE_ENABLED, IsWindowsContext)) === null || _a2 === void 0 ? void 0 : _a2.negate()),
        primary: 2048 | 15,
        mac: {
          primary: 512 | 15
          /* KeyCode.LeftArrow */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
}
class CursorWordStartLeftSelect extends WordLeftCommand {
  constructor() {
    super({
      inSelectionMode: true,
      wordNavigationType: 0,
      id: "cursorWordStartLeftSelect",
      precondition: void 0
    });
  }
}
class CursorWordEndLeftSelect extends WordLeftCommand {
  constructor() {
    super({
      inSelectionMode: true,
      wordNavigationType: 2,
      id: "cursorWordEndLeftSelect",
      precondition: void 0
    });
  }
}
class CursorWordLeftSelect extends WordLeftCommand {
  constructor() {
    var _a2;
    super({
      inSelectionMode: true,
      wordNavigationType: 1,
      id: "cursorWordLeftSelect",
      precondition: void 0,
      kbOpts: {
        kbExpr: ContextKeyExpr.and(EditorContextKeys.textInputFocus, (_a2 = ContextKeyExpr.and(CONTEXT_ACCESSIBILITY_MODE_ENABLED, IsWindowsContext)) === null || _a2 === void 0 ? void 0 : _a2.negate()),
        primary: 2048 | 1024 | 15,
        mac: {
          primary: 512 | 1024 | 15
          /* KeyCode.LeftArrow */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
}
class CursorWordAccessibilityLeft extends WordLeftCommand {
  constructor() {
    super({
      inSelectionMode: false,
      wordNavigationType: 3,
      id: "cursorWordAccessibilityLeft",
      precondition: void 0
    });
  }
  _move(_, model, position, wordNavigationType) {
    return super._move(getMapForWordSeparators(EditorOptions.wordSeparators.defaultValue), model, position, wordNavigationType);
  }
}
class CursorWordAccessibilityLeftSelect extends WordLeftCommand {
  constructor() {
    super({
      inSelectionMode: true,
      wordNavigationType: 3,
      id: "cursorWordAccessibilityLeftSelect",
      precondition: void 0
    });
  }
  _move(_, model, position, wordNavigationType) {
    return super._move(getMapForWordSeparators(EditorOptions.wordSeparators.defaultValue), model, position, wordNavigationType);
  }
}
class CursorWordStartRight extends WordRightCommand {
  constructor() {
    super({
      inSelectionMode: false,
      wordNavigationType: 0,
      id: "cursorWordStartRight",
      precondition: void 0
    });
  }
}
class CursorWordEndRight extends WordRightCommand {
  constructor() {
    var _a2;
    super({
      inSelectionMode: false,
      wordNavigationType: 2,
      id: "cursorWordEndRight",
      precondition: void 0,
      kbOpts: {
        kbExpr: ContextKeyExpr.and(EditorContextKeys.textInputFocus, (_a2 = ContextKeyExpr.and(CONTEXT_ACCESSIBILITY_MODE_ENABLED, IsWindowsContext)) === null || _a2 === void 0 ? void 0 : _a2.negate()),
        primary: 2048 | 17,
        mac: {
          primary: 512 | 17
          /* KeyCode.RightArrow */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
}
class CursorWordRight extends WordRightCommand {
  constructor() {
    super({
      inSelectionMode: false,
      wordNavigationType: 2,
      id: "cursorWordRight",
      precondition: void 0
    });
  }
}
class CursorWordStartRightSelect extends WordRightCommand {
  constructor() {
    super({
      inSelectionMode: true,
      wordNavigationType: 0,
      id: "cursorWordStartRightSelect",
      precondition: void 0
    });
  }
}
class CursorWordEndRightSelect extends WordRightCommand {
  constructor() {
    var _a2;
    super({
      inSelectionMode: true,
      wordNavigationType: 2,
      id: "cursorWordEndRightSelect",
      precondition: void 0,
      kbOpts: {
        kbExpr: ContextKeyExpr.and(EditorContextKeys.textInputFocus, (_a2 = ContextKeyExpr.and(CONTEXT_ACCESSIBILITY_MODE_ENABLED, IsWindowsContext)) === null || _a2 === void 0 ? void 0 : _a2.negate()),
        primary: 2048 | 1024 | 17,
        mac: {
          primary: 512 | 1024 | 17
          /* KeyCode.RightArrow */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
}
class CursorWordRightSelect extends WordRightCommand {
  constructor() {
    super({
      inSelectionMode: true,
      wordNavigationType: 2,
      id: "cursorWordRightSelect",
      precondition: void 0
    });
  }
}
class CursorWordAccessibilityRight extends WordRightCommand {
  constructor() {
    super({
      inSelectionMode: false,
      wordNavigationType: 3,
      id: "cursorWordAccessibilityRight",
      precondition: void 0
    });
  }
  _move(_, model, position, wordNavigationType) {
    return super._move(getMapForWordSeparators(EditorOptions.wordSeparators.defaultValue), model, position, wordNavigationType);
  }
}
class CursorWordAccessibilityRightSelect extends WordRightCommand {
  constructor() {
    super({
      inSelectionMode: true,
      wordNavigationType: 3,
      id: "cursorWordAccessibilityRightSelect",
      precondition: void 0
    });
  }
  _move(_, model, position, wordNavigationType) {
    return super._move(getMapForWordSeparators(EditorOptions.wordSeparators.defaultValue), model, position, wordNavigationType);
  }
}
class DeleteWordCommand extends EditorCommand {
  constructor(opts) {
    super(opts);
    this._whitespaceHeuristics = opts.whitespaceHeuristics;
    this._wordNavigationType = opts.wordNavigationType;
  }
  runEditorCommand(accessor, editor2, args) {
    const languageConfigurationService = accessor.get(ILanguageConfigurationService);
    if (!editor2.hasModel()) {
      return;
    }
    const wordSeparators2 = getMapForWordSeparators(editor2.getOption(
      128
      /* EditorOption.wordSeparators */
    ));
    const model = editor2.getModel();
    const selections2 = editor2.getSelections();
    const autoClosingBrackets = editor2.getOption(
      6
      /* EditorOption.autoClosingBrackets */
    );
    const autoClosingQuotes = editor2.getOption(
      10
      /* EditorOption.autoClosingQuotes */
    );
    const autoClosingPairs = languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).getAutoClosingPairs();
    const viewModel = editor2._getViewModel();
    const commands = selections2.map((sel) => {
      const deleteRange = this._delete({
        wordSeparators: wordSeparators2,
        model,
        selection: sel,
        whitespaceHeuristics: this._whitespaceHeuristics,
        autoClosingDelete: editor2.getOption(
          8
          /* EditorOption.autoClosingDelete */
        ),
        autoClosingBrackets,
        autoClosingQuotes,
        autoClosingPairs,
        autoClosedCharacters: viewModel.getCursorAutoClosedCharacters()
      }, this._wordNavigationType);
      return new ReplaceCommand(deleteRange, "");
    });
    editor2.pushUndoStop();
    editor2.executeCommands(this.id, commands);
    editor2.pushUndoStop();
  }
}
class DeleteWordLeftCommand extends DeleteWordCommand {
  _delete(ctx, wordNavigationType) {
    const r = WordOperations.deleteWordLeft(ctx, wordNavigationType);
    if (r) {
      return r;
    }
    return new Range$2(1, 1, 1, 1);
  }
}
class DeleteWordRightCommand extends DeleteWordCommand {
  _delete(ctx, wordNavigationType) {
    const r = WordOperations.deleteWordRight(ctx, wordNavigationType);
    if (r) {
      return r;
    }
    const lineCount = ctx.model.getLineCount();
    const maxColumn = ctx.model.getLineMaxColumn(lineCount);
    return new Range$2(lineCount, maxColumn, lineCount, maxColumn);
  }
}
class DeleteWordStartLeft extends DeleteWordLeftCommand {
  constructor() {
    super({
      whitespaceHeuristics: false,
      wordNavigationType: 0,
      id: "deleteWordStartLeft",
      precondition: EditorContextKeys.writable
    });
  }
}
class DeleteWordEndLeft extends DeleteWordLeftCommand {
  constructor() {
    super({
      whitespaceHeuristics: false,
      wordNavigationType: 2,
      id: "deleteWordEndLeft",
      precondition: EditorContextKeys.writable
    });
  }
}
class DeleteWordLeft extends DeleteWordLeftCommand {
  constructor() {
    super({
      whitespaceHeuristics: true,
      wordNavigationType: 0,
      id: "deleteWordLeft",
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 2048 | 1,
        mac: {
          primary: 512 | 1
          /* KeyCode.Backspace */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
}
class DeleteWordStartRight extends DeleteWordRightCommand {
  constructor() {
    super({
      whitespaceHeuristics: false,
      wordNavigationType: 0,
      id: "deleteWordStartRight",
      precondition: EditorContextKeys.writable
    });
  }
}
class DeleteWordEndRight extends DeleteWordRightCommand {
  constructor() {
    super({
      whitespaceHeuristics: false,
      wordNavigationType: 2,
      id: "deleteWordEndRight",
      precondition: EditorContextKeys.writable
    });
  }
}
class DeleteWordRight extends DeleteWordRightCommand {
  constructor() {
    super({
      whitespaceHeuristics: true,
      wordNavigationType: 2,
      id: "deleteWordRight",
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 2048 | 20,
        mac: {
          primary: 512 | 20
          /* KeyCode.Delete */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
}
class DeleteInsideWord extends EditorAction {
  constructor() {
    super({
      id: "deleteInsideWord",
      precondition: EditorContextKeys.writable,
      label: localize("deleteInsideWord", "Delete Word"),
      alias: "Delete Word"
    });
  }
  run(accessor, editor2, args) {
    if (!editor2.hasModel()) {
      return;
    }
    const wordSeparators2 = getMapForWordSeparators(editor2.getOption(
      128
      /* EditorOption.wordSeparators */
    ));
    const model = editor2.getModel();
    const selections2 = editor2.getSelections();
    const commands = selections2.map((sel) => {
      const deleteRange = WordOperations.deleteInsideWord(wordSeparators2, model, sel);
      return new ReplaceCommand(deleteRange, "");
    });
    editor2.pushUndoStop();
    editor2.executeCommands(this.id, commands);
    editor2.pushUndoStop();
  }
}
registerEditorCommand(new CursorWordStartLeft());
registerEditorCommand(new CursorWordEndLeft());
registerEditorCommand(new CursorWordLeft());
registerEditorCommand(new CursorWordStartLeftSelect());
registerEditorCommand(new CursorWordEndLeftSelect());
registerEditorCommand(new CursorWordLeftSelect());
registerEditorCommand(new CursorWordStartRight());
registerEditorCommand(new CursorWordEndRight());
registerEditorCommand(new CursorWordRight());
registerEditorCommand(new CursorWordStartRightSelect());
registerEditorCommand(new CursorWordEndRightSelect());
registerEditorCommand(new CursorWordRightSelect());
registerEditorCommand(new CursorWordAccessibilityLeft());
registerEditorCommand(new CursorWordAccessibilityLeftSelect());
registerEditorCommand(new CursorWordAccessibilityRight());
registerEditorCommand(new CursorWordAccessibilityRightSelect());
registerEditorCommand(new DeleteWordStartLeft());
registerEditorCommand(new DeleteWordEndLeft());
registerEditorCommand(new DeleteWordLeft());
registerEditorCommand(new DeleteWordStartRight());
registerEditorCommand(new DeleteWordEndRight());
registerEditorCommand(new DeleteWordRight());
registerEditorAction(DeleteInsideWord);
class DeleteWordPartLeft extends DeleteWordCommand {
  constructor() {
    super({
      whitespaceHeuristics: true,
      wordNavigationType: 0,
      id: "deleteWordPartLeft",
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 0,
        mac: {
          primary: 256 | 512 | 1
          /* KeyCode.Backspace */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  _delete(ctx, wordNavigationType) {
    const r = WordPartOperations.deleteWordPartLeft(ctx);
    if (r) {
      return r;
    }
    return new Range$2(1, 1, 1, 1);
  }
}
class DeleteWordPartRight extends DeleteWordCommand {
  constructor() {
    super({
      whitespaceHeuristics: true,
      wordNavigationType: 2,
      id: "deleteWordPartRight",
      precondition: EditorContextKeys.writable,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 0,
        mac: {
          primary: 256 | 512 | 20
          /* KeyCode.Delete */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  _delete(ctx, wordNavigationType) {
    const r = WordPartOperations.deleteWordPartRight(ctx);
    if (r) {
      return r;
    }
    const lineCount = ctx.model.getLineCount();
    const maxColumn = ctx.model.getLineMaxColumn(lineCount);
    return new Range$2(lineCount, maxColumn, lineCount, maxColumn);
  }
}
class WordPartLeftCommand extends MoveWordCommand {
  _move(wordSeparators2, model, position, wordNavigationType) {
    return WordPartOperations.moveWordPartLeft(wordSeparators2, model, position);
  }
}
class CursorWordPartLeft extends WordPartLeftCommand {
  constructor() {
    super({
      inSelectionMode: false,
      wordNavigationType: 0,
      id: "cursorWordPartLeft",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 0,
        mac: {
          primary: 256 | 512 | 15
          /* KeyCode.LeftArrow */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
}
CommandsRegistry.registerCommandAlias("cursorWordPartStartLeft", "cursorWordPartLeft");
class CursorWordPartLeftSelect extends WordPartLeftCommand {
  constructor() {
    super({
      inSelectionMode: true,
      wordNavigationType: 0,
      id: "cursorWordPartLeftSelect",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 0,
        mac: {
          primary: 256 | 512 | 1024 | 15
          /* KeyCode.LeftArrow */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
}
CommandsRegistry.registerCommandAlias("cursorWordPartStartLeftSelect", "cursorWordPartLeftSelect");
class WordPartRightCommand extends MoveWordCommand {
  _move(wordSeparators2, model, position, wordNavigationType) {
    return WordPartOperations.moveWordPartRight(wordSeparators2, model, position);
  }
}
class CursorWordPartRight extends WordPartRightCommand {
  constructor() {
    super({
      inSelectionMode: false,
      wordNavigationType: 2,
      id: "cursorWordPartRight",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 0,
        mac: {
          primary: 256 | 512 | 17
          /* KeyCode.RightArrow */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
}
class CursorWordPartRightSelect extends WordPartRightCommand {
  constructor() {
    super({
      inSelectionMode: true,
      wordNavigationType: 2,
      id: "cursorWordPartRightSelect",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.textInputFocus,
        primary: 0,
        mac: {
          primary: 256 | 512 | 1024 | 17
          /* KeyCode.RightArrow */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
}
registerEditorCommand(new DeleteWordPartLeft());
registerEditorCommand(new DeleteWordPartRight());
registerEditorCommand(new CursorWordPartLeft());
registerEditorCommand(new CursorWordPartLeftSelect());
registerEditorCommand(new CursorWordPartRight());
registerEditorCommand(new CursorWordPartRightSelect());
class ReadOnlyMessageController extends Disposable {
  constructor(editor2) {
    super();
    this.editor = editor2;
    this._register(this.editor.onDidAttemptReadOnlyEdit(() => this._onDidAttemptReadOnlyEdit()));
  }
  _onDidAttemptReadOnlyEdit() {
    const messageController2 = MessageController.get(this.editor);
    if (messageController2 && this.editor.hasModel()) {
      let message = this.editor.getOptions().get(
        90
        /* EditorOption.readOnlyMessage */
      );
      if (!message) {
        if (this.editor.isSimpleWidget) {
          message = new MarkdownString(localize("editor.simple.readonly", "Cannot edit in read-only input"));
        } else {
          message = new MarkdownString(localize("editor.readonly", "Cannot edit in read-only editor"));
        }
      }
      messageController2.showMessage(message, this.editor.getPosition());
    }
  }
}
ReadOnlyMessageController.ID = "editor.contrib.readOnlyMessageController";
registerEditorContribution(
  ReadOnlyMessageController.ID,
  ReadOnlyMessageController,
  2
  /* EditorContributionInstantiation.BeforeFirstInteraction */
);
var InspectTokensNLS;
(function(InspectTokensNLS2) {
  InspectTokensNLS2.inspectTokensAction = localize("inspectTokens", "Developer: Inspect Tokens");
})(InspectTokensNLS || (InspectTokensNLS = {}));
var GoToLineNLS;
(function(GoToLineNLS2) {
  GoToLineNLS2.gotoLineActionLabel = localize("gotoLineActionLabel", "Go to Line/Column...");
})(GoToLineNLS || (GoToLineNLS = {}));
var QuickHelpNLS;
(function(QuickHelpNLS2) {
  QuickHelpNLS2.helpQuickAccessActionLabel = localize("helpQuickAccess", "Show all Quick Access Providers");
})(QuickHelpNLS || (QuickHelpNLS = {}));
var QuickCommandNLS;
(function(QuickCommandNLS2) {
  QuickCommandNLS2.quickCommandActionLabel = localize("quickCommandActionLabel", "Command Palette");
  QuickCommandNLS2.quickCommandHelp = localize("quickCommandActionHelp", "Show And Run Commands");
})(QuickCommandNLS || (QuickCommandNLS = {}));
var QuickOutlineNLS;
(function(QuickOutlineNLS2) {
  QuickOutlineNLS2.quickOutlineActionLabel = localize("quickOutlineActionLabel", "Go to Symbol...");
  QuickOutlineNLS2.quickOutlineByCategoryActionLabel = localize("quickOutlineByCategoryActionLabel", "Go to Symbol by Category...");
})(QuickOutlineNLS || (QuickOutlineNLS = {}));
var StandaloneCodeEditorNLS;
(function(StandaloneCodeEditorNLS2) {
  StandaloneCodeEditorNLS2.editorViewAccessibleLabel = localize("editorViewAccessibleLabel", "Editor content");
  StandaloneCodeEditorNLS2.accessibilityHelpMessage = localize("accessibilityHelpMessage", "Press Alt+F1 for Accessibility Options.");
})(StandaloneCodeEditorNLS || (StandaloneCodeEditorNLS = {}));
var ToggleHighContrastNLS;
(function(ToggleHighContrastNLS2) {
  ToggleHighContrastNLS2.toggleHighContrast = localize("toggleHighContrast", "Toggle High Contrast Theme");
})(ToggleHighContrastNLS || (ToggleHighContrastNLS = {}));
var StandaloneServicesNLS;
(function(StandaloneServicesNLS2) {
  StandaloneServicesNLS2.bulkEditServiceSummary = localize("bulkEditServiceSummary", "Made {0} edits in {1} files");
})(StandaloneServicesNLS || (StandaloneServicesNLS = {}));
const iPadShowKeyboard = "";
class IPadShowKeyboard extends Disposable {
  constructor(editor2) {
    super();
    this.editor = editor2;
    this.widget = null;
    if (isIOS) {
      this._register(editor2.onDidChangeConfiguration(() => this.update()));
      this.update();
    }
  }
  update() {
    const shouldHaveWidget = !this.editor.getOption(
      89
      /* EditorOption.readOnly */
    );
    if (!this.widget && shouldHaveWidget) {
      this.widget = new ShowKeyboardWidget(this.editor);
    } else if (this.widget && !shouldHaveWidget) {
      this.widget.dispose();
      this.widget = null;
    }
  }
  dispose() {
    super.dispose();
    if (this.widget) {
      this.widget.dispose();
      this.widget = null;
    }
  }
}
IPadShowKeyboard.ID = "editor.contrib.iPadShowKeyboard";
class ShowKeyboardWidget extends Disposable {
  constructor(editor2) {
    super();
    this.editor = editor2;
    this._domNode = document.createElement("textarea");
    this._domNode.className = "iPadShowKeyboard";
    this._register(addDisposableListener(this._domNode, "touchstart", (e) => {
      this.editor.focus();
    }));
    this._register(addDisposableListener(this._domNode, "focus", (e) => {
      this.editor.focus();
    }));
    this.editor.addOverlayWidget(this);
  }
  dispose() {
    this.editor.removeOverlayWidget(this);
    super.dispose();
  }
  // ----- IOverlayWidget API
  getId() {
    return ShowKeyboardWidget.ID;
  }
  getDomNode() {
    return this._domNode;
  }
  getPosition() {
    return {
      preference: 1
      /* OverlayWidgetPositionPreference.BOTTOM_RIGHT_CORNER */
    };
  }
}
ShowKeyboardWidget.ID = "editor.contrib.ShowKeyboardWidget";
registerEditorContribution(
  IPadShowKeyboard.ID,
  IPadShowKeyboard,
  3
  /* EditorContributionInstantiation.Eventually */
);
const inspectTokens = "";
const IStandaloneThemeService = createDecorator("themeService");
var __decorate$y = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$w = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let InspectTokensController = class InspectTokensController2 extends Disposable {
  static get(editor2) {
    return editor2.getContribution(InspectTokensController2.ID);
  }
  constructor(editor2, standaloneColorService, languageService) {
    super();
    this._editor = editor2;
    this._languageService = languageService;
    this._widget = null;
    this._register(this._editor.onDidChangeModel((e) => this.stop()));
    this._register(this._editor.onDidChangeModelLanguage((e) => this.stop()));
    this._register(TokenizationRegistry2.onDidChange((e) => this.stop()));
    this._register(this._editor.onKeyUp((e) => e.keyCode === 9 && this.stop()));
  }
  dispose() {
    this.stop();
    super.dispose();
  }
  launch() {
    if (this._widget) {
      return;
    }
    if (!this._editor.hasModel()) {
      return;
    }
    this._widget = new InspectTokensWidget(this._editor, this._languageService);
  }
  stop() {
    if (this._widget) {
      this._widget.dispose();
      this._widget = null;
    }
  }
};
InspectTokensController.ID = "editor.contrib.inspectTokens";
InspectTokensController = __decorate$y([
  __param$w(1, IStandaloneThemeService),
  __param$w(2, ILanguageService)
], InspectTokensController);
class InspectTokens extends EditorAction {
  constructor() {
    super({
      id: "editor.action.inspectTokens",
      label: InspectTokensNLS.inspectTokensAction,
      alias: "Developer: Inspect Tokens",
      precondition: void 0
    });
  }
  run(accessor, editor2) {
    const controller = InspectTokensController.get(editor2);
    controller === null || controller === void 0 ? void 0 : controller.launch();
  }
}
function renderTokenText(tokenText) {
  let result2 = "";
  for (let charIndex = 0, len = tokenText.length; charIndex < len; charIndex++) {
    const charCode = tokenText.charCodeAt(charIndex);
    switch (charCode) {
      case 9:
        result2 += "→";
        break;
      case 32:
        result2 += "·";
        break;
      default:
        result2 += String.fromCharCode(charCode);
    }
  }
  return result2;
}
function getSafeTokenizationSupport$1(languageIdCodec, languageId) {
  const tokenizationSupport = TokenizationRegistry2.get(languageId);
  if (tokenizationSupport) {
    return tokenizationSupport;
  }
  const encodedLanguageId = languageIdCodec.encodeLanguageId(languageId);
  return {
    getInitialState: () => NullState,
    tokenize: (line, hasEOL, state) => nullTokenize(languageId, state),
    tokenizeEncoded: (line, hasEOL, state) => nullTokenizeEncoded(encodedLanguageId, state)
  };
}
class InspectTokensWidget extends Disposable {
  constructor(editor2, languageService) {
    super();
    this.allowEditorOverflow = true;
    this._editor = editor2;
    this._languageService = languageService;
    this._model = this._editor.getModel();
    this._domNode = document.createElement("div");
    this._domNode.className = "tokens-inspect-widget";
    this._tokenizationSupport = getSafeTokenizationSupport$1(this._languageService.languageIdCodec, this._model.getLanguageId());
    this._compute(this._editor.getPosition());
    this._register(this._editor.onDidChangeCursorPosition((e) => this._compute(this._editor.getPosition())));
    this._editor.addContentWidget(this);
  }
  dispose() {
    this._editor.removeContentWidget(this);
    super.dispose();
  }
  getId() {
    return InspectTokensWidget._ID;
  }
  _compute(position) {
    const data = this._getTokensAtLine(position.lineNumber);
    let token1Index = 0;
    for (let i = data.tokens1.length - 1; i >= 0; i--) {
      const t = data.tokens1[i];
      if (position.column - 1 >= t.offset) {
        token1Index = i;
        break;
      }
    }
    let token2Index = 0;
    for (let i = data.tokens2.length >>> 1; i >= 0; i--) {
      if (position.column - 1 >= data.tokens2[i << 1]) {
        token2Index = i;
        break;
      }
    }
    const lineContent = this._model.getLineContent(position.lineNumber);
    let tokenText = "";
    if (token1Index < data.tokens1.length) {
      const tokenStartIndex = data.tokens1[token1Index].offset;
      const tokenEndIndex = token1Index + 1 < data.tokens1.length ? data.tokens1[token1Index + 1].offset : lineContent.length;
      tokenText = lineContent.substring(tokenStartIndex, tokenEndIndex);
    }
    reset(this._domNode, $$d("h2.tm-token", void 0, renderTokenText(tokenText), $$d("span.tm-token-length", void 0, `${tokenText.length} ${tokenText.length === 1 ? "char" : "chars"}`)));
    append$1(this._domNode, $$d("hr.tokens-inspect-separator", { "style": "clear:both" }));
    const metadata = (token2Index << 1) + 1 < data.tokens2.length ? this._decodeMetadata(data.tokens2[(token2Index << 1) + 1]) : null;
    append$1(this._domNode, $$d("table.tm-metadata-table", void 0, $$d("tbody", void 0, $$d("tr", void 0, $$d("td.tm-metadata-key", void 0, "language"), $$d("td.tm-metadata-value", void 0, `${metadata ? metadata.languageId : "-?-"}`)), $$d("tr", void 0, $$d("td.tm-metadata-key", void 0, "token type"), $$d("td.tm-metadata-value", void 0, `${metadata ? this._tokenTypeToString(metadata.tokenType) : "-?-"}`)), $$d("tr", void 0, $$d("td.tm-metadata-key", void 0, "font style"), $$d("td.tm-metadata-value", void 0, `${metadata ? this._fontStyleToString(metadata.fontStyle) : "-?-"}`)), $$d("tr", void 0, $$d("td.tm-metadata-key", void 0, "foreground"), $$d("td.tm-metadata-value", void 0, `${metadata ? Color.Format.CSS.formatHex(metadata.foreground) : "-?-"}`)), $$d("tr", void 0, $$d("td.tm-metadata-key", void 0, "background"), $$d("td.tm-metadata-value", void 0, `${metadata ? Color.Format.CSS.formatHex(metadata.background) : "-?-"}`)))));
    append$1(this._domNode, $$d("hr.tokens-inspect-separator"));
    if (token1Index < data.tokens1.length) {
      append$1(this._domNode, $$d("span.tm-token-type", void 0, data.tokens1[token1Index].type));
    }
    this._editor.layoutContentWidget(this);
  }
  _decodeMetadata(metadata) {
    const colorMap = TokenizationRegistry2.getColorMap();
    const languageId = TokenMetadata.getLanguageId(metadata);
    const tokenType = TokenMetadata.getTokenType(metadata);
    const fontStyle = TokenMetadata.getFontStyle(metadata);
    const foreground2 = TokenMetadata.getForeground(metadata);
    const background = TokenMetadata.getBackground(metadata);
    return {
      languageId: this._languageService.languageIdCodec.decodeLanguageId(languageId),
      tokenType,
      fontStyle,
      foreground: colorMap[foreground2],
      background: colorMap[background]
    };
  }
  _tokenTypeToString(tokenType) {
    switch (tokenType) {
      case 0:
        return "Other";
      case 1:
        return "Comment";
      case 2:
        return "String";
      case 3:
        return "RegEx";
      default:
        return "??";
    }
  }
  _fontStyleToString(fontStyle) {
    let r = "";
    if (fontStyle & 1) {
      r += "italic ";
    }
    if (fontStyle & 2) {
      r += "bold ";
    }
    if (fontStyle & 4) {
      r += "underline ";
    }
    if (fontStyle & 8) {
      r += "strikethrough ";
    }
    if (r.length === 0) {
      r = "---";
    }
    return r;
  }
  _getTokensAtLine(lineNumber) {
    const stateBeforeLine = this._getStateBeforeLine(lineNumber);
    const tokenizationResult1 = this._tokenizationSupport.tokenize(this._model.getLineContent(lineNumber), true, stateBeforeLine);
    const tokenizationResult2 = this._tokenizationSupport.tokenizeEncoded(this._model.getLineContent(lineNumber), true, stateBeforeLine);
    return {
      startState: stateBeforeLine,
      tokens1: tokenizationResult1.tokens,
      tokens2: tokenizationResult2.tokens,
      endState: tokenizationResult1.endState
    };
  }
  _getStateBeforeLine(lineNumber) {
    let state = this._tokenizationSupport.getInitialState();
    for (let i = 1; i < lineNumber; i++) {
      const tokenizationResult = this._tokenizationSupport.tokenize(this._model.getLineContent(i), true, state);
      state = tokenizationResult.endState;
    }
    return state;
  }
  getDomNode() {
    return this._domNode;
  }
  getPosition() {
    return {
      position: this._editor.getPosition(),
      preference: [
        2,
        1
        /* ContentWidgetPositionPreference.ABOVE */
      ]
    };
  }
}
InspectTokensWidget._ID = "editor.contrib.inspectTokensWidget";
registerEditorContribution(
  InspectTokensController.ID,
  InspectTokensController,
  4
  /* EditorContributionInstantiation.Lazy */
);
registerEditorAction(InspectTokens);
var DefaultQuickAccessFilterValue;
(function(DefaultQuickAccessFilterValue2) {
  DefaultQuickAccessFilterValue2[DefaultQuickAccessFilterValue2["PRESERVE"] = 0] = "PRESERVE";
  DefaultQuickAccessFilterValue2[DefaultQuickAccessFilterValue2["LAST"] = 1] = "LAST";
})(DefaultQuickAccessFilterValue || (DefaultQuickAccessFilterValue = {}));
const Extensions = {
  Quickaccess: "workbench.contributions.quickaccess"
};
class QuickAccessRegistry {
  constructor() {
    this.providers = [];
    this.defaultProvider = void 0;
  }
  registerQuickAccessProvider(provider) {
    if (provider.prefix.length === 0) {
      this.defaultProvider = provider;
    } else {
      this.providers.push(provider);
    }
    this.providers.sort((providerA, providerB) => providerB.prefix.length - providerA.prefix.length);
    return toDisposable(() => {
      this.providers.splice(this.providers.indexOf(provider), 1);
      if (this.defaultProvider === provider) {
        this.defaultProvider = void 0;
      }
    });
  }
  getQuickAccessProviders() {
    return coalesce([this.defaultProvider, ...this.providers]);
  }
  getQuickAccessProvider(prefix2) {
    const result2 = prefix2 ? this.providers.find((provider) => prefix2.startsWith(provider.prefix)) || void 0 : void 0;
    return result2 || this.defaultProvider;
  }
}
Registry.add(Extensions.Quickaccess, new QuickAccessRegistry());
var __decorate$x = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$v = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let HelpQuickAccessProvider = class HelpQuickAccessProvider2 {
  constructor(quickInputService, keybindingService) {
    this.quickInputService = quickInputService;
    this.keybindingService = keybindingService;
    this.registry = Registry.as(Extensions.Quickaccess);
  }
  provide(picker) {
    const disposables = new DisposableStore();
    disposables.add(picker.onDidAccept(() => {
      const [item] = picker.selectedItems;
      if (item) {
        this.quickInputService.quickAccess.show(item.prefix, { preserveValue: true });
      }
    }));
    disposables.add(picker.onDidChangeValue((value) => {
      const providerDescriptor = this.registry.getQuickAccessProvider(value.substr(HelpQuickAccessProvider2.PREFIX.length));
      if (providerDescriptor && providerDescriptor.prefix && providerDescriptor.prefix !== HelpQuickAccessProvider2.PREFIX) {
        this.quickInputService.quickAccess.show(providerDescriptor.prefix, { preserveValue: true });
      }
    }));
    picker.items = this.getQuickAccessProviders().filter((p2) => p2.prefix !== HelpQuickAccessProvider2.PREFIX);
    return disposables;
  }
  getQuickAccessProviders() {
    const providers = this.registry.getQuickAccessProviders().sort((providerA, providerB) => providerA.prefix.localeCompare(providerB.prefix)).flatMap((provider) => this.createPicks(provider));
    return providers;
  }
  createPicks(provider) {
    return provider.helpEntries.map((helpEntry) => {
      const prefix2 = helpEntry.prefix || provider.prefix;
      const label = prefix2 || "…";
      return {
        prefix: prefix2,
        label,
        keybinding: helpEntry.commandId ? this.keybindingService.lookupKeybinding(helpEntry.commandId) : void 0,
        ariaLabel: localize("helpPickAriaLabel", "{0}, {1}", label, helpEntry.description),
        description: helpEntry.description
      };
    });
  }
};
HelpQuickAccessProvider.PREFIX = "?";
HelpQuickAccessProvider = __decorate$x([
  __param$v(0, IQuickInputService),
  __param$v(1, IKeybindingService)
], HelpQuickAccessProvider);
Registry.as(Extensions.Quickaccess).registerQuickAccessProvider({
  ctor: HelpQuickAccessProvider,
  prefix: "",
  helpEntries: [{ description: QuickHelpNLS.helpQuickAccessActionLabel }]
});
class AbstractEditorNavigationQuickAccessProvider {
  constructor(options) {
    this.options = options;
    this.rangeHighlightDecorationId = void 0;
  }
  //#region Provider methods
  provide(picker, token) {
    var _a2;
    const disposables = new DisposableStore();
    picker.canAcceptInBackground = !!((_a2 = this.options) === null || _a2 === void 0 ? void 0 : _a2.canAcceptInBackground);
    picker.matchOnLabel = picker.matchOnDescription = picker.matchOnDetail = picker.sortByLabel = false;
    const pickerDisposable = disposables.add(new MutableDisposable());
    pickerDisposable.value = this.doProvide(picker, token);
    disposables.add(this.onDidActiveTextEditorControlChange(() => {
      pickerDisposable.value = void 0;
      pickerDisposable.value = this.doProvide(picker, token);
    }));
    return disposables;
  }
  doProvide(picker, token) {
    const disposables = new DisposableStore();
    const editor2 = this.activeTextEditorControl;
    if (editor2 && this.canProvideWithTextEditor(editor2)) {
      const context = { editor: editor2 };
      const codeEditor = getCodeEditor(editor2);
      if (codeEditor) {
        let lastKnownEditorViewState = withNullAsUndefined(editor2.saveViewState());
        disposables.add(codeEditor.onDidChangeCursorPosition(() => {
          lastKnownEditorViewState = withNullAsUndefined(editor2.saveViewState());
        }));
        context.restoreViewState = () => {
          if (lastKnownEditorViewState && editor2 === this.activeTextEditorControl) {
            editor2.restoreViewState(lastKnownEditorViewState);
          }
        };
        disposables.add(once$2(token.onCancellationRequested)(() => {
          var _a2;
          return (_a2 = context.restoreViewState) === null || _a2 === void 0 ? void 0 : _a2.call(context);
        }));
      }
      disposables.add(toDisposable(() => this.clearDecorations(editor2)));
      disposables.add(this.provideWithTextEditor(context, picker, token));
    } else {
      disposables.add(this.provideWithoutTextEditor(picker, token));
    }
    return disposables;
  }
  /**
   * Subclasses to implement if they can operate on the text editor.
   */
  canProvideWithTextEditor(editor2) {
    return true;
  }
  gotoLocation({ editor: editor2 }, options) {
    editor2.setSelection(options.range);
    editor2.revealRangeInCenter(
      options.range,
      0
      /* ScrollType.Smooth */
    );
    if (!options.preserveFocus) {
      editor2.focus();
    }
    const model = editor2.getModel();
    if (model && "getLineContent" in model) {
      status(`${model.getLineContent(options.range.startLineNumber)}`);
    }
  }
  getModel(editor2) {
    var _a2;
    return isDiffEditor(editor2) ? (_a2 = editor2.getModel()) === null || _a2 === void 0 ? void 0 : _a2.modified : editor2.getModel();
  }
  addDecorations(editor2, range2) {
    editor2.changeDecorations((changeAccessor) => {
      const deleteDecorations = [];
      if (this.rangeHighlightDecorationId) {
        deleteDecorations.push(this.rangeHighlightDecorationId.overviewRulerDecorationId);
        deleteDecorations.push(this.rangeHighlightDecorationId.rangeHighlightId);
        this.rangeHighlightDecorationId = void 0;
      }
      const newDecorations = [
        // highlight the entire line on the range
        {
          range: range2,
          options: {
            description: "quick-access-range-highlight",
            className: "rangeHighlight",
            isWholeLine: true
          }
        },
        // also add overview ruler highlight
        {
          range: range2,
          options: {
            description: "quick-access-range-highlight-overview",
            overviewRuler: {
              color: themeColorFromId(overviewRulerRangeHighlight),
              position: OverviewRulerLane$1.Full
            }
          }
        }
      ];
      const [rangeHighlightId, overviewRulerDecorationId] = changeAccessor.deltaDecorations(deleteDecorations, newDecorations);
      this.rangeHighlightDecorationId = { rangeHighlightId, overviewRulerDecorationId };
    });
  }
  clearDecorations(editor2) {
    const rangeHighlightDecorationId = this.rangeHighlightDecorationId;
    if (rangeHighlightDecorationId) {
      editor2.changeDecorations((changeAccessor) => {
        changeAccessor.deltaDecorations([
          rangeHighlightDecorationId.overviewRulerDecorationId,
          rangeHighlightDecorationId.rangeHighlightId
        ], []);
      });
      this.rangeHighlightDecorationId = void 0;
    }
  }
}
class AbstractGotoLineQuickAccessProvider extends AbstractEditorNavigationQuickAccessProvider {
  constructor() {
    super({ canAcceptInBackground: true });
  }
  provideWithoutTextEditor(picker) {
    const label = localize("cannotRunGotoLine", "Open a text editor first to go to a line.");
    picker.items = [{ label }];
    picker.ariaLabel = label;
    return Disposable.None;
  }
  provideWithTextEditor(context, picker, token) {
    const editor2 = context.editor;
    const disposables = new DisposableStore();
    disposables.add(picker.onDidAccept((event) => {
      const [item] = picker.selectedItems;
      if (item) {
        if (!this.isValidLineNumber(editor2, item.lineNumber)) {
          return;
        }
        this.gotoLocation(context, { range: this.toRange(item.lineNumber, item.column), keyMods: picker.keyMods, preserveFocus: event.inBackground });
        if (!event.inBackground) {
          picker.hide();
        }
      }
    }));
    const updatePickerAndEditor = () => {
      const position = this.parsePosition(editor2, picker.value.trim().substr(AbstractGotoLineQuickAccessProvider.PREFIX.length));
      const label = this.getPickLabel(editor2, position.lineNumber, position.column);
      picker.items = [{
        lineNumber: position.lineNumber,
        column: position.column,
        label
      }];
      picker.ariaLabel = label;
      if (!this.isValidLineNumber(editor2, position.lineNumber)) {
        this.clearDecorations(editor2);
        return;
      }
      const range2 = this.toRange(position.lineNumber, position.column);
      editor2.revealRangeInCenter(
        range2,
        0
        /* ScrollType.Smooth */
      );
      this.addDecorations(editor2, range2);
    };
    updatePickerAndEditor();
    disposables.add(picker.onDidChangeValue(() => updatePickerAndEditor()));
    const codeEditor = getCodeEditor(editor2);
    if (codeEditor) {
      const options = codeEditor.getOptions();
      const lineNumbers2 = options.get(
        66
        /* EditorOption.lineNumbers */
      );
      if (lineNumbers2.renderType === 2) {
        codeEditor.updateOptions({ lineNumbers: "on" });
        disposables.add(toDisposable(() => codeEditor.updateOptions({ lineNumbers: "relative" })));
      }
    }
    return disposables;
  }
  toRange(lineNumber = 1, column = 1) {
    return {
      startLineNumber: lineNumber,
      startColumn: column,
      endLineNumber: lineNumber,
      endColumn: column
    };
  }
  parsePosition(editor2, value) {
    const numbers = value.split(/,|:|#/).map((part) => parseInt(part, 10)).filter((part) => !isNaN(part));
    const endLine = this.lineCount(editor2) + 1;
    return {
      lineNumber: numbers[0] > 0 ? numbers[0] : endLine + numbers[0],
      column: numbers[1]
    };
  }
  getPickLabel(editor2, lineNumber, column) {
    if (this.isValidLineNumber(editor2, lineNumber)) {
      if (this.isValidColumn(editor2, lineNumber, column)) {
        return localize("gotoLineColumnLabel", "Go to line {0} and character {1}.", lineNumber, column);
      }
      return localize("gotoLineLabel", "Go to line {0}.", lineNumber);
    }
    const position = editor2.getPosition() || { lineNumber: 1, column: 1 };
    const lineCount = this.lineCount(editor2);
    if (lineCount > 1) {
      return localize("gotoLineLabelEmptyWithLimit", "Current Line: {0}, Character: {1}. Type a line number between 1 and {2} to navigate to.", position.lineNumber, position.column, lineCount);
    }
    return localize("gotoLineLabelEmpty", "Current Line: {0}, Character: {1}. Type a line number to navigate to.", position.lineNumber, position.column);
  }
  isValidLineNumber(editor2, lineNumber) {
    if (!lineNumber || typeof lineNumber !== "number") {
      return false;
    }
    return lineNumber > 0 && lineNumber <= this.lineCount(editor2);
  }
  isValidColumn(editor2, lineNumber, column) {
    if (!column || typeof column !== "number") {
      return false;
    }
    const model = this.getModel(editor2);
    if (!model) {
      return false;
    }
    const positionCandidate = { lineNumber, column };
    return model.validatePosition(positionCandidate).equals(positionCandidate);
  }
  lineCount(editor2) {
    var _a2, _b2;
    return (_b2 = (_a2 = this.getModel(editor2)) === null || _a2 === void 0 ? void 0 : _a2.getLineCount()) !== null && _b2 !== void 0 ? _b2 : 0;
  }
}
AbstractGotoLineQuickAccessProvider.PREFIX = ":";
var __decorate$w = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$u = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let StandaloneGotoLineQuickAccessProvider = class StandaloneGotoLineQuickAccessProvider2 extends AbstractGotoLineQuickAccessProvider {
  constructor(editorService) {
    super();
    this.editorService = editorService;
    this.onDidActiveTextEditorControlChange = Event$1.None;
  }
  get activeTextEditorControl() {
    return withNullAsUndefined(this.editorService.getFocusedCodeEditor());
  }
};
StandaloneGotoLineQuickAccessProvider = __decorate$w([
  __param$u(0, ICodeEditorService)
], StandaloneGotoLineQuickAccessProvider);
let GotoLineAction$1 = class GotoLineAction extends EditorAction {
  constructor() {
    super({
      id: GotoLineAction.ID,
      label: GoToLineNLS.gotoLineActionLabel,
      alias: "Go to Line/Column...",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.focus,
        primary: 2048 | 37,
        mac: {
          primary: 256 | 37
          /* KeyCode.KeyG */
        },
        weight: 100
        /* KeybindingWeight.EditorContrib */
      }
    });
  }
  run(accessor) {
    accessor.get(IQuickInputService).quickAccess.show(StandaloneGotoLineQuickAccessProvider.PREFIX);
  }
};
GotoLineAction$1.ID = "editor.action.gotoLine";
registerEditorAction(GotoLineAction$1);
Registry.as(Extensions.Quickaccess).registerQuickAccessProvider({
  ctor: StandaloneGotoLineQuickAccessProvider,
  prefix: StandaloneGotoLineQuickAccessProvider.PREFIX,
  helpEntries: [{ description: GoToLineNLS.gotoLineActionLabel, commandId: GotoLineAction$1.ID }]
});
const NO_SCORE2 = [void 0, []];
function scoreFuzzy2(target, query, patternStart = 0, wordStart = 0) {
  const preparedQuery = query;
  if (preparedQuery.values && preparedQuery.values.length > 1) {
    return doScoreFuzzy2Multiple(target, preparedQuery.values, patternStart, wordStart);
  }
  return doScoreFuzzy2Single(target, query, patternStart, wordStart);
}
function doScoreFuzzy2Multiple(target, query, patternStart, wordStart) {
  let totalScore = 0;
  const totalMatches = [];
  for (const queryPiece of query) {
    const [score2, matches] = doScoreFuzzy2Single(target, queryPiece, patternStart, wordStart);
    if (typeof score2 !== "number") {
      return NO_SCORE2;
    }
    totalScore += score2;
    totalMatches.push(...matches);
  }
  return [totalScore, normalizeMatches(totalMatches)];
}
function doScoreFuzzy2Single(target, query, patternStart, wordStart) {
  const score2 = fuzzyScore(query.original, query.originalLowercase, patternStart, target, target.toLowerCase(), wordStart, { firstMatchCanBeWeak: true, boostFullMatch: true });
  if (!score2) {
    return NO_SCORE2;
  }
  return [score2[0], createMatches(score2)];
}
function normalizeMatches(matches) {
  const sortedMatches = matches.sort((matchA, matchB) => {
    return matchA.start - matchB.start;
  });
  const normalizedMatches = [];
  let currentMatch = void 0;
  for (const match2 of sortedMatches) {
    if (!currentMatch || !matchOverlaps(currentMatch, match2)) {
      currentMatch = match2;
      normalizedMatches.push(match2);
    } else {
      currentMatch.start = Math.min(currentMatch.start, match2.start);
      currentMatch.end = Math.max(currentMatch.end, match2.end);
    }
  }
  return normalizedMatches;
}
function matchOverlaps(matchA, matchB) {
  if (matchA.end < matchB.start) {
    return false;
  }
  if (matchB.end < matchA.start) {
    return false;
  }
  return true;
}
function queryExpectsExactMatch(query) {
  return query.startsWith('"') && query.endsWith('"');
}
const MULTIPLE_QUERY_VALUES_SEPARATOR = " ";
function prepareQuery(original) {
  if (typeof original !== "string") {
    original = "";
  }
  const originalLowercase = original.toLowerCase();
  const { pathNormalized, normalized, normalizedLowercase } = normalizeQuery(original);
  const containsPathSeparator = pathNormalized.indexOf(sep$2) >= 0;
  const expectExactMatch = queryExpectsExactMatch(original);
  let values = void 0;
  const originalSplit = original.split(MULTIPLE_QUERY_VALUES_SEPARATOR);
  if (originalSplit.length > 1) {
    for (const originalPiece of originalSplit) {
      const expectExactMatchPiece = queryExpectsExactMatch(originalPiece);
      const { pathNormalized: pathNormalizedPiece, normalized: normalizedPiece, normalizedLowercase: normalizedLowercasePiece } = normalizeQuery(originalPiece);
      if (normalizedPiece) {
        if (!values) {
          values = [];
        }
        values.push({
          original: originalPiece,
          originalLowercase: originalPiece.toLowerCase(),
          pathNormalized: pathNormalizedPiece,
          normalized: normalizedPiece,
          normalizedLowercase: normalizedLowercasePiece,
          expectContiguousMatch: expectExactMatchPiece
        });
      }
    }
  }
  return { original, originalLowercase, pathNormalized, normalized, normalizedLowercase, values, containsPathSeparator, expectContiguousMatch: expectExactMatch };
}
function normalizeQuery(original) {
  let pathNormalized;
  if (isWindows) {
    pathNormalized = original.replace(/\//g, sep$2);
  } else {
    pathNormalized = original.replace(/\\/g, sep$2);
  }
  const normalized = stripWildcards(pathNormalized).replace(/\s|"/g, "");
  return {
    pathNormalized,
    normalized,
    normalizedLowercase: normalized.toLowerCase()
  };
}
function pieceToQuery(arg1) {
  if (Array.isArray(arg1)) {
    return prepareQuery(arg1.map((piece) => piece.original).join(MULTIPLE_QUERY_VALUES_SEPARATOR));
  }
  return prepareQuery(arg1.original);
}
var __decorate$v = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$t = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$i = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
let AbstractGotoSymbolQuickAccessProvider = class AbstractGotoSymbolQuickAccessProvider2 extends AbstractEditorNavigationQuickAccessProvider {
  constructor(_languageFeaturesService, _outlineModelService, options = /* @__PURE__ */ Object.create(null)) {
    super(options);
    this._languageFeaturesService = _languageFeaturesService;
    this._outlineModelService = _outlineModelService;
    this.options = options;
    this.options.canAcceptInBackground = true;
  }
  provideWithoutTextEditor(picker) {
    this.provideLabelPick(picker, localize("cannotRunGotoSymbolWithoutEditor", "To go to a symbol, first open a text editor with symbol information."));
    return Disposable.None;
  }
  provideWithTextEditor(context, picker, token) {
    const editor2 = context.editor;
    const model = this.getModel(editor2);
    if (!model) {
      return Disposable.None;
    }
    if (this._languageFeaturesService.documentSymbolProvider.has(model)) {
      return this.doProvideWithEditorSymbols(context, model, picker, token);
    }
    return this.doProvideWithoutEditorSymbols(context, model, picker, token);
  }
  doProvideWithoutEditorSymbols(context, model, picker, token) {
    const disposables = new DisposableStore();
    this.provideLabelPick(picker, localize("cannotRunGotoSymbolWithoutSymbolProvider", "The active text editor does not provide symbol information."));
    (() => __awaiter$i(this, void 0, void 0, function* () {
      const result2 = yield this.waitForLanguageSymbolRegistry(model, disposables);
      if (!result2 || token.isCancellationRequested) {
        return;
      }
      disposables.add(this.doProvideWithEditorSymbols(context, model, picker, token));
    }))();
    return disposables;
  }
  provideLabelPick(picker, label) {
    picker.items = [{
      label,
      index: 0,
      kind: 14
      /* SymbolKind.String */
    }];
    picker.ariaLabel = label;
  }
  waitForLanguageSymbolRegistry(model, disposables) {
    return __awaiter$i(this, void 0, void 0, function* () {
      if (this._languageFeaturesService.documentSymbolProvider.has(model)) {
        return true;
      }
      const symbolProviderRegistryPromise = new DeferredPromise();
      const symbolProviderListener = disposables.add(this._languageFeaturesService.documentSymbolProvider.onDidChange(() => {
        if (this._languageFeaturesService.documentSymbolProvider.has(model)) {
          symbolProviderListener.dispose();
          symbolProviderRegistryPromise.complete(true);
        }
      }));
      disposables.add(toDisposable(() => symbolProviderRegistryPromise.complete(false)));
      return symbolProviderRegistryPromise.p;
    });
  }
  doProvideWithEditorSymbols(context, model, picker, token) {
    var _a2;
    const editor2 = context.editor;
    const disposables = new DisposableStore();
    disposables.add(picker.onDidAccept((event) => {
      const [item] = picker.selectedItems;
      if (item && item.range) {
        this.gotoLocation(context, { range: item.range.selection, keyMods: picker.keyMods, preserveFocus: event.inBackground });
        if (!event.inBackground) {
          picker.hide();
        }
      }
    }));
    disposables.add(picker.onDidTriggerItemButton(({ item }) => {
      if (item && item.range) {
        this.gotoLocation(context, { range: item.range.selection, keyMods: picker.keyMods, forceSideBySide: true });
        picker.hide();
      }
    }));
    const symbolsPromise = this.getDocumentSymbols(model, token);
    let picksCts = void 0;
    const updatePickerItems = (positionToEnclose) => __awaiter$i(this, void 0, void 0, function* () {
      picksCts === null || picksCts === void 0 ? void 0 : picksCts.dispose(true);
      picker.busy = false;
      picksCts = new CancellationTokenSource$1(token);
      picker.busy = true;
      try {
        const query = prepareQuery(picker.value.substr(AbstractGotoSymbolQuickAccessProvider2.PREFIX.length).trim());
        const items = yield this.doGetSymbolPicks(symbolsPromise, query, void 0, picksCts.token);
        if (token.isCancellationRequested) {
          return;
        }
        if (items.length > 0) {
          picker.items = items;
          if (positionToEnclose && query.original.length === 0) {
            const candidate = findLast(items, (item) => Boolean(item.type !== "separator" && item.range && Range$2.containsPosition(item.range.decoration, positionToEnclose)));
            if (candidate) {
              picker.activeItems = [candidate];
            }
          }
        } else {
          if (query.original.length > 0) {
            this.provideLabelPick(picker, localize("noMatchingSymbolResults", "No matching editor symbols"));
          } else {
            this.provideLabelPick(picker, localize("noSymbolResults", "No editor symbols"));
          }
        }
      } finally {
        if (!token.isCancellationRequested) {
          picker.busy = false;
        }
      }
    });
    disposables.add(picker.onDidChangeValue(() => updatePickerItems(void 0)));
    updatePickerItems((_a2 = editor2.getSelection()) === null || _a2 === void 0 ? void 0 : _a2.getPosition());
    disposables.add(picker.onDidChangeActive(() => {
      const [item] = picker.activeItems;
      if (item && item.range) {
        editor2.revealRangeInCenter(
          item.range.selection,
          0
          /* ScrollType.Smooth */
        );
        this.addDecorations(editor2, item.range.decoration);
      }
    }));
    return disposables;
  }
  doGetSymbolPicks(symbolsPromise, query, options, token) {
    var _a2, _b2;
    return __awaiter$i(this, void 0, void 0, function* () {
      const symbols2 = yield symbolsPromise;
      if (token.isCancellationRequested) {
        return [];
      }
      const filterBySymbolKind = query.original.indexOf(AbstractGotoSymbolQuickAccessProvider2.SCOPE_PREFIX) === 0;
      const filterPos = filterBySymbolKind ? 1 : 0;
      let symbolQuery;
      let containerQuery;
      if (query.values && query.values.length > 1) {
        symbolQuery = pieceToQuery(query.values[0]);
        containerQuery = pieceToQuery(query.values.slice(1));
      } else {
        symbolQuery = query;
      }
      let buttons;
      const openSideBySideDirection = (_b2 = (_a2 = this.options) === null || _a2 === void 0 ? void 0 : _a2.openSideBySideDirection) === null || _b2 === void 0 ? void 0 : _b2.call(_a2);
      if (openSideBySideDirection) {
        buttons = [{
          iconClass: openSideBySideDirection === "right" ? ThemeIcon.asClassName(Codicon.splitHorizontal) : ThemeIcon.asClassName(Codicon.splitVertical),
          tooltip: openSideBySideDirection === "right" ? localize("openToSide", "Open to the Side") : localize("openToBottom", "Open to the Bottom")
        }];
      }
      const filteredSymbolPicks = [];
      for (let index = 0; index < symbols2.length; index++) {
        const symbol = symbols2[index];
        const symbolLabel = trim$1(symbol.name);
        const symbolLabelWithIcon = `$(${SymbolKinds.toIcon(symbol.kind).id}) ${symbolLabel}`;
        const symbolLabelIconOffset = symbolLabelWithIcon.length - symbolLabel.length;
        let containerLabel = symbol.containerName;
        if (options === null || options === void 0 ? void 0 : options.extraContainerLabel) {
          if (containerLabel) {
            containerLabel = `${options.extraContainerLabel} • ${containerLabel}`;
          } else {
            containerLabel = options.extraContainerLabel;
          }
        }
        let symbolScore = void 0;
        let symbolMatches = void 0;
        let containerScore = void 0;
        let containerMatches = void 0;
        if (query.original.length > filterPos) {
          let skipContainerQuery = false;
          if (symbolQuery !== query) {
            [symbolScore, symbolMatches] = scoreFuzzy2(symbolLabelWithIcon, Object.assign(Object.assign({}, query), {
              values: void 0
              /* disable multi-query support */
            }), filterPos, symbolLabelIconOffset);
            if (typeof symbolScore === "number") {
              skipContainerQuery = true;
            }
          }
          if (typeof symbolScore !== "number") {
            [symbolScore, symbolMatches] = scoreFuzzy2(symbolLabelWithIcon, symbolQuery, filterPos, symbolLabelIconOffset);
            if (typeof symbolScore !== "number") {
              continue;
            }
          }
          if (!skipContainerQuery && containerQuery) {
            if (containerLabel && containerQuery.original.length > 0) {
              [containerScore, containerMatches] = scoreFuzzy2(containerLabel, containerQuery);
            }
            if (typeof containerScore !== "number") {
              continue;
            }
            if (typeof symbolScore === "number") {
              symbolScore += containerScore;
            }
          }
        }
        const deprecated = symbol.tags && symbol.tags.indexOf(
          1
          /* SymbolTag.Deprecated */
        ) >= 0;
        filteredSymbolPicks.push({
          index,
          kind: symbol.kind,
          score: symbolScore,
          label: symbolLabelWithIcon,
          ariaLabel: getAriaLabelForSymbol(symbol.name, symbol.kind),
          description: containerLabel,
          highlights: deprecated ? void 0 : {
            label: symbolMatches,
            description: containerMatches
          },
          range: {
            selection: Range$2.collapseToStart(symbol.selectionRange),
            decoration: symbol.range
          },
          strikethrough: deprecated,
          buttons
        });
      }
      const sortedFilteredSymbolPicks = filteredSymbolPicks.sort((symbolA, symbolB) => filterBySymbolKind ? this.compareByKindAndScore(symbolA, symbolB) : this.compareByScore(symbolA, symbolB));
      let symbolPicks = [];
      if (filterBySymbolKind) {
        let updateLastSeparatorLabel = function() {
          if (lastSeparator && typeof lastSymbolKind === "number" && lastSymbolKindCounter > 0) {
            lastSeparator.label = format$2(NLS_SYMBOL_KIND_CACHE[lastSymbolKind] || FALLBACK_NLS_SYMBOL_KIND, lastSymbolKindCounter);
          }
        };
        let lastSymbolKind = void 0;
        let lastSeparator = void 0;
        let lastSymbolKindCounter = 0;
        for (const symbolPick of sortedFilteredSymbolPicks) {
          if (lastSymbolKind !== symbolPick.kind) {
            updateLastSeparatorLabel();
            lastSymbolKind = symbolPick.kind;
            lastSymbolKindCounter = 1;
            lastSeparator = { type: "separator" };
            symbolPicks.push(lastSeparator);
          } else {
            lastSymbolKindCounter++;
          }
          symbolPicks.push(symbolPick);
        }
        updateLastSeparatorLabel();
      } else if (sortedFilteredSymbolPicks.length > 0) {
        symbolPicks = [
          { label: localize("symbols", "symbols ({0})", filteredSymbolPicks.length), type: "separator" },
          ...sortedFilteredSymbolPicks
        ];
      }
      return symbolPicks;
    });
  }
  compareByScore(symbolA, symbolB) {
    if (typeof symbolA.score !== "number" && typeof symbolB.score === "number") {
      return 1;
    } else if (typeof symbolA.score === "number" && typeof symbolB.score !== "number") {
      return -1;
    }
    if (typeof symbolA.score === "number" && typeof symbolB.score === "number") {
      if (symbolA.score > symbolB.score) {
        return -1;
      } else if (symbolA.score < symbolB.score) {
        return 1;
      }
    }
    if (symbolA.index < symbolB.index) {
      return -1;
    } else if (symbolA.index > symbolB.index) {
      return 1;
    }
    return 0;
  }
  compareByKindAndScore(symbolA, symbolB) {
    const kindA = NLS_SYMBOL_KIND_CACHE[symbolA.kind] || FALLBACK_NLS_SYMBOL_KIND;
    const kindB = NLS_SYMBOL_KIND_CACHE[symbolB.kind] || FALLBACK_NLS_SYMBOL_KIND;
    const result2 = kindA.localeCompare(kindB);
    if (result2 === 0) {
      return this.compareByScore(symbolA, symbolB);
    }
    return result2;
  }
  getDocumentSymbols(document2, token) {
    return __awaiter$i(this, void 0, void 0, function* () {
      const model = yield this._outlineModelService.getOrCreate(document2, token);
      return token.isCancellationRequested ? [] : model.asListOfDocumentSymbols();
    });
  }
};
AbstractGotoSymbolQuickAccessProvider.PREFIX = "@";
AbstractGotoSymbolQuickAccessProvider.SCOPE_PREFIX = ":";
AbstractGotoSymbolQuickAccessProvider.PREFIX_BY_CATEGORY = `${AbstractGotoSymbolQuickAccessProvider.PREFIX}${AbstractGotoSymbolQuickAccessProvider.SCOPE_PREFIX}`;
AbstractGotoSymbolQuickAccessProvider = __decorate$v([
  __param$t(0, ILanguageFeaturesService),
  __param$t(1, IOutlineModelService)
], AbstractGotoSymbolQuickAccessProvider);
const FALLBACK_NLS_SYMBOL_KIND = localize("property", "properties ({0})");
const NLS_SYMBOL_KIND_CACHE = {
  [
    5
    /* SymbolKind.Method */
  ]: localize("method", "methods ({0})"),
  [
    11
    /* SymbolKind.Function */
  ]: localize("function", "functions ({0})"),
  [
    8
    /* SymbolKind.Constructor */
  ]: localize("_constructor", "constructors ({0})"),
  [
    12
    /* SymbolKind.Variable */
  ]: localize("variable", "variables ({0})"),
  [
    4
    /* SymbolKind.Class */
  ]: localize("class", "classes ({0})"),
  [
    22
    /* SymbolKind.Struct */
  ]: localize("struct", "structs ({0})"),
  [
    23
    /* SymbolKind.Event */
  ]: localize("event", "events ({0})"),
  [
    24
    /* SymbolKind.Operator */
  ]: localize("operator", "operators ({0})"),
  [
    10
    /* SymbolKind.Interface */
  ]: localize("interface", "interfaces ({0})"),
  [
    2
    /* SymbolKind.Namespace */
  ]: localize("namespace", "namespaces ({0})"),
  [
    3
    /* SymbolKind.Package */
  ]: localize("package", "packages ({0})"),
  [
    25
    /* SymbolKind.TypeParameter */
  ]: localize("typeParameter", "type parameters ({0})"),
  [
    1
    /* SymbolKind.Module */
  ]: localize("modules", "modules ({0})"),
  [
    6
    /* SymbolKind.Property */
  ]: localize("property", "properties ({0})"),
  [
    9
    /* SymbolKind.Enum */
  ]: localize("enum", "enumerations ({0})"),
  [
    21
    /* SymbolKind.EnumMember */
  ]: localize("enumMember", "enumeration members ({0})"),
  [
    14
    /* SymbolKind.String */
  ]: localize("string", "strings ({0})"),
  [
    0
    /* SymbolKind.File */
  ]: localize("file", "files ({0})"),
  [
    17
    /* SymbolKind.Array */
  ]: localize("array", "arrays ({0})"),
  [
    15
    /* SymbolKind.Number */
  ]: localize("number", "numbers ({0})"),
  [
    16
    /* SymbolKind.Boolean */
  ]: localize("boolean", "booleans ({0})"),
  [
    18
    /* SymbolKind.Object */
  ]: localize("object", "objects ({0})"),
  [
    19
    /* SymbolKind.Key */
  ]: localize("key", "keys ({0})"),
  [
    7
    /* SymbolKind.Field */
  ]: localize("field", "fields ({0})"),
  [
    13
    /* SymbolKind.Constant */
  ]: localize("constant", "constants ({0})")
};
var __decorate$u = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$s = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let StandaloneGotoSymbolQuickAccessProvider = class StandaloneGotoSymbolQuickAccessProvider2 extends AbstractGotoSymbolQuickAccessProvider {
  constructor(editorService, languageFeaturesService, outlineModelService) {
    super(languageFeaturesService, outlineModelService);
    this.editorService = editorService;
    this.onDidActiveTextEditorControlChange = Event$1.None;
  }
  get activeTextEditorControl() {
    return withNullAsUndefined(this.editorService.getFocusedCodeEditor());
  }
};
StandaloneGotoSymbolQuickAccessProvider = __decorate$u([
  __param$s(0, ICodeEditorService),
  __param$s(1, ILanguageFeaturesService),
  __param$s(2, IOutlineModelService)
], StandaloneGotoSymbolQuickAccessProvider);
class GotoSymbolAction extends EditorAction {
  constructor() {
    super({
      id: GotoSymbolAction.ID,
      label: QuickOutlineNLS.quickOutlineActionLabel,
      alias: "Go to Symbol...",
      precondition: EditorContextKeys.hasDocumentSymbolProvider,
      kbOpts: {
        kbExpr: EditorContextKeys.focus,
        primary: 2048 | 1024 | 45,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      contextMenuOpts: {
        group: "navigation",
        order: 3
      }
    });
  }
  run(accessor) {
    accessor.get(IQuickInputService).quickAccess.show(AbstractGotoSymbolQuickAccessProvider.PREFIX, { itemActivation: ItemActivation.NONE });
  }
}
GotoSymbolAction.ID = "editor.action.quickOutline";
registerEditorAction(GotoSymbolAction);
Registry.as(Extensions.Quickaccess).registerQuickAccessProvider({
  ctor: StandaloneGotoSymbolQuickAccessProvider,
  prefix: AbstractGotoSymbolQuickAccessProvider.PREFIX,
  helpEntries: [
    { description: QuickOutlineNLS.quickOutlineActionLabel, prefix: AbstractGotoSymbolQuickAccessProvider.PREFIX, commandId: GotoSymbolAction.ID },
    { description: QuickOutlineNLS.quickOutlineByCategoryActionLabel, prefix: AbstractGotoSymbolQuickAccessProvider.PREFIX_BY_CATEGORY }
  ]
});
function exceptionToErrorMessage(exception, verbose) {
  if (verbose && (exception.stack || exception.stacktrace)) {
    return localize("stackTrace.format", "{0}: {1}", detectSystemErrorMessage(exception), stackToString(exception.stack) || stackToString(exception.stacktrace));
  }
  return detectSystemErrorMessage(exception);
}
function stackToString(stack) {
  if (Array.isArray(stack)) {
    return stack.join("\n");
  }
  return stack;
}
function detectSystemErrorMessage(exception) {
  if (exception.code === "ERR_UNC_HOST_NOT_ALLOWED") {
    return `${exception.message}. Please update the 'security.allowedUNCHosts' setting if you want to allow this host.`;
  }
  if (typeof exception.code === "string" && typeof exception.errno === "number" && typeof exception.syscall === "string") {
    return localize("nodeExceptionMessage", "A system error occurred ({0})", exception.message);
  }
  return exception.message || localize("error.defaultMessage", "An unknown error occurred. Please consult the log for more details.");
}
function toErrorMessage(error2 = null, verbose = false) {
  if (!error2) {
    return localize("error.defaultMessage", "An unknown error occurred. Please consult the log for more details.");
  }
  if (Array.isArray(error2)) {
    const errors2 = coalesce(error2);
    const msg = toErrorMessage(errors2[0], verbose);
    if (errors2.length > 1) {
      return localize("error.moreErrors", "{0} ({1} errors in total)", msg, errors2.length);
    }
    return msg;
  }
  if (isString$4(error2)) {
    return error2;
  }
  if (error2.detail) {
    const detail = error2.detail;
    if (detail.error) {
      return exceptionToErrorMessage(detail.error, verbose);
    }
    if (detail.exception) {
      return exceptionToErrorMessage(detail.exception, verbose);
    }
  }
  if (error2.stack) {
    return exceptionToErrorMessage(error2, verbose);
  }
  if (error2.message) {
    return error2.message;
  }
  return localize("error.defaultMessage", "An unknown error occurred. Please consult the log for more details.");
}
var __awaiter$h = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
var TriggerAction;
(function(TriggerAction2) {
  TriggerAction2[TriggerAction2["NO_ACTION"] = 0] = "NO_ACTION";
  TriggerAction2[TriggerAction2["CLOSE_PICKER"] = 1] = "CLOSE_PICKER";
  TriggerAction2[TriggerAction2["REFRESH_PICKER"] = 2] = "REFRESH_PICKER";
  TriggerAction2[TriggerAction2["REMOVE_ITEM"] = 3] = "REMOVE_ITEM";
})(TriggerAction || (TriggerAction = {}));
function isPicksWithActive(obj) {
  const candidate = obj;
  return Array.isArray(candidate.items);
}
function isFastAndSlowPicks(obj) {
  const candidate = obj;
  return !!candidate.picks && candidate.additionalPicks instanceof Promise;
}
class PickerQuickAccessProvider extends Disposable {
  constructor(prefix2, options) {
    super();
    this.prefix = prefix2;
    this.options = options;
  }
  provide(picker, token, runOptions) {
    var _a2;
    const disposables = new DisposableStore();
    picker.canAcceptInBackground = !!((_a2 = this.options) === null || _a2 === void 0 ? void 0 : _a2.canAcceptInBackground);
    picker.matchOnLabel = picker.matchOnDescription = picker.matchOnDetail = picker.sortByLabel = false;
    let picksCts = void 0;
    const picksDisposable = disposables.add(new MutableDisposable());
    const updatePickerItems = () => __awaiter$h(this, void 0, void 0, function* () {
      const picksDisposables = picksDisposable.value = new DisposableStore();
      picksCts === null || picksCts === void 0 ? void 0 : picksCts.dispose(true);
      picker.busy = false;
      picksCts = new CancellationTokenSource$1(token);
      const picksToken = picksCts.token;
      const picksFilter = picker.value.substr(this.prefix.length).trim();
      const providedPicks = this._getPicks(picksFilter, picksDisposables, picksToken, runOptions);
      const applyPicks = (picks, skipEmpty) => {
        var _a3;
        let items;
        let activeItem = void 0;
        if (isPicksWithActive(picks)) {
          items = picks.items;
          activeItem = picks.active;
        } else {
          items = picks;
        }
        if (items.length === 0) {
          if (skipEmpty) {
            return false;
          }
          if ((picksFilter.length > 0 || picker.hideInput) && ((_a3 = this.options) === null || _a3 === void 0 ? void 0 : _a3.noResultsPick)) {
            if (isFunction$2(this.options.noResultsPick)) {
              items = [this.options.noResultsPick(picksFilter)];
            } else {
              items = [this.options.noResultsPick];
            }
          }
        }
        picker.items = items;
        if (activeItem) {
          picker.activeItems = [activeItem];
        }
        return true;
      };
      const applyFastAndSlowPicks = (fastAndSlowPicks) => __awaiter$h(this, void 0, void 0, function* () {
        let fastPicksApplied = false;
        let slowPicksApplied = false;
        yield Promise.all([
          // Fast Picks: if `mergeDelay` is configured, in order to reduce
          // amount of flicker, we race against the slow picks over some delay
          // and then set the fast picks.
          // If the slow picks are faster, we reduce the flicker by only
          // setting the items once.
          (() => __awaiter$h(this, void 0, void 0, function* () {
            if (typeof fastAndSlowPicks.mergeDelay === "number") {
              yield timeout(fastAndSlowPicks.mergeDelay);
              if (picksToken.isCancellationRequested) {
                return;
              }
            }
            if (!slowPicksApplied) {
              fastPicksApplied = applyPicks(
                fastAndSlowPicks.picks,
                true
                /* skip over empty to reduce flicker */
              );
            }
          }))(),
          // Slow Picks: we await the slow picks and then set them at
          // once together with the fast picks, but only if we actually
          // have additional results.
          (() => __awaiter$h(this, void 0, void 0, function* () {
            picker.busy = true;
            try {
              const awaitedAdditionalPicks = yield fastAndSlowPicks.additionalPicks;
              if (picksToken.isCancellationRequested) {
                return;
              }
              let picks;
              let activePick = void 0;
              if (isPicksWithActive(fastAndSlowPicks.picks)) {
                picks = fastAndSlowPicks.picks.items;
                activePick = fastAndSlowPicks.picks.active;
              } else {
                picks = fastAndSlowPicks.picks;
              }
              let additionalPicks;
              let additionalActivePick = void 0;
              if (isPicksWithActive(awaitedAdditionalPicks)) {
                additionalPicks = awaitedAdditionalPicks.items;
                additionalActivePick = awaitedAdditionalPicks.active;
              } else {
                additionalPicks = awaitedAdditionalPicks;
              }
              if (additionalPicks.length > 0 || !fastPicksApplied) {
                let fallbackActivePick = void 0;
                if (!activePick && !additionalActivePick) {
                  const fallbackActivePickCandidate = picker.activeItems[0];
                  if (fallbackActivePickCandidate && picks.indexOf(fallbackActivePickCandidate) !== -1) {
                    fallbackActivePick = fallbackActivePickCandidate;
                  }
                }
                applyPicks({
                  items: [...picks, ...additionalPicks],
                  active: activePick || additionalActivePick || fallbackActivePick
                });
              }
            } finally {
              if (!picksToken.isCancellationRequested) {
                picker.busy = false;
              }
              slowPicksApplied = true;
            }
          }))()
        ]);
      });
      if (providedPicks === null)
        ;
      else if (isFastAndSlowPicks(providedPicks)) {
        yield applyFastAndSlowPicks(providedPicks);
      } else if (!(providedPicks instanceof Promise)) {
        applyPicks(providedPicks);
      } else {
        picker.busy = true;
        try {
          const awaitedPicks = yield providedPicks;
          if (picksToken.isCancellationRequested) {
            return;
          }
          if (isFastAndSlowPicks(awaitedPicks)) {
            yield applyFastAndSlowPicks(awaitedPicks);
          } else {
            applyPicks(awaitedPicks);
          }
        } finally {
          if (!picksToken.isCancellationRequested) {
            picker.busy = false;
          }
        }
      }
    });
    disposables.add(picker.onDidChangeValue(() => updatePickerItems()));
    updatePickerItems();
    disposables.add(picker.onDidAccept((event) => {
      const [item] = picker.selectedItems;
      if (typeof (item === null || item === void 0 ? void 0 : item.accept) === "function") {
        if (!event.inBackground) {
          picker.hide();
        }
        item.accept(picker.keyMods, event);
      }
    }));
    disposables.add(picker.onDidTriggerItemButton(({ button: button2, item }) => __awaiter$h(this, void 0, void 0, function* () {
      var _b2, _c2;
      if (typeof item.trigger === "function") {
        const buttonIndex = (_c2 = (_b2 = item.buttons) === null || _b2 === void 0 ? void 0 : _b2.indexOf(button2)) !== null && _c2 !== void 0 ? _c2 : -1;
        if (buttonIndex >= 0) {
          const result2 = item.trigger(buttonIndex, picker.keyMods);
          const action = typeof result2 === "number" ? result2 : yield result2;
          if (token.isCancellationRequested) {
            return;
          }
          switch (action) {
            case TriggerAction.NO_ACTION:
              break;
            case TriggerAction.CLOSE_PICKER:
              picker.hide();
              break;
            case TriggerAction.REFRESH_PICKER:
              updatePickerItems();
              break;
            case TriggerAction.REMOVE_ITEM: {
              const index = picker.items.indexOf(item);
              if (index !== -1) {
                const items = picker.items.slice();
                const removed = items.splice(index, 1);
                const activeItems = picker.activeItems.filter((activeItem) => activeItem !== removed[0]);
                const keepScrollPositionBefore = picker.keepScrollPosition;
                picker.keepScrollPosition = true;
                picker.items = items;
                if (activeItems) {
                  picker.activeItems = activeItems;
                }
                picker.keepScrollPosition = keepScrollPositionBefore;
              }
              break;
            }
          }
        }
      }
    })));
    return disposables;
  }
}
var __decorate$t = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$r = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$g = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
let AbstractCommandsQuickAccessProvider = class AbstractCommandsQuickAccessProvider2 extends PickerQuickAccessProvider {
  constructor(options, instantiationService, keybindingService, commandService, telemetryService, dialogService) {
    super(AbstractCommandsQuickAccessProvider2.PREFIX, options);
    this.instantiationService = instantiationService;
    this.keybindingService = keybindingService;
    this.commandService = commandService;
    this.telemetryService = telemetryService;
    this.dialogService = dialogService;
    this.commandsHistory = this._register(this.instantiationService.createInstance(CommandsHistory));
    this.options = options;
  }
  _getPicks(filter2, _disposables, token, runOptions) {
    var _a2, _b2;
    return __awaiter$g(this, void 0, void 0, function* () {
      const allCommandPicks = yield this.getCommandPicks(token);
      if (token.isCancellationRequested) {
        return [];
      }
      const filteredCommandPicks = [];
      for (const commandPick of allCommandPicks) {
        const labelHighlights = withNullAsUndefined(AbstractCommandsQuickAccessProvider2.WORD_FILTER(filter2, commandPick.label));
        const aliasHighlights = commandPick.commandAlias ? withNullAsUndefined(AbstractCommandsQuickAccessProvider2.WORD_FILTER(filter2, commandPick.commandAlias)) : void 0;
        if (labelHighlights || aliasHighlights) {
          commandPick.highlights = {
            label: labelHighlights,
            detail: this.options.showAlias ? aliasHighlights : void 0
          };
          filteredCommandPicks.push(commandPick);
        } else if (filter2 === commandPick.commandId) {
          filteredCommandPicks.push(commandPick);
        }
      }
      const mapLabelToCommand = /* @__PURE__ */ new Map();
      for (const commandPick of filteredCommandPicks) {
        const existingCommandForLabel = mapLabelToCommand.get(commandPick.label);
        if (existingCommandForLabel) {
          commandPick.description = commandPick.commandId;
          existingCommandForLabel.description = existingCommandForLabel.commandId;
        } else {
          mapLabelToCommand.set(commandPick.label, commandPick);
        }
      }
      filteredCommandPicks.sort((commandPickA, commandPickB) => {
        const commandACounter = this.commandsHistory.peek(commandPickA.commandId);
        const commandBCounter = this.commandsHistory.peek(commandPickB.commandId);
        if (commandACounter && commandBCounter) {
          return commandACounter > commandBCounter ? -1 : 1;
        }
        if (commandACounter) {
          return -1;
        }
        if (commandBCounter) {
          return 1;
        }
        if (this.options.suggestedCommandIds) {
          const commandASuggestion = this.options.suggestedCommandIds.has(commandPickA.commandId);
          const commandBSuggestion = this.options.suggestedCommandIds.has(commandPickB.commandId);
          if (commandASuggestion && commandBSuggestion) {
            return 0;
          }
          if (commandASuggestion) {
            return -1;
          }
          if (commandBSuggestion) {
            return 1;
          }
        }
        return commandPickA.label.localeCompare(commandPickB.label);
      });
      const commandPicks = [];
      let addOtherSeparator = false;
      let addCommonlyUsedSeparator = !!this.options.suggestedCommandIds;
      for (let i = 0; i < filteredCommandPicks.length; i++) {
        const commandPick = filteredCommandPicks[i];
        if (i === 0 && this.commandsHistory.peek(commandPick.commandId)) {
          commandPicks.push({ type: "separator", label: localize("recentlyUsed", "recently used") });
          addOtherSeparator = true;
        }
        if (addCommonlyUsedSeparator && !this.commandsHistory.peek(commandPick.commandId) && ((_a2 = this.options.suggestedCommandIds) === null || _a2 === void 0 ? void 0 : _a2.has(commandPick.commandId))) {
          commandPicks.push({ type: "separator", label: localize("commonlyUsed", "commonly used") });
          addOtherSeparator = true;
          addCommonlyUsedSeparator = false;
        }
        if (addOtherSeparator && !this.commandsHistory.peek(commandPick.commandId) && !((_b2 = this.options.suggestedCommandIds) === null || _b2 === void 0 ? void 0 : _b2.has(commandPick.commandId))) {
          commandPicks.push({ type: "separator", label: localize("morecCommands", "other commands") });
          addOtherSeparator = false;
        }
        commandPicks.push(this.toCommandPick(commandPick, runOptions));
      }
      if (!this.hasAdditionalCommandPicks(filter2, token)) {
        return commandPicks;
      }
      return {
        picks: commandPicks,
        additionalPicks: (() => __awaiter$g(this, void 0, void 0, function* () {
          const additionalCommandPicks = yield this.getAdditionalCommandPicks(allCommandPicks, filteredCommandPicks, filter2, token);
          if (token.isCancellationRequested) {
            return [];
          }
          return additionalCommandPicks.map((commandPick) => this.toCommandPick(commandPick, runOptions));
        }))()
      };
    });
  }
  toCommandPick(commandPick, runOptions) {
    if (commandPick.type === "separator") {
      return commandPick;
    }
    const keybinding = this.keybindingService.lookupKeybinding(commandPick.commandId);
    const ariaLabel = keybinding ? localize("commandPickAriaLabelWithKeybinding", "{0}, {1}", commandPick.label, keybinding.getAriaLabel()) : commandPick.label;
    return Object.assign(Object.assign({}, commandPick), { ariaLabel, detail: this.options.showAlias && commandPick.commandAlias !== commandPick.label ? commandPick.commandAlias : void 0, keybinding, accept: () => __awaiter$g(this, void 0, void 0, function* () {
      var _a2, _b2;
      this.commandsHistory.push(commandPick.commandId);
      this.telemetryService.publicLog2("workbenchActionExecuted", {
        id: commandPick.commandId,
        from: (_a2 = runOptions === null || runOptions === void 0 ? void 0 : runOptions.from) !== null && _a2 !== void 0 ? _a2 : "quick open"
      });
      try {
        ((_b2 = commandPick.args) === null || _b2 === void 0 ? void 0 : _b2.length) ? yield this.commandService.executeCommand(commandPick.commandId, ...commandPick.args) : yield this.commandService.executeCommand(commandPick.commandId);
      } catch (error2) {
        if (!isCancellationError(error2)) {
          this.dialogService.error(localize("canNotRun", "Command '{0}' resulted in an error", commandPick.label), toErrorMessage(error2));
        }
      }
    }) });
  }
};
AbstractCommandsQuickAccessProvider.PREFIX = ">";
AbstractCommandsQuickAccessProvider.WORD_FILTER = or(matchesPrefix, matchesWords, matchesContiguousSubString);
AbstractCommandsQuickAccessProvider = __decorate$t([
  __param$r(1, IInstantiationService),
  __param$r(2, IKeybindingService),
  __param$r(3, ICommandService),
  __param$r(4, ITelemetryService),
  __param$r(5, IDialogService)
], AbstractCommandsQuickAccessProvider);
let CommandsHistory = class CommandsHistory2 extends Disposable {
  constructor(storageService, configurationService) {
    super();
    this.storageService = storageService;
    this.configurationService = configurationService;
    this.configuredCommandsHistoryLength = 0;
    this.updateConfiguration();
    this.load();
    this.registerListeners();
  }
  registerListeners() {
    this._register(this.configurationService.onDidChangeConfiguration((e) => this.updateConfiguration(e)));
  }
  updateConfiguration(e) {
    if (e && !e.affectsConfiguration("workbench.commandPalette.history")) {
      return;
    }
    this.configuredCommandsHistoryLength = CommandsHistory2.getConfiguredCommandHistoryLength(this.configurationService);
    if (CommandsHistory2.cache && CommandsHistory2.cache.limit !== this.configuredCommandsHistoryLength) {
      CommandsHistory2.cache.limit = this.configuredCommandsHistoryLength;
      CommandsHistory2.saveState(this.storageService);
    }
  }
  load() {
    const raw = this.storageService.get(
      CommandsHistory2.PREF_KEY_CACHE,
      0
      /* StorageScope.PROFILE */
    );
    let serializedCache;
    if (raw) {
      try {
        serializedCache = JSON.parse(raw);
      } catch (error2) {
      }
    }
    const cache2 = CommandsHistory2.cache = new LRUCache$2(this.configuredCommandsHistoryLength, 1);
    if (serializedCache) {
      let entries;
      if (serializedCache.usesLRU) {
        entries = serializedCache.entries;
      } else {
        entries = serializedCache.entries.sort((a, b) => a.value - b.value);
      }
      entries.forEach((entry) => cache2.set(entry.key, entry.value));
    }
    CommandsHistory2.counter = this.storageService.getNumber(CommandsHistory2.PREF_KEY_COUNTER, 0, CommandsHistory2.counter);
  }
  push(commandId) {
    if (!CommandsHistory2.cache) {
      return;
    }
    CommandsHistory2.cache.set(commandId, CommandsHistory2.counter++);
    CommandsHistory2.saveState(this.storageService);
  }
  peek(commandId) {
    var _a2;
    return (_a2 = CommandsHistory2.cache) === null || _a2 === void 0 ? void 0 : _a2.peek(commandId);
  }
  static saveState(storageService) {
    if (!CommandsHistory2.cache) {
      return;
    }
    const serializedCache = { usesLRU: true, entries: [] };
    CommandsHistory2.cache.forEach((value, key) => serializedCache.entries.push({ key, value }));
    storageService.store(
      CommandsHistory2.PREF_KEY_CACHE,
      JSON.stringify(serializedCache),
      0,
      0
      /* StorageTarget.USER */
    );
    storageService.store(
      CommandsHistory2.PREF_KEY_COUNTER,
      CommandsHistory2.counter,
      0,
      0
      /* StorageTarget.USER */
    );
  }
  static getConfiguredCommandHistoryLength(configurationService) {
    var _a2, _b2;
    const config2 = configurationService.getValue();
    const configuredCommandHistoryLength = (_b2 = (_a2 = config2.workbench) === null || _a2 === void 0 ? void 0 : _a2.commandPalette) === null || _b2 === void 0 ? void 0 : _b2.history;
    if (typeof configuredCommandHistoryLength === "number") {
      return configuredCommandHistoryLength;
    }
    return CommandsHistory2.DEFAULT_COMMANDS_HISTORY_LENGTH;
  }
};
CommandsHistory.DEFAULT_COMMANDS_HISTORY_LENGTH = 50;
CommandsHistory.PREF_KEY_CACHE = "commandPalette.mru.cache";
CommandsHistory.PREF_KEY_COUNTER = "commandPalette.mru.counter";
CommandsHistory.counter = 1;
CommandsHistory = __decorate$t([
  __param$r(0, IStorageService),
  __param$r(1, IConfigurationService)
], CommandsHistory);
class AbstractEditorCommandsQuickAccessProvider extends AbstractCommandsQuickAccessProvider {
  constructor(options, instantiationService, keybindingService, commandService, telemetryService, dialogService) {
    super(options, instantiationService, keybindingService, commandService, telemetryService, dialogService);
  }
  getCodeEditorCommandPicks() {
    const activeTextEditorControl = this.activeTextEditorControl;
    if (!activeTextEditorControl) {
      return [];
    }
    const editorCommandPicks = [];
    for (const editorAction of activeTextEditorControl.getSupportedActions()) {
      editorCommandPicks.push({
        commandId: editorAction.id,
        commandAlias: editorAction.alias,
        label: stripIcons(editorAction.label) || editorAction.id
      });
    }
    return editorCommandPicks;
  }
}
var __decorate$s = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$q = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$f = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
let StandaloneCommandsQuickAccessProvider = class StandaloneCommandsQuickAccessProvider2 extends AbstractEditorCommandsQuickAccessProvider {
  get activeTextEditorControl() {
    return withNullAsUndefined(this.codeEditorService.getFocusedCodeEditor());
  }
  constructor(instantiationService, codeEditorService, keybindingService, commandService, telemetryService, dialogService) {
    super({ showAlias: false }, instantiationService, keybindingService, commandService, telemetryService, dialogService);
    this.codeEditorService = codeEditorService;
  }
  getCommandPicks() {
    return __awaiter$f(this, void 0, void 0, function* () {
      return this.getCodeEditorCommandPicks();
    });
  }
  hasAdditionalCommandPicks() {
    return false;
  }
  getAdditionalCommandPicks() {
    return __awaiter$f(this, void 0, void 0, function* () {
      return [];
    });
  }
};
StandaloneCommandsQuickAccessProvider = __decorate$s([
  __param$q(0, IInstantiationService),
  __param$q(1, ICodeEditorService),
  __param$q(2, IKeybindingService),
  __param$q(3, ICommandService),
  __param$q(4, ITelemetryService),
  __param$q(5, IDialogService)
], StandaloneCommandsQuickAccessProvider);
class GotoLineAction2 extends EditorAction {
  constructor() {
    super({
      id: GotoLineAction2.ID,
      label: QuickCommandNLS.quickCommandActionLabel,
      alias: "Command Palette",
      precondition: void 0,
      kbOpts: {
        kbExpr: EditorContextKeys.focus,
        primary: 59,
        weight: 100
        /* KeybindingWeight.EditorContrib */
      },
      contextMenuOpts: {
        group: "z_commands",
        order: 1
      }
    });
  }
  run(accessor) {
    accessor.get(IQuickInputService).quickAccess.show(StandaloneCommandsQuickAccessProvider.PREFIX);
  }
}
GotoLineAction2.ID = "editor.action.quickCommand";
registerEditorAction(GotoLineAction2);
Registry.as(Extensions.Quickaccess).registerQuickAccessProvider({
  ctor: StandaloneCommandsQuickAccessProvider,
  prefix: StandaloneCommandsQuickAccessProvider.PREFIX,
  helpEntries: [{ description: QuickCommandNLS.quickCommandHelp, commandId: GotoLineAction2.ID }]
});
var __decorate$r = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$p = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let StandaloneReferencesController = class StandaloneReferencesController2 extends ReferencesController {
  constructor(editor2, contextKeyService, editorService, notificationService, instantiationService, storageService, configurationService) {
    super(true, editor2, contextKeyService, editorService, notificationService, instantiationService, storageService, configurationService);
  }
};
StandaloneReferencesController = __decorate$r([
  __param$p(1, IContextKeyService),
  __param$p(2, ICodeEditorService),
  __param$p(3, INotificationService),
  __param$p(4, IInstantiationService),
  __param$p(5, IStorageService),
  __param$p(6, IConfigurationService)
], StandaloneReferencesController);
registerEditorContribution(
  ReferencesController.ID,
  StandaloneReferencesController,
  4
  /* EditorContributionInstantiation.Lazy */
);
class ParsedTokenThemeRule {
  constructor(token, index, fontStyle, foreground2, background) {
    this._parsedThemeRuleBrand = void 0;
    this.token = token;
    this.index = index;
    this.fontStyle = fontStyle;
    this.foreground = foreground2;
    this.background = background;
  }
}
function parseTokenTheme(source) {
  if (!source || !Array.isArray(source)) {
    return [];
  }
  const result2 = [];
  let resultLen = 0;
  for (let i = 0, len = source.length; i < len; i++) {
    const entry = source[i];
    let fontStyle = -1;
    if (typeof entry.fontStyle === "string") {
      fontStyle = 0;
      const segments = entry.fontStyle.split(" ");
      for (let j = 0, lenJ = segments.length; j < lenJ; j++) {
        const segment = segments[j];
        switch (segment) {
          case "italic":
            fontStyle = fontStyle | 1;
            break;
          case "bold":
            fontStyle = fontStyle | 2;
            break;
          case "underline":
            fontStyle = fontStyle | 4;
            break;
          case "strikethrough":
            fontStyle = fontStyle | 8;
            break;
        }
      }
    }
    let foreground2 = null;
    if (typeof entry.foreground === "string") {
      foreground2 = entry.foreground;
    }
    let background = null;
    if (typeof entry.background === "string") {
      background = entry.background;
    }
    result2[resultLen++] = new ParsedTokenThemeRule(entry.token || "", i, fontStyle, foreground2, background);
  }
  return result2;
}
function resolveParsedTokenThemeRules(parsedThemeRules, customTokenColors) {
  parsedThemeRules.sort((a, b) => {
    const r = strcmp(a.token, b.token);
    if (r !== 0) {
      return r;
    }
    return a.index - b.index;
  });
  let defaultFontStyle = 0;
  let defaultForeground = "000000";
  let defaultBackground = "ffffff";
  while (parsedThemeRules.length >= 1 && parsedThemeRules[0].token === "") {
    const incomingDefaults = parsedThemeRules.shift();
    if (incomingDefaults.fontStyle !== -1) {
      defaultFontStyle = incomingDefaults.fontStyle;
    }
    if (incomingDefaults.foreground !== null) {
      defaultForeground = incomingDefaults.foreground;
    }
    if (incomingDefaults.background !== null) {
      defaultBackground = incomingDefaults.background;
    }
  }
  const colorMap = new ColorMap();
  for (const color of customTokenColors) {
    colorMap.getId(color);
  }
  const foregroundColorId = colorMap.getId(defaultForeground);
  const backgroundColorId = colorMap.getId(defaultBackground);
  const defaults = new ThemeTrieElementRule(defaultFontStyle, foregroundColorId, backgroundColorId);
  const root3 = new ThemeTrieElement(defaults);
  for (let i = 0, len = parsedThemeRules.length; i < len; i++) {
    const rule2 = parsedThemeRules[i];
    root3.insert(rule2.token, rule2.fontStyle, colorMap.getId(rule2.foreground), colorMap.getId(rule2.background));
  }
  return new TokenTheme(colorMap, root3);
}
const colorRegExp = /^#?([0-9A-Fa-f]{6})([0-9A-Fa-f]{2})?$/;
class ColorMap {
  constructor() {
    this._lastColorId = 0;
    this._id2color = [];
    this._color2id = /* @__PURE__ */ new Map();
  }
  getId(color) {
    if (color === null) {
      return 0;
    }
    const match2 = color.match(colorRegExp);
    if (!match2) {
      throw new Error("Illegal value for token color: " + color);
    }
    color = match2[1].toUpperCase();
    let value = this._color2id.get(color);
    if (value) {
      return value;
    }
    value = ++this._lastColorId;
    this._color2id.set(color, value);
    this._id2color[value] = Color.fromHex("#" + color);
    return value;
  }
  getColorMap() {
    return this._id2color.slice(0);
  }
}
class TokenTheme {
  static createFromRawTokenTheme(source, customTokenColors) {
    return this.createFromParsedTokenTheme(parseTokenTheme(source), customTokenColors);
  }
  static createFromParsedTokenTheme(source, customTokenColors) {
    return resolveParsedTokenThemeRules(source, customTokenColors);
  }
  constructor(colorMap, root3) {
    this._colorMap = colorMap;
    this._root = root3;
    this._cache = /* @__PURE__ */ new Map();
  }
  getColorMap() {
    return this._colorMap.getColorMap();
  }
  _match(token) {
    return this._root.match(token);
  }
  match(languageId, token) {
    let result2 = this._cache.get(token);
    if (typeof result2 === "undefined") {
      const rule2 = this._match(token);
      const standardToken = toStandardTokenType(token);
      result2 = (rule2.metadata | standardToken << 8) >>> 0;
      this._cache.set(token, result2);
    }
    return (result2 | languageId << 0) >>> 0;
  }
}
const STANDARD_TOKEN_TYPE_REGEXP = /\b(comment|string|regex|regexp)\b/;
function toStandardTokenType(tokenType) {
  const m = tokenType.match(STANDARD_TOKEN_TYPE_REGEXP);
  if (!m) {
    return 0;
  }
  switch (m[1]) {
    case "comment":
      return 1;
    case "string":
      return 2;
    case "regex":
      return 3;
    case "regexp":
      return 3;
  }
  throw new Error("Unexpected match for standard token type!");
}
function strcmp(a, b) {
  if (a < b) {
    return -1;
  }
  if (a > b) {
    return 1;
  }
  return 0;
}
class ThemeTrieElementRule {
  constructor(fontStyle, foreground2, background) {
    this._themeTrieElementRuleBrand = void 0;
    this._fontStyle = fontStyle;
    this._foreground = foreground2;
    this._background = background;
    this.metadata = (this._fontStyle << 11 | this._foreground << 15 | this._background << 24) >>> 0;
  }
  clone() {
    return new ThemeTrieElementRule(this._fontStyle, this._foreground, this._background);
  }
  acceptOverwrite(fontStyle, foreground2, background) {
    if (fontStyle !== -1) {
      this._fontStyle = fontStyle;
    }
    if (foreground2 !== 0) {
      this._foreground = foreground2;
    }
    if (background !== 0) {
      this._background = background;
    }
    this.metadata = (this._fontStyle << 11 | this._foreground << 15 | this._background << 24) >>> 0;
  }
}
class ThemeTrieElement {
  constructor(mainRule) {
    this._themeTrieElementBrand = void 0;
    this._mainRule = mainRule;
    this._children = /* @__PURE__ */ new Map();
  }
  match(token) {
    if (token === "") {
      return this._mainRule;
    }
    const dotIndex = token.indexOf(".");
    let head;
    let tail3;
    if (dotIndex === -1) {
      head = token;
      tail3 = "";
    } else {
      head = token.substring(0, dotIndex);
      tail3 = token.substring(dotIndex + 1);
    }
    const child = this._children.get(head);
    if (typeof child !== "undefined") {
      return child.match(tail3);
    }
    return this._mainRule;
  }
  insert(token, fontStyle, foreground2, background) {
    if (token === "") {
      this._mainRule.acceptOverwrite(fontStyle, foreground2, background);
      return;
    }
    const dotIndex = token.indexOf(".");
    let head;
    let tail3;
    if (dotIndex === -1) {
      head = token;
      tail3 = "";
    } else {
      head = token.substring(0, dotIndex);
      tail3 = token.substring(dotIndex + 1);
    }
    let child = this._children.get(head);
    if (typeof child === "undefined") {
      child = new ThemeTrieElement(this._mainRule.clone());
      this._children.set(head, child);
    }
    child.insert(tail3, fontStyle, foreground2, background);
  }
}
function generateTokensCSSForColorMap(colorMap) {
  const rules = [];
  for (let i = 1, len = colorMap.length; i < len; i++) {
    const color = colorMap[i];
    rules[i] = `.mtk${i} { color: ${color}; }`;
  }
  rules.push(".mtki { font-style: italic; }");
  rules.push(".mtkb { font-weight: bold; }");
  rules.push(".mtku { text-decoration: underline; text-underline-position: under; }");
  rules.push(".mtks { text-decoration: line-through; }");
  rules.push(".mtks.mtku { text-decoration: underline line-through; text-underline-position: under; }");
  return rules.join("\n");
}
const vs = {
  base: "vs",
  inherit: false,
  rules: [
    { token: "", foreground: "000000", background: "fffffe" },
    { token: "invalid", foreground: "cd3131" },
    { token: "emphasis", fontStyle: "italic" },
    { token: "strong", fontStyle: "bold" },
    { token: "variable", foreground: "001188" },
    { token: "variable.predefined", foreground: "4864AA" },
    { token: "constant", foreground: "dd0000" },
    { token: "comment", foreground: "008000" },
    { token: "number", foreground: "098658" },
    { token: "number.hex", foreground: "3030c0" },
    { token: "regexp", foreground: "800000" },
    { token: "annotation", foreground: "808080" },
    { token: "type", foreground: "008080" },
    { token: "delimiter", foreground: "000000" },
    { token: "delimiter.html", foreground: "383838" },
    { token: "delimiter.xml", foreground: "0000FF" },
    { token: "tag", foreground: "800000" },
    { token: "tag.id.pug", foreground: "4F76AC" },
    { token: "tag.class.pug", foreground: "4F76AC" },
    { token: "meta.scss", foreground: "800000" },
    { token: "metatag", foreground: "e00000" },
    { token: "metatag.content.html", foreground: "FF0000" },
    { token: "metatag.html", foreground: "808080" },
    { token: "metatag.xml", foreground: "808080" },
    { token: "metatag.php", fontStyle: "bold" },
    { token: "key", foreground: "863B00" },
    { token: "string.key.json", foreground: "A31515" },
    { token: "string.value.json", foreground: "0451A5" },
    { token: "attribute.name", foreground: "FF0000" },
    { token: "attribute.value", foreground: "0451A5" },
    { token: "attribute.value.number", foreground: "098658" },
    { token: "attribute.value.unit", foreground: "098658" },
    { token: "attribute.value.html", foreground: "0000FF" },
    { token: "attribute.value.xml", foreground: "0000FF" },
    { token: "string", foreground: "A31515" },
    { token: "string.html", foreground: "0000FF" },
    { token: "string.sql", foreground: "FF0000" },
    { token: "string.yaml", foreground: "0451A5" },
    { token: "keyword", foreground: "0000FF" },
    { token: "keyword.json", foreground: "0451A5" },
    { token: "keyword.flow", foreground: "AF00DB" },
    { token: "keyword.flow.scss", foreground: "0000FF" },
    { token: "operator.scss", foreground: "666666" },
    { token: "operator.sql", foreground: "778899" },
    { token: "operator.swift", foreground: "666666" },
    { token: "predefined.sql", foreground: "C700C7" }
  ],
  colors: {
    [editorBackground]: "#FFFFFE",
    [editorForeground]: "#000000",
    [editorInactiveSelection]: "#E5EBF1",
    [editorIndentGuide1]: "#D3D3D3",
    [editorActiveIndentGuide1]: "#939393",
    [editorSelectionHighlight]: "#ADD6FF4D"
  }
};
const vs_dark = {
  base: "vs-dark",
  inherit: false,
  rules: [
    { token: "", foreground: "D4D4D4", background: "1E1E1E" },
    { token: "invalid", foreground: "f44747" },
    { token: "emphasis", fontStyle: "italic" },
    { token: "strong", fontStyle: "bold" },
    { token: "variable", foreground: "74B0DF" },
    { token: "variable.predefined", foreground: "4864AA" },
    { token: "variable.parameter", foreground: "9CDCFE" },
    { token: "constant", foreground: "569CD6" },
    { token: "comment", foreground: "608B4E" },
    { token: "number", foreground: "B5CEA8" },
    { token: "number.hex", foreground: "5BB498" },
    { token: "regexp", foreground: "B46695" },
    { token: "annotation", foreground: "cc6666" },
    { token: "type", foreground: "3DC9B0" },
    { token: "delimiter", foreground: "DCDCDC" },
    { token: "delimiter.html", foreground: "808080" },
    { token: "delimiter.xml", foreground: "808080" },
    { token: "tag", foreground: "569CD6" },
    { token: "tag.id.pug", foreground: "4F76AC" },
    { token: "tag.class.pug", foreground: "4F76AC" },
    { token: "meta.scss", foreground: "A79873" },
    { token: "meta.tag", foreground: "CE9178" },
    { token: "metatag", foreground: "DD6A6F" },
    { token: "metatag.content.html", foreground: "9CDCFE" },
    { token: "metatag.html", foreground: "569CD6" },
    { token: "metatag.xml", foreground: "569CD6" },
    { token: "metatag.php", fontStyle: "bold" },
    { token: "key", foreground: "9CDCFE" },
    { token: "string.key.json", foreground: "9CDCFE" },
    { token: "string.value.json", foreground: "CE9178" },
    { token: "attribute.name", foreground: "9CDCFE" },
    { token: "attribute.value", foreground: "CE9178" },
    { token: "attribute.value.number.css", foreground: "B5CEA8" },
    { token: "attribute.value.unit.css", foreground: "B5CEA8" },
    { token: "attribute.value.hex.css", foreground: "D4D4D4" },
    { token: "string", foreground: "CE9178" },
    { token: "string.sql", foreground: "FF0000" },
    { token: "keyword", foreground: "569CD6" },
    { token: "keyword.flow", foreground: "C586C0" },
    { token: "keyword.json", foreground: "CE9178" },
    { token: "keyword.flow.scss", foreground: "569CD6" },
    { token: "operator.scss", foreground: "909090" },
    { token: "operator.sql", foreground: "778899" },
    { token: "operator.swift", foreground: "909090" },
    { token: "predefined.sql", foreground: "FF00FF" }
  ],
  colors: {
    [editorBackground]: "#1E1E1E",
    [editorForeground]: "#D4D4D4",
    [editorInactiveSelection]: "#3A3D41",
    [editorIndentGuide1]: "#404040",
    [editorActiveIndentGuide1]: "#707070",
    [editorSelectionHighlight]: "#ADD6FF26"
  }
};
const hc_black = {
  base: "hc-black",
  inherit: false,
  rules: [
    { token: "", foreground: "FFFFFF", background: "000000" },
    { token: "invalid", foreground: "f44747" },
    { token: "emphasis", fontStyle: "italic" },
    { token: "strong", fontStyle: "bold" },
    { token: "variable", foreground: "1AEBFF" },
    { token: "variable.parameter", foreground: "9CDCFE" },
    { token: "constant", foreground: "569CD6" },
    { token: "comment", foreground: "608B4E" },
    { token: "number", foreground: "FFFFFF" },
    { token: "regexp", foreground: "C0C0C0" },
    { token: "annotation", foreground: "569CD6" },
    { token: "type", foreground: "3DC9B0" },
    { token: "delimiter", foreground: "FFFF00" },
    { token: "delimiter.html", foreground: "FFFF00" },
    { token: "tag", foreground: "569CD6" },
    { token: "tag.id.pug", foreground: "4F76AC" },
    { token: "tag.class.pug", foreground: "4F76AC" },
    { token: "meta", foreground: "D4D4D4" },
    { token: "meta.tag", foreground: "CE9178" },
    { token: "metatag", foreground: "569CD6" },
    { token: "metatag.content.html", foreground: "1AEBFF" },
    { token: "metatag.html", foreground: "569CD6" },
    { token: "metatag.xml", foreground: "569CD6" },
    { token: "metatag.php", fontStyle: "bold" },
    { token: "key", foreground: "9CDCFE" },
    { token: "string.key", foreground: "9CDCFE" },
    { token: "string.value", foreground: "CE9178" },
    { token: "attribute.name", foreground: "569CD6" },
    { token: "attribute.value", foreground: "3FF23F" },
    { token: "string", foreground: "CE9178" },
    { token: "string.sql", foreground: "FF0000" },
    { token: "keyword", foreground: "569CD6" },
    { token: "keyword.flow", foreground: "C586C0" },
    { token: "operator.sql", foreground: "778899" },
    { token: "operator.swift", foreground: "909090" },
    { token: "predefined.sql", foreground: "FF00FF" }
  ],
  colors: {
    [editorBackground]: "#000000",
    [editorForeground]: "#FFFFFF",
    [editorIndentGuide1]: "#FFFFFF",
    [editorActiveIndentGuide1]: "#FFFFFF"
  }
};
const hc_light = {
  base: "hc-light",
  inherit: false,
  rules: [
    { token: "", foreground: "292929", background: "FFFFFF" },
    { token: "invalid", foreground: "B5200D" },
    { token: "emphasis", fontStyle: "italic" },
    { token: "strong", fontStyle: "bold" },
    { token: "variable", foreground: "264F70" },
    { token: "variable.predefined", foreground: "4864AA" },
    { token: "constant", foreground: "dd0000" },
    { token: "comment", foreground: "008000" },
    { token: "number", foreground: "098658" },
    { token: "number.hex", foreground: "3030c0" },
    { token: "regexp", foreground: "800000" },
    { token: "annotation", foreground: "808080" },
    { token: "type", foreground: "008080" },
    { token: "delimiter", foreground: "000000" },
    { token: "delimiter.html", foreground: "383838" },
    { token: "tag", foreground: "800000" },
    { token: "tag.id.pug", foreground: "4F76AC" },
    { token: "tag.class.pug", foreground: "4F76AC" },
    { token: "meta.scss", foreground: "800000" },
    { token: "metatag", foreground: "e00000" },
    { token: "metatag.content.html", foreground: "B5200D" },
    { token: "metatag.html", foreground: "808080" },
    { token: "metatag.xml", foreground: "808080" },
    { token: "metatag.php", fontStyle: "bold" },
    { token: "key", foreground: "863B00" },
    { token: "string.key.json", foreground: "A31515" },
    { token: "string.value.json", foreground: "0451A5" },
    { token: "attribute.name", foreground: "264F78" },
    { token: "attribute.value", foreground: "0451A5" },
    { token: "string", foreground: "A31515" },
    { token: "string.sql", foreground: "B5200D" },
    { token: "keyword", foreground: "0000FF" },
    { token: "keyword.flow", foreground: "AF00DB" },
    { token: "operator.sql", foreground: "778899" },
    { token: "operator.swift", foreground: "666666" },
    { token: "predefined.sql", foreground: "C700C7" }
  ],
  colors: {
    [editorBackground]: "#FFFFFF",
    [editorForeground]: "#292929",
    [editorIndentGuide1]: "#292929",
    [editorActiveIndentGuide1]: "#292929"
  }
};
function getIconsStyleSheet(themeService) {
  const onDidChangeEmmiter = new Emitter$1();
  const iconRegistry2 = getIconRegistry();
  iconRegistry2.onDidChange(() => onDidChangeEmmiter.fire());
  themeService === null || themeService === void 0 ? void 0 : themeService.onDidProductIconThemeChange(() => onDidChangeEmmiter.fire());
  return {
    onDidChange: onDidChangeEmmiter.event,
    getCSS() {
      const productIconTheme = themeService ? themeService.getProductIconTheme() : new UnthemedProductIconTheme();
      const usedFontIds = {};
      const formatIconRule = (contribution) => {
        const definition = productIconTheme.getIcon(contribution);
        if (!definition) {
          return void 0;
        }
        const fontContribution = definition.font;
        if (fontContribution) {
          usedFontIds[fontContribution.id] = fontContribution.definition;
          return `.codicon-${contribution.id}:before { content: '${definition.fontCharacter}'; font-family: ${asCSSPropertyValue(fontContribution.id)}; }`;
        }
        return `.codicon-${contribution.id}:before { content: '${definition.fontCharacter}'; }`;
      };
      const rules = [];
      for (const contribution of iconRegistry2.getIcons()) {
        const rule2 = formatIconRule(contribution);
        if (rule2) {
          rules.push(rule2);
        }
      }
      for (const id3 in usedFontIds) {
        const definition = usedFontIds[id3];
        const fontWeight = definition.weight ? `font-weight: ${definition.weight};` : "";
        const fontStyle = definition.style ? `font-style: ${definition.style};` : "";
        const src = definition.src.map((l) => `${asCSSUrl(l.location)} format('${l.format}')`).join(", ");
        rules.push(`@font-face { src: ${src}; font-family: ${asCSSPropertyValue(id3)};${fontWeight}${fontStyle} font-display: block; }`);
      }
      return rules.join("\n");
    }
  };
}
class UnthemedProductIconTheme {
  getIcon(contribution) {
    const iconRegistry2 = getIconRegistry();
    let definition = contribution.defaults;
    while (ThemeIcon.isThemeIcon(definition)) {
      const c = iconRegistry2.getIcon(definition.id);
      if (!c) {
        return void 0;
      }
      definition = c.defaults;
    }
    return definition;
  }
}
const VS_LIGHT_THEME_NAME = "vs";
const VS_DARK_THEME_NAME = "vs-dark";
const HC_BLACK_THEME_NAME = "hc-black";
const HC_LIGHT_THEME_NAME = "hc-light";
const colorRegistry = Registry.as(Extensions$4.ColorContribution);
const themingRegistry = Registry.as(Extensions$3.ThemingContribution);
class StandaloneTheme {
  constructor(name, standaloneThemeData) {
    this.semanticHighlighting = false;
    this.themeData = standaloneThemeData;
    const base2 = standaloneThemeData.base;
    if (name.length > 0) {
      if (isBuiltinTheme(name)) {
        this.id = name;
      } else {
        this.id = base2 + " " + name;
      }
      this.themeName = name;
    } else {
      this.id = base2;
      this.themeName = base2;
    }
    this.colors = null;
    this.defaultColors = /* @__PURE__ */ Object.create(null);
    this._tokenTheme = null;
  }
  get base() {
    return this.themeData.base;
  }
  notifyBaseUpdated() {
    if (this.themeData.inherit) {
      this.colors = null;
      this._tokenTheme = null;
    }
  }
  getColors() {
    if (!this.colors) {
      const colors = /* @__PURE__ */ new Map();
      for (const id3 in this.themeData.colors) {
        colors.set(id3, Color.fromHex(this.themeData.colors[id3]));
      }
      if (this.themeData.inherit) {
        const baseData = getBuiltinRules(this.themeData.base);
        for (const id3 in baseData.colors) {
          if (!colors.has(id3)) {
            colors.set(id3, Color.fromHex(baseData.colors[id3]));
          }
        }
      }
      this.colors = colors;
    }
    return this.colors;
  }
  getColor(colorId, useDefault) {
    const color = this.getColors().get(colorId);
    if (color) {
      return color;
    }
    if (useDefault !== false) {
      return this.getDefault(colorId);
    }
    return void 0;
  }
  getDefault(colorId) {
    let color = this.defaultColors[colorId];
    if (color) {
      return color;
    }
    color = colorRegistry.resolveDefaultColor(colorId, this);
    this.defaultColors[colorId] = color;
    return color;
  }
  defines(colorId) {
    return this.getColors().has(colorId);
  }
  get type() {
    switch (this.base) {
      case VS_LIGHT_THEME_NAME:
        return ColorScheme.LIGHT;
      case HC_BLACK_THEME_NAME:
        return ColorScheme.HIGH_CONTRAST_DARK;
      case HC_LIGHT_THEME_NAME:
        return ColorScheme.HIGH_CONTRAST_LIGHT;
      default:
        return ColorScheme.DARK;
    }
  }
  get tokenTheme() {
    if (!this._tokenTheme) {
      let rules = [];
      let encodedTokensColors = [];
      if (this.themeData.inherit) {
        const baseData = getBuiltinRules(this.themeData.base);
        rules = baseData.rules;
        if (baseData.encodedTokensColors) {
          encodedTokensColors = baseData.encodedTokensColors;
        }
      }
      const editorForeground2 = this.themeData.colors["editor.foreground"];
      const editorBackground2 = this.themeData.colors["editor.background"];
      if (editorForeground2 || editorBackground2) {
        const rule2 = { token: "" };
        if (editorForeground2) {
          rule2.foreground = editorForeground2;
        }
        if (editorBackground2) {
          rule2.background = editorBackground2;
        }
        rules.push(rule2);
      }
      rules = rules.concat(this.themeData.rules);
      if (this.themeData.encodedTokensColors) {
        encodedTokensColors = this.themeData.encodedTokensColors;
      }
      this._tokenTheme = TokenTheme.createFromRawTokenTheme(rules, encodedTokensColors);
    }
    return this._tokenTheme;
  }
  getTokenStyleMetadata(type, modifiers, modelLanguage) {
    const style2 = this.tokenTheme._match([type].concat(modifiers).join("."));
    const metadata = style2.metadata;
    const foreground2 = TokenMetadata.getForeground(metadata);
    const fontStyle = TokenMetadata.getFontStyle(metadata);
    return {
      foreground: foreground2,
      italic: Boolean(
        fontStyle & 1
        /* FontStyle.Italic */
      ),
      bold: Boolean(
        fontStyle & 2
        /* FontStyle.Bold */
      ),
      underline: Boolean(
        fontStyle & 4
        /* FontStyle.Underline */
      ),
      strikethrough: Boolean(
        fontStyle & 8
        /* FontStyle.Strikethrough */
      )
    };
  }
}
function isBuiltinTheme(themeName) {
  return themeName === VS_LIGHT_THEME_NAME || themeName === VS_DARK_THEME_NAME || themeName === HC_BLACK_THEME_NAME || themeName === HC_LIGHT_THEME_NAME;
}
function getBuiltinRules(builtinTheme) {
  switch (builtinTheme) {
    case VS_LIGHT_THEME_NAME:
      return vs;
    case VS_DARK_THEME_NAME:
      return vs_dark;
    case HC_BLACK_THEME_NAME:
      return hc_black;
    case HC_LIGHT_THEME_NAME:
      return hc_light;
  }
}
function newBuiltInTheme(builtinTheme) {
  const themeData = getBuiltinRules(builtinTheme);
  return new StandaloneTheme(builtinTheme, themeData);
}
class StandaloneThemeService extends Disposable {
  constructor() {
    super();
    this._onColorThemeChange = this._register(new Emitter$1());
    this.onDidColorThemeChange = this._onColorThemeChange.event;
    this._onProductIconThemeChange = this._register(new Emitter$1());
    this.onDidProductIconThemeChange = this._onProductIconThemeChange.event;
    this._environment = /* @__PURE__ */ Object.create(null);
    this._builtInProductIconTheme = new UnthemedProductIconTheme();
    this._autoDetectHighContrast = true;
    this._knownThemes = /* @__PURE__ */ new Map();
    this._knownThemes.set(VS_LIGHT_THEME_NAME, newBuiltInTheme(VS_LIGHT_THEME_NAME));
    this._knownThemes.set(VS_DARK_THEME_NAME, newBuiltInTheme(VS_DARK_THEME_NAME));
    this._knownThemes.set(HC_BLACK_THEME_NAME, newBuiltInTheme(HC_BLACK_THEME_NAME));
    this._knownThemes.set(HC_LIGHT_THEME_NAME, newBuiltInTheme(HC_LIGHT_THEME_NAME));
    const iconsStyleSheet = getIconsStyleSheet(this);
    this._codiconCSS = iconsStyleSheet.getCSS();
    this._themeCSS = "";
    this._allCSS = `${this._codiconCSS}
${this._themeCSS}`;
    this._globalStyleElement = null;
    this._styleElements = [];
    this._colorMapOverride = null;
    this.setTheme(VS_LIGHT_THEME_NAME);
    this._onOSSchemeChanged();
    iconsStyleSheet.onDidChange(() => {
      this._codiconCSS = iconsStyleSheet.getCSS();
      this._updateCSS();
    });
    addMatchMediaChangeListener("(forced-colors: active)", () => {
      this._onOSSchemeChanged();
    });
  }
  registerEditorContainer(domNode) {
    if (isInShadowDOM(domNode)) {
      return this._registerShadowDomContainer(domNode);
    }
    return this._registerRegularEditorContainer();
  }
  _registerRegularEditorContainer() {
    if (!this._globalStyleElement) {
      this._globalStyleElement = createStyleSheet(void 0, (style2) => {
        style2.className = "monaco-colors";
        style2.textContent = this._allCSS;
      });
      this._styleElements.push(this._globalStyleElement);
    }
    return Disposable.None;
  }
  _registerShadowDomContainer(domNode) {
    const styleElement = createStyleSheet(domNode, (style2) => {
      style2.className = "monaco-colors";
      style2.textContent = this._allCSS;
    });
    this._styleElements.push(styleElement);
    return {
      dispose: () => {
        for (let i = 0; i < this._styleElements.length; i++) {
          if (this._styleElements[i] === styleElement) {
            this._styleElements.splice(i, 1);
            return;
          }
        }
      }
    };
  }
  defineTheme(themeName, themeData) {
    if (!/^[a-z0-9\-]+$/i.test(themeName)) {
      throw new Error("Illegal theme name!");
    }
    if (!isBuiltinTheme(themeData.base) && !isBuiltinTheme(themeName)) {
      throw new Error("Illegal theme base!");
    }
    this._knownThemes.set(themeName, new StandaloneTheme(themeName, themeData));
    if (isBuiltinTheme(themeName)) {
      this._knownThemes.forEach((theme) => {
        if (theme.base === themeName) {
          theme.notifyBaseUpdated();
        }
      });
    }
    if (this._theme.themeName === themeName) {
      this.setTheme(themeName);
    }
  }
  getColorTheme() {
    return this._theme;
  }
  setColorMapOverride(colorMapOverride) {
    this._colorMapOverride = colorMapOverride;
    this._updateThemeOrColorMap();
  }
  setTheme(themeName) {
    let theme;
    if (this._knownThemes.has(themeName)) {
      theme = this._knownThemes.get(themeName);
    } else {
      theme = this._knownThemes.get(VS_LIGHT_THEME_NAME);
    }
    this._updateActualTheme(theme);
  }
  _updateActualTheme(desiredTheme) {
    if (!desiredTheme || this._theme === desiredTheme) {
      return;
    }
    this._theme = desiredTheme;
    this._updateThemeOrColorMap();
  }
  _onOSSchemeChanged() {
    if (this._autoDetectHighContrast) {
      const wantsHighContrast = window.matchMedia(`(forced-colors: active)`).matches;
      if (wantsHighContrast !== isHighContrast(this._theme.type)) {
        let newThemeName;
        if (isDark(this._theme.type)) {
          newThemeName = wantsHighContrast ? HC_BLACK_THEME_NAME : VS_DARK_THEME_NAME;
        } else {
          newThemeName = wantsHighContrast ? HC_LIGHT_THEME_NAME : VS_LIGHT_THEME_NAME;
        }
        this._updateActualTheme(this._knownThemes.get(newThemeName));
      }
    }
  }
  setAutoDetectHighContrast(autoDetectHighContrast) {
    this._autoDetectHighContrast = autoDetectHighContrast;
    this._onOSSchemeChanged();
  }
  _updateThemeOrColorMap() {
    const cssRules = [];
    const hasRule = {};
    const ruleCollector = {
      addRule: (rule2) => {
        if (!hasRule[rule2]) {
          cssRules.push(rule2);
          hasRule[rule2] = true;
        }
      }
    };
    themingRegistry.getThemingParticipants().forEach((p2) => p2(this._theme, ruleCollector, this._environment));
    const colorVariables = [];
    for (const item of colorRegistry.getColors()) {
      const color = this._theme.getColor(item.id, true);
      if (color) {
        colorVariables.push(`${asCssVariableName(item.id)}: ${color.toString()};`);
      }
    }
    ruleCollector.addRule(`.monaco-editor, .monaco-diff-editor { ${colorVariables.join("\n")} }`);
    const colorMap = this._colorMapOverride || this._theme.tokenTheme.getColorMap();
    ruleCollector.addRule(generateTokensCSSForColorMap(colorMap));
    this._themeCSS = cssRules.join("\n");
    this._updateCSS();
    TokenizationRegistry2.setColorMap(colorMap);
    this._onColorThemeChange.fire(this._theme);
  }
  _updateCSS() {
    this._allCSS = `${this._codiconCSS}
${this._themeCSS}`;
    this._styleElements.forEach((styleElement) => styleElement.textContent = this._allCSS);
  }
  getFileIconTheme() {
    return {
      hasFileIcons: false,
      hasFolderIcons: false,
      hidesExplorerArrows: false
    };
  }
  getProductIconTheme() {
    return this._builtInProductIconTheme;
  }
}
class ToggleHighContrast extends EditorAction {
  constructor() {
    super({
      id: "editor.action.toggleHighContrast",
      label: ToggleHighContrastNLS.toggleHighContrast,
      alias: "Toggle High Contrast Theme",
      precondition: void 0
    });
    this._originalThemeName = null;
  }
  run(accessor, editor2) {
    const standaloneThemeService = accessor.get(IStandaloneThemeService);
    const currentTheme = standaloneThemeService.getColorTheme();
    if (isHighContrast(currentTheme.type)) {
      standaloneThemeService.setTheme(this._originalThemeName || (isDark(currentTheme.type) ? VS_DARK_THEME_NAME : VS_LIGHT_THEME_NAME));
      this._originalThemeName = null;
    } else {
      standaloneThemeService.setTheme(isDark(currentTheme.type) ? HC_BLACK_THEME_NAME : HC_LIGHT_THEME_NAME);
      this._originalThemeName = currentTheme.themeName;
    }
  }
}
registerEditorAction(ToggleHighContrast);
const standaloneTokens = "";
function createWebWorker$1(modelService, languageConfigurationService, opts) {
  return new MonacoWebWorkerImpl(modelService, languageConfigurationService, opts);
}
class MonacoWebWorkerImpl extends EditorWorkerClient {
  constructor(modelService, languageConfigurationService, opts) {
    super(modelService, opts.keepIdleModels || false, opts.label, languageConfigurationService);
    this._foreignModuleId = opts.moduleId;
    this._foreignModuleCreateData = opts.createData || null;
    this._foreignModuleHost = opts.host || null;
    this._foreignProxy = null;
  }
  // foreign host request
  fhr(method, args) {
    if (!this._foreignModuleHost || typeof this._foreignModuleHost[method] !== "function") {
      return Promise.reject(new Error("Missing method " + method + " or missing main thread foreign host."));
    }
    try {
      return Promise.resolve(this._foreignModuleHost[method].apply(this._foreignModuleHost, args));
    } catch (e) {
      return Promise.reject(e);
    }
  }
  _getForeignProxy() {
    if (!this._foreignProxy) {
      this._foreignProxy = this._getProxy().then((proxy) => {
        const foreignHostMethods = this._foreignModuleHost ? getAllMethodNames(this._foreignModuleHost) : [];
        return proxy.loadForeignModule(this._foreignModuleId, this._foreignModuleCreateData, foreignHostMethods).then((foreignMethods) => {
          this._foreignModuleCreateData = null;
          const proxyMethodRequest = (method, args) => {
            return proxy.fmr(method, args);
          };
          const createProxyMethod = (method, proxyMethodRequest2) => {
            return function() {
              const args = Array.prototype.slice.call(arguments, 0);
              return proxyMethodRequest2(method, args);
            };
          };
          const foreignProxy = {};
          for (const foreignMethod of foreignMethods) {
            foreignProxy[foreignMethod] = createProxyMethod(foreignMethod, proxyMethodRequest);
          }
          return foreignProxy;
        });
      });
    }
    return this._foreignProxy;
  }
  getProxy() {
    return this._getForeignProxy();
  }
  withSyncedResources(resources) {
    return this._withSyncedResources(resources).then((_) => this.getProxy());
  }
}
function isFuzzyActionArr(what) {
  return Array.isArray(what);
}
function isFuzzyAction(what) {
  return !isFuzzyActionArr(what);
}
function isString$3(what) {
  return typeof what === "string";
}
function isIAction(what) {
  return !isString$3(what);
}
function empty(s) {
  return s ? false : true;
}
function fixCase(lexer, str2) {
  return lexer.ignoreCase && str2 ? str2.toLowerCase() : str2;
}
function sanitize(s) {
  return s.replace(/[&<>'"_]/g, "-");
}
function log$1(lexer, msg) {
  console.log(`${lexer.languageId}: ${msg}`);
}
function createError(lexer, msg) {
  return new Error(`${lexer.languageId}: ${msg}`);
}
function substituteMatches(lexer, str2, id3, matches, state) {
  const re = /\$((\$)|(#)|(\d\d?)|[sS](\d\d?)|@(\w+))/g;
  let stateMatches = null;
  return str2.replace(re, function(full, sub, dollar2, hash2, n2, s, attr, ofs, total) {
    if (!empty(dollar2)) {
      return "$";
    }
    if (!empty(hash2)) {
      return fixCase(lexer, id3);
    }
    if (!empty(n2) && n2 < matches.length) {
      return fixCase(lexer, matches[n2]);
    }
    if (!empty(attr) && lexer && typeof lexer[attr] === "string") {
      return lexer[attr];
    }
    if (stateMatches === null) {
      stateMatches = state.split(".");
      stateMatches.unshift(state);
    }
    if (!empty(s) && s < stateMatches.length) {
      return fixCase(lexer, stateMatches[s]);
    }
    return "";
  });
}
function findRules(lexer, inState) {
  let state = inState;
  while (state && state.length > 0) {
    const rules = lexer.tokenizer[state];
    if (rules) {
      return rules;
    }
    const idx = state.lastIndexOf(".");
    if (idx < 0) {
      state = null;
    } else {
      state = state.substr(0, idx);
    }
  }
  return null;
}
function stateExists(lexer, inState) {
  let state = inState;
  while (state && state.length > 0) {
    const exist = lexer.stateNames[state];
    if (exist) {
      return true;
    }
    const idx = state.lastIndexOf(".");
    if (idx < 0) {
      state = null;
    } else {
      state = state.substr(0, idx);
    }
  }
  return false;
}
var __decorate$q = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$o = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
const CACHE_STACK_DEPTH = 5;
class MonarchStackElementFactory {
  static create(parent, state) {
    return this._INSTANCE.create(parent, state);
  }
  constructor(maxCacheDepth) {
    this._maxCacheDepth = maxCacheDepth;
    this._entries = /* @__PURE__ */ Object.create(null);
  }
  create(parent, state) {
    if (parent !== null && parent.depth >= this._maxCacheDepth) {
      return new MonarchStackElement(parent, state);
    }
    let stackElementId = MonarchStackElement.getStackElementId(parent);
    if (stackElementId.length > 0) {
      stackElementId += "|";
    }
    stackElementId += state;
    let result2 = this._entries[stackElementId];
    if (result2) {
      return result2;
    }
    result2 = new MonarchStackElement(parent, state);
    this._entries[stackElementId] = result2;
    return result2;
  }
}
MonarchStackElementFactory._INSTANCE = new MonarchStackElementFactory(CACHE_STACK_DEPTH);
class MonarchStackElement {
  constructor(parent, state) {
    this.parent = parent;
    this.state = state;
    this.depth = (this.parent ? this.parent.depth : 0) + 1;
  }
  static getStackElementId(element) {
    let result2 = "";
    while (element !== null) {
      if (result2.length > 0) {
        result2 += "|";
      }
      result2 += element.state;
      element = element.parent;
    }
    return result2;
  }
  static _equals(a, b) {
    while (a !== null && b !== null) {
      if (a === b) {
        return true;
      }
      if (a.state !== b.state) {
        return false;
      }
      a = a.parent;
      b = b.parent;
    }
    if (a === null && b === null) {
      return true;
    }
    return false;
  }
  equals(other) {
    return MonarchStackElement._equals(this, other);
  }
  push(state) {
    return MonarchStackElementFactory.create(this, state);
  }
  pop() {
    return this.parent;
  }
  popall() {
    let result2 = this;
    while (result2.parent) {
      result2 = result2.parent;
    }
    return result2;
  }
  switchTo(state) {
    return MonarchStackElementFactory.create(this.parent, state);
  }
}
class EmbeddedLanguageData {
  constructor(languageId, state) {
    this.languageId = languageId;
    this.state = state;
  }
  equals(other) {
    return this.languageId === other.languageId && this.state.equals(other.state);
  }
  clone() {
    const stateClone = this.state.clone();
    if (stateClone === this.state) {
      return this;
    }
    return new EmbeddedLanguageData(this.languageId, this.state);
  }
}
class MonarchLineStateFactory {
  static create(stack, embeddedLanguageData) {
    return this._INSTANCE.create(stack, embeddedLanguageData);
  }
  constructor(maxCacheDepth) {
    this._maxCacheDepth = maxCacheDepth;
    this._entries = /* @__PURE__ */ Object.create(null);
  }
  create(stack, embeddedLanguageData) {
    if (embeddedLanguageData !== null) {
      return new MonarchLineState(stack, embeddedLanguageData);
    }
    if (stack !== null && stack.depth >= this._maxCacheDepth) {
      return new MonarchLineState(stack, embeddedLanguageData);
    }
    const stackElementId = MonarchStackElement.getStackElementId(stack);
    let result2 = this._entries[stackElementId];
    if (result2) {
      return result2;
    }
    result2 = new MonarchLineState(stack, null);
    this._entries[stackElementId] = result2;
    return result2;
  }
}
MonarchLineStateFactory._INSTANCE = new MonarchLineStateFactory(CACHE_STACK_DEPTH);
class MonarchLineState {
  constructor(stack, embeddedLanguageData) {
    this.stack = stack;
    this.embeddedLanguageData = embeddedLanguageData;
  }
  clone() {
    const embeddedlanguageDataClone = this.embeddedLanguageData ? this.embeddedLanguageData.clone() : null;
    if (embeddedlanguageDataClone === this.embeddedLanguageData) {
      return this;
    }
    return MonarchLineStateFactory.create(this.stack, this.embeddedLanguageData);
  }
  equals(other) {
    if (!(other instanceof MonarchLineState)) {
      return false;
    }
    if (!this.stack.equals(other.stack)) {
      return false;
    }
    if (this.embeddedLanguageData === null && other.embeddedLanguageData === null) {
      return true;
    }
    if (this.embeddedLanguageData === null || other.embeddedLanguageData === null) {
      return false;
    }
    return this.embeddedLanguageData.equals(other.embeddedLanguageData);
  }
}
class MonarchClassicTokensCollector {
  constructor() {
    this._tokens = [];
    this._languageId = null;
    this._lastTokenType = null;
    this._lastTokenLanguage = null;
  }
  enterLanguage(languageId) {
    this._languageId = languageId;
  }
  emit(startOffset, type) {
    if (this._lastTokenType === type && this._lastTokenLanguage === this._languageId) {
      return;
    }
    this._lastTokenType = type;
    this._lastTokenLanguage = this._languageId;
    this._tokens.push(new Token$3(startOffset, type, this._languageId));
  }
  nestedLanguageTokenize(embeddedLanguageLine, hasEOL, embeddedLanguageData, offsetDelta) {
    const nestedLanguageId = embeddedLanguageData.languageId;
    const embeddedModeState = embeddedLanguageData.state;
    const nestedLanguageTokenizationSupport = TokenizationRegistry2.get(nestedLanguageId);
    if (!nestedLanguageTokenizationSupport) {
      this.enterLanguage(nestedLanguageId);
      this.emit(offsetDelta, "");
      return embeddedModeState;
    }
    const nestedResult = nestedLanguageTokenizationSupport.tokenize(embeddedLanguageLine, hasEOL, embeddedModeState);
    if (offsetDelta !== 0) {
      for (const token of nestedResult.tokens) {
        this._tokens.push(new Token$3(token.offset + offsetDelta, token.type, token.language));
      }
    } else {
      this._tokens = this._tokens.concat(nestedResult.tokens);
    }
    this._lastTokenType = null;
    this._lastTokenLanguage = null;
    this._languageId = null;
    return nestedResult.endState;
  }
  finalize(endState) {
    return new TokenizationResult(this._tokens, endState);
  }
}
class MonarchModernTokensCollector {
  constructor(languageService, theme) {
    this._languageService = languageService;
    this._theme = theme;
    this._prependTokens = null;
    this._tokens = [];
    this._currentLanguageId = 0;
    this._lastTokenMetadata = 0;
  }
  enterLanguage(languageId) {
    this._currentLanguageId = this._languageService.languageIdCodec.encodeLanguageId(languageId);
  }
  emit(startOffset, type) {
    const metadata = this._theme.match(this._currentLanguageId, type) | 1024;
    if (this._lastTokenMetadata === metadata) {
      return;
    }
    this._lastTokenMetadata = metadata;
    this._tokens.push(startOffset);
    this._tokens.push(metadata);
  }
  static _merge(a, b, c) {
    const aLen = a !== null ? a.length : 0;
    const bLen = b.length;
    const cLen = c !== null ? c.length : 0;
    if (aLen === 0 && bLen === 0 && cLen === 0) {
      return new Uint32Array(0);
    }
    if (aLen === 0 && bLen === 0) {
      return c;
    }
    if (bLen === 0 && cLen === 0) {
      return a;
    }
    const result2 = new Uint32Array(aLen + bLen + cLen);
    if (a !== null) {
      result2.set(a);
    }
    for (let i = 0; i < bLen; i++) {
      result2[aLen + i] = b[i];
    }
    if (c !== null) {
      result2.set(c, aLen + bLen);
    }
    return result2;
  }
  nestedLanguageTokenize(embeddedLanguageLine, hasEOL, embeddedLanguageData, offsetDelta) {
    const nestedLanguageId = embeddedLanguageData.languageId;
    const embeddedModeState = embeddedLanguageData.state;
    const nestedLanguageTokenizationSupport = TokenizationRegistry2.get(nestedLanguageId);
    if (!nestedLanguageTokenizationSupport) {
      this.enterLanguage(nestedLanguageId);
      this.emit(offsetDelta, "");
      return embeddedModeState;
    }
    const nestedResult = nestedLanguageTokenizationSupport.tokenizeEncoded(embeddedLanguageLine, hasEOL, embeddedModeState);
    if (offsetDelta !== 0) {
      for (let i = 0, len = nestedResult.tokens.length; i < len; i += 2) {
        nestedResult.tokens[i] += offsetDelta;
      }
    }
    this._prependTokens = MonarchModernTokensCollector._merge(this._prependTokens, this._tokens, nestedResult.tokens);
    this._tokens = [];
    this._currentLanguageId = 0;
    this._lastTokenMetadata = 0;
    return nestedResult.endState;
  }
  finalize(endState) {
    return new EncodedTokenizationResult(MonarchModernTokensCollector._merge(this._prependTokens, this._tokens, null), endState);
  }
}
let MonarchTokenizer = class MonarchTokenizer2 {
  constructor(languageService, standaloneThemeService, languageId, lexer, _configurationService) {
    this._configurationService = _configurationService;
    this._languageService = languageService;
    this._standaloneThemeService = standaloneThemeService;
    this._languageId = languageId;
    this._lexer = lexer;
    this._embeddedLanguages = /* @__PURE__ */ Object.create(null);
    this.embeddedLoaded = Promise.resolve(void 0);
    let emitting = false;
    this._tokenizationRegistryListener = TokenizationRegistry2.onDidChange((e) => {
      if (emitting) {
        return;
      }
      let isOneOfMyEmbeddedModes = false;
      for (let i = 0, len = e.changedLanguages.length; i < len; i++) {
        const language2 = e.changedLanguages[i];
        if (this._embeddedLanguages[language2]) {
          isOneOfMyEmbeddedModes = true;
          break;
        }
      }
      if (isOneOfMyEmbeddedModes) {
        emitting = true;
        TokenizationRegistry2.handleChange([this._languageId]);
        emitting = false;
      }
    });
    this._maxTokenizationLineLength = this._configurationService.getValue("editor.maxTokenizationLineLength", {
      overrideIdentifier: this._languageId
    });
    this._configurationService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("editor.maxTokenizationLineLength")) {
        this._maxTokenizationLineLength = this._configurationService.getValue("editor.maxTokenizationLineLength", {
          overrideIdentifier: this._languageId
        });
      }
    });
  }
  dispose() {
    this._tokenizationRegistryListener.dispose();
  }
  getLoadStatus() {
    const promises = [];
    for (const nestedLanguageId in this._embeddedLanguages) {
      const tokenizationSupport = TokenizationRegistry2.get(nestedLanguageId);
      if (tokenizationSupport) {
        if (tokenizationSupport instanceof MonarchTokenizer2) {
          const nestedModeStatus = tokenizationSupport.getLoadStatus();
          if (nestedModeStatus.loaded === false) {
            promises.push(nestedModeStatus.promise);
          }
        }
        continue;
      }
      if (!TokenizationRegistry2.isResolved(nestedLanguageId)) {
        promises.push(TokenizationRegistry2.getOrCreate(nestedLanguageId));
      }
    }
    if (promises.length === 0) {
      return {
        loaded: true
      };
    }
    return {
      loaded: false,
      promise: Promise.all(promises).then((_) => void 0)
    };
  }
  getInitialState() {
    const rootState = MonarchStackElementFactory.create(null, this._lexer.start);
    return MonarchLineStateFactory.create(rootState, null);
  }
  tokenize(line, hasEOL, lineState) {
    if (line.length >= this._maxTokenizationLineLength) {
      return nullTokenize(this._languageId, lineState);
    }
    const tokensCollector = new MonarchClassicTokensCollector();
    const endLineState = this._tokenize(line, hasEOL, lineState, tokensCollector);
    return tokensCollector.finalize(endLineState);
  }
  tokenizeEncoded(line, hasEOL, lineState) {
    if (line.length >= this._maxTokenizationLineLength) {
      return nullTokenizeEncoded(this._languageService.languageIdCodec.encodeLanguageId(this._languageId), lineState);
    }
    const tokensCollector = new MonarchModernTokensCollector(this._languageService, this._standaloneThemeService.getColorTheme().tokenTheme);
    const endLineState = this._tokenize(line, hasEOL, lineState, tokensCollector);
    return tokensCollector.finalize(endLineState);
  }
  _tokenize(line, hasEOL, lineState, collector) {
    if (lineState.embeddedLanguageData) {
      return this._nestedTokenize(line, hasEOL, lineState, 0, collector);
    } else {
      return this._myTokenize(line, hasEOL, lineState, 0, collector);
    }
  }
  _findLeavingNestedLanguageOffset(line, state) {
    let rules = this._lexer.tokenizer[state.stack.state];
    if (!rules) {
      rules = findRules(this._lexer, state.stack.state);
      if (!rules) {
        throw createError(this._lexer, "tokenizer state is not defined: " + state.stack.state);
      }
    }
    let popOffset = -1;
    let hasEmbeddedPopRule = false;
    for (const rule2 of rules) {
      if (!isIAction(rule2.action) || rule2.action.nextEmbedded !== "@pop") {
        continue;
      }
      hasEmbeddedPopRule = true;
      let regex = rule2.regex;
      const regexSource = rule2.regex.source;
      if (regexSource.substr(0, 4) === "^(?:" && regexSource.substr(regexSource.length - 1, 1) === ")") {
        const flags = (regex.ignoreCase ? "i" : "") + (regex.unicode ? "u" : "");
        regex = new RegExp(regexSource.substr(4, regexSource.length - 5), flags);
      }
      const result2 = line.search(regex);
      if (result2 === -1 || result2 !== 0 && rule2.matchOnlyAtLineStart) {
        continue;
      }
      if (popOffset === -1 || result2 < popOffset) {
        popOffset = result2;
      }
    }
    if (!hasEmbeddedPopRule) {
      throw createError(this._lexer, 'no rule containing nextEmbedded: "@pop" in tokenizer embedded state: ' + state.stack.state);
    }
    return popOffset;
  }
  _nestedTokenize(line, hasEOL, lineState, offsetDelta, tokensCollector) {
    const popOffset = this._findLeavingNestedLanguageOffset(line, lineState);
    if (popOffset === -1) {
      const nestedEndState = tokensCollector.nestedLanguageTokenize(line, hasEOL, lineState.embeddedLanguageData, offsetDelta);
      return MonarchLineStateFactory.create(lineState.stack, new EmbeddedLanguageData(lineState.embeddedLanguageData.languageId, nestedEndState));
    }
    const nestedLanguageLine = line.substring(0, popOffset);
    if (nestedLanguageLine.length > 0) {
      tokensCollector.nestedLanguageTokenize(nestedLanguageLine, false, lineState.embeddedLanguageData, offsetDelta);
    }
    const restOfTheLine = line.substring(popOffset);
    return this._myTokenize(restOfTheLine, hasEOL, lineState, offsetDelta + popOffset, tokensCollector);
  }
  _safeRuleName(rule2) {
    if (rule2) {
      return rule2.name;
    }
    return "(unknown)";
  }
  _myTokenize(lineWithoutLF, hasEOL, lineState, offsetDelta, tokensCollector) {
    tokensCollector.enterLanguage(this._languageId);
    const lineWithoutLFLength = lineWithoutLF.length;
    const line = hasEOL && this._lexer.includeLF ? lineWithoutLF + "\n" : lineWithoutLF;
    const lineLength = line.length;
    let embeddedLanguageData = lineState.embeddedLanguageData;
    let stack = lineState.stack;
    let pos = 0;
    let groupMatching = null;
    let forceEvaluation = true;
    while (forceEvaluation || pos < lineLength) {
      const pos0 = pos;
      const stackLen0 = stack.depth;
      const groupLen0 = groupMatching ? groupMatching.groups.length : 0;
      const state = stack.state;
      let matches = null;
      let matched = null;
      let action = null;
      let rule2 = null;
      let enteringEmbeddedLanguage = null;
      if (groupMatching) {
        matches = groupMatching.matches;
        const groupEntry = groupMatching.groups.shift();
        matched = groupEntry.matched;
        action = groupEntry.action;
        rule2 = groupMatching.rule;
        if (groupMatching.groups.length === 0) {
          groupMatching = null;
        }
      } else {
        if (!forceEvaluation && pos >= lineLength) {
          break;
        }
        forceEvaluation = false;
        let rules = this._lexer.tokenizer[state];
        if (!rules) {
          rules = findRules(this._lexer, state);
          if (!rules) {
            throw createError(this._lexer, "tokenizer state is not defined: " + state);
          }
        }
        const restOfLine = line.substr(pos);
        for (const rule3 of rules) {
          if (pos === 0 || !rule3.matchOnlyAtLineStart) {
            matches = restOfLine.match(rule3.regex);
            if (matches) {
              matched = matches[0];
              action = rule3.action;
              break;
            }
          }
        }
      }
      if (!matches) {
        matches = [""];
        matched = "";
      }
      if (!action) {
        if (pos < lineLength) {
          matches = [line.charAt(pos)];
          matched = matches[0];
        }
        action = this._lexer.defaultToken;
      }
      if (matched === null) {
        break;
      }
      pos += matched.length;
      while (isFuzzyAction(action) && isIAction(action) && action.test) {
        action = action.test(matched, matches, state, pos === lineLength);
      }
      let result2 = null;
      if (typeof action === "string" || Array.isArray(action)) {
        result2 = action;
      } else if (action.group) {
        result2 = action.group;
      } else if (action.token !== null && action.token !== void 0) {
        if (action.tokenSubst) {
          result2 = substituteMatches(this._lexer, action.token, matched, matches, state);
        } else {
          result2 = action.token;
        }
        if (action.nextEmbedded) {
          if (action.nextEmbedded === "@pop") {
            if (!embeddedLanguageData) {
              throw createError(this._lexer, "cannot pop embedded language if not inside one");
            }
            embeddedLanguageData = null;
          } else if (embeddedLanguageData) {
            throw createError(this._lexer, "cannot enter embedded language from within an embedded language");
          } else {
            enteringEmbeddedLanguage = substituteMatches(this._lexer, action.nextEmbedded, matched, matches, state);
          }
        }
        if (action.goBack) {
          pos = Math.max(0, pos - action.goBack);
        }
        if (action.switchTo && typeof action.switchTo === "string") {
          let nextState = substituteMatches(this._lexer, action.switchTo, matched, matches, state);
          if (nextState[0] === "@") {
            nextState = nextState.substr(1);
          }
          if (!findRules(this._lexer, nextState)) {
            throw createError(this._lexer, "trying to switch to a state '" + nextState + "' that is undefined in rule: " + this._safeRuleName(rule2));
          } else {
            stack = stack.switchTo(nextState);
          }
        } else if (action.transform && typeof action.transform === "function") {
          throw createError(this._lexer, "action.transform not supported");
        } else if (action.next) {
          if (action.next === "@push") {
            if (stack.depth >= this._lexer.maxStack) {
              throw createError(this._lexer, "maximum tokenizer stack size reached: [" + stack.state + "," + stack.parent.state + ",...]");
            } else {
              stack = stack.push(state);
            }
          } else if (action.next === "@pop") {
            if (stack.depth <= 1) {
              throw createError(this._lexer, "trying to pop an empty stack in rule: " + this._safeRuleName(rule2));
            } else {
              stack = stack.pop();
            }
          } else if (action.next === "@popall") {
            stack = stack.popall();
          } else {
            let nextState = substituteMatches(this._lexer, action.next, matched, matches, state);
            if (nextState[0] === "@") {
              nextState = nextState.substr(1);
            }
            if (!findRules(this._lexer, nextState)) {
              throw createError(this._lexer, "trying to set a next state '" + nextState + "' that is undefined in rule: " + this._safeRuleName(rule2));
            } else {
              stack = stack.push(nextState);
            }
          }
        }
        if (action.log && typeof action.log === "string") {
          log$1(this._lexer, this._lexer.languageId + ": " + substituteMatches(this._lexer, action.log, matched, matches, state));
        }
      }
      if (result2 === null) {
        throw createError(this._lexer, "lexer rule has no well-defined action in rule: " + this._safeRuleName(rule2));
      }
      const computeNewStateForEmbeddedLanguage = (enteringEmbeddedLanguage2) => {
        const languageId = this._languageService.getLanguageIdByLanguageName(enteringEmbeddedLanguage2) || this._languageService.getLanguageIdByMimeType(enteringEmbeddedLanguage2) || enteringEmbeddedLanguage2;
        const embeddedLanguageData2 = this._getNestedEmbeddedLanguageData(languageId);
        if (pos < lineLength) {
          const restOfLine = lineWithoutLF.substr(pos);
          return this._nestedTokenize(restOfLine, hasEOL, MonarchLineStateFactory.create(stack, embeddedLanguageData2), offsetDelta + pos, tokensCollector);
        } else {
          return MonarchLineStateFactory.create(stack, embeddedLanguageData2);
        }
      };
      if (Array.isArray(result2)) {
        if (groupMatching && groupMatching.groups.length > 0) {
          throw createError(this._lexer, "groups cannot be nested: " + this._safeRuleName(rule2));
        }
        if (matches.length !== result2.length + 1) {
          throw createError(this._lexer, "matched number of groups does not match the number of actions in rule: " + this._safeRuleName(rule2));
        }
        let totalLen = 0;
        for (let i = 1; i < matches.length; i++) {
          totalLen += matches[i].length;
        }
        if (totalLen !== matched.length) {
          throw createError(this._lexer, "with groups, all characters should be matched in consecutive groups in rule: " + this._safeRuleName(rule2));
        }
        groupMatching = {
          rule: rule2,
          matches,
          groups: []
        };
        for (let i = 0; i < result2.length; i++) {
          groupMatching.groups[i] = {
            action: result2[i],
            matched: matches[i + 1]
          };
        }
        pos -= matched.length;
        continue;
      } else {
        if (result2 === "@rematch") {
          pos -= matched.length;
          matched = "";
          matches = null;
          result2 = "";
          if (enteringEmbeddedLanguage !== null) {
            return computeNewStateForEmbeddedLanguage(enteringEmbeddedLanguage);
          }
        }
        if (matched.length === 0) {
          if (lineLength === 0 || stackLen0 !== stack.depth || state !== stack.state || (!groupMatching ? 0 : groupMatching.groups.length) !== groupLen0) {
            continue;
          } else {
            throw createError(this._lexer, "no progress in tokenizer in rule: " + this._safeRuleName(rule2));
          }
        }
        let tokenType = null;
        if (isString$3(result2) && result2.indexOf("@brackets") === 0) {
          const rest = result2.substr("@brackets".length);
          const bracket = findBracket(this._lexer, matched);
          if (!bracket) {
            throw createError(this._lexer, "@brackets token returned but no bracket defined as: " + matched);
          }
          tokenType = sanitize(bracket.token + rest);
        } else {
          const token = result2 === "" ? "" : result2 + this._lexer.tokenPostfix;
          tokenType = sanitize(token);
        }
        if (pos0 < lineWithoutLFLength) {
          tokensCollector.emit(pos0 + offsetDelta, tokenType);
        }
      }
      if (enteringEmbeddedLanguage !== null) {
        return computeNewStateForEmbeddedLanguage(enteringEmbeddedLanguage);
      }
    }
    return MonarchLineStateFactory.create(stack, embeddedLanguageData);
  }
  _getNestedEmbeddedLanguageData(languageId) {
    if (!this._languageService.isRegisteredLanguageId(languageId)) {
      return new EmbeddedLanguageData(languageId, NullState);
    }
    if (languageId !== this._languageId) {
      this._languageService.requestBasicLanguageFeatures(languageId);
      TokenizationRegistry2.getOrCreate(languageId);
      this._embeddedLanguages[languageId] = true;
    }
    const tokenizationSupport = TokenizationRegistry2.get(languageId);
    if (tokenizationSupport) {
      return new EmbeddedLanguageData(languageId, tokenizationSupport.getInitialState());
    }
    return new EmbeddedLanguageData(languageId, NullState);
  }
};
MonarchTokenizer = __decorate$q([
  __param$o(4, IConfigurationService)
], MonarchTokenizer);
function findBracket(lexer, matched) {
  if (!matched) {
    return null;
  }
  matched = fixCase(lexer, matched);
  const brackets = lexer.brackets;
  for (const bracket of brackets) {
    if (bracket.open === matched) {
      return {
        token: bracket.token,
        bracketType: 1
        /* monarchCommon.MonarchBracket.Open */
      };
    } else if (bracket.close === matched) {
      return {
        token: bracket.token,
        bracketType: -1
        /* monarchCommon.MonarchBracket.Close */
      };
    }
  }
  return null;
}
var __awaiter$e = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
const ttPolicy$1 = createTrustedTypesPolicy("standaloneColorizer", { createHTML: (value) => value });
class Colorizer {
  static colorizeElement(themeService, languageService, domNode, options) {
    options = options || {};
    const theme = options.theme || "vs";
    const mimeType = options.mimeType || domNode.getAttribute("lang") || domNode.getAttribute("data-lang");
    if (!mimeType) {
      console.error("Mode not detected");
      return Promise.resolve();
    }
    const languageId = languageService.getLanguageIdByMimeType(mimeType) || mimeType;
    themeService.setTheme(theme);
    const text2 = domNode.firstChild ? domNode.firstChild.nodeValue : "";
    domNode.className += " " + theme;
    const render = (str2) => {
      var _a2;
      const trustedhtml = (_a2 = ttPolicy$1 === null || ttPolicy$1 === void 0 ? void 0 : ttPolicy$1.createHTML(str2)) !== null && _a2 !== void 0 ? _a2 : str2;
      domNode.innerHTML = trustedhtml;
    };
    return this.colorize(languageService, text2 || "", languageId, options).then(render, (err) => console.error(err));
  }
  static colorize(languageService, text2, languageId, options) {
    return __awaiter$e(this, void 0, void 0, function* () {
      const languageIdCodec = languageService.languageIdCodec;
      let tabSize = 4;
      if (options && typeof options.tabSize === "number") {
        tabSize = options.tabSize;
      }
      if (startsWithUTF8BOM(text2)) {
        text2 = text2.substr(1);
      }
      const lines = splitLines(text2);
      if (!languageService.isRegisteredLanguageId(languageId)) {
        return _fakeColorize(lines, tabSize, languageIdCodec);
      }
      const tokenizationSupport = yield TokenizationRegistry2.getOrCreate(languageId);
      if (tokenizationSupport) {
        return _colorize(lines, tabSize, tokenizationSupport, languageIdCodec);
      }
      return _fakeColorize(lines, tabSize, languageIdCodec);
    });
  }
  static colorizeLine(line, mightContainNonBasicASCII, mightContainRTL, tokens, tabSize = 4) {
    const isBasicASCII2 = ViewLineRenderingData.isBasicASCII(line, mightContainNonBasicASCII);
    const containsRTL2 = ViewLineRenderingData.containsRTL(line, isBasicASCII2, mightContainRTL);
    const renderResult = renderViewLine2(new RenderLineInput(false, true, line, false, isBasicASCII2, containsRTL2, 0, tokens, [], tabSize, 0, 0, 0, 0, -1, "none", false, false, null));
    return renderResult.html;
  }
  static colorizeModelLine(model, lineNumber, tabSize = 4) {
    const content = model.getLineContent(lineNumber);
    model.tokenization.forceTokenization(lineNumber);
    const tokens = model.tokenization.getLineTokens(lineNumber);
    const inflatedTokens = tokens.inflate();
    return this.colorizeLine(content, model.mightContainNonBasicASCII(), model.mightContainRTL(), inflatedTokens, tabSize);
  }
}
function _colorize(lines, tabSize, tokenizationSupport, languageIdCodec) {
  return new Promise((c, e) => {
    const execute = () => {
      const result2 = _actualColorize(lines, tabSize, tokenizationSupport, languageIdCodec);
      if (tokenizationSupport instanceof MonarchTokenizer) {
        const status2 = tokenizationSupport.getLoadStatus();
        if (status2.loaded === false) {
          status2.promise.then(execute, e);
          return;
        }
      }
      c(result2);
    };
    execute();
  });
}
function _fakeColorize(lines, tabSize, languageIdCodec) {
  let html2 = [];
  const defaultMetadata = (0 << 11 | 1 << 15 | 2 << 24) >>> 0;
  const tokens = new Uint32Array(2);
  tokens[0] = 0;
  tokens[1] = defaultMetadata;
  for (let i = 0, length2 = lines.length; i < length2; i++) {
    const line = lines[i];
    tokens[0] = line.length;
    const lineTokens = new LineTokens(tokens, line, languageIdCodec);
    const isBasicASCII2 = ViewLineRenderingData.isBasicASCII(
      line,
      /* check for basic ASCII */
      true
    );
    const containsRTL2 = ViewLineRenderingData.containsRTL(
      line,
      isBasicASCII2,
      /* check for RTL */
      true
    );
    const renderResult = renderViewLine2(new RenderLineInput(false, true, line, false, isBasicASCII2, containsRTL2, 0, lineTokens, [], tabSize, 0, 0, 0, 0, -1, "none", false, false, null));
    html2 = html2.concat(renderResult.html);
    html2.push("<br/>");
  }
  return html2.join("");
}
function _actualColorize(lines, tabSize, tokenizationSupport, languageIdCodec) {
  let html2 = [];
  let state = tokenizationSupport.getInitialState();
  for (let i = 0, length2 = lines.length; i < length2; i++) {
    const line = lines[i];
    const tokenizeResult = tokenizationSupport.tokenizeEncoded(line, true, state);
    LineTokens.convertToEndOffset(tokenizeResult.tokens, line.length);
    const lineTokens = new LineTokens(tokenizeResult.tokens, line, languageIdCodec);
    const isBasicASCII2 = ViewLineRenderingData.isBasicASCII(
      line,
      /* check for basic ASCII */
      true
    );
    const containsRTL2 = ViewLineRenderingData.containsRTL(
      line,
      isBasicASCII2,
      /* check for RTL */
      true
    );
    const renderResult = renderViewLine2(new RenderLineInput(false, true, line, false, isBasicASCII2, containsRTL2, 0, lineTokens.inflate(), [], tabSize, 0, 0, 0, 0, -1, "none", false, false, null));
    html2 = html2.concat(renderResult.html);
    html2.push("<br/>");
    state = tokenizeResult.endState;
  }
  return html2.join("");
}
var __decorate$p = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$n = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$d = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
let AbstractCodeEditorService = class AbstractCodeEditorService2 extends Disposable {
  constructor(_themeService) {
    super();
    this._themeService = _themeService;
    this._onWillCreateCodeEditor = this._register(new Emitter$1());
    this._onCodeEditorAdd = this._register(new Emitter$1());
    this.onCodeEditorAdd = this._onCodeEditorAdd.event;
    this._onCodeEditorRemove = this._register(new Emitter$1());
    this.onCodeEditorRemove = this._onCodeEditorRemove.event;
    this._onWillCreateDiffEditor = this._register(new Emitter$1());
    this._onDiffEditorAdd = this._register(new Emitter$1());
    this.onDiffEditorAdd = this._onDiffEditorAdd.event;
    this._onDiffEditorRemove = this._register(new Emitter$1());
    this.onDiffEditorRemove = this._onDiffEditorRemove.event;
    this._decorationOptionProviders = /* @__PURE__ */ new Map();
    this._codeEditorOpenHandlers = new LinkedList();
    this._modelProperties = /* @__PURE__ */ new Map();
    this._codeEditors = /* @__PURE__ */ Object.create(null);
    this._diffEditors = /* @__PURE__ */ Object.create(null);
    this._globalStyleSheet = null;
  }
  willCreateCodeEditor() {
    this._onWillCreateCodeEditor.fire();
  }
  addCodeEditor(editor2) {
    this._codeEditors[editor2.getId()] = editor2;
    this._onCodeEditorAdd.fire(editor2);
  }
  removeCodeEditor(editor2) {
    if (delete this._codeEditors[editor2.getId()]) {
      this._onCodeEditorRemove.fire(editor2);
    }
  }
  listCodeEditors() {
    return Object.keys(this._codeEditors).map((id3) => this._codeEditors[id3]);
  }
  willCreateDiffEditor() {
    this._onWillCreateDiffEditor.fire();
  }
  addDiffEditor(editor2) {
    this._diffEditors[editor2.getId()] = editor2;
    this._onDiffEditorAdd.fire(editor2);
  }
  removeDiffEditor(editor2) {
    if (delete this._diffEditors[editor2.getId()]) {
      this._onDiffEditorRemove.fire(editor2);
    }
  }
  listDiffEditors() {
    return Object.keys(this._diffEditors).map((id3) => this._diffEditors[id3]);
  }
  getFocusedCodeEditor() {
    let editorWithWidgetFocus = null;
    const editors = this.listCodeEditors();
    for (const editor2 of editors) {
      if (editor2.hasTextFocus()) {
        return editor2;
      }
      if (editor2.hasWidgetFocus()) {
        editorWithWidgetFocus = editor2;
      }
    }
    return editorWithWidgetFocus;
  }
  removeDecorationType(key) {
    const provider = this._decorationOptionProviders.get(key);
    if (provider) {
      provider.refCount--;
      if (provider.refCount <= 0) {
        this._decorationOptionProviders.delete(key);
        provider.dispose();
        this.listCodeEditors().forEach((ed) => ed.removeDecorationsByType(key));
      }
    }
  }
  setModelProperty(resource, key, value) {
    const key1 = resource.toString();
    let dest;
    if (this._modelProperties.has(key1)) {
      dest = this._modelProperties.get(key1);
    } else {
      dest = /* @__PURE__ */ new Map();
      this._modelProperties.set(key1, dest);
    }
    dest.set(key, value);
  }
  getModelProperty(resource, key) {
    const key1 = resource.toString();
    if (this._modelProperties.has(key1)) {
      const innerMap = this._modelProperties.get(key1);
      return innerMap.get(key);
    }
    return void 0;
  }
  openCodeEditor(input2, source, sideBySide) {
    return __awaiter$d(this, void 0, void 0, function* () {
      for (const handler of this._codeEditorOpenHandlers) {
        const candidate = yield handler(input2, source, sideBySide);
        if (candidate !== null) {
          return candidate;
        }
      }
      return null;
    });
  }
  registerCodeEditorOpenHandler(handler) {
    const rm = this._codeEditorOpenHandlers.unshift(handler);
    return toDisposable(rm);
  }
};
AbstractCodeEditorService = __decorate$p([
  __param$n(0, IThemeService)
], AbstractCodeEditorService);
var __decorate$o = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$m = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$c = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
let StandaloneCodeEditorService = class StandaloneCodeEditorService2 extends AbstractCodeEditorService {
  constructor(contextKeyService, themeService) {
    super(themeService);
    this.onCodeEditorAdd(() => this._checkContextKey());
    this.onCodeEditorRemove(() => this._checkContextKey());
    this._editorIsOpen = contextKeyService.createKey("editorIsOpen", false);
    this._activeCodeEditor = null;
    this.registerCodeEditorOpenHandler((input2, source, sideBySide) => __awaiter$c(this, void 0, void 0, function* () {
      if (!source) {
        return null;
      }
      return this.doOpenEditor(source, input2);
    }));
  }
  _checkContextKey() {
    let hasCodeEditor = false;
    for (const editor2 of this.listCodeEditors()) {
      if (!editor2.isSimpleWidget) {
        hasCodeEditor = true;
        break;
      }
    }
    this._editorIsOpen.set(hasCodeEditor);
  }
  setActiveCodeEditor(activeCodeEditor) {
    this._activeCodeEditor = activeCodeEditor;
  }
  getActiveCodeEditor() {
    return this._activeCodeEditor;
  }
  doOpenEditor(editor2, input2) {
    const model = this.findModel(editor2, input2.resource);
    if (!model) {
      if (input2.resource) {
        const schema = input2.resource.scheme;
        if (schema === Schemas.http || schema === Schemas.https) {
          windowOpenNoOpener(input2.resource.toString());
          return editor2;
        }
      }
      return null;
    }
    const selection = input2.options ? input2.options.selection : null;
    if (selection) {
      if (typeof selection.endLineNumber === "number" && typeof selection.endColumn === "number") {
        editor2.setSelection(selection);
        editor2.revealRangeInCenter(
          selection,
          1
          /* ScrollType.Immediate */
        );
      } else {
        const pos = {
          lineNumber: selection.startLineNumber,
          column: selection.startColumn
        };
        editor2.setPosition(pos);
        editor2.revealPositionInCenter(
          pos,
          1
          /* ScrollType.Immediate */
        );
      }
    }
    return editor2;
  }
  findModel(editor2, resource) {
    const model = editor2.getModel();
    if (model && model.uri.toString() !== resource.toString()) {
      return null;
    }
    return model;
  }
};
StandaloneCodeEditorService = __decorate$o([
  __param$m(0, IContextKeyService),
  __param$m(1, IThemeService)
], StandaloneCodeEditorService);
registerSingleton(
  ICodeEditorService,
  StandaloneCodeEditorService,
  0
  /* InstantiationType.Eager */
);
const ILayoutService = createDecorator("layoutService");
var __decorate$n = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$l = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let StandaloneLayoutService = class StandaloneLayoutService2 {
  get dimension() {
    if (!this._dimension) {
      this._dimension = getClientArea(window.document.body);
    }
    return this._dimension;
  }
  get hasContainer() {
    return false;
  }
  get container() {
    throw new Error(`ILayoutService.container is not available in the standalone editor!`);
  }
  focus() {
    var _a2;
    (_a2 = this._codeEditorService.getFocusedCodeEditor()) === null || _a2 === void 0 ? void 0 : _a2.focus();
  }
  constructor(_codeEditorService) {
    this._codeEditorService = _codeEditorService;
    this.onDidLayout = Event$1.None;
    this.offset = { top: 0, quickPickTop: 0 };
  }
};
StandaloneLayoutService = __decorate$n([
  __param$l(0, ICodeEditorService)
], StandaloneLayoutService);
let EditorScopedLayoutService = class EditorScopedLayoutService2 extends StandaloneLayoutService {
  get hasContainer() {
    return false;
  }
  get container() {
    return this._container;
  }
  constructor(_container, codeEditorService) {
    super(codeEditorService);
    this._container = _container;
  }
};
EditorScopedLayoutService = __decorate$n([
  __param$l(1, ICodeEditorService)
], EditorScopedLayoutService);
registerSingleton(
  ILayoutService,
  StandaloneLayoutService,
  1
  /* InstantiationType.Delayed */
);
var __decorate$m = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$k = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$b = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
function getResourceLabel(resource) {
  return resource.scheme === Schemas.file ? resource.fsPath : resource.path;
}
let stackElementCounter = 0;
class ResourceStackElement {
  constructor(actual, resourceLabel, strResource, groupId, groupOrder, sourceId, sourceOrder) {
    this.id = ++stackElementCounter;
    this.type = 0;
    this.actual = actual;
    this.label = actual.label;
    this.confirmBeforeUndo = actual.confirmBeforeUndo || false;
    this.resourceLabel = resourceLabel;
    this.strResource = strResource;
    this.resourceLabels = [this.resourceLabel];
    this.strResources = [this.strResource];
    this.groupId = groupId;
    this.groupOrder = groupOrder;
    this.sourceId = sourceId;
    this.sourceOrder = sourceOrder;
    this.isValid = true;
  }
  setValid(isValid2) {
    this.isValid = isValid2;
  }
  toString() {
    return `[id:${this.id}] [group:${this.groupId}] [${this.isValid ? "  VALID" : "INVALID"}] ${this.actual.constructor.name} - ${this.actual}`;
  }
}
class ResourceReasonPair {
  constructor(resourceLabel, reason) {
    this.resourceLabel = resourceLabel;
    this.reason = reason;
  }
}
class RemovedResources {
  constructor() {
    this.elements = /* @__PURE__ */ new Map();
  }
  createMessage() {
    const externalRemoval = [];
    const noParallelUniverses = [];
    for (const [, element] of this.elements) {
      const dest = element.reason === 0 ? externalRemoval : noParallelUniverses;
      dest.push(element.resourceLabel);
    }
    const messages = [];
    if (externalRemoval.length > 0) {
      messages.push(localize({ key: "externalRemoval", comment: ["{0} is a list of filenames"] }, "The following files have been closed and modified on disk: {0}.", externalRemoval.join(", ")));
    }
    if (noParallelUniverses.length > 0) {
      messages.push(localize({ key: "noParallelUniverses", comment: ["{0} is a list of filenames"] }, "The following files have been modified in an incompatible way: {0}.", noParallelUniverses.join(", ")));
    }
    return messages.join("\n");
  }
  get size() {
    return this.elements.size;
  }
  has(strResource) {
    return this.elements.has(strResource);
  }
  set(strResource, value) {
    this.elements.set(strResource, value);
  }
  delete(strResource) {
    return this.elements.delete(strResource);
  }
}
class WorkspaceStackElement {
  constructor(actual, resourceLabels, strResources, groupId, groupOrder, sourceId, sourceOrder) {
    this.id = ++stackElementCounter;
    this.type = 1;
    this.actual = actual;
    this.label = actual.label;
    this.confirmBeforeUndo = actual.confirmBeforeUndo || false;
    this.resourceLabels = resourceLabels;
    this.strResources = strResources;
    this.groupId = groupId;
    this.groupOrder = groupOrder;
    this.sourceId = sourceId;
    this.sourceOrder = sourceOrder;
    this.removedResources = null;
    this.invalidatedResources = null;
  }
  canSplit() {
    return typeof this.actual.split === "function";
  }
  removeResource(resourceLabel, strResource, reason) {
    if (!this.removedResources) {
      this.removedResources = new RemovedResources();
    }
    if (!this.removedResources.has(strResource)) {
      this.removedResources.set(strResource, new ResourceReasonPair(resourceLabel, reason));
    }
  }
  setValid(resourceLabel, strResource, isValid2) {
    if (isValid2) {
      if (this.invalidatedResources) {
        this.invalidatedResources.delete(strResource);
        if (this.invalidatedResources.size === 0) {
          this.invalidatedResources = null;
        }
      }
    } else {
      if (!this.invalidatedResources) {
        this.invalidatedResources = new RemovedResources();
      }
      if (!this.invalidatedResources.has(strResource)) {
        this.invalidatedResources.set(strResource, new ResourceReasonPair(
          resourceLabel,
          0
          /* RemovedResourceReason.ExternalRemoval */
        ));
      }
    }
  }
  toString() {
    return `[id:${this.id}] [group:${this.groupId}] [${this.invalidatedResources ? "INVALID" : "  VALID"}] ${this.actual.constructor.name} - ${this.actual}`;
  }
}
class ResourceEditStack {
  constructor(resourceLabel, strResource) {
    this.resourceLabel = resourceLabel;
    this.strResource = strResource;
    this._past = [];
    this._future = [];
    this.locked = false;
    this.versionId = 1;
  }
  dispose() {
    for (const element of this._past) {
      if (element.type === 1) {
        element.removeResource(
          this.resourceLabel,
          this.strResource,
          0
          /* RemovedResourceReason.ExternalRemoval */
        );
      }
    }
    for (const element of this._future) {
      if (element.type === 1) {
        element.removeResource(
          this.resourceLabel,
          this.strResource,
          0
          /* RemovedResourceReason.ExternalRemoval */
        );
      }
    }
    this.versionId++;
  }
  toString() {
    const result2 = [];
    result2.push(`* ${this.strResource}:`);
    for (let i = 0; i < this._past.length; i++) {
      result2.push(`   * [UNDO] ${this._past[i]}`);
    }
    for (let i = this._future.length - 1; i >= 0; i--) {
      result2.push(`   * [REDO] ${this._future[i]}`);
    }
    return result2.join("\n");
  }
  flushAllElements() {
    this._past = [];
    this._future = [];
    this.versionId++;
  }
  _setElementValidFlag(element, isValid2) {
    if (element.type === 1) {
      element.setValid(this.resourceLabel, this.strResource, isValid2);
    } else {
      element.setValid(isValid2);
    }
  }
  setElementsValidFlag(isValid2, filter2) {
    for (const element of this._past) {
      if (filter2(element.actual)) {
        this._setElementValidFlag(element, isValid2);
      }
    }
    for (const element of this._future) {
      if (filter2(element.actual)) {
        this._setElementValidFlag(element, isValid2);
      }
    }
  }
  pushElement(element) {
    for (const futureElement of this._future) {
      if (futureElement.type === 1) {
        futureElement.removeResource(
          this.resourceLabel,
          this.strResource,
          1
          /* RemovedResourceReason.NoParallelUniverses */
        );
      }
    }
    this._future = [];
    this._past.push(element);
    this.versionId++;
  }
  createSnapshot(resource) {
    const elements = [];
    for (let i = 0, len = this._past.length; i < len; i++) {
      elements.push(this._past[i].id);
    }
    for (let i = this._future.length - 1; i >= 0; i--) {
      elements.push(this._future[i].id);
    }
    return new ResourceEditStackSnapshot(resource, elements);
  }
  restoreSnapshot(snapshot) {
    const snapshotLength = snapshot.elements.length;
    let isOK = true;
    let snapshotIndex = 0;
    let removePastAfter = -1;
    for (let i = 0, len = this._past.length; i < len; i++, snapshotIndex++) {
      const element = this._past[i];
      if (isOK && (snapshotIndex >= snapshotLength || element.id !== snapshot.elements[snapshotIndex])) {
        isOK = false;
        removePastAfter = 0;
      }
      if (!isOK && element.type === 1) {
        element.removeResource(
          this.resourceLabel,
          this.strResource,
          0
          /* RemovedResourceReason.ExternalRemoval */
        );
      }
    }
    let removeFutureBefore = -1;
    for (let i = this._future.length - 1; i >= 0; i--, snapshotIndex++) {
      const element = this._future[i];
      if (isOK && (snapshotIndex >= snapshotLength || element.id !== snapshot.elements[snapshotIndex])) {
        isOK = false;
        removeFutureBefore = i;
      }
      if (!isOK && element.type === 1) {
        element.removeResource(
          this.resourceLabel,
          this.strResource,
          0
          /* RemovedResourceReason.ExternalRemoval */
        );
      }
    }
    if (removePastAfter !== -1) {
      this._past = this._past.slice(0, removePastAfter);
    }
    if (removeFutureBefore !== -1) {
      this._future = this._future.slice(removeFutureBefore + 1);
    }
    this.versionId++;
  }
  getElements() {
    const past = [];
    const future = [];
    for (const element of this._past) {
      past.push(element.actual);
    }
    for (const element of this._future) {
      future.push(element.actual);
    }
    return { past, future };
  }
  getClosestPastElement() {
    if (this._past.length === 0) {
      return null;
    }
    return this._past[this._past.length - 1];
  }
  getSecondClosestPastElement() {
    if (this._past.length < 2) {
      return null;
    }
    return this._past[this._past.length - 2];
  }
  getClosestFutureElement() {
    if (this._future.length === 0) {
      return null;
    }
    return this._future[this._future.length - 1];
  }
  hasPastElements() {
    return this._past.length > 0;
  }
  hasFutureElements() {
    return this._future.length > 0;
  }
  splitPastWorkspaceElement(toRemove, individualMap) {
    for (let j = this._past.length - 1; j >= 0; j--) {
      if (this._past[j] === toRemove) {
        if (individualMap.has(this.strResource)) {
          this._past[j] = individualMap.get(this.strResource);
        } else {
          this._past.splice(j, 1);
        }
        break;
      }
    }
    this.versionId++;
  }
  splitFutureWorkspaceElement(toRemove, individualMap) {
    for (let j = this._future.length - 1; j >= 0; j--) {
      if (this._future[j] === toRemove) {
        if (individualMap.has(this.strResource)) {
          this._future[j] = individualMap.get(this.strResource);
        } else {
          this._future.splice(j, 1);
        }
        break;
      }
    }
    this.versionId++;
  }
  moveBackward(element) {
    this._past.pop();
    this._future.push(element);
    this.versionId++;
  }
  moveForward(element) {
    this._future.pop();
    this._past.push(element);
    this.versionId++;
  }
}
class EditStackSnapshot {
  constructor(editStacks) {
    this.editStacks = editStacks;
    this._versionIds = [];
    for (let i = 0, len = this.editStacks.length; i < len; i++) {
      this._versionIds[i] = this.editStacks[i].versionId;
    }
  }
  isValid() {
    for (let i = 0, len = this.editStacks.length; i < len; i++) {
      if (this._versionIds[i] !== this.editStacks[i].versionId) {
        return false;
      }
    }
    return true;
  }
}
const missingEditStack = new ResourceEditStack("", "");
missingEditStack.locked = true;
let UndoRedoService = class UndoRedoService2 {
  constructor(_dialogService, _notificationService) {
    this._dialogService = _dialogService;
    this._notificationService = _notificationService;
    this._editStacks = /* @__PURE__ */ new Map();
    this._uriComparisonKeyComputers = [];
  }
  getUriComparisonKey(resource) {
    for (const uriComparisonKeyComputer of this._uriComparisonKeyComputers) {
      if (uriComparisonKeyComputer[0] === resource.scheme) {
        return uriComparisonKeyComputer[1].getComparisonKey(resource);
      }
    }
    return resource.toString();
  }
  _print(label) {
    console.log(`------------------------------------`);
    console.log(`AFTER ${label}: `);
    const str2 = [];
    for (const element of this._editStacks) {
      str2.push(element[1].toString());
    }
    console.log(str2.join("\n"));
  }
  pushElement(element, group2 = UndoRedoGroup.None, source = UndoRedoSource.None) {
    if (element.type === 0) {
      const resourceLabel = getResourceLabel(element.resource);
      const strResource = this.getUriComparisonKey(element.resource);
      this._pushElement(new ResourceStackElement(element, resourceLabel, strResource, group2.id, group2.nextOrder(), source.id, source.nextOrder()));
    } else {
      const seen2 = /* @__PURE__ */ new Set();
      const resourceLabels = [];
      const strResources = [];
      for (const resource of element.resources) {
        const resourceLabel = getResourceLabel(resource);
        const strResource = this.getUriComparisonKey(resource);
        if (seen2.has(strResource)) {
          continue;
        }
        seen2.add(strResource);
        resourceLabels.push(resourceLabel);
        strResources.push(strResource);
      }
      if (resourceLabels.length === 1) {
        this._pushElement(new ResourceStackElement(element, resourceLabels[0], strResources[0], group2.id, group2.nextOrder(), source.id, source.nextOrder()));
      } else {
        this._pushElement(new WorkspaceStackElement(element, resourceLabels, strResources, group2.id, group2.nextOrder(), source.id, source.nextOrder()));
      }
    }
  }
  _pushElement(element) {
    for (let i = 0, len = element.strResources.length; i < len; i++) {
      const resourceLabel = element.resourceLabels[i];
      const strResource = element.strResources[i];
      let editStack;
      if (this._editStacks.has(strResource)) {
        editStack = this._editStacks.get(strResource);
      } else {
        editStack = new ResourceEditStack(resourceLabel, strResource);
        this._editStacks.set(strResource, editStack);
      }
      editStack.pushElement(element);
    }
  }
  getLastElement(resource) {
    const strResource = this.getUriComparisonKey(resource);
    if (this._editStacks.has(strResource)) {
      const editStack = this._editStacks.get(strResource);
      if (editStack.hasFutureElements()) {
        return null;
      }
      const closestPastElement = editStack.getClosestPastElement();
      return closestPastElement ? closestPastElement.actual : null;
    }
    return null;
  }
  _splitPastWorkspaceElement(toRemove, ignoreResources) {
    const individualArr = toRemove.actual.split();
    const individualMap = /* @__PURE__ */ new Map();
    for (const _element of individualArr) {
      const resourceLabel = getResourceLabel(_element.resource);
      const strResource = this.getUriComparisonKey(_element.resource);
      const element = new ResourceStackElement(_element, resourceLabel, strResource, 0, 0, 0, 0);
      individualMap.set(element.strResource, element);
    }
    for (const strResource of toRemove.strResources) {
      if (ignoreResources && ignoreResources.has(strResource)) {
        continue;
      }
      const editStack = this._editStacks.get(strResource);
      editStack.splitPastWorkspaceElement(toRemove, individualMap);
    }
  }
  _splitFutureWorkspaceElement(toRemove, ignoreResources) {
    const individualArr = toRemove.actual.split();
    const individualMap = /* @__PURE__ */ new Map();
    for (const _element of individualArr) {
      const resourceLabel = getResourceLabel(_element.resource);
      const strResource = this.getUriComparisonKey(_element.resource);
      const element = new ResourceStackElement(_element, resourceLabel, strResource, 0, 0, 0, 0);
      individualMap.set(element.strResource, element);
    }
    for (const strResource of toRemove.strResources) {
      if (ignoreResources && ignoreResources.has(strResource)) {
        continue;
      }
      const editStack = this._editStacks.get(strResource);
      editStack.splitFutureWorkspaceElement(toRemove, individualMap);
    }
  }
  removeElements(resource) {
    const strResource = typeof resource === "string" ? resource : this.getUriComparisonKey(resource);
    if (this._editStacks.has(strResource)) {
      const editStack = this._editStacks.get(strResource);
      editStack.dispose();
      this._editStacks.delete(strResource);
    }
  }
  setElementsValidFlag(resource, isValid2, filter2) {
    const strResource = this.getUriComparisonKey(resource);
    if (this._editStacks.has(strResource)) {
      const editStack = this._editStacks.get(strResource);
      editStack.setElementsValidFlag(isValid2, filter2);
    }
  }
  createSnapshot(resource) {
    const strResource = this.getUriComparisonKey(resource);
    if (this._editStacks.has(strResource)) {
      const editStack = this._editStacks.get(strResource);
      return editStack.createSnapshot(resource);
    }
    return new ResourceEditStackSnapshot(resource, []);
  }
  restoreSnapshot(snapshot) {
    const strResource = this.getUriComparisonKey(snapshot.resource);
    if (this._editStacks.has(strResource)) {
      const editStack = this._editStacks.get(strResource);
      editStack.restoreSnapshot(snapshot);
      if (!editStack.hasPastElements() && !editStack.hasFutureElements()) {
        editStack.dispose();
        this._editStacks.delete(strResource);
      }
    }
  }
  getElements(resource) {
    const strResource = this.getUriComparisonKey(resource);
    if (this._editStacks.has(strResource)) {
      const editStack = this._editStacks.get(strResource);
      return editStack.getElements();
    }
    return { past: [], future: [] };
  }
  _findClosestUndoElementWithSource(sourceId) {
    if (!sourceId) {
      return [null, null];
    }
    let matchedElement = null;
    let matchedStrResource = null;
    for (const [strResource, editStack] of this._editStacks) {
      const candidate = editStack.getClosestPastElement();
      if (!candidate) {
        continue;
      }
      if (candidate.sourceId === sourceId) {
        if (!matchedElement || candidate.sourceOrder > matchedElement.sourceOrder) {
          matchedElement = candidate;
          matchedStrResource = strResource;
        }
      }
    }
    return [matchedElement, matchedStrResource];
  }
  canUndo(resourceOrSource) {
    if (resourceOrSource instanceof UndoRedoSource) {
      const [, matchedStrResource] = this._findClosestUndoElementWithSource(resourceOrSource.id);
      return matchedStrResource ? true : false;
    }
    const strResource = this.getUriComparisonKey(resourceOrSource);
    if (this._editStacks.has(strResource)) {
      const editStack = this._editStacks.get(strResource);
      return editStack.hasPastElements();
    }
    return false;
  }
  _onError(err, element) {
    onUnexpectedError(err);
    for (const strResource of element.strResources) {
      this.removeElements(strResource);
    }
    this._notificationService.error(err);
  }
  _acquireLocks(editStackSnapshot) {
    for (const editStack of editStackSnapshot.editStacks) {
      if (editStack.locked) {
        throw new Error("Cannot acquire edit stack lock");
      }
    }
    for (const editStack of editStackSnapshot.editStacks) {
      editStack.locked = true;
    }
    return () => {
      for (const editStack of editStackSnapshot.editStacks) {
        editStack.locked = false;
      }
    };
  }
  _safeInvokeWithLocks(element, invoke, editStackSnapshot, cleanup, continuation) {
    const releaseLocks = this._acquireLocks(editStackSnapshot);
    let result2;
    try {
      result2 = invoke();
    } catch (err) {
      releaseLocks();
      cleanup.dispose();
      return this._onError(err, element);
    }
    if (result2) {
      return result2.then(() => {
        releaseLocks();
        cleanup.dispose();
        return continuation();
      }, (err) => {
        releaseLocks();
        cleanup.dispose();
        return this._onError(err, element);
      });
    } else {
      releaseLocks();
      cleanup.dispose();
      return continuation();
    }
  }
  _invokeWorkspacePrepare(element) {
    return __awaiter$b(this, void 0, void 0, function* () {
      if (typeof element.actual.prepareUndoRedo === "undefined") {
        return Disposable.None;
      }
      const result2 = element.actual.prepareUndoRedo();
      if (typeof result2 === "undefined") {
        return Disposable.None;
      }
      return result2;
    });
  }
  _invokeResourcePrepare(element, callback) {
    if (element.actual.type !== 1 || typeof element.actual.prepareUndoRedo === "undefined") {
      return callback(Disposable.None);
    }
    const r = element.actual.prepareUndoRedo();
    if (!r) {
      return callback(Disposable.None);
    }
    if (isDisposable(r)) {
      return callback(r);
    }
    return r.then((disposable) => {
      return callback(disposable);
    });
  }
  _getAffectedEditStacks(element) {
    const affectedEditStacks = [];
    for (const strResource of element.strResources) {
      affectedEditStacks.push(this._editStacks.get(strResource) || missingEditStack);
    }
    return new EditStackSnapshot(affectedEditStacks);
  }
  _tryToSplitAndUndo(strResource, element, ignoreResources, message) {
    if (element.canSplit()) {
      this._splitPastWorkspaceElement(element, ignoreResources);
      this._notificationService.warn(message);
      return new WorkspaceVerificationError(this._undo(strResource, 0, true));
    } else {
      for (const strResource2 of element.strResources) {
        this.removeElements(strResource2);
      }
      this._notificationService.warn(message);
      return new WorkspaceVerificationError();
    }
  }
  _checkWorkspaceUndo(strResource, element, editStackSnapshot, checkInvalidatedResources) {
    if (element.removedResources) {
      return this._tryToSplitAndUndo(strResource, element, element.removedResources, localize({ key: "cannotWorkspaceUndo", comment: ["{0} is a label for an operation. {1} is another message."] }, "Could not undo '{0}' across all files. {1}", element.label, element.removedResources.createMessage()));
    }
    if (checkInvalidatedResources && element.invalidatedResources) {
      return this._tryToSplitAndUndo(strResource, element, element.invalidatedResources, localize({ key: "cannotWorkspaceUndo", comment: ["{0} is a label for an operation. {1} is another message."] }, "Could not undo '{0}' across all files. {1}", element.label, element.invalidatedResources.createMessage()));
    }
    const cannotUndoDueToResources = [];
    for (const editStack of editStackSnapshot.editStacks) {
      if (editStack.getClosestPastElement() !== element) {
        cannotUndoDueToResources.push(editStack.resourceLabel);
      }
    }
    if (cannotUndoDueToResources.length > 0) {
      return this._tryToSplitAndUndo(strResource, element, null, localize({ key: "cannotWorkspaceUndoDueToChanges", comment: ["{0} is a label for an operation. {1} is a list of filenames."] }, "Could not undo '{0}' across all files because changes were made to {1}", element.label, cannotUndoDueToResources.join(", ")));
    }
    const cannotLockDueToResources = [];
    for (const editStack of editStackSnapshot.editStacks) {
      if (editStack.locked) {
        cannotLockDueToResources.push(editStack.resourceLabel);
      }
    }
    if (cannotLockDueToResources.length > 0) {
      return this._tryToSplitAndUndo(strResource, element, null, localize({ key: "cannotWorkspaceUndoDueToInProgressUndoRedo", comment: ["{0} is a label for an operation. {1} is a list of filenames."] }, "Could not undo '{0}' across all files because there is already an undo or redo operation running on {1}", element.label, cannotLockDueToResources.join(", ")));
    }
    if (!editStackSnapshot.isValid()) {
      return this._tryToSplitAndUndo(strResource, element, null, localize({ key: "cannotWorkspaceUndoDueToInMeantimeUndoRedo", comment: ["{0} is a label for an operation. {1} is a list of filenames."] }, "Could not undo '{0}' across all files because an undo or redo operation occurred in the meantime", element.label));
    }
    return null;
  }
  _workspaceUndo(strResource, element, undoConfirmed) {
    const affectedEditStacks = this._getAffectedEditStacks(element);
    const verificationError = this._checkWorkspaceUndo(
      strResource,
      element,
      affectedEditStacks,
      /*invalidated resources will be checked after the prepare call*/
      false
    );
    if (verificationError) {
      return verificationError.returnValue;
    }
    return this._confirmAndExecuteWorkspaceUndo(strResource, element, affectedEditStacks, undoConfirmed);
  }
  _isPartOfUndoGroup(element) {
    if (!element.groupId) {
      return false;
    }
    for (const [, editStack] of this._editStacks) {
      const pastElement = editStack.getClosestPastElement();
      if (!pastElement) {
        continue;
      }
      if (pastElement === element) {
        const secondPastElement = editStack.getSecondClosestPastElement();
        if (secondPastElement && secondPastElement.groupId === element.groupId) {
          return true;
        }
      }
      if (pastElement.groupId === element.groupId) {
        return true;
      }
    }
    return false;
  }
  _confirmAndExecuteWorkspaceUndo(strResource, element, editStackSnapshot, undoConfirmed) {
    return __awaiter$b(this, void 0, void 0, function* () {
      if (element.canSplit() && !this._isPartOfUndoGroup(element)) {
        let UndoChoice;
        (function(UndoChoice2) {
          UndoChoice2[UndoChoice2["All"] = 0] = "All";
          UndoChoice2[UndoChoice2["This"] = 1] = "This";
          UndoChoice2[UndoChoice2["Cancel"] = 2] = "Cancel";
        })(UndoChoice || (UndoChoice = {}));
        const { result: result2 } = yield this._dialogService.prompt({
          type: Severity$2.Info,
          message: localize("confirmWorkspace", "Would you like to undo '{0}' across all files?", element.label),
          buttons: [
            {
              label: localize({ key: "ok", comment: ["{0} denotes a number that is > 1, && denotes a mnemonic"] }, "&&Undo in {0} Files", editStackSnapshot.editStacks.length),
              run: () => UndoChoice.All
            },
            {
              label: localize({ key: "nok", comment: ["&& denotes a mnemonic"] }, "Undo this &&File"),
              run: () => UndoChoice.This
            }
          ],
          cancelButton: {
            run: () => UndoChoice.Cancel
          }
        });
        if (result2 === UndoChoice.Cancel) {
          return;
        }
        if (result2 === UndoChoice.This) {
          this._splitPastWorkspaceElement(element, null);
          return this._undo(strResource, 0, true);
        }
        const verificationError1 = this._checkWorkspaceUndo(
          strResource,
          element,
          editStackSnapshot,
          /*invalidated resources will be checked after the prepare call*/
          false
        );
        if (verificationError1) {
          return verificationError1.returnValue;
        }
        undoConfirmed = true;
      }
      let cleanup;
      try {
        cleanup = yield this._invokeWorkspacePrepare(element);
      } catch (err) {
        return this._onError(err, element);
      }
      const verificationError2 = this._checkWorkspaceUndo(
        strResource,
        element,
        editStackSnapshot,
        /*now also check that there are no more invalidated resources*/
        true
      );
      if (verificationError2) {
        cleanup.dispose();
        return verificationError2.returnValue;
      }
      for (const editStack of editStackSnapshot.editStacks) {
        editStack.moveBackward(element);
      }
      return this._safeInvokeWithLocks(element, () => element.actual.undo(), editStackSnapshot, cleanup, () => this._continueUndoInGroup(element.groupId, undoConfirmed));
    });
  }
  _resourceUndo(editStack, element, undoConfirmed) {
    if (!element.isValid) {
      editStack.flushAllElements();
      return;
    }
    if (editStack.locked) {
      const message = localize({ key: "cannotResourceUndoDueToInProgressUndoRedo", comment: ["{0} is a label for an operation."] }, "Could not undo '{0}' because there is already an undo or redo operation running.", element.label);
      this._notificationService.warn(message);
      return;
    }
    return this._invokeResourcePrepare(element, (cleanup) => {
      editStack.moveBackward(element);
      return this._safeInvokeWithLocks(element, () => element.actual.undo(), new EditStackSnapshot([editStack]), cleanup, () => this._continueUndoInGroup(element.groupId, undoConfirmed));
    });
  }
  _findClosestUndoElementInGroup(groupId) {
    if (!groupId) {
      return [null, null];
    }
    let matchedElement = null;
    let matchedStrResource = null;
    for (const [strResource, editStack] of this._editStacks) {
      const candidate = editStack.getClosestPastElement();
      if (!candidate) {
        continue;
      }
      if (candidate.groupId === groupId) {
        if (!matchedElement || candidate.groupOrder > matchedElement.groupOrder) {
          matchedElement = candidate;
          matchedStrResource = strResource;
        }
      }
    }
    return [matchedElement, matchedStrResource];
  }
  _continueUndoInGroup(groupId, undoConfirmed) {
    if (!groupId) {
      return;
    }
    const [, matchedStrResource] = this._findClosestUndoElementInGroup(groupId);
    if (matchedStrResource) {
      return this._undo(matchedStrResource, 0, undoConfirmed);
    }
  }
  undo(resourceOrSource) {
    if (resourceOrSource instanceof UndoRedoSource) {
      const [, matchedStrResource] = this._findClosestUndoElementWithSource(resourceOrSource.id);
      return matchedStrResource ? this._undo(matchedStrResource, resourceOrSource.id, false) : void 0;
    }
    if (typeof resourceOrSource === "string") {
      return this._undo(resourceOrSource, 0, false);
    }
    return this._undo(this.getUriComparisonKey(resourceOrSource), 0, false);
  }
  _undo(strResource, sourceId = 0, undoConfirmed) {
    if (!this._editStacks.has(strResource)) {
      return;
    }
    const editStack = this._editStacks.get(strResource);
    const element = editStack.getClosestPastElement();
    if (!element) {
      return;
    }
    if (element.groupId) {
      const [matchedElement, matchedStrResource] = this._findClosestUndoElementInGroup(element.groupId);
      if (element !== matchedElement && matchedStrResource) {
        return this._undo(matchedStrResource, sourceId, undoConfirmed);
      }
    }
    const shouldPromptForConfirmation = element.sourceId !== sourceId || element.confirmBeforeUndo;
    if (shouldPromptForConfirmation && !undoConfirmed) {
      return this._confirmAndContinueUndo(strResource, sourceId, element);
    }
    try {
      if (element.type === 1) {
        return this._workspaceUndo(strResource, element, undoConfirmed);
      } else {
        return this._resourceUndo(editStack, element, undoConfirmed);
      }
    } finally {
    }
  }
  _confirmAndContinueUndo(strResource, sourceId, element) {
    return __awaiter$b(this, void 0, void 0, function* () {
      const result2 = yield this._dialogService.confirm({
        message: localize("confirmDifferentSource", "Would you like to undo '{0}'?", element.label),
        primaryButton: localize({ key: "confirmDifferentSource.yes", comment: ["&& denotes a mnemonic"] }, "&&Yes"),
        cancelButton: localize("confirmDifferentSource.no", "No")
      });
      if (!result2.confirmed) {
        return;
      }
      return this._undo(strResource, sourceId, true);
    });
  }
  _findClosestRedoElementWithSource(sourceId) {
    if (!sourceId) {
      return [null, null];
    }
    let matchedElement = null;
    let matchedStrResource = null;
    for (const [strResource, editStack] of this._editStacks) {
      const candidate = editStack.getClosestFutureElement();
      if (!candidate) {
        continue;
      }
      if (candidate.sourceId === sourceId) {
        if (!matchedElement || candidate.sourceOrder < matchedElement.sourceOrder) {
          matchedElement = candidate;
          matchedStrResource = strResource;
        }
      }
    }
    return [matchedElement, matchedStrResource];
  }
  canRedo(resourceOrSource) {
    if (resourceOrSource instanceof UndoRedoSource) {
      const [, matchedStrResource] = this._findClosestRedoElementWithSource(resourceOrSource.id);
      return matchedStrResource ? true : false;
    }
    const strResource = this.getUriComparisonKey(resourceOrSource);
    if (this._editStacks.has(strResource)) {
      const editStack = this._editStacks.get(strResource);
      return editStack.hasFutureElements();
    }
    return false;
  }
  _tryToSplitAndRedo(strResource, element, ignoreResources, message) {
    if (element.canSplit()) {
      this._splitFutureWorkspaceElement(element, ignoreResources);
      this._notificationService.warn(message);
      return new WorkspaceVerificationError(this._redo(strResource));
    } else {
      for (const strResource2 of element.strResources) {
        this.removeElements(strResource2);
      }
      this._notificationService.warn(message);
      return new WorkspaceVerificationError();
    }
  }
  _checkWorkspaceRedo(strResource, element, editStackSnapshot, checkInvalidatedResources) {
    if (element.removedResources) {
      return this._tryToSplitAndRedo(strResource, element, element.removedResources, localize({ key: "cannotWorkspaceRedo", comment: ["{0} is a label for an operation. {1} is another message."] }, "Could not redo '{0}' across all files. {1}", element.label, element.removedResources.createMessage()));
    }
    if (checkInvalidatedResources && element.invalidatedResources) {
      return this._tryToSplitAndRedo(strResource, element, element.invalidatedResources, localize({ key: "cannotWorkspaceRedo", comment: ["{0} is a label for an operation. {1} is another message."] }, "Could not redo '{0}' across all files. {1}", element.label, element.invalidatedResources.createMessage()));
    }
    const cannotRedoDueToResources = [];
    for (const editStack of editStackSnapshot.editStacks) {
      if (editStack.getClosestFutureElement() !== element) {
        cannotRedoDueToResources.push(editStack.resourceLabel);
      }
    }
    if (cannotRedoDueToResources.length > 0) {
      return this._tryToSplitAndRedo(strResource, element, null, localize({ key: "cannotWorkspaceRedoDueToChanges", comment: ["{0} is a label for an operation. {1} is a list of filenames."] }, "Could not redo '{0}' across all files because changes were made to {1}", element.label, cannotRedoDueToResources.join(", ")));
    }
    const cannotLockDueToResources = [];
    for (const editStack of editStackSnapshot.editStacks) {
      if (editStack.locked) {
        cannotLockDueToResources.push(editStack.resourceLabel);
      }
    }
    if (cannotLockDueToResources.length > 0) {
      return this._tryToSplitAndRedo(strResource, element, null, localize({ key: "cannotWorkspaceRedoDueToInProgressUndoRedo", comment: ["{0} is a label for an operation. {1} is a list of filenames."] }, "Could not redo '{0}' across all files because there is already an undo or redo operation running on {1}", element.label, cannotLockDueToResources.join(", ")));
    }
    if (!editStackSnapshot.isValid()) {
      return this._tryToSplitAndRedo(strResource, element, null, localize({ key: "cannotWorkspaceRedoDueToInMeantimeUndoRedo", comment: ["{0} is a label for an operation. {1} is a list of filenames."] }, "Could not redo '{0}' across all files because an undo or redo operation occurred in the meantime", element.label));
    }
    return null;
  }
  _workspaceRedo(strResource, element) {
    const affectedEditStacks = this._getAffectedEditStacks(element);
    const verificationError = this._checkWorkspaceRedo(
      strResource,
      element,
      affectedEditStacks,
      /*invalidated resources will be checked after the prepare call*/
      false
    );
    if (verificationError) {
      return verificationError.returnValue;
    }
    return this._executeWorkspaceRedo(strResource, element, affectedEditStacks);
  }
  _executeWorkspaceRedo(strResource, element, editStackSnapshot) {
    return __awaiter$b(this, void 0, void 0, function* () {
      let cleanup;
      try {
        cleanup = yield this._invokeWorkspacePrepare(element);
      } catch (err) {
        return this._onError(err, element);
      }
      const verificationError = this._checkWorkspaceRedo(
        strResource,
        element,
        editStackSnapshot,
        /*now also check that there are no more invalidated resources*/
        true
      );
      if (verificationError) {
        cleanup.dispose();
        return verificationError.returnValue;
      }
      for (const editStack of editStackSnapshot.editStacks) {
        editStack.moveForward(element);
      }
      return this._safeInvokeWithLocks(element, () => element.actual.redo(), editStackSnapshot, cleanup, () => this._continueRedoInGroup(element.groupId));
    });
  }
  _resourceRedo(editStack, element) {
    if (!element.isValid) {
      editStack.flushAllElements();
      return;
    }
    if (editStack.locked) {
      const message = localize({ key: "cannotResourceRedoDueToInProgressUndoRedo", comment: ["{0} is a label for an operation."] }, "Could not redo '{0}' because there is already an undo or redo operation running.", element.label);
      this._notificationService.warn(message);
      return;
    }
    return this._invokeResourcePrepare(element, (cleanup) => {
      editStack.moveForward(element);
      return this._safeInvokeWithLocks(element, () => element.actual.redo(), new EditStackSnapshot([editStack]), cleanup, () => this._continueRedoInGroup(element.groupId));
    });
  }
  _findClosestRedoElementInGroup(groupId) {
    if (!groupId) {
      return [null, null];
    }
    let matchedElement = null;
    let matchedStrResource = null;
    for (const [strResource, editStack] of this._editStacks) {
      const candidate = editStack.getClosestFutureElement();
      if (!candidate) {
        continue;
      }
      if (candidate.groupId === groupId) {
        if (!matchedElement || candidate.groupOrder < matchedElement.groupOrder) {
          matchedElement = candidate;
          matchedStrResource = strResource;
        }
      }
    }
    return [matchedElement, matchedStrResource];
  }
  _continueRedoInGroup(groupId) {
    if (!groupId) {
      return;
    }
    const [, matchedStrResource] = this._findClosestRedoElementInGroup(groupId);
    if (matchedStrResource) {
      return this._redo(matchedStrResource);
    }
  }
  redo(resourceOrSource) {
    if (resourceOrSource instanceof UndoRedoSource) {
      const [, matchedStrResource] = this._findClosestRedoElementWithSource(resourceOrSource.id);
      return matchedStrResource ? this._redo(matchedStrResource) : void 0;
    }
    if (typeof resourceOrSource === "string") {
      return this._redo(resourceOrSource);
    }
    return this._redo(this.getUriComparisonKey(resourceOrSource));
  }
  _redo(strResource) {
    if (!this._editStacks.has(strResource)) {
      return;
    }
    const editStack = this._editStacks.get(strResource);
    const element = editStack.getClosestFutureElement();
    if (!element) {
      return;
    }
    if (element.groupId) {
      const [matchedElement, matchedStrResource] = this._findClosestRedoElementInGroup(element.groupId);
      if (element !== matchedElement && matchedStrResource) {
        return this._redo(matchedStrResource);
      }
    }
    try {
      if (element.type === 1) {
        return this._workspaceRedo(strResource, element);
      } else {
        return this._resourceRedo(editStack, element);
      }
    } finally {
    }
  }
};
UndoRedoService = __decorate$m([
  __param$k(0, IDialogService),
  __param$k(1, INotificationService)
], UndoRedoService);
class WorkspaceVerificationError {
  constructor(returnValue) {
    this.returnValue = returnValue;
  }
}
registerSingleton(
  IUndoRedoService,
  UndoRedoService,
  1
  /* InstantiationType.Delayed */
);
var __decorate$l = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$j = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let SemanticTokensStylingService = class SemanticTokensStylingService2 extends Disposable {
  constructor(_themeService, _logService, _languageService) {
    super();
    this._themeService = _themeService;
    this._logService = _logService;
    this._languageService = _languageService;
    this._caches = /* @__PURE__ */ new WeakMap();
    this._register(this._themeService.onDidColorThemeChange(() => {
      this._caches = /* @__PURE__ */ new WeakMap();
    }));
  }
  getStyling(provider) {
    if (!this._caches.has(provider)) {
      this._caches.set(provider, new SemanticTokensProviderStyling(provider.getLegend(), this._themeService, this._languageService, this._logService));
    }
    return this._caches.get(provider);
  }
};
SemanticTokensStylingService = __decorate$l([
  __param$j(0, IThemeService),
  __param$j(1, ILogService),
  __param$j(2, ILanguageService)
], SemanticTokensStylingService);
registerSingleton(
  ISemanticTokensStylingService,
  SemanticTokensStylingService,
  1
  /* InstantiationType.Delayed */
);
var __awaiter$a = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
const GLOBSTAR = "**";
const GLOB_SPLIT = "/";
const PATH_REGEX = "[/\\\\]";
const NO_PATH_REGEX = "[^/\\\\]";
const ALL_FORWARD_SLASHES = /\//g;
function starsToRegExp(starCount, isLastPattern) {
  switch (starCount) {
    case 0:
      return "";
    case 1:
      return `${NO_PATH_REGEX}*?`;
    default:
      return `(?:${PATH_REGEX}|${NO_PATH_REGEX}+${PATH_REGEX}${isLastPattern ? `|${PATH_REGEX}${NO_PATH_REGEX}+` : ""})*?`;
  }
}
function splitGlobAware(pattern, splitChar) {
  if (!pattern) {
    return [];
  }
  const segments = [];
  let inBraces = false;
  let inBrackets = false;
  let curVal = "";
  for (const char of pattern) {
    switch (char) {
      case splitChar:
        if (!inBraces && !inBrackets) {
          segments.push(curVal);
          curVal = "";
          continue;
        }
        break;
      case "{":
        inBraces = true;
        break;
      case "}":
        inBraces = false;
        break;
      case "[":
        inBrackets = true;
        break;
      case "]":
        inBrackets = false;
        break;
    }
    curVal += char;
  }
  if (curVal) {
    segments.push(curVal);
  }
  return segments;
}
function parseRegExp(pattern) {
  if (!pattern) {
    return "";
  }
  let regEx = "";
  const segments = splitGlobAware(pattern, GLOB_SPLIT);
  if (segments.every((segment) => segment === GLOBSTAR)) {
    regEx = ".*";
  } else {
    let previousSegmentWasGlobStar = false;
    segments.forEach((segment, index) => {
      if (segment === GLOBSTAR) {
        if (previousSegmentWasGlobStar) {
          return;
        }
        regEx += starsToRegExp(2, index === segments.length - 1);
      } else {
        let inBraces = false;
        let braceVal = "";
        let inBrackets = false;
        let bracketVal = "";
        for (const char of segment) {
          if (char !== "}" && inBraces) {
            braceVal += char;
            continue;
          }
          if (inBrackets && (char !== "]" || !bracketVal)) {
            let res;
            if (char === "-") {
              res = char;
            } else if ((char === "^" || char === "!") && !bracketVal) {
              res = "^";
            } else if (char === GLOB_SPLIT) {
              res = "";
            } else {
              res = escapeRegExpCharacters(char);
            }
            bracketVal += res;
            continue;
          }
          switch (char) {
            case "{":
              inBraces = true;
              continue;
            case "[":
              inBrackets = true;
              continue;
            case "}": {
              const choices = splitGlobAware(braceVal, ",");
              const braceRegExp = `(?:${choices.map((choice) => parseRegExp(choice)).join("|")})`;
              regEx += braceRegExp;
              inBraces = false;
              braceVal = "";
              break;
            }
            case "]": {
              regEx += "[" + bracketVal + "]";
              inBrackets = false;
              bracketVal = "";
              break;
            }
            case "?":
              regEx += NO_PATH_REGEX;
              continue;
            case "*":
              regEx += starsToRegExp(1);
              continue;
            default:
              regEx += escapeRegExpCharacters(char);
          }
        }
        if (index < segments.length - 1 && // more segments to come after this
        (segments[index + 1] !== GLOBSTAR || // next segment is not **, or...
        index + 2 < segments.length)) {
          regEx += PATH_REGEX;
        }
      }
      previousSegmentWasGlobStar = segment === GLOBSTAR;
    });
  }
  return regEx;
}
const T1 = /^\*\*\/\*\.[\w\.-]+$/;
const T2 = /^\*\*\/([\w\.-]+)\/?$/;
const T3 = /^{\*\*\/\*?[\w\.-]+\/?(,\*\*\/\*?[\w\.-]+\/?)*}$/;
const T3_2 = /^{\*\*\/\*?[\w\.-]+(\/(\*\*)?)?(,\*\*\/\*?[\w\.-]+(\/(\*\*)?)?)*}$/;
const T4 = /^\*\*((\/[\w\.-]+)+)\/?$/;
const T5 = /^([\w\.-]+(\/[\w\.-]+)*)\/?$/;
const CACHE$1 = new LRUCache$2(1e4);
const FALSE = function() {
  return false;
};
const NULL = function() {
  return null;
};
function parsePattern(arg1, options) {
  if (!arg1) {
    return NULL;
  }
  let pattern;
  if (typeof arg1 !== "string") {
    pattern = arg1.pattern;
  } else {
    pattern = arg1;
  }
  pattern = pattern.trim();
  const patternKey = `${pattern}_${!!options.trimForExclusions}`;
  let parsedPattern = CACHE$1.get(patternKey);
  if (parsedPattern) {
    return wrapRelativePattern(parsedPattern, arg1);
  }
  let match2;
  if (T1.test(pattern)) {
    parsedPattern = trivia1(pattern.substr(4), pattern);
  } else if (match2 = T2.exec(trimForExclusions(pattern, options))) {
    parsedPattern = trivia2(match2[1], pattern);
  } else if ((options.trimForExclusions ? T3_2 : T3).test(pattern)) {
    parsedPattern = trivia3(pattern, options);
  } else if (match2 = T4.exec(trimForExclusions(pattern, options))) {
    parsedPattern = trivia4and5(match2[1].substr(1), pattern, true);
  } else if (match2 = T5.exec(trimForExclusions(pattern, options))) {
    parsedPattern = trivia4and5(match2[1], pattern, false);
  } else {
    parsedPattern = toRegExp(pattern);
  }
  CACHE$1.set(patternKey, parsedPattern);
  return wrapRelativePattern(parsedPattern, arg1);
}
function wrapRelativePattern(parsedPattern, arg2) {
  if (typeof arg2 === "string") {
    return parsedPattern;
  }
  const wrappedPattern = function(path2, basename2) {
    if (!isEqualOrParent(path2, arg2.base, !isLinux)) {
      return null;
    }
    return parsedPattern(ltrim(path2.substr(arg2.base.length), sep$2), basename2);
  };
  wrappedPattern.allBasenames = parsedPattern.allBasenames;
  wrappedPattern.allPaths = parsedPattern.allPaths;
  wrappedPattern.basenames = parsedPattern.basenames;
  wrappedPattern.patterns = parsedPattern.patterns;
  return wrappedPattern;
}
function trimForExclusions(pattern, options) {
  return options.trimForExclusions && pattern.endsWith("/**") ? pattern.substr(0, pattern.length - 2) : pattern;
}
function trivia1(base2, pattern) {
  return function(path2, basename2) {
    return typeof path2 === "string" && path2.endsWith(base2) ? pattern : null;
  };
}
function trivia2(base2, pattern) {
  const slashBase = `/${base2}`;
  const backslashBase = `\\${base2}`;
  const parsedPattern = function(path2, basename2) {
    if (typeof path2 !== "string") {
      return null;
    }
    if (basename2) {
      return basename2 === base2 ? pattern : null;
    }
    return path2 === base2 || path2.endsWith(slashBase) || path2.endsWith(backslashBase) ? pattern : null;
  };
  const basenames = [base2];
  parsedPattern.basenames = basenames;
  parsedPattern.patterns = [pattern];
  parsedPattern.allBasenames = basenames;
  return parsedPattern;
}
function trivia3(pattern, options) {
  const parsedPatterns = aggregateBasenameMatches(pattern.slice(1, -1).split(",").map((pattern2) => parsePattern(pattern2, options)).filter((pattern2) => pattern2 !== NULL), pattern);
  const patternsLength = parsedPatterns.length;
  if (!patternsLength) {
    return NULL;
  }
  if (patternsLength === 1) {
    return parsedPatterns[0];
  }
  const parsedPattern = function(path2, basename2) {
    for (let i = 0, n2 = parsedPatterns.length; i < n2; i++) {
      if (parsedPatterns[i](path2, basename2)) {
        return pattern;
      }
    }
    return null;
  };
  const withBasenames = parsedPatterns.find((pattern2) => !!pattern2.allBasenames);
  if (withBasenames) {
    parsedPattern.allBasenames = withBasenames.allBasenames;
  }
  const allPaths = parsedPatterns.reduce((all, current) => current.allPaths ? all.concat(current.allPaths) : all, []);
  if (allPaths.length) {
    parsedPattern.allPaths = allPaths;
  }
  return parsedPattern;
}
function trivia4and5(targetPath, pattern, matchPathEnds) {
  const usingPosixSep = sep$2 === posix.sep;
  const nativePath = usingPosixSep ? targetPath : targetPath.replace(ALL_FORWARD_SLASHES, sep$2);
  const nativePathEnd = sep$2 + nativePath;
  const targetPathEnd = posix.sep + targetPath;
  let parsedPattern;
  if (matchPathEnds) {
    parsedPattern = function(path2, basename2) {
      return typeof path2 === "string" && (path2 === nativePath || path2.endsWith(nativePathEnd) || !usingPosixSep && (path2 === targetPath || path2.endsWith(targetPathEnd))) ? pattern : null;
    };
  } else {
    parsedPattern = function(path2, basename2) {
      return typeof path2 === "string" && (path2 === nativePath || !usingPosixSep && path2 === targetPath) ? pattern : null;
    };
  }
  parsedPattern.allPaths = [(matchPathEnds ? "*/" : "./") + targetPath];
  return parsedPattern;
}
function toRegExp(pattern) {
  try {
    const regExp = new RegExp(`^${parseRegExp(pattern)}$`);
    return function(path2) {
      regExp.lastIndex = 0;
      return typeof path2 === "string" && regExp.test(path2) ? pattern : null;
    };
  } catch (error2) {
    return NULL;
  }
}
function match(arg1, path2, hasSibling) {
  if (!arg1 || typeof path2 !== "string") {
    return false;
  }
  return parse$a(arg1)(path2, void 0, hasSibling);
}
function parse$a(arg1, options = {}) {
  if (!arg1) {
    return FALSE;
  }
  if (typeof arg1 === "string" || isRelativePattern(arg1)) {
    const parsedPattern = parsePattern(arg1, options);
    if (parsedPattern === NULL) {
      return FALSE;
    }
    const resultPattern = function(path2, basename2) {
      return !!parsedPattern(path2, basename2);
    };
    if (parsedPattern.allBasenames) {
      resultPattern.allBasenames = parsedPattern.allBasenames;
    }
    if (parsedPattern.allPaths) {
      resultPattern.allPaths = parsedPattern.allPaths;
    }
    return resultPattern;
  }
  return parsedExpression(arg1, options);
}
function isRelativePattern(obj) {
  const rp = obj;
  if (!rp) {
    return false;
  }
  return typeof rp.base === "string" && typeof rp.pattern === "string";
}
function parsedExpression(expression, options) {
  const parsedPatterns = aggregateBasenameMatches(Object.getOwnPropertyNames(expression).map((pattern) => parseExpressionPattern(pattern, expression[pattern], options)).filter((pattern) => pattern !== NULL));
  const patternsLength = parsedPatterns.length;
  if (!patternsLength) {
    return NULL;
  }
  if (!parsedPatterns.some((parsedPattern) => !!parsedPattern.requiresSiblings)) {
    if (patternsLength === 1) {
      return parsedPatterns[0];
    }
    const resultExpression2 = function(path2, basename2) {
      let resultPromises = void 0;
      for (let i = 0, n2 = parsedPatterns.length; i < n2; i++) {
        const result2 = parsedPatterns[i](path2, basename2);
        if (typeof result2 === "string") {
          return result2;
        }
        if (isThenable$1(result2)) {
          if (!resultPromises) {
            resultPromises = [];
          }
          resultPromises.push(result2);
        }
      }
      if (resultPromises) {
        return (() => __awaiter$a(this, void 0, void 0, function* () {
          for (const resultPromise of resultPromises) {
            const result2 = yield resultPromise;
            if (typeof result2 === "string") {
              return result2;
            }
          }
          return null;
        }))();
      }
      return null;
    };
    const withBasenames2 = parsedPatterns.find((pattern) => !!pattern.allBasenames);
    if (withBasenames2) {
      resultExpression2.allBasenames = withBasenames2.allBasenames;
    }
    const allPaths2 = parsedPatterns.reduce((all, current) => current.allPaths ? all.concat(current.allPaths) : all, []);
    if (allPaths2.length) {
      resultExpression2.allPaths = allPaths2;
    }
    return resultExpression2;
  }
  const resultExpression = function(path2, base2, hasSibling) {
    let name = void 0;
    let resultPromises = void 0;
    for (let i = 0, n2 = parsedPatterns.length; i < n2; i++) {
      const parsedPattern = parsedPatterns[i];
      if (parsedPattern.requiresSiblings && hasSibling) {
        if (!base2) {
          base2 = basename$2(path2);
        }
        if (!name) {
          name = base2.substr(0, base2.length - extname$2(path2).length);
        }
      }
      const result2 = parsedPattern(path2, base2, name, hasSibling);
      if (typeof result2 === "string") {
        return result2;
      }
      if (isThenable$1(result2)) {
        if (!resultPromises) {
          resultPromises = [];
        }
        resultPromises.push(result2);
      }
    }
    if (resultPromises) {
      return (() => __awaiter$a(this, void 0, void 0, function* () {
        for (const resultPromise of resultPromises) {
          const result2 = yield resultPromise;
          if (typeof result2 === "string") {
            return result2;
          }
        }
        return null;
      }))();
    }
    return null;
  };
  const withBasenames = parsedPatterns.find((pattern) => !!pattern.allBasenames);
  if (withBasenames) {
    resultExpression.allBasenames = withBasenames.allBasenames;
  }
  const allPaths = parsedPatterns.reduce((all, current) => current.allPaths ? all.concat(current.allPaths) : all, []);
  if (allPaths.length) {
    resultExpression.allPaths = allPaths;
  }
  return resultExpression;
}
function parseExpressionPattern(pattern, value, options) {
  if (value === false) {
    return NULL;
  }
  const parsedPattern = parsePattern(pattern, options);
  if (parsedPattern === NULL) {
    return NULL;
  }
  if (typeof value === "boolean") {
    return parsedPattern;
  }
  if (value) {
    const when = value.when;
    if (typeof when === "string") {
      const result2 = (path2, basename2, name, hasSibling) => {
        if (!hasSibling || !parsedPattern(path2, basename2)) {
          return null;
        }
        const clausePattern = when.replace("$(basename)", () => name);
        const matched = hasSibling(clausePattern);
        return isThenable$1(matched) ? matched.then((match2) => match2 ? pattern : null) : matched ? pattern : null;
      };
      result2.requiresSiblings = true;
      return result2;
    }
  }
  return parsedPattern;
}
function aggregateBasenameMatches(parsedPatterns, result2) {
  const basenamePatterns = parsedPatterns.filter((parsedPattern) => !!parsedPattern.basenames);
  if (basenamePatterns.length < 2) {
    return parsedPatterns;
  }
  const basenames = basenamePatterns.reduce((all, current) => {
    const basenames2 = current.basenames;
    return basenames2 ? all.concat(basenames2) : all;
  }, []);
  let patterns;
  if (result2) {
    patterns = [];
    for (let i = 0, n2 = basenames.length; i < n2; i++) {
      patterns.push(result2);
    }
  } else {
    patterns = basenamePatterns.reduce((all, current) => {
      const patterns2 = current.patterns;
      return patterns2 ? all.concat(patterns2) : all;
    }, []);
  }
  const aggregate = function(path2, basename2) {
    if (typeof path2 !== "string") {
      return null;
    }
    if (!basename2) {
      let i;
      for (i = path2.length; i > 0; i--) {
        const ch = path2.charCodeAt(i - 1);
        if (ch === 47 || ch === 92) {
          break;
        }
      }
      basename2 = path2.substr(i);
    }
    const index = basenames.indexOf(basename2);
    return index !== -1 ? patterns[index] : null;
  };
  aggregate.basenames = basenames;
  aggregate.patterns = patterns;
  aggregate.allBasenames = basenames;
  const aggregatedPatterns = parsedPatterns.filter((parsedPattern) => !parsedPattern.basenames);
  aggregatedPatterns.push(aggregate);
  return aggregatedPatterns;
}
function score(selector3, candidateUri, candidateLanguage, candidateIsSynchronized, candidateNotebookUri, candidateNotebookType) {
  if (Array.isArray(selector3)) {
    let ret = 0;
    for (const filter2 of selector3) {
      const value = score(filter2, candidateUri, candidateLanguage, candidateIsSynchronized, candidateNotebookUri, candidateNotebookType);
      if (value === 10) {
        return value;
      }
      if (value > ret) {
        ret = value;
      }
    }
    return ret;
  } else if (typeof selector3 === "string") {
    if (!candidateIsSynchronized) {
      return 0;
    }
    if (selector3 === "*") {
      return 5;
    } else if (selector3 === candidateLanguage) {
      return 10;
    } else {
      return 0;
    }
  } else if (selector3) {
    const { language: language2, pattern, scheme, hasAccessToAllModels, notebookType } = selector3;
    if (!candidateIsSynchronized && !hasAccessToAllModels) {
      return 0;
    }
    if (notebookType && candidateNotebookUri) {
      candidateUri = candidateNotebookUri;
    }
    let ret = 0;
    if (scheme) {
      if (scheme === candidateUri.scheme) {
        ret = 10;
      } else if (scheme === "*") {
        ret = 5;
      } else {
        return 0;
      }
    }
    if (language2) {
      if (language2 === candidateLanguage) {
        ret = 10;
      } else if (language2 === "*") {
        ret = Math.max(ret, 5);
      } else {
        return 0;
      }
    }
    if (notebookType) {
      if (notebookType === candidateNotebookType) {
        ret = 10;
      } else if (notebookType === "*" && candidateNotebookType !== void 0) {
        ret = Math.max(ret, 5);
      } else {
        return 0;
      }
    }
    if (pattern) {
      let normalizedPattern;
      if (typeof pattern === "string") {
        normalizedPattern = pattern;
      } else {
        normalizedPattern = Object.assign(Object.assign({}, pattern), { base: normalize(pattern.base) });
      }
      if (normalizedPattern === candidateUri.fsPath || match(normalizedPattern, candidateUri.fsPath)) {
        ret = 10;
      } else {
        return 0;
      }
    }
    return ret;
  } else {
    return 0;
  }
}
function isExclusive(selector3) {
  if (typeof selector3 === "string") {
    return false;
  } else if (Array.isArray(selector3)) {
    return selector3.every(isExclusive);
  } else {
    return !!selector3.exclusive;
  }
}
class MatchCandidate {
  constructor(uri, languageId, notebookUri, notebookType) {
    this.uri = uri;
    this.languageId = languageId;
    this.notebookUri = notebookUri;
    this.notebookType = notebookType;
  }
  equals(other) {
    var _a2, _b2;
    return this.notebookType === other.notebookType && this.languageId === other.languageId && this.uri.toString() === other.uri.toString() && ((_a2 = this.notebookUri) === null || _a2 === void 0 ? void 0 : _a2.toString()) === ((_b2 = other.notebookUri) === null || _b2 === void 0 ? void 0 : _b2.toString());
  }
}
class LanguageFeatureRegistry {
  constructor(_notebookInfoResolver) {
    this._notebookInfoResolver = _notebookInfoResolver;
    this._clock = 0;
    this._entries = [];
    this._onDidChange = new Emitter$1();
    this.onDidChange = this._onDidChange.event;
  }
  register(selector3, provider) {
    let entry = {
      selector: selector3,
      provider,
      _score: -1,
      _time: this._clock++
    };
    this._entries.push(entry);
    this._lastCandidate = void 0;
    this._onDidChange.fire(this._entries.length);
    return toDisposable(() => {
      if (entry) {
        const idx = this._entries.indexOf(entry);
        if (idx >= 0) {
          this._entries.splice(idx, 1);
          this._lastCandidate = void 0;
          this._onDidChange.fire(this._entries.length);
          entry = void 0;
        }
      }
    });
  }
  has(model) {
    return this.all(model).length > 0;
  }
  all(model) {
    if (!model) {
      return [];
    }
    this._updateScores(model);
    const result2 = [];
    for (const entry of this._entries) {
      if (entry._score > 0) {
        result2.push(entry.provider);
      }
    }
    return result2;
  }
  ordered(model) {
    const result2 = [];
    this._orderedForEach(model, (entry) => result2.push(entry.provider));
    return result2;
  }
  orderedGroups(model) {
    const result2 = [];
    let lastBucket;
    let lastBucketScore;
    this._orderedForEach(model, (entry) => {
      if (lastBucket && lastBucketScore === entry._score) {
        lastBucket.push(entry.provider);
      } else {
        lastBucketScore = entry._score;
        lastBucket = [entry.provider];
        result2.push(lastBucket);
      }
    });
    return result2;
  }
  _orderedForEach(model, callback) {
    this._updateScores(model);
    for (const entry of this._entries) {
      if (entry._score > 0) {
        callback(entry);
      }
    }
  }
  _updateScores(model) {
    var _a2, _b2;
    const notebookInfo = (_a2 = this._notebookInfoResolver) === null || _a2 === void 0 ? void 0 : _a2.call(this, model.uri);
    const candidate = notebookInfo ? new MatchCandidate(model.uri, model.getLanguageId(), notebookInfo.uri, notebookInfo.type) : new MatchCandidate(model.uri, model.getLanguageId(), void 0, void 0);
    if ((_b2 = this._lastCandidate) === null || _b2 === void 0 ? void 0 : _b2.equals(candidate)) {
      return;
    }
    this._lastCandidate = candidate;
    for (const entry of this._entries) {
      entry._score = score(entry.selector, candidate.uri, candidate.languageId, shouldSynchronizeModel(model), candidate.notebookUri, candidate.notebookType);
      if (isExclusive(entry.selector) && entry._score > 0) {
        for (const entry2 of this._entries) {
          entry2._score = 0;
        }
        entry._score = 1e3;
        break;
      }
    }
    this._entries.sort(LanguageFeatureRegistry._compareByScoreAndTime);
  }
  static _compareByScoreAndTime(a, b) {
    if (a._score < b._score) {
      return 1;
    } else if (a._score > b._score) {
      return -1;
    }
    if (isBuiltinSelector(a.selector) && !isBuiltinSelector(b.selector)) {
      return 1;
    } else if (!isBuiltinSelector(a.selector) && isBuiltinSelector(b.selector)) {
      return -1;
    }
    if (a._time < b._time) {
      return 1;
    } else if (a._time > b._time) {
      return -1;
    } else {
      return 0;
    }
  }
}
function isBuiltinSelector(selector3) {
  if (typeof selector3 === "string") {
    return false;
  }
  if (Array.isArray(selector3)) {
    return selector3.some(isBuiltinSelector);
  }
  return Boolean(selector3.isBuiltin);
}
class LanguageFeaturesService {
  constructor() {
    this.referenceProvider = new LanguageFeatureRegistry(this._score.bind(this));
    this.renameProvider = new LanguageFeatureRegistry(this._score.bind(this));
    this.codeActionProvider = new LanguageFeatureRegistry(this._score.bind(this));
    this.definitionProvider = new LanguageFeatureRegistry(this._score.bind(this));
    this.typeDefinitionProvider = new LanguageFeatureRegistry(this._score.bind(this));
    this.declarationProvider = new LanguageFeatureRegistry(this._score.bind(this));
    this.implementationProvider = new LanguageFeatureRegistry(this._score.bind(this));
    this.documentSymbolProvider = new LanguageFeatureRegistry(this._score.bind(this));
    this.inlayHintsProvider = new LanguageFeatureRegistry(this._score.bind(this));
    this.colorProvider = new LanguageFeatureRegistry(this._score.bind(this));
    this.codeLensProvider = new LanguageFeatureRegistry(this._score.bind(this));
    this.documentFormattingEditProvider = new LanguageFeatureRegistry(this._score.bind(this));
    this.documentRangeFormattingEditProvider = new LanguageFeatureRegistry(this._score.bind(this));
    this.onTypeFormattingEditProvider = new LanguageFeatureRegistry(this._score.bind(this));
    this.signatureHelpProvider = new LanguageFeatureRegistry(this._score.bind(this));
    this.hoverProvider = new LanguageFeatureRegistry(this._score.bind(this));
    this.documentHighlightProvider = new LanguageFeatureRegistry(this._score.bind(this));
    this.selectionRangeProvider = new LanguageFeatureRegistry(this._score.bind(this));
    this.foldingRangeProvider = new LanguageFeatureRegistry(this._score.bind(this));
    this.linkProvider = new LanguageFeatureRegistry(this._score.bind(this));
    this.inlineCompletionsProvider = new LanguageFeatureRegistry(this._score.bind(this));
    this.completionProvider = new LanguageFeatureRegistry(this._score.bind(this));
    this.linkedEditingRangeProvider = new LanguageFeatureRegistry(this._score.bind(this));
    this.documentRangeSemanticTokensProvider = new LanguageFeatureRegistry(this._score.bind(this));
    this.documentSemanticTokensProvider = new LanguageFeatureRegistry(this._score.bind(this));
    this.documentOnDropEditProvider = new LanguageFeatureRegistry(this._score.bind(this));
    this.documentPasteEditProvider = new LanguageFeatureRegistry(this._score.bind(this));
  }
  _score(uri) {
    var _a2;
    return (_a2 = this._notebookTypeResolver) === null || _a2 === void 0 ? void 0 : _a2.call(this, uri);
  }
}
registerSingleton(
  ILanguageFeaturesService,
  LanguageFeaturesService,
  1
  /* InstantiationType.Delayed */
);
function freeze(data) {
  return Object.isFrozen(data) ? data : deepFreeze(data);
}
class ConfigurationModel {
  constructor(_contents = {}, _keys = [], _overrides = [], raw) {
    this._contents = _contents;
    this._keys = _keys;
    this._overrides = _overrides;
    this.raw = raw;
    this.overrideConfigurations = /* @__PURE__ */ new Map();
  }
  get rawConfiguration() {
    var _a2;
    if (!this._rawConfiguration) {
      if ((_a2 = this.raw) === null || _a2 === void 0 ? void 0 : _a2.length) {
        const rawConfigurationModels = this.raw.map((raw) => {
          if (raw instanceof ConfigurationModel) {
            return raw;
          }
          const parser2 = new ConfigurationModelParser("");
          parser2.parseRaw(raw);
          return parser2.configurationModel;
        });
        this._rawConfiguration = rawConfigurationModels.reduce((previous, current) => current === previous ? current : previous.merge(current), rawConfigurationModels[0]);
      } else {
        this._rawConfiguration = this;
      }
    }
    return this._rawConfiguration;
  }
  get contents() {
    return this._contents;
  }
  get overrides() {
    return this._overrides;
  }
  get keys() {
    return this._keys;
  }
  isEmpty() {
    return this._keys.length === 0 && Object.keys(this._contents).length === 0 && this._overrides.length === 0;
  }
  getValue(section) {
    return section ? getConfigurationValue(this.contents, section) : this.contents;
  }
  inspect(section, overrideIdentifier) {
    const value = this.rawConfiguration.getValue(section);
    const override = overrideIdentifier ? this.rawConfiguration.getOverrideValue(section, overrideIdentifier) : void 0;
    const merged = overrideIdentifier ? this.rawConfiguration.override(overrideIdentifier).getValue(section) : value;
    return { value, override, merged };
  }
  getOverrideValue(section, overrideIdentifier) {
    const overrideContents = this.getContentsForOverrideIdentifer(overrideIdentifier);
    return overrideContents ? section ? getConfigurationValue(overrideContents, section) : overrideContents : void 0;
  }
  override(identifier) {
    let overrideConfigurationModel = this.overrideConfigurations.get(identifier);
    if (!overrideConfigurationModel) {
      overrideConfigurationModel = this.createOverrideConfigurationModel(identifier);
      this.overrideConfigurations.set(identifier, overrideConfigurationModel);
    }
    return overrideConfigurationModel;
  }
  merge(...others) {
    var _a2, _b2;
    const contents = deepClone(this.contents);
    const overrides = deepClone(this.overrides);
    const keys = [...this.keys];
    const raws = ((_a2 = this.raw) === null || _a2 === void 0 ? void 0 : _a2.length) ? [...this.raw] : [this];
    for (const other of others) {
      raws.push(...((_b2 = other.raw) === null || _b2 === void 0 ? void 0 : _b2.length) ? other.raw : [other]);
      if (other.isEmpty()) {
        continue;
      }
      this.mergeContents(contents, other.contents);
      for (const otherOverride of other.overrides) {
        const [override] = overrides.filter((o) => equals$3(o.identifiers, otherOverride.identifiers));
        if (override) {
          this.mergeContents(override.contents, otherOverride.contents);
          override.keys.push(...otherOverride.keys);
          override.keys = distinct(override.keys);
        } else {
          overrides.push(deepClone(otherOverride));
        }
      }
      for (const key of other.keys) {
        if (keys.indexOf(key) === -1) {
          keys.push(key);
        }
      }
    }
    return new ConfigurationModel(contents, keys, overrides, raws.every((raw) => raw instanceof ConfigurationModel) ? void 0 : raws);
  }
  createOverrideConfigurationModel(identifier) {
    const overrideContents = this.getContentsForOverrideIdentifer(identifier);
    if (!overrideContents || typeof overrideContents !== "object" || !Object.keys(overrideContents).length) {
      return this;
    }
    const contents = {};
    for (const key of distinct([...Object.keys(this.contents), ...Object.keys(overrideContents)])) {
      let contentsForKey = this.contents[key];
      const overrideContentsForKey = overrideContents[key];
      if (overrideContentsForKey) {
        if (typeof contentsForKey === "object" && typeof overrideContentsForKey === "object") {
          contentsForKey = deepClone(contentsForKey);
          this.mergeContents(contentsForKey, overrideContentsForKey);
        } else {
          contentsForKey = overrideContentsForKey;
        }
      }
      contents[key] = contentsForKey;
    }
    return new ConfigurationModel(contents, this.keys, this.overrides);
  }
  mergeContents(source, target) {
    for (const key of Object.keys(target)) {
      if (key in source) {
        if (isObject$4(source[key]) && isObject$4(target[key])) {
          this.mergeContents(source[key], target[key]);
          continue;
        }
      }
      source[key] = deepClone(target[key]);
    }
  }
  getContentsForOverrideIdentifer(identifier) {
    let contentsForIdentifierOnly = null;
    let contents = null;
    const mergeContents = (contentsToMerge) => {
      if (contentsToMerge) {
        if (contents) {
          this.mergeContents(contents, contentsToMerge);
        } else {
          contents = deepClone(contentsToMerge);
        }
      }
    };
    for (const override of this.overrides) {
      if (override.identifiers.length === 1 && override.identifiers[0] === identifier) {
        contentsForIdentifierOnly = override.contents;
      } else if (override.identifiers.includes(identifier)) {
        mergeContents(override.contents);
      }
    }
    mergeContents(contentsForIdentifierOnly);
    return contents;
  }
  toJSON() {
    return {
      contents: this.contents,
      overrides: this.overrides,
      keys: this.keys
    };
  }
  // Update methods
  addValue(key, value) {
    this.updateValue(key, value, true);
  }
  setValue(key, value) {
    this.updateValue(key, value, false);
  }
  removeValue(key) {
    const index = this.keys.indexOf(key);
    if (index === -1) {
      return;
    }
    this.keys.splice(index, 1);
    removeFromValueTree(this.contents, key);
    if (OVERRIDE_PROPERTY_REGEX.test(key)) {
      this.overrides.splice(this.overrides.findIndex((o) => equals$3(o.identifiers, overrideIdentifiersFromKey(key))), 1);
    }
  }
  updateValue(key, value, add2) {
    addToValueTree(this.contents, key, value, (e) => console.error(e));
    add2 = add2 || this.keys.indexOf(key) === -1;
    if (add2) {
      this.keys.push(key);
    }
    if (OVERRIDE_PROPERTY_REGEX.test(key)) {
      this.overrides.push({
        identifiers: overrideIdentifiersFromKey(key),
        keys: Object.keys(this.contents[key]),
        contents: toValuesTree(this.contents[key], (message) => console.error(message))
      });
    }
  }
}
class ConfigurationModelParser {
  constructor(_name) {
    this._name = _name;
    this._raw = null;
    this._configurationModel = null;
    this._restrictedConfigurations = [];
  }
  get configurationModel() {
    return this._configurationModel || new ConfigurationModel();
  }
  parseRaw(raw, options) {
    this._raw = raw;
    const { contents, keys, overrides, restricted, hasExcludedProperties } = this.doParseRaw(raw, options);
    this._configurationModel = new ConfigurationModel(
      contents,
      keys,
      overrides,
      hasExcludedProperties ? [raw] : void 0
      /* raw has not changed */
    );
    this._restrictedConfigurations = restricted || [];
  }
  doParseRaw(raw, options) {
    const configurationProperties = Registry.as(Extensions$6.Configuration).getConfigurationProperties();
    const filtered = this.filter(raw, configurationProperties, true, options);
    raw = filtered.raw;
    const contents = toValuesTree(raw, (message) => console.error(`Conflict in settings file ${this._name}: ${message}`));
    const keys = Object.keys(raw);
    const overrides = this.toOverrides(raw, (message) => console.error(`Conflict in settings file ${this._name}: ${message}`));
    return { contents, keys, overrides, restricted: filtered.restricted, hasExcludedProperties: filtered.hasExcludedProperties };
  }
  filter(properties, configurationProperties, filterOverriddenProperties, options) {
    var _a2, _b2, _c2;
    let hasExcludedProperties = false;
    if (!(options === null || options === void 0 ? void 0 : options.scopes) && !(options === null || options === void 0 ? void 0 : options.skipRestricted) && !((_a2 = options === null || options === void 0 ? void 0 : options.exclude) === null || _a2 === void 0 ? void 0 : _a2.length)) {
      return { raw: properties, restricted: [], hasExcludedProperties };
    }
    const raw = {};
    const restricted = [];
    for (const key in properties) {
      if (OVERRIDE_PROPERTY_REGEX.test(key) && filterOverriddenProperties) {
        const result2 = this.filter(properties[key], configurationProperties, false, options);
        raw[key] = result2.raw;
        hasExcludedProperties = hasExcludedProperties || result2.hasExcludedProperties;
        restricted.push(...result2.restricted);
      } else {
        const propertySchema = configurationProperties[key];
        const scope = propertySchema ? typeof propertySchema.scope !== "undefined" ? propertySchema.scope : 3 : void 0;
        if (propertySchema === null || propertySchema === void 0 ? void 0 : propertySchema.restricted) {
          restricted.push(key);
        }
        if (!((_b2 = options.exclude) === null || _b2 === void 0 ? void 0 : _b2.includes(key)) && (((_c2 = options.include) === null || _c2 === void 0 ? void 0 : _c2.includes(key)) || (scope === void 0 || options.scopes === void 0 || options.scopes.includes(scope)) && !(options.skipRestricted && (propertySchema === null || propertySchema === void 0 ? void 0 : propertySchema.restricted)))) {
          raw[key] = properties[key];
        } else {
          hasExcludedProperties = true;
        }
      }
    }
    return { raw, restricted, hasExcludedProperties };
  }
  toOverrides(raw, conflictReporter) {
    const overrides = [];
    for (const key of Object.keys(raw)) {
      if (OVERRIDE_PROPERTY_REGEX.test(key)) {
        const overrideRaw = {};
        for (const keyInOverrideRaw in raw[key]) {
          overrideRaw[keyInOverrideRaw] = raw[key][keyInOverrideRaw];
        }
        overrides.push({
          identifiers: overrideIdentifiersFromKey(key),
          keys: Object.keys(overrideRaw),
          contents: toValuesTree(overrideRaw, conflictReporter)
        });
      }
    }
    return overrides;
  }
}
class ConfigurationInspectValue {
  constructor(key, overrides, _value, overrideIdentifiers, defaultConfiguration, policyConfiguration, applicationConfiguration, userConfiguration, localUserConfiguration, remoteUserConfiguration, workspaceConfiguration, folderConfigurationModel, memoryConfigurationModel) {
    this.key = key;
    this.overrides = overrides;
    this._value = _value;
    this.overrideIdentifiers = overrideIdentifiers;
    this.defaultConfiguration = defaultConfiguration;
    this.policyConfiguration = policyConfiguration;
    this.applicationConfiguration = applicationConfiguration;
    this.userConfiguration = userConfiguration;
    this.localUserConfiguration = localUserConfiguration;
    this.remoteUserConfiguration = remoteUserConfiguration;
    this.workspaceConfiguration = workspaceConfiguration;
    this.folderConfigurationModel = folderConfigurationModel;
    this.memoryConfigurationModel = memoryConfigurationModel;
  }
  inspect(model, section, overrideIdentifier) {
    const inspectValue = model.inspect(section, overrideIdentifier);
    return {
      get value() {
        return freeze(inspectValue.value);
      },
      get override() {
        return freeze(inspectValue.override);
      },
      get merged() {
        return freeze(inspectValue.merged);
      }
    };
  }
  get userInspectValue() {
    if (!this._userInspectValue) {
      this._userInspectValue = this.inspect(this.userConfiguration, this.key, this.overrides.overrideIdentifier);
    }
    return this._userInspectValue;
  }
  get user() {
    return this.userInspectValue.value !== void 0 || this.userInspectValue.override !== void 0 ? { value: this.userInspectValue.value, override: this.userInspectValue.override } : void 0;
  }
}
class Configuration {
  constructor(_defaultConfiguration, _policyConfiguration, _applicationConfiguration, _localUserConfiguration, _remoteUserConfiguration = new ConfigurationModel(), _workspaceConfiguration = new ConfigurationModel(), _folderConfigurations = new ResourceMap(), _memoryConfiguration = new ConfigurationModel(), _memoryConfigurationByResource = new ResourceMap()) {
    this._defaultConfiguration = _defaultConfiguration;
    this._policyConfiguration = _policyConfiguration;
    this._applicationConfiguration = _applicationConfiguration;
    this._localUserConfiguration = _localUserConfiguration;
    this._remoteUserConfiguration = _remoteUserConfiguration;
    this._workspaceConfiguration = _workspaceConfiguration;
    this._folderConfigurations = _folderConfigurations;
    this._memoryConfiguration = _memoryConfiguration;
    this._memoryConfigurationByResource = _memoryConfigurationByResource;
    this._workspaceConsolidatedConfiguration = null;
    this._foldersConsolidatedConfigurations = new ResourceMap();
    this._userConfiguration = null;
  }
  getValue(section, overrides, workspace) {
    const consolidateConfigurationModel = this.getConsolidatedConfigurationModel(section, overrides, workspace);
    return consolidateConfigurationModel.getValue(section);
  }
  updateValue(key, value, overrides = {}) {
    let memoryConfiguration;
    if (overrides.resource) {
      memoryConfiguration = this._memoryConfigurationByResource.get(overrides.resource);
      if (!memoryConfiguration) {
        memoryConfiguration = new ConfigurationModel();
        this._memoryConfigurationByResource.set(overrides.resource, memoryConfiguration);
      }
    } else {
      memoryConfiguration = this._memoryConfiguration;
    }
    if (value === void 0) {
      memoryConfiguration.removeValue(key);
    } else {
      memoryConfiguration.setValue(key, value);
    }
    if (!overrides.resource) {
      this._workspaceConsolidatedConfiguration = null;
    }
  }
  inspect(key, overrides, workspace) {
    const consolidateConfigurationModel = this.getConsolidatedConfigurationModel(key, overrides, workspace);
    const folderConfigurationModel = this.getFolderConfigurationModelForResource(overrides.resource, workspace);
    const memoryConfigurationModel = overrides.resource ? this._memoryConfigurationByResource.get(overrides.resource) || this._memoryConfiguration : this._memoryConfiguration;
    const overrideIdentifiers = /* @__PURE__ */ new Set();
    for (const override of consolidateConfigurationModel.overrides) {
      for (const overrideIdentifier of override.identifiers) {
        if (consolidateConfigurationModel.getOverrideValue(key, overrideIdentifier) !== void 0) {
          overrideIdentifiers.add(overrideIdentifier);
        }
      }
    }
    return new ConfigurationInspectValue(key, overrides, consolidateConfigurationModel.getValue(key), overrideIdentifiers.size ? [...overrideIdentifiers] : void 0, this._defaultConfiguration, this._policyConfiguration.isEmpty() ? void 0 : this._policyConfiguration, this.applicationConfiguration.isEmpty() ? void 0 : this.applicationConfiguration, this.userConfiguration, this.localUserConfiguration, this.remoteUserConfiguration, workspace ? this._workspaceConfiguration : void 0, folderConfigurationModel ? folderConfigurationModel : void 0, memoryConfigurationModel);
  }
  get applicationConfiguration() {
    return this._applicationConfiguration;
  }
  get userConfiguration() {
    if (!this._userConfiguration) {
      this._userConfiguration = this._remoteUserConfiguration.isEmpty() ? this._localUserConfiguration : this._localUserConfiguration.merge(this._remoteUserConfiguration);
    }
    return this._userConfiguration;
  }
  get localUserConfiguration() {
    return this._localUserConfiguration;
  }
  get remoteUserConfiguration() {
    return this._remoteUserConfiguration;
  }
  getConsolidatedConfigurationModel(section, overrides, workspace) {
    let configurationModel = this.getConsolidatedConfigurationModelForResource(overrides, workspace);
    if (overrides.overrideIdentifier) {
      configurationModel = configurationModel.override(overrides.overrideIdentifier);
    }
    if (!this._policyConfiguration.isEmpty() && this._policyConfiguration.getValue(section) !== void 0) {
      configurationModel = configurationModel.merge(this._policyConfiguration);
    }
    return configurationModel;
  }
  getConsolidatedConfigurationModelForResource({ resource }, workspace) {
    let consolidateConfiguration = this.getWorkspaceConsolidatedConfiguration();
    if (workspace && resource) {
      const root3 = workspace.getFolder(resource);
      if (root3) {
        consolidateConfiguration = this.getFolderConsolidatedConfiguration(root3.uri) || consolidateConfiguration;
      }
      const memoryConfigurationForResource = this._memoryConfigurationByResource.get(resource);
      if (memoryConfigurationForResource) {
        consolidateConfiguration = consolidateConfiguration.merge(memoryConfigurationForResource);
      }
    }
    return consolidateConfiguration;
  }
  getWorkspaceConsolidatedConfiguration() {
    if (!this._workspaceConsolidatedConfiguration) {
      this._workspaceConsolidatedConfiguration = this._defaultConfiguration.merge(this.applicationConfiguration, this.userConfiguration, this._workspaceConfiguration, this._memoryConfiguration);
    }
    return this._workspaceConsolidatedConfiguration;
  }
  getFolderConsolidatedConfiguration(folder) {
    let folderConsolidatedConfiguration = this._foldersConsolidatedConfigurations.get(folder);
    if (!folderConsolidatedConfiguration) {
      const workspaceConsolidateConfiguration = this.getWorkspaceConsolidatedConfiguration();
      const folderConfiguration = this._folderConfigurations.get(folder);
      if (folderConfiguration) {
        folderConsolidatedConfiguration = workspaceConsolidateConfiguration.merge(folderConfiguration);
        this._foldersConsolidatedConfigurations.set(folder, folderConsolidatedConfiguration);
      } else {
        folderConsolidatedConfiguration = workspaceConsolidateConfiguration;
      }
    }
    return folderConsolidatedConfiguration;
  }
  getFolderConfigurationModelForResource(resource, workspace) {
    if (workspace && resource) {
      const root3 = workspace.getFolder(resource);
      if (root3) {
        return this._folderConfigurations.get(root3.uri);
      }
    }
    return void 0;
  }
  toData() {
    return {
      defaults: {
        contents: this._defaultConfiguration.contents,
        overrides: this._defaultConfiguration.overrides,
        keys: this._defaultConfiguration.keys
      },
      policy: {
        contents: this._policyConfiguration.contents,
        overrides: this._policyConfiguration.overrides,
        keys: this._policyConfiguration.keys
      },
      application: {
        contents: this.applicationConfiguration.contents,
        overrides: this.applicationConfiguration.overrides,
        keys: this.applicationConfiguration.keys
      },
      user: {
        contents: this.userConfiguration.contents,
        overrides: this.userConfiguration.overrides,
        keys: this.userConfiguration.keys
      },
      workspace: {
        contents: this._workspaceConfiguration.contents,
        overrides: this._workspaceConfiguration.overrides,
        keys: this._workspaceConfiguration.keys
      },
      folders: [...this._folderConfigurations.keys()].reduce((result2, folder) => {
        const { contents, overrides, keys } = this._folderConfigurations.get(folder);
        result2.push([folder, { contents, overrides, keys }]);
        return result2;
      }, [])
    };
  }
  static parse(data) {
    const defaultConfiguration = this.parseConfigurationModel(data.defaults);
    const policyConfiguration = this.parseConfigurationModel(data.policy);
    const applicationConfiguration = this.parseConfigurationModel(data.application);
    const userConfiguration = this.parseConfigurationModel(data.user);
    const workspaceConfiguration = this.parseConfigurationModel(data.workspace);
    const folders = data.folders.reduce((result2, value) => {
      result2.set(URI.revive(value[0]), this.parseConfigurationModel(value[1]));
      return result2;
    }, new ResourceMap());
    return new Configuration(defaultConfiguration, policyConfiguration, applicationConfiguration, userConfiguration, new ConfigurationModel(), workspaceConfiguration, folders, new ConfigurationModel(), new ResourceMap());
  }
  static parseConfigurationModel(model) {
    return new ConfigurationModel(model.contents, model.keys, model.overrides);
  }
}
class ConfigurationChangeEvent {
  constructor(change, previous, currentConfiguraiton, currentWorkspace) {
    this.change = change;
    this.previous = previous;
    this.currentConfiguraiton = currentConfiguraiton;
    this.currentWorkspace = currentWorkspace;
    this._marker = "\n";
    this._markerCode1 = this._marker.charCodeAt(0);
    this._markerCode2 = ".".charCodeAt(0);
    this.affectedKeys = /* @__PURE__ */ new Set();
    this._previousConfiguration = void 0;
    for (const key of change.keys) {
      this.affectedKeys.add(key);
    }
    for (const [, keys] of change.overrides) {
      for (const key of keys) {
        this.affectedKeys.add(key);
      }
    }
    this._affectsConfigStr = this._marker;
    for (const key of this.affectedKeys) {
      this._affectsConfigStr += key + this._marker;
    }
  }
  get previousConfiguration() {
    if (!this._previousConfiguration && this.previous) {
      this._previousConfiguration = Configuration.parse(this.previous.data);
    }
    return this._previousConfiguration;
  }
  affectsConfiguration(section, overrides) {
    var _a2;
    const needle = this._marker + section;
    const idx = this._affectsConfigStr.indexOf(needle);
    if (idx < 0) {
      return false;
    }
    const pos = idx + needle.length;
    if (pos >= this._affectsConfigStr.length) {
      return false;
    }
    const code = this._affectsConfigStr.charCodeAt(pos);
    if (code !== this._markerCode1 && code !== this._markerCode2) {
      return false;
    }
    if (overrides) {
      const value1 = this.previousConfiguration ? this.previousConfiguration.getValue(section, overrides, (_a2 = this.previous) === null || _a2 === void 0 ? void 0 : _a2.workspace) : void 0;
      const value2 = this.currentConfiguraiton.getValue(section, overrides, this.currentWorkspace);
      return !equals$2(value1, value2);
    }
    return true;
  }
}
const NoMatchingKb = {
  kind: 0
  /* ResultKind.NoMatchingKb */
};
const MoreChordsNeeded = {
  kind: 1
  /* ResultKind.MoreChordsNeeded */
};
function KbFound(commandId, commandArgs, isBubble) {
  return { kind: 2, commandId, commandArgs, isBubble };
}
class KeybindingResolver {
  constructor(defaultKeybindings, overrides, log2) {
    var _a2;
    this._log = log2;
    this._defaultKeybindings = defaultKeybindings;
    this._defaultBoundCommands = /* @__PURE__ */ new Map();
    for (const defaultKeybinding of defaultKeybindings) {
      const command = defaultKeybinding.command;
      if (command && command.charAt(0) !== "-") {
        this._defaultBoundCommands.set(command, true);
      }
    }
    this._map = /* @__PURE__ */ new Map();
    this._lookupMap = /* @__PURE__ */ new Map();
    this._keybindings = KeybindingResolver.handleRemovals([].concat(defaultKeybindings).concat(overrides));
    for (let i = 0, len = this._keybindings.length; i < len; i++) {
      const k = this._keybindings[i];
      if (k.chords.length === 0) {
        continue;
      }
      const when = (_a2 = k.when) === null || _a2 === void 0 ? void 0 : _a2.substituteConstants();
      if (when && when.type === 0) {
        continue;
      }
      this._addKeyPress(k.chords[0], k);
    }
  }
  static _isTargetedForRemoval(defaultKb, keypress, when) {
    if (keypress) {
      for (let i = 0; i < keypress.length; i++) {
        if (keypress[i] !== defaultKb.chords[i]) {
          return false;
        }
      }
    }
    if (when && when.type !== 1) {
      if (!defaultKb.when) {
        return false;
      }
      if (!expressionsAreEqualWithConstantSubstitution(when, defaultKb.when)) {
        return false;
      }
    }
    return true;
  }
  /**
   * Looks for rules containing "-commandId" and removes them.
   */
  static handleRemovals(rules) {
    const removals = /* @__PURE__ */ new Map();
    for (let i = 0, len = rules.length; i < len; i++) {
      const rule2 = rules[i];
      if (rule2.command && rule2.command.charAt(0) === "-") {
        const command = rule2.command.substring(1);
        if (!removals.has(command)) {
          removals.set(command, [rule2]);
        } else {
          removals.get(command).push(rule2);
        }
      }
    }
    if (removals.size === 0) {
      return rules;
    }
    const result2 = [];
    for (let i = 0, len = rules.length; i < len; i++) {
      const rule2 = rules[i];
      if (!rule2.command || rule2.command.length === 0) {
        result2.push(rule2);
        continue;
      }
      if (rule2.command.charAt(0) === "-") {
        continue;
      }
      const commandRemovals = removals.get(rule2.command);
      if (!commandRemovals || !rule2.isDefault) {
        result2.push(rule2);
        continue;
      }
      let isRemoved = false;
      for (const commandRemoval of commandRemovals) {
        const when = commandRemoval.when;
        if (this._isTargetedForRemoval(rule2, commandRemoval.chords, when)) {
          isRemoved = true;
          break;
        }
      }
      if (!isRemoved) {
        result2.push(rule2);
        continue;
      }
    }
    return result2;
  }
  _addKeyPress(keypress, item) {
    const conflicts = this._map.get(keypress);
    if (typeof conflicts === "undefined") {
      this._map.set(keypress, [item]);
      this._addToLookupMap(item);
      return;
    }
    for (let i = conflicts.length - 1; i >= 0; i--) {
      const conflict = conflicts[i];
      if (conflict.command === item.command) {
        continue;
      }
      let isShorterKbPrefix = true;
      for (let i2 = 1; i2 < conflict.chords.length && i2 < item.chords.length; i2++) {
        if (conflict.chords[i2] !== item.chords[i2]) {
          isShorterKbPrefix = false;
          break;
        }
      }
      if (!isShorterKbPrefix) {
        continue;
      }
      if (KeybindingResolver.whenIsEntirelyIncluded(conflict.when, item.when)) {
        this._removeFromLookupMap(conflict);
      }
    }
    conflicts.push(item);
    this._addToLookupMap(item);
  }
  _addToLookupMap(item) {
    if (!item.command) {
      return;
    }
    let arr = this._lookupMap.get(item.command);
    if (typeof arr === "undefined") {
      arr = [item];
      this._lookupMap.set(item.command, arr);
    } else {
      arr.push(item);
    }
  }
  _removeFromLookupMap(item) {
    if (!item.command) {
      return;
    }
    const arr = this._lookupMap.get(item.command);
    if (typeof arr === "undefined") {
      return;
    }
    for (let i = 0, len = arr.length; i < len; i++) {
      if (arr[i] === item) {
        arr.splice(i, 1);
        return;
      }
    }
  }
  /**
   * Returns true if it is provable `a` implies `b`.
   */
  static whenIsEntirelyIncluded(a, b) {
    if (!b || b.type === 1) {
      return true;
    }
    if (!a || a.type === 1) {
      return false;
    }
    return implies(a, b);
  }
  getKeybindings() {
    return this._keybindings;
  }
  lookupPrimaryKeybinding(commandId, context) {
    const items = this._lookupMap.get(commandId);
    if (typeof items === "undefined" || items.length === 0) {
      return null;
    }
    if (items.length === 1) {
      return items[0];
    }
    for (let i = items.length - 1; i >= 0; i--) {
      const item = items[i];
      if (context.contextMatchesRules(item.when)) {
        return item;
      }
    }
    return items[items.length - 1];
  }
  /**
   * Looks up a keybinding trigged as a result of pressing a sequence of chords - `[...currentChords, keypress]`
   *
   * Example: resolving 3 chords pressed sequentially - `cmd+k cmd+p cmd+i`:
   * 	`currentChords = [ 'cmd+k' , 'cmd+p' ]` and `keypress = `cmd+i` - last pressed chord
   */
  resolve(context, currentChords, keypress) {
    const pressedChords = [...currentChords, keypress];
    this._log(`| Resolving ${pressedChords}`);
    const kbCandidates = this._map.get(pressedChords[0]);
    if (kbCandidates === void 0) {
      this._log(`\\ No keybinding entries.`);
      return NoMatchingKb;
    }
    let lookupMap = null;
    if (pressedChords.length < 2) {
      lookupMap = kbCandidates;
    } else {
      lookupMap = [];
      for (let i = 0, len = kbCandidates.length; i < len; i++) {
        const candidate = kbCandidates[i];
        if (pressedChords.length > candidate.chords.length) {
          continue;
        }
        let prefixMatches = true;
        for (let i2 = 1; i2 < pressedChords.length; i2++) {
          if (candidate.chords[i2] !== pressedChords[i2]) {
            prefixMatches = false;
            break;
          }
        }
        if (prefixMatches) {
          lookupMap.push(candidate);
        }
      }
    }
    const result2 = this._findCommand(context, lookupMap);
    if (!result2) {
      this._log(`\\ From ${lookupMap.length} keybinding entries, no when clauses matched the context.`);
      return NoMatchingKb;
    }
    if (pressedChords.length < result2.chords.length) {
      this._log(`\\ From ${lookupMap.length} keybinding entries, awaiting ${result2.chords.length - pressedChords.length} more chord(s), when: ${printWhenExplanation(result2.when)}, source: ${printSourceExplanation(result2)}.`);
      return MoreChordsNeeded;
    }
    this._log(`\\ From ${lookupMap.length} keybinding entries, matched ${result2.command}, when: ${printWhenExplanation(result2.when)}, source: ${printSourceExplanation(result2)}.`);
    return KbFound(result2.command, result2.commandArgs, result2.bubble);
  }
  _findCommand(context, matches) {
    for (let i = matches.length - 1; i >= 0; i--) {
      const k = matches[i];
      if (!KeybindingResolver._contextMatchesRules(context, k.when)) {
        continue;
      }
      return k;
    }
    return null;
  }
  static _contextMatchesRules(context, rules) {
    if (!rules) {
      return true;
    }
    return rules.evaluate(context);
  }
}
function printWhenExplanation(when) {
  if (!when) {
    return `no when condition`;
  }
  return `${when.serialize()}`;
}
function printSourceExplanation(kb) {
  return kb.extensionId ? kb.isBuiltinExtension ? `built-in extension ${kb.extensionId}` : `user extension ${kb.extensionId}` : kb.isDefault ? `built-in` : `user`;
}
const HIGH_FREQ_COMMANDS = /^(cursor|delete|undo|redo|tab|editor\.action\.clipboard)/;
class AbstractKeybindingService extends Disposable {
  get onDidUpdateKeybindings() {
    return this._onDidUpdateKeybindings ? this._onDidUpdateKeybindings.event : Event$1.None;
  }
  get inChordMode() {
    return this._currentChords.length > 0;
  }
  constructor(_contextKeyService, _commandService, _telemetryService, _notificationService, _logService) {
    super();
    this._contextKeyService = _contextKeyService;
    this._commandService = _commandService;
    this._telemetryService = _telemetryService;
    this._notificationService = _notificationService;
    this._logService = _logService;
    this._onDidUpdateKeybindings = this._register(new Emitter$1());
    this._currentChords = [];
    this._currentChordChecker = new IntervalTimer();
    this._currentChordStatusMessage = null;
    this._ignoreSingleModifiers = KeybindingModifierSet.EMPTY;
    this._currentSingleModifier = null;
    this._currentSingleModifierClearTimeout = new TimeoutTimer();
    this._logging = false;
  }
  dispose() {
    super.dispose();
  }
  _log(str2) {
    if (this._logging) {
      this._logService.info(`[KeybindingService]: ${str2}`);
    }
  }
  getKeybindings() {
    return this._getResolver().getKeybindings();
  }
  lookupKeybinding(commandId, context) {
    const result2 = this._getResolver().lookupPrimaryKeybinding(commandId, context || this._contextKeyService);
    if (!result2) {
      return void 0;
    }
    return result2.resolvedKeybinding;
  }
  dispatchEvent(e, target) {
    return this._dispatch(e, target);
  }
  // TODO@ulugbekna: update namings to align with `_doDispatch`
  // TODO@ulugbekna: this fn doesn't seem to take into account single-modifier keybindings, eg `shift shift`
  softDispatch(e, target) {
    this._log(`/ Soft dispatching keyboard event`);
    const keybinding = this.resolveKeyboardEvent(e);
    if (keybinding.hasMultipleChords()) {
      console.warn("keyboard event should not be mapped to multiple chords");
      return NoMatchingKb;
    }
    const [firstChord] = keybinding.getDispatchChords();
    if (firstChord === null) {
      this._log(`\\ Keyboard event cannot be dispatched`);
      return NoMatchingKb;
    }
    const contextValue = this._contextKeyService.getContext(target);
    const currentChords = this._currentChords.map(({ keypress }) => keypress);
    return this._getResolver().resolve(contextValue, currentChords, firstChord);
  }
  _scheduleLeaveChordMode() {
    const chordLastInteractedTime = Date.now();
    this._currentChordChecker.cancelAndSet(() => {
      if (!this._documentHasFocus()) {
        this._leaveChordMode();
        return;
      }
      if (Date.now() - chordLastInteractedTime > 5e3) {
        this._leaveChordMode();
      }
    }, 500);
  }
  _expectAnotherChord(firstChord, keypressLabel) {
    this._currentChords.push({ keypress: firstChord, label: keypressLabel });
    switch (this._currentChords.length) {
      case 0:
        throw illegalState("impossible");
      case 1:
        this._currentChordStatusMessage = this._notificationService.status(localize("first.chord", "({0}) was pressed. Waiting for second key of chord...", keypressLabel));
        break;
      default: {
        const fullKeypressLabel = this._currentChords.map(({ label }) => label).join(", ");
        this._currentChordStatusMessage = this._notificationService.status(localize("next.chord", "({0}) was pressed. Waiting for next key of chord...", fullKeypressLabel));
      }
    }
    this._scheduleLeaveChordMode();
    if (IME.enabled) {
      IME.disable();
    }
  }
  _leaveChordMode() {
    if (this._currentChordStatusMessage) {
      this._currentChordStatusMessage.dispose();
      this._currentChordStatusMessage = null;
    }
    this._currentChordChecker.cancel();
    this._currentChords = [];
    IME.enable();
  }
  _dispatch(e, target) {
    return this._doDispatch(
      this.resolveKeyboardEvent(e),
      target,
      /*isSingleModiferChord*/
      false
    );
  }
  _singleModifierDispatch(e, target) {
    const keybinding = this.resolveKeyboardEvent(e);
    const [singleModifier] = keybinding.getSingleModifierDispatchChords();
    if (singleModifier) {
      if (this._ignoreSingleModifiers.has(singleModifier)) {
        this._log(`+ Ignoring single modifier ${singleModifier} due to it being pressed together with other keys.`);
        this._ignoreSingleModifiers = KeybindingModifierSet.EMPTY;
        this._currentSingleModifierClearTimeout.cancel();
        this._currentSingleModifier = null;
        return false;
      }
      this._ignoreSingleModifiers = KeybindingModifierSet.EMPTY;
      if (this._currentSingleModifier === null) {
        this._log(`+ Storing single modifier for possible chord ${singleModifier}.`);
        this._currentSingleModifier = singleModifier;
        this._currentSingleModifierClearTimeout.cancelAndSet(() => {
          this._log(`+ Clearing single modifier due to 300ms elapsed.`);
          this._currentSingleModifier = null;
        }, 300);
        return false;
      }
      if (singleModifier === this._currentSingleModifier) {
        this._log(`/ Dispatching single modifier chord ${singleModifier} ${singleModifier}`);
        this._currentSingleModifierClearTimeout.cancel();
        this._currentSingleModifier = null;
        return this._doDispatch(
          keybinding,
          target,
          /*isSingleModiferChord*/
          true
        );
      }
      this._log(`+ Clearing single modifier due to modifier mismatch: ${this._currentSingleModifier} ${singleModifier}`);
      this._currentSingleModifierClearTimeout.cancel();
      this._currentSingleModifier = null;
      return false;
    }
    const [firstChord] = keybinding.getChords();
    this._ignoreSingleModifiers = new KeybindingModifierSet(firstChord);
    if (this._currentSingleModifier !== null) {
      this._log(`+ Clearing single modifier due to other key up.`);
    }
    this._currentSingleModifierClearTimeout.cancel();
    this._currentSingleModifier = null;
    return false;
  }
  _doDispatch(userKeypress, target, isSingleModiferChord = false) {
    var _a2;
    let shouldPreventDefault = false;
    if (userKeypress.hasMultipleChords()) {
      console.warn("Unexpected keyboard event mapped to multiple chords");
      return false;
    }
    let userPressedChord = null;
    let currentChords = null;
    if (isSingleModiferChord) {
      const [dispatchKeyname] = userKeypress.getSingleModifierDispatchChords();
      userPressedChord = dispatchKeyname;
      currentChords = dispatchKeyname ? [dispatchKeyname] : [];
    } else {
      [userPressedChord] = userKeypress.getDispatchChords();
      currentChords = this._currentChords.map(({ keypress }) => keypress);
    }
    if (userPressedChord === null) {
      this._log(`\\ Keyboard event cannot be dispatched in keydown phase.`);
      return shouldPreventDefault;
    }
    const contextValue = this._contextKeyService.getContext(target);
    const keypressLabel = userKeypress.getLabel();
    const resolveResult = this._getResolver().resolve(contextValue, currentChords, userPressedChord);
    switch (resolveResult.kind) {
      case 0: {
        this._logService.trace("KeybindingService#dispatch", keypressLabel, `[ No matching keybinding ]`);
        if (this.inChordMode) {
          const currentChordsLabel = this._currentChords.map(({ label }) => label).join(", ");
          this._log(`+ Leaving multi-chord mode: Nothing bound to "${currentChordsLabel}, ${keypressLabel}".`);
          this._notificationService.status(localize("missing.chord", "The key combination ({0}, {1}) is not a command.", currentChordsLabel, keypressLabel), {
            hideAfter: 10 * 1e3
            /* 10s */
          });
          this._leaveChordMode();
          shouldPreventDefault = true;
        }
        return shouldPreventDefault;
      }
      case 1: {
        this._logService.trace("KeybindingService#dispatch", keypressLabel, `[ Several keybindings match - more chords needed ]`);
        shouldPreventDefault = true;
        this._expectAnotherChord(userPressedChord, keypressLabel);
        this._log(this._currentChords.length === 1 ? `+ Entering multi-chord mode...` : `+ Continuing multi-chord mode...`);
        return shouldPreventDefault;
      }
      case 2: {
        this._logService.trace("KeybindingService#dispatch", keypressLabel, `[ Will dispatch command ${resolveResult.commandId} ]`);
        if (resolveResult.commandId === null || resolveResult.commandId === "") {
          if (this.inChordMode) {
            const currentChordsLabel = this._currentChords.map(({ label }) => label).join(", ");
            this._log(`+ Leaving chord mode: Nothing bound to "${currentChordsLabel}, ${keypressLabel}".`);
            this._notificationService.status(localize("missing.chord", "The key combination ({0}, {1}) is not a command.", currentChordsLabel, keypressLabel), {
              hideAfter: 10 * 1e3
              /* 10s */
            });
            this._leaveChordMode();
            shouldPreventDefault = true;
          }
        } else {
          if (this.inChordMode) {
            this._leaveChordMode();
          }
          if (!resolveResult.isBubble) {
            shouldPreventDefault = true;
          }
          this._log(`+ Invoking command ${resolveResult.commandId}.`);
          if (typeof resolveResult.commandArgs === "undefined") {
            this._commandService.executeCommand(resolveResult.commandId).then(void 0, (err) => this._notificationService.warn(err));
          } else {
            this._commandService.executeCommand(resolveResult.commandId, resolveResult.commandArgs).then(void 0, (err) => this._notificationService.warn(err));
          }
          if (!HIGH_FREQ_COMMANDS.test(resolveResult.commandId)) {
            this._telemetryService.publicLog2("workbenchActionExecuted", { id: resolveResult.commandId, from: "keybinding", detail: (_a2 = userKeypress.getUserSettingsLabel()) !== null && _a2 !== void 0 ? _a2 : void 0 });
          }
        }
        return shouldPreventDefault;
      }
    }
  }
  mightProducePrintableCharacter(event) {
    if (event.ctrlKey || event.metaKey) {
      return false;
    }
    if (event.keyCode >= 31 && event.keyCode <= 56 || event.keyCode >= 21 && event.keyCode <= 30) {
      return true;
    }
    return false;
  }
}
class KeybindingModifierSet {
  constructor(source) {
    this._ctrlKey = source ? source.ctrlKey : false;
    this._shiftKey = source ? source.shiftKey : false;
    this._altKey = source ? source.altKey : false;
    this._metaKey = source ? source.metaKey : false;
  }
  has(modifier) {
    switch (modifier) {
      case "ctrl":
        return this._ctrlKey;
      case "shift":
        return this._shiftKey;
      case "alt":
        return this._altKey;
      case "meta":
        return this._metaKey;
    }
  }
}
KeybindingModifierSet.EMPTY = new KeybindingModifierSet(null);
class ResolvedKeybindingItem {
  constructor(resolvedKeybinding, command, commandArgs, when, isDefault, extensionId, isBuiltinExtension) {
    this._resolvedKeybindingItemBrand = void 0;
    this.resolvedKeybinding = resolvedKeybinding;
    this.chords = resolvedKeybinding ? toEmptyArrayIfContainsNull(resolvedKeybinding.getDispatchChords()) : [];
    if (resolvedKeybinding && this.chords.length === 0) {
      this.chords = toEmptyArrayIfContainsNull(resolvedKeybinding.getSingleModifierDispatchChords());
    }
    this.bubble = command ? command.charCodeAt(0) === 94 : false;
    this.command = this.bubble ? command.substr(1) : command;
    this.commandArgs = commandArgs;
    this.when = when;
    this.isDefault = isDefault;
    this.extensionId = extensionId;
    this.isBuiltinExtension = isBuiltinExtension;
  }
}
function toEmptyArrayIfContainsNull(arr) {
  const result2 = [];
  for (let i = 0, len = arr.length; i < len; i++) {
    const element = arr[i];
    if (!element) {
      return [];
    }
    result2.push(element);
  }
  return result2;
}
class BaseResolvedKeybinding extends ResolvedKeybinding {
  constructor(os, chords) {
    super();
    if (chords.length === 0) {
      throw illegalArgument(`chords`);
    }
    this._os = os;
    this._chords = chords;
  }
  getLabel() {
    return UILabelProvider.toLabel(this._os, this._chords, (keybinding) => this._getLabel(keybinding));
  }
  getAriaLabel() {
    return AriaLabelProvider.toLabel(this._os, this._chords, (keybinding) => this._getAriaLabel(keybinding));
  }
  getElectronAccelerator() {
    if (this._chords.length > 1) {
      return null;
    }
    if (this._chords[0].isDuplicateModifierCase()) {
      return null;
    }
    return ElectronAcceleratorLabelProvider.toLabel(this._os, this._chords, (keybinding) => this._getElectronAccelerator(keybinding));
  }
  getUserSettingsLabel() {
    return UserSettingsLabelProvider.toLabel(this._os, this._chords, (keybinding) => this._getUserSettingsLabel(keybinding));
  }
  hasMultipleChords() {
    return this._chords.length > 1;
  }
  getChords() {
    return this._chords.map((keybinding) => this._getChord(keybinding));
  }
  _getChord(keybinding) {
    return new ResolvedChord(keybinding.ctrlKey, keybinding.shiftKey, keybinding.altKey, keybinding.metaKey, this._getLabel(keybinding), this._getAriaLabel(keybinding));
  }
  getDispatchChords() {
    return this._chords.map((keybinding) => this._getChordDispatch(keybinding));
  }
  getSingleModifierDispatchChords() {
    return this._chords.map((keybinding) => this._getSingleModifierChordDispatch(keybinding));
  }
}
class USLayoutResolvedKeybinding extends BaseResolvedKeybinding {
  constructor(chords, os) {
    super(os, chords);
  }
  _keyCodeToUILabel(keyCode) {
    if (this._os === 2) {
      switch (keyCode) {
        case 15:
          return "←";
        case 16:
          return "↑";
        case 17:
          return "→";
        case 18:
          return "↓";
      }
    }
    return KeyCodeUtils.toString(keyCode);
  }
  _getLabel(chord) {
    if (chord.isDuplicateModifierCase()) {
      return "";
    }
    return this._keyCodeToUILabel(chord.keyCode);
  }
  _getAriaLabel(chord) {
    if (chord.isDuplicateModifierCase()) {
      return "";
    }
    return KeyCodeUtils.toString(chord.keyCode);
  }
  _getElectronAccelerator(chord) {
    return KeyCodeUtils.toElectronAccelerator(chord.keyCode);
  }
  _getUserSettingsLabel(chord) {
    if (chord.isDuplicateModifierCase()) {
      return "";
    }
    const result2 = KeyCodeUtils.toUserSettingsUS(chord.keyCode);
    return result2 ? result2.toLowerCase() : result2;
  }
  _getChordDispatch(chord) {
    return USLayoutResolvedKeybinding.getDispatchStr(chord);
  }
  static getDispatchStr(chord) {
    if (chord.isModifierKey()) {
      return null;
    }
    let result2 = "";
    if (chord.ctrlKey) {
      result2 += "ctrl+";
    }
    if (chord.shiftKey) {
      result2 += "shift+";
    }
    if (chord.altKey) {
      result2 += "alt+";
    }
    if (chord.metaKey) {
      result2 += "meta+";
    }
    result2 += KeyCodeUtils.toString(chord.keyCode);
    return result2;
  }
  _getSingleModifierChordDispatch(keybinding) {
    if (keybinding.keyCode === 5 && !keybinding.shiftKey && !keybinding.altKey && !keybinding.metaKey) {
      return "ctrl";
    }
    if (keybinding.keyCode === 4 && !keybinding.ctrlKey && !keybinding.altKey && !keybinding.metaKey) {
      return "shift";
    }
    if (keybinding.keyCode === 6 && !keybinding.ctrlKey && !keybinding.shiftKey && !keybinding.metaKey) {
      return "alt";
    }
    if (keybinding.keyCode === 57 && !keybinding.ctrlKey && !keybinding.shiftKey && !keybinding.altKey) {
      return "meta";
    }
    return null;
  }
  /**
   * *NOTE*: Check return value for `KeyCode.Unknown`.
   */
  static _scanCodeToKeyCode(scanCode) {
    const immutableKeyCode = IMMUTABLE_CODE_TO_KEY_CODE[scanCode];
    if (immutableKeyCode !== -1) {
      return immutableKeyCode;
    }
    switch (scanCode) {
      case 10:
        return 31;
      case 11:
        return 32;
      case 12:
        return 33;
      case 13:
        return 34;
      case 14:
        return 35;
      case 15:
        return 36;
      case 16:
        return 37;
      case 17:
        return 38;
      case 18:
        return 39;
      case 19:
        return 40;
      case 20:
        return 41;
      case 21:
        return 42;
      case 22:
        return 43;
      case 23:
        return 44;
      case 24:
        return 45;
      case 25:
        return 46;
      case 26:
        return 47;
      case 27:
        return 48;
      case 28:
        return 49;
      case 29:
        return 50;
      case 30:
        return 51;
      case 31:
        return 52;
      case 32:
        return 53;
      case 33:
        return 54;
      case 34:
        return 55;
      case 35:
        return 56;
      case 36:
        return 22;
      case 37:
        return 23;
      case 38:
        return 24;
      case 39:
        return 25;
      case 40:
        return 26;
      case 41:
        return 27;
      case 42:
        return 28;
      case 43:
        return 29;
      case 44:
        return 30;
      case 45:
        return 21;
      case 51:
        return 88;
      case 52:
        return 86;
      case 53:
        return 92;
      case 54:
        return 94;
      case 55:
        return 93;
      case 56:
        return 0;
      case 57:
        return 85;
      case 58:
        return 95;
      case 59:
        return 91;
      case 60:
        return 87;
      case 61:
        return 89;
      case 62:
        return 90;
      case 106:
        return 97;
    }
    return 0;
  }
  static _toKeyCodeChord(chord) {
    if (!chord) {
      return null;
    }
    if (chord instanceof KeyCodeChord) {
      return chord;
    }
    const keyCode = this._scanCodeToKeyCode(chord.scanCode);
    if (keyCode === 0) {
      return null;
    }
    return new KeyCodeChord(chord.ctrlKey, chord.shiftKey, chord.altKey, chord.metaKey, keyCode);
  }
  static resolveKeybinding(keybinding, os) {
    const chords = toEmptyArrayIfContainsNull(keybinding.chords.map((chord) => this._toKeyCodeChord(chord)));
    if (chords.length > 0) {
      return [new USLayoutResolvedKeybinding(chords, os)];
    }
    return [];
  }
}
const contextview = "";
function isAnchor(obj) {
  const anchor = obj;
  return !!anchor && typeof anchor.x === "number" && typeof anchor.y === "number";
}
var LayoutAnchorMode;
(function(LayoutAnchorMode2) {
  LayoutAnchorMode2[LayoutAnchorMode2["AVOID"] = 0] = "AVOID";
  LayoutAnchorMode2[LayoutAnchorMode2["ALIGN"] = 1] = "ALIGN";
})(LayoutAnchorMode || (LayoutAnchorMode = {}));
function layout(viewportSize, viewSize, anchor) {
  const layoutAfterAnchorBoundary = anchor.mode === LayoutAnchorMode.ALIGN ? anchor.offset : anchor.offset + anchor.size;
  const layoutBeforeAnchorBoundary = anchor.mode === LayoutAnchorMode.ALIGN ? anchor.offset + anchor.size : anchor.offset;
  if (anchor.position === 0) {
    if (viewSize <= viewportSize - layoutAfterAnchorBoundary) {
      return layoutAfterAnchorBoundary;
    }
    if (viewSize <= layoutBeforeAnchorBoundary) {
      return layoutBeforeAnchorBoundary - viewSize;
    }
    return Math.max(viewportSize - viewSize, 0);
  } else {
    if (viewSize <= layoutBeforeAnchorBoundary) {
      return layoutBeforeAnchorBoundary - viewSize;
    }
    if (viewSize <= viewportSize - layoutAfterAnchorBoundary) {
      return layoutAfterAnchorBoundary;
    }
    return 0;
  }
}
class ContextView extends Disposable {
  constructor(container2, domPosition) {
    super();
    this.container = null;
    this.delegate = null;
    this.toDisposeOnClean = Disposable.None;
    this.toDisposeOnSetContainer = Disposable.None;
    this.shadowRoot = null;
    this.shadowRootHostElement = null;
    this.view = $$d(".context-view");
    this.useFixedPosition = false;
    this.useShadowDOM = false;
    hide(this.view);
    this.setContainer(container2, domPosition);
    this._register(toDisposable(() => this.setContainer(
      null,
      1
      /* ContextViewDOMPosition.ABSOLUTE */
    )));
  }
  setContainer(container2, domPosition) {
    var _a2;
    if (this.container) {
      this.toDisposeOnSetContainer.dispose();
      if (this.shadowRoot) {
        this.shadowRoot.removeChild(this.view);
        this.shadowRoot = null;
        (_a2 = this.shadowRootHostElement) === null || _a2 === void 0 ? void 0 : _a2.remove();
        this.shadowRootHostElement = null;
      } else {
        this.container.removeChild(this.view);
      }
      this.container = null;
    }
    if (container2) {
      this.container = container2;
      this.useFixedPosition = domPosition !== 1;
      this.useShadowDOM = domPosition === 3;
      if (this.useShadowDOM) {
        this.shadowRootHostElement = $$d(".shadow-root-host");
        this.container.appendChild(this.shadowRootHostElement);
        this.shadowRoot = this.shadowRootHostElement.attachShadow({ mode: "open" });
        const style2 = document.createElement("style");
        style2.textContent = SHADOW_ROOT_CSS;
        this.shadowRoot.appendChild(style2);
        this.shadowRoot.appendChild(this.view);
        this.shadowRoot.appendChild($$d("slot"));
      } else {
        this.container.appendChild(this.view);
      }
      const toDisposeOnSetContainer = new DisposableStore();
      ContextView.BUBBLE_UP_EVENTS.forEach((event) => {
        toDisposeOnSetContainer.add(addStandardDisposableListener(this.container, event, (e) => {
          this.onDOMEvent(e, false);
        }));
      });
      ContextView.BUBBLE_DOWN_EVENTS.forEach((event) => {
        toDisposeOnSetContainer.add(addStandardDisposableListener(this.container, event, (e) => {
          this.onDOMEvent(e, true);
        }, true));
      });
      this.toDisposeOnSetContainer = toDisposeOnSetContainer;
    }
  }
  show(delegate) {
    var _a2, _b2;
    if (this.isVisible()) {
      this.hide();
    }
    clearNode(this.view);
    this.view.className = "context-view";
    this.view.style.top = "0px";
    this.view.style.left = "0px";
    this.view.style.zIndex = "2575";
    this.view.style.position = this.useFixedPosition ? "fixed" : "absolute";
    show(this.view);
    this.toDisposeOnClean = delegate.render(this.view) || Disposable.None;
    this.delegate = delegate;
    this.doLayout();
    (_b2 = (_a2 = this.delegate).focus) === null || _b2 === void 0 ? void 0 : _b2.call(_a2);
  }
  getViewElement() {
    return this.view;
  }
  layout() {
    if (!this.isVisible()) {
      return;
    }
    if (this.delegate.canRelayout === false && !(isIOS && BrowserFeatures.pointerEvents)) {
      this.hide();
      return;
    }
    if (this.delegate.layout) {
      this.delegate.layout();
    }
    this.doLayout();
  }
  doLayout() {
    if (!this.isVisible()) {
      return;
    }
    const anchor = this.delegate.getAnchor();
    let around;
    if (isHTMLElement(anchor)) {
      const elementPosition = getDomNodePagePosition(anchor);
      const zoom = getDomNodeZoomLevel(anchor);
      around = {
        top: elementPosition.top * zoom,
        left: elementPosition.left * zoom,
        width: elementPosition.width * zoom,
        height: elementPosition.height * zoom
      };
    } else if (isAnchor(anchor)) {
      around = {
        top: anchor.y,
        left: anchor.x,
        width: anchor.width || 1,
        height: anchor.height || 2
      };
    } else {
      around = {
        top: anchor.posy,
        left: anchor.posx,
        // We are about to position the context view where the mouse
        // cursor is. To prevent the view being exactly under the mouse
        // when showing and thus potentially triggering an action within,
        // we treat the mouse location like a small sized block element.
        width: 2,
        height: 2
      };
    }
    const viewSizeWidth = getTotalWidth(this.view);
    const viewSizeHeight = getTotalHeight(this.view);
    const anchorPosition = this.delegate.anchorPosition || 0;
    const anchorAlignment = this.delegate.anchorAlignment || 0;
    const anchorAxisAlignment = this.delegate.anchorAxisAlignment || 0;
    let top;
    let left;
    if (anchorAxisAlignment === 0) {
      const verticalAnchor = {
        offset: around.top - window.pageYOffset,
        size: around.height,
        position: anchorPosition === 0 ? 0 : 1
        /* LayoutAnchorPosition.After */
      };
      const horizontalAnchor = { offset: around.left, size: around.width, position: anchorAlignment === 0 ? 0 : 1, mode: LayoutAnchorMode.ALIGN };
      top = layout(window.innerHeight, viewSizeHeight, verticalAnchor) + window.pageYOffset;
      if (Range$1.intersects({ start: top, end: top + viewSizeHeight }, { start: verticalAnchor.offset, end: verticalAnchor.offset + verticalAnchor.size })) {
        horizontalAnchor.mode = LayoutAnchorMode.AVOID;
      }
      left = layout(window.innerWidth, viewSizeWidth, horizontalAnchor);
    } else {
      const horizontalAnchor = {
        offset: around.left,
        size: around.width,
        position: anchorAlignment === 0 ? 0 : 1
        /* LayoutAnchorPosition.After */
      };
      const verticalAnchor = { offset: around.top, size: around.height, position: anchorPosition === 0 ? 0 : 1, mode: LayoutAnchorMode.ALIGN };
      left = layout(window.innerWidth, viewSizeWidth, horizontalAnchor);
      if (Range$1.intersects({ start: left, end: left + viewSizeWidth }, { start: horizontalAnchor.offset, end: horizontalAnchor.offset + horizontalAnchor.size })) {
        verticalAnchor.mode = LayoutAnchorMode.AVOID;
      }
      top = layout(window.innerHeight, viewSizeHeight, verticalAnchor) + window.pageYOffset;
    }
    this.view.classList.remove("top", "bottom", "left", "right");
    this.view.classList.add(anchorPosition === 0 ? "bottom" : "top");
    this.view.classList.add(anchorAlignment === 0 ? "left" : "right");
    this.view.classList.toggle("fixed", this.useFixedPosition);
    const containerPosition = getDomNodePagePosition(this.container);
    this.view.style.top = `${top - (this.useFixedPosition ? getDomNodePagePosition(this.view).top : containerPosition.top)}px`;
    this.view.style.left = `${left - (this.useFixedPosition ? getDomNodePagePosition(this.view).left : containerPosition.left)}px`;
    this.view.style.width = "initial";
  }
  hide(data) {
    const delegate = this.delegate;
    this.delegate = null;
    if (delegate === null || delegate === void 0 ? void 0 : delegate.onHide) {
      delegate.onHide(data);
    }
    this.toDisposeOnClean.dispose();
    hide(this.view);
  }
  isVisible() {
    return !!this.delegate;
  }
  onDOMEvent(e, onCapture) {
    if (this.delegate) {
      if (this.delegate.onDOMEvent) {
        this.delegate.onDOMEvent(e, document.activeElement);
      } else if (onCapture && !isAncestor$1(e.target, this.container)) {
        this.hide();
      }
    }
  }
  dispose() {
    this.hide();
    super.dispose();
  }
}
ContextView.BUBBLE_UP_EVENTS = ["click", "keydown", "focus", "blur"];
ContextView.BUBBLE_DOWN_EVENTS = ["click"];
const SHADOW_ROOT_CSS = (
  /* css */
  `
	:host {
		all: initial; /* 1st rule so subsequent properties are reset. */
	}

	.codicon[class*='codicon-'] {
		font: normal normal normal 16px/1 codicon;
		display: inline-block;
		text-decoration: none;
		text-rendering: auto;
		text-align: center;
		-webkit-font-smoothing: antialiased;
		-moz-osx-font-smoothing: grayscale;
		user-select: none;
		-webkit-user-select: none;
		-ms-user-select: none;
	}

	:host {
		font-family: -apple-system, BlinkMacSystemFont, "Segoe WPC", "Segoe UI", "HelveticaNeue-Light", system-ui, "Ubuntu", "Droid Sans", sans-serif;
	}

	:host-context(.mac) { font-family: -apple-system, BlinkMacSystemFont, sans-serif; }
	:host-context(.mac:lang(zh-Hans)) { font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Hiragino Sans GB", sans-serif; }
	:host-context(.mac:lang(zh-Hant)) { font-family: -apple-system, BlinkMacSystemFont, "PingFang TC", sans-serif; }
	:host-context(.mac:lang(ja)) { font-family: -apple-system, BlinkMacSystemFont, "Hiragino Kaku Gothic Pro", sans-serif; }
	:host-context(.mac:lang(ko)) { font-family: -apple-system, BlinkMacSystemFont, "Nanum Gothic", "Apple SD Gothic Neo", "AppleGothic", sans-serif; }

	:host-context(.windows) { font-family: "Segoe WPC", "Segoe UI", sans-serif; }
	:host-context(.windows:lang(zh-Hans)) { font-family: "Segoe WPC", "Segoe UI", "Microsoft YaHei", sans-serif; }
	:host-context(.windows:lang(zh-Hant)) { font-family: "Segoe WPC", "Segoe UI", "Microsoft Jhenghei", sans-serif; }
	:host-context(.windows:lang(ja)) { font-family: "Segoe WPC", "Segoe UI", "Yu Gothic UI", "Meiryo UI", sans-serif; }
	:host-context(.windows:lang(ko)) { font-family: "Segoe WPC", "Segoe UI", "Malgun Gothic", "Dotom", sans-serif; }

	:host-context(.linux) { font-family: system-ui, "Ubuntu", "Droid Sans", sans-serif; }
	:host-context(.linux:lang(zh-Hans)) { font-family: system-ui, "Ubuntu", "Droid Sans", "Source Han Sans SC", "Source Han Sans CN", "Source Han Sans", sans-serif; }
	:host-context(.linux:lang(zh-Hant)) { font-family: system-ui, "Ubuntu", "Droid Sans", "Source Han Sans TC", "Source Han Sans TW", "Source Han Sans", sans-serif; }
	:host-context(.linux:lang(ja)) { font-family: system-ui, "Ubuntu", "Droid Sans", "Source Han Sans J", "Source Han Sans JP", "Source Han Sans", sans-serif; }
	:host-context(.linux:lang(ko)) { font-family: system-ui, "Ubuntu", "Droid Sans", "Source Han Sans K", "Source Han Sans JR", "Source Han Sans", "UnDotum", "FBaekmuk Gulim", sans-serif; }
`
);
var __decorate$k = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$i = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let ContextViewService = class ContextViewService2 extends Disposable {
  constructor(layoutService) {
    super();
    this.layoutService = layoutService;
    this.currentViewDisposable = Disposable.None;
    this.container = layoutService.hasContainer ? layoutService.container : null;
    this.contextView = this._register(new ContextView(
      this.container,
      1
      /* ContextViewDOMPosition.ABSOLUTE */
    ));
    this.layout();
    this._register(layoutService.onDidLayout(() => this.layout()));
  }
  // ContextView
  setContainer(container2, domPosition) {
    this.contextView.setContainer(
      container2,
      domPosition || 1
      /* ContextViewDOMPosition.ABSOLUTE */
    );
  }
  showContextView(delegate, container2, shadowRoot) {
    if (container2) {
      if (container2 !== this.container || this.shadowRoot !== shadowRoot) {
        this.container = container2;
        this.setContainer(
          container2,
          shadowRoot ? 3 : 2
          /* ContextViewDOMPosition.FIXED */
        );
      }
    } else {
      if (this.layoutService.hasContainer && this.container !== this.layoutService.container) {
        this.container = this.layoutService.container;
        this.setContainer(
          this.container,
          1
          /* ContextViewDOMPosition.ABSOLUTE */
        );
      }
    }
    this.shadowRoot = shadowRoot;
    this.contextView.show(delegate);
    const disposable = toDisposable(() => {
      if (this.currentViewDisposable === disposable) {
        this.hideContextView();
      }
    });
    this.currentViewDisposable = disposable;
    return disposable;
  }
  getContextViewElement() {
    return this.contextView.getViewElement();
  }
  layout() {
    this.contextView.layout();
  }
  hideContextView(data) {
    this.contextView.hide(data);
  }
};
ContextViewService = __decorate$k([
  __param$i(0, ILayoutService)
], ContextViewService);
let registeredAssociations = [];
let nonUserRegisteredAssociations = [];
let userRegisteredAssociations = [];
function registerPlatformLanguageAssociation(association, warnOnOverwrite = false) {
  _registerLanguageAssociation(association, false, warnOnOverwrite);
}
function _registerLanguageAssociation(association, userConfigured, warnOnOverwrite) {
  const associationItem = toLanguageAssociationItem(association, userConfigured);
  registeredAssociations.push(associationItem);
  if (!associationItem.userConfigured) {
    nonUserRegisteredAssociations.push(associationItem);
  } else {
    userRegisteredAssociations.push(associationItem);
  }
  if (warnOnOverwrite && !associationItem.userConfigured) {
    registeredAssociations.forEach((a) => {
      if (a.mime === associationItem.mime || a.userConfigured) {
        return;
      }
      if (associationItem.extension && a.extension === associationItem.extension) {
        console.warn(`Overwriting extension <<${associationItem.extension}>> to now point to mime <<${associationItem.mime}>>`);
      }
      if (associationItem.filename && a.filename === associationItem.filename) {
        console.warn(`Overwriting filename <<${associationItem.filename}>> to now point to mime <<${associationItem.mime}>>`);
      }
      if (associationItem.filepattern && a.filepattern === associationItem.filepattern) {
        console.warn(`Overwriting filepattern <<${associationItem.filepattern}>> to now point to mime <<${associationItem.mime}>>`);
      }
      if (associationItem.firstline && a.firstline === associationItem.firstline) {
        console.warn(`Overwriting firstline <<${associationItem.firstline}>> to now point to mime <<${associationItem.mime}>>`);
      }
    });
  }
}
function toLanguageAssociationItem(association, userConfigured) {
  return {
    id: association.id,
    mime: association.mime,
    filename: association.filename,
    extension: association.extension,
    filepattern: association.filepattern,
    firstline: association.firstline,
    userConfigured,
    filenameLowercase: association.filename ? association.filename.toLowerCase() : void 0,
    extensionLowercase: association.extension ? association.extension.toLowerCase() : void 0,
    filepatternLowercase: association.filepattern ? parse$a(association.filepattern.toLowerCase()) : void 0,
    filepatternOnPath: association.filepattern ? association.filepattern.indexOf(posix.sep) >= 0 : false
  };
}
function clearPlatformLanguageAssociations() {
  registeredAssociations = registeredAssociations.filter((a) => a.userConfigured);
  nonUserRegisteredAssociations = [];
}
function getLanguageIds(resource, firstLine) {
  return getAssociations(resource, firstLine).map((item) => item.id);
}
function getAssociations(resource, firstLine) {
  let path2;
  if (resource) {
    switch (resource.scheme) {
      case Schemas.file:
        path2 = resource.fsPath;
        break;
      case Schemas.data: {
        const metadata = DataUri.parseMetaData(resource);
        path2 = metadata.get(DataUri.META_DATA_LABEL);
        break;
      }
      case Schemas.vscodeNotebookCell:
        path2 = void 0;
        break;
      default:
        path2 = resource.path;
    }
  }
  if (!path2) {
    return [{ id: "unknown", mime: Mimes.unknown }];
  }
  path2 = path2.toLowerCase();
  const filename = basename$2(path2);
  const configuredLanguage = getAssociationByPath(path2, filename, userRegisteredAssociations);
  if (configuredLanguage) {
    return [configuredLanguage, { id: PLAINTEXT_LANGUAGE_ID, mime: Mimes.text }];
  }
  const registeredLanguage = getAssociationByPath(path2, filename, nonUserRegisteredAssociations);
  if (registeredLanguage) {
    return [registeredLanguage, { id: PLAINTEXT_LANGUAGE_ID, mime: Mimes.text }];
  }
  if (firstLine) {
    const firstlineLanguage = getAssociationByFirstline(firstLine);
    if (firstlineLanguage) {
      return [firstlineLanguage, { id: PLAINTEXT_LANGUAGE_ID, mime: Mimes.text }];
    }
  }
  return [{ id: "unknown", mime: Mimes.unknown }];
}
function getAssociationByPath(path2, filename, associations) {
  var _a2;
  let filenameMatch = void 0;
  let patternMatch = void 0;
  let extensionMatch = void 0;
  for (let i = associations.length - 1; i >= 0; i--) {
    const association = associations[i];
    if (filename === association.filenameLowercase) {
      filenameMatch = association;
      break;
    }
    if (association.filepattern) {
      if (!patternMatch || association.filepattern.length > patternMatch.filepattern.length) {
        const target = association.filepatternOnPath ? path2 : filename;
        if ((_a2 = association.filepatternLowercase) === null || _a2 === void 0 ? void 0 : _a2.call(association, target)) {
          patternMatch = association;
        }
      }
    }
    if (association.extension) {
      if (!extensionMatch || association.extension.length > extensionMatch.extension.length) {
        if (filename.endsWith(association.extensionLowercase)) {
          extensionMatch = association;
        }
      }
    }
  }
  if (filenameMatch) {
    return filenameMatch;
  }
  if (patternMatch) {
    return patternMatch;
  }
  if (extensionMatch) {
    return extensionMatch;
  }
  return void 0;
}
function getAssociationByFirstline(firstLine) {
  if (startsWithUTF8BOM(firstLine)) {
    firstLine = firstLine.substr(1);
  }
  if (firstLine.length > 0) {
    for (let i = registeredAssociations.length - 1; i >= 0; i--) {
      const association = registeredAssociations[i];
      if (!association.firstline) {
        continue;
      }
      const matches = firstLine.match(association.firstline);
      if (matches && matches.length > 0) {
        return association;
      }
    }
  }
  return void 0;
}
const hasOwnProperty$4 = Object.prototype.hasOwnProperty;
const NULL_LANGUAGE_ID = "vs.editor.nullLanguage";
class LanguageIdCodec {
  constructor() {
    this._languageIdToLanguage = [];
    this._languageToLanguageId = /* @__PURE__ */ new Map();
    this._register(
      NULL_LANGUAGE_ID,
      0
      /* LanguageId.Null */
    );
    this._register(
      PLAINTEXT_LANGUAGE_ID,
      1
      /* LanguageId.PlainText */
    );
    this._nextLanguageId = 2;
  }
  _register(language2, languageId) {
    this._languageIdToLanguage[languageId] = language2;
    this._languageToLanguageId.set(language2, languageId);
  }
  register(language2) {
    if (this._languageToLanguageId.has(language2)) {
      return;
    }
    const languageId = this._nextLanguageId++;
    this._register(language2, languageId);
  }
  encodeLanguageId(languageId) {
    return this._languageToLanguageId.get(languageId) || 0;
  }
  decodeLanguageId(languageId) {
    return this._languageIdToLanguage[languageId] || NULL_LANGUAGE_ID;
  }
}
class LanguagesRegistry extends Disposable {
  constructor(useModesRegistry = true, warnOnOverwrite = false) {
    super();
    this._onDidChange = this._register(new Emitter$1());
    this.onDidChange = this._onDidChange.event;
    LanguagesRegistry.instanceCount++;
    this._warnOnOverwrite = warnOnOverwrite;
    this.languageIdCodec = new LanguageIdCodec();
    this._dynamicLanguages = [];
    this._languages = {};
    this._mimeTypesMap = {};
    this._nameMap = {};
    this._lowercaseNameMap = {};
    if (useModesRegistry) {
      this._initializeFromRegistry();
      this._register(ModesRegistry.onDidChangeLanguages((m) => {
        this._initializeFromRegistry();
      }));
    }
  }
  dispose() {
    LanguagesRegistry.instanceCount--;
    super.dispose();
  }
  _initializeFromRegistry() {
    this._languages = {};
    this._mimeTypesMap = {};
    this._nameMap = {};
    this._lowercaseNameMap = {};
    clearPlatformLanguageAssociations();
    const desc = [].concat(ModesRegistry.getLanguages()).concat(this._dynamicLanguages);
    this._registerLanguages(desc);
  }
  _registerLanguages(desc) {
    for (const d of desc) {
      this._registerLanguage(d);
    }
    this._mimeTypesMap = {};
    this._nameMap = {};
    this._lowercaseNameMap = {};
    Object.keys(this._languages).forEach((langId) => {
      const language2 = this._languages[langId];
      if (language2.name) {
        this._nameMap[language2.name] = language2.identifier;
      }
      language2.aliases.forEach((alias) => {
        this._lowercaseNameMap[alias.toLowerCase()] = language2.identifier;
      });
      language2.mimetypes.forEach((mimetype) => {
        this._mimeTypesMap[mimetype] = language2.identifier;
      });
    });
    Registry.as(Extensions$6.Configuration).registerOverrideIdentifiers(this.getRegisteredLanguageIds());
    this._onDidChange.fire();
  }
  _registerLanguage(lang) {
    const langId = lang.id;
    let resolvedLanguage;
    if (hasOwnProperty$4.call(this._languages, langId)) {
      resolvedLanguage = this._languages[langId];
    } else {
      this.languageIdCodec.register(langId);
      resolvedLanguage = {
        identifier: langId,
        name: null,
        mimetypes: [],
        aliases: [],
        extensions: [],
        filenames: [],
        configurationFiles: [],
        icons: []
      };
      this._languages[langId] = resolvedLanguage;
    }
    this._mergeLanguage(resolvedLanguage, lang);
  }
  _mergeLanguage(resolvedLanguage, lang) {
    const langId = lang.id;
    let primaryMime = null;
    if (Array.isArray(lang.mimetypes) && lang.mimetypes.length > 0) {
      resolvedLanguage.mimetypes.push(...lang.mimetypes);
      primaryMime = lang.mimetypes[0];
    }
    if (!primaryMime) {
      primaryMime = `text/x-${langId}`;
      resolvedLanguage.mimetypes.push(primaryMime);
    }
    if (Array.isArray(lang.extensions)) {
      if (lang.configuration) {
        resolvedLanguage.extensions = lang.extensions.concat(resolvedLanguage.extensions);
      } else {
        resolvedLanguage.extensions = resolvedLanguage.extensions.concat(lang.extensions);
      }
      for (const extension of lang.extensions) {
        registerPlatformLanguageAssociation({ id: langId, mime: primaryMime, extension }, this._warnOnOverwrite);
      }
    }
    if (Array.isArray(lang.filenames)) {
      for (const filename of lang.filenames) {
        registerPlatformLanguageAssociation({ id: langId, mime: primaryMime, filename }, this._warnOnOverwrite);
        resolvedLanguage.filenames.push(filename);
      }
    }
    if (Array.isArray(lang.filenamePatterns)) {
      for (const filenamePattern of lang.filenamePatterns) {
        registerPlatformLanguageAssociation({ id: langId, mime: primaryMime, filepattern: filenamePattern }, this._warnOnOverwrite);
      }
    }
    if (typeof lang.firstLine === "string" && lang.firstLine.length > 0) {
      let firstLineRegexStr = lang.firstLine;
      if (firstLineRegexStr.charAt(0) !== "^") {
        firstLineRegexStr = "^" + firstLineRegexStr;
      }
      try {
        const firstLineRegex = new RegExp(firstLineRegexStr);
        if (!regExpLeadsToEndlessLoop(firstLineRegex)) {
          registerPlatformLanguageAssociation({ id: langId, mime: primaryMime, firstline: firstLineRegex }, this._warnOnOverwrite);
        }
      } catch (err) {
        console.warn(`[${lang.id}]: Invalid regular expression \`${firstLineRegexStr}\`: `, err);
      }
    }
    resolvedLanguage.aliases.push(langId);
    let langAliases = null;
    if (typeof lang.aliases !== "undefined" && Array.isArray(lang.aliases)) {
      if (lang.aliases.length === 0) {
        langAliases = [null];
      } else {
        langAliases = lang.aliases;
      }
    }
    if (langAliases !== null) {
      for (const langAlias of langAliases) {
        if (!langAlias || langAlias.length === 0) {
          continue;
        }
        resolvedLanguage.aliases.push(langAlias);
      }
    }
    const containsAliases = langAliases !== null && langAliases.length > 0;
    if (containsAliases && langAliases[0] === null)
      ;
    else {
      const bestName = (containsAliases ? langAliases[0] : null) || langId;
      if (containsAliases || !resolvedLanguage.name) {
        resolvedLanguage.name = bestName;
      }
    }
    if (lang.configuration) {
      resolvedLanguage.configurationFiles.push(lang.configuration);
    }
    if (lang.icon) {
      resolvedLanguage.icons.push(lang.icon);
    }
  }
  isRegisteredLanguageId(languageId) {
    if (!languageId) {
      return false;
    }
    return hasOwnProperty$4.call(this._languages, languageId);
  }
  getRegisteredLanguageIds() {
    return Object.keys(this._languages);
  }
  getLanguageIdByLanguageName(languageName) {
    const languageNameLower = languageName.toLowerCase();
    if (!hasOwnProperty$4.call(this._lowercaseNameMap, languageNameLower)) {
      return null;
    }
    return this._lowercaseNameMap[languageNameLower];
  }
  getLanguageIdByMimeType(mimeType) {
    if (!mimeType) {
      return null;
    }
    if (hasOwnProperty$4.call(this._mimeTypesMap, mimeType)) {
      return this._mimeTypesMap[mimeType];
    }
    return null;
  }
  guessLanguageIdByFilepathOrFirstLine(resource, firstLine) {
    if (!resource && !firstLine) {
      return [];
    }
    return getLanguageIds(resource, firstLine);
  }
}
LanguagesRegistry.instanceCount = 0;
class LanguageService extends Disposable {
  constructor(warnOnOverwrite = false) {
    super();
    this._onDidRequestBasicLanguageFeatures = this._register(new Emitter$1());
    this.onDidRequestBasicLanguageFeatures = this._onDidRequestBasicLanguageFeatures.event;
    this._onDidRequestRichLanguageFeatures = this._register(new Emitter$1());
    this.onDidRequestRichLanguageFeatures = this._onDidRequestRichLanguageFeatures.event;
    this._onDidChange = this._register(new Emitter$1({
      leakWarningThreshold: 200
      /* https://github.com/microsoft/vscode/issues/119968 */
    }));
    this.onDidChange = this._onDidChange.event;
    this._requestedBasicLanguages = /* @__PURE__ */ new Set();
    this._requestedRichLanguages = /* @__PURE__ */ new Set();
    LanguageService.instanceCount++;
    this._registry = this._register(new LanguagesRegistry(true, warnOnOverwrite));
    this.languageIdCodec = this._registry.languageIdCodec;
    this._register(this._registry.onDidChange(() => this._onDidChange.fire()));
  }
  dispose() {
    LanguageService.instanceCount--;
    super.dispose();
  }
  isRegisteredLanguageId(languageId) {
    return this._registry.isRegisteredLanguageId(languageId);
  }
  getLanguageIdByLanguageName(languageName) {
    return this._registry.getLanguageIdByLanguageName(languageName);
  }
  getLanguageIdByMimeType(mimeType) {
    return this._registry.getLanguageIdByMimeType(mimeType);
  }
  guessLanguageIdByFilepathOrFirstLine(resource, firstLine) {
    const languageIds = this._registry.guessLanguageIdByFilepathOrFirstLine(resource, firstLine);
    return firstOrDefault(languageIds, null);
  }
  createById(languageId) {
    return new LanguageSelection(this.onDidChange, () => {
      return this._createAndGetLanguageIdentifier(languageId);
    });
  }
  createByFilepathOrFirstLine(resource, firstLine) {
    return new LanguageSelection(this.onDidChange, () => {
      const languageId = this.guessLanguageIdByFilepathOrFirstLine(resource, firstLine);
      return this._createAndGetLanguageIdentifier(languageId);
    });
  }
  _createAndGetLanguageIdentifier(languageId) {
    if (!languageId || !this.isRegisteredLanguageId(languageId)) {
      languageId = PLAINTEXT_LANGUAGE_ID;
    }
    return languageId;
  }
  requestBasicLanguageFeatures(languageId) {
    if (!this._requestedBasicLanguages.has(languageId)) {
      this._requestedBasicLanguages.add(languageId);
      this._onDidRequestBasicLanguageFeatures.fire(languageId);
    }
  }
  requestRichLanguageFeatures(languageId) {
    if (!this._requestedRichLanguages.has(languageId)) {
      this._requestedRichLanguages.add(languageId);
      this.requestBasicLanguageFeatures(languageId);
      TokenizationRegistry2.getOrCreate(languageId);
      this._onDidRequestRichLanguageFeatures.fire(languageId);
    }
  }
}
LanguageService.instanceCount = 0;
class LanguageSelection {
  constructor(_onDidChangeLanguages, _selector2) {
    this._onDidChangeLanguages = _onDidChangeLanguages;
    this._selector = _selector2;
    this._listener = null;
    this._emitter = null;
    this.languageId = this._selector();
  }
  _dispose() {
    if (this._listener) {
      this._listener.dispose();
      this._listener = null;
    }
    if (this._emitter) {
      this._emitter.dispose();
      this._emitter = null;
    }
  }
  get onDidChange() {
    if (!this._listener) {
      this._listener = this._onDidChangeLanguages(() => this._evaluate());
    }
    if (!this._emitter) {
      this._emitter = new Emitter$1({
        onDidRemoveLastListener: () => {
          this._dispose();
        }
      });
    }
    return this._emitter.event;
  }
  _evaluate() {
    var _a2;
    const languageId = this._selector();
    if (languageId === this.languageId) {
      return;
    }
    this.languageId = languageId;
    (_a2 = this._emitter) === null || _a2 === void 0 ? void 0 : _a2.fire(this.languageId);
  }
}
const MENU_MNEMONIC_REGEX = /\(&([^\s&])\)|(^|[^&])&([^\s&])/;
const MENU_ESCAPED_MNEMONIC_REGEX = /(&amp;)?(&amp;)([^\s&])/g;
var Direction;
(function(Direction2) {
  Direction2[Direction2["Right"] = 0] = "Right";
  Direction2[Direction2["Left"] = 1] = "Left";
})(Direction || (Direction = {}));
class Menu extends ActionBar {
  constructor(container2, actions, options, menuStyles) {
    container2.classList.add("monaco-menu-container");
    container2.setAttribute("role", "presentation");
    const menuElement = document.createElement("div");
    menuElement.classList.add("monaco-menu");
    menuElement.setAttribute("role", "presentation");
    super(menuElement, {
      orientation: 1,
      actionViewItemProvider: (action) => this.doGetActionViewItem(action, options, parentData),
      context: options.context,
      actionRunner: options.actionRunner,
      ariaLabel: options.ariaLabel,
      ariaRole: "menu",
      focusOnlyEnabledItems: true,
      triggerKeys: { keys: [3, ...isMacintosh || isLinux ? [
        10
        /* KeyCode.Space */
      ] : []], keyDown: true }
    });
    this.menuStyles = menuStyles;
    this.menuElement = menuElement;
    this.actionsList.tabIndex = 0;
    this.menuDisposables = this._register(new DisposableStore());
    this.initializeOrUpdateStyleSheet(container2, menuStyles);
    this._register(Gesture.addTarget(menuElement));
    addDisposableListener(menuElement, EventType$1.KEY_DOWN, (e) => {
      const event = new StandardKeyboardEvent(e);
      if (event.equals(
        2
        /* KeyCode.Tab */
      )) {
        e.preventDefault();
      }
    });
    if (options.enableMnemonics) {
      this.menuDisposables.add(addDisposableListener(menuElement, EventType$1.KEY_DOWN, (e) => {
        const key = e.key.toLocaleLowerCase();
        if (this.mnemonics.has(key)) {
          EventHelper.stop(e, true);
          const actions2 = this.mnemonics.get(key);
          if (actions2.length === 1) {
            if (actions2[0] instanceof SubmenuMenuActionViewItem && actions2[0].container) {
              this.focusItemByElement(actions2[0].container);
            }
            actions2[0].onClick(e);
          }
          if (actions2.length > 1) {
            const action = actions2.shift();
            if (action && action.container) {
              this.focusItemByElement(action.container);
              actions2.push(action);
            }
            this.mnemonics.set(key, actions2);
          }
        }
      }));
    }
    if (isLinux) {
      this._register(addDisposableListener(menuElement, EventType$1.KEY_DOWN, (e) => {
        const event = new StandardKeyboardEvent(e);
        if (event.equals(
          14
          /* KeyCode.Home */
        ) || event.equals(
          11
          /* KeyCode.PageUp */
        )) {
          this.focusedItem = this.viewItems.length - 1;
          this.focusNext();
          EventHelper.stop(e, true);
        } else if (event.equals(
          13
          /* KeyCode.End */
        ) || event.equals(
          12
          /* KeyCode.PageDown */
        )) {
          this.focusedItem = 0;
          this.focusPrevious();
          EventHelper.stop(e, true);
        }
      }));
    }
    this._register(addDisposableListener(this.domNode, EventType$1.MOUSE_OUT, (e) => {
      const relatedTarget = e.relatedTarget;
      if (!isAncestor$1(relatedTarget, this.domNode)) {
        this.focusedItem = void 0;
        this.updateFocus();
        e.stopPropagation();
      }
    }));
    this._register(addDisposableListener(this.actionsList, EventType$1.MOUSE_OVER, (e) => {
      let target = e.target;
      if (!target || !isAncestor$1(target, this.actionsList) || target === this.actionsList) {
        return;
      }
      while (target.parentElement !== this.actionsList && target.parentElement !== null) {
        target = target.parentElement;
      }
      if (target.classList.contains("action-item")) {
        const lastFocusedItem = this.focusedItem;
        this.setFocusedItem(target);
        if (lastFocusedItem !== this.focusedItem) {
          this.updateFocus();
        }
      }
    }));
    this._register(Gesture.addTarget(this.actionsList));
    this._register(addDisposableListener(this.actionsList, EventType.Tap, (e) => {
      let target = e.initialTarget;
      if (!target || !isAncestor$1(target, this.actionsList) || target === this.actionsList) {
        return;
      }
      while (target.parentElement !== this.actionsList && target.parentElement !== null) {
        target = target.parentElement;
      }
      if (target.classList.contains("action-item")) {
        const lastFocusedItem = this.focusedItem;
        this.setFocusedItem(target);
        if (lastFocusedItem !== this.focusedItem) {
          this.updateFocus();
        }
      }
    }));
    const parentData = {
      parent: this
    };
    this.mnemonics = /* @__PURE__ */ new Map();
    this.scrollableElement = this._register(new DomScrollableElement(menuElement, {
      alwaysConsumeMouseWheel: true,
      horizontal: 2,
      vertical: 3,
      verticalScrollbarSize: 7,
      handleMouseWheel: true,
      useShadows: true
    }));
    const scrollElement = this.scrollableElement.getDomNode();
    scrollElement.style.position = "";
    this.styleScrollElement(scrollElement, menuStyles);
    this._register(addDisposableListener(menuElement, EventType.Change, (e) => {
      EventHelper.stop(e, true);
      const scrollTop = this.scrollableElement.getScrollPosition().scrollTop;
      this.scrollableElement.setScrollPosition({ scrollTop: scrollTop - e.translationY });
    }));
    this._register(addDisposableListener(scrollElement, EventType$1.MOUSE_UP, (e) => {
      e.preventDefault();
    }));
    menuElement.style.maxHeight = `${Math.max(10, window.innerHeight - container2.getBoundingClientRect().top - 35)}px`;
    actions = actions.filter((a) => {
      var _a2;
      if ((_a2 = options.submenuIds) === null || _a2 === void 0 ? void 0 : _a2.has(a.id)) {
        console.warn(`Found submenu cycle: ${a.id}`);
        return false;
      }
      return true;
    });
    this.push(actions, { icon: true, label: true, isMenu: true });
    container2.appendChild(this.scrollableElement.getDomNode());
    this.scrollableElement.scanDomNode();
    this.viewItems.filter((item) => !(item instanceof MenuSeparatorActionViewItem)).forEach((item, index, array2) => {
      item.updatePositionInSet(index + 1, array2.length);
    });
  }
  initializeOrUpdateStyleSheet(container2, style2) {
    if (!this.styleSheet) {
      if (isInShadowDOM(container2)) {
        this.styleSheet = createStyleSheet(container2);
      } else {
        if (!Menu.globalStyleSheet) {
          Menu.globalStyleSheet = createStyleSheet();
        }
        this.styleSheet = Menu.globalStyleSheet;
      }
    }
    this.styleSheet.textContent = getMenuWidgetCSS(style2, isInShadowDOM(container2));
  }
  styleScrollElement(scrollElement, style2) {
    var _a2, _b2;
    const fgColor = (_a2 = style2.foregroundColor) !== null && _a2 !== void 0 ? _a2 : "";
    const bgColor = (_b2 = style2.backgroundColor) !== null && _b2 !== void 0 ? _b2 : "";
    const border = style2.borderColor ? `1px solid ${style2.borderColor}` : "";
    const borderRadius = "5px";
    const shadow = style2.shadowColor ? `0 2px 8px ${style2.shadowColor}` : "";
    scrollElement.style.outline = border;
    scrollElement.style.borderRadius = borderRadius;
    scrollElement.style.color = fgColor;
    scrollElement.style.backgroundColor = bgColor;
    scrollElement.style.boxShadow = shadow;
  }
  getContainer() {
    return this.scrollableElement.getDomNode();
  }
  get onScroll() {
    return this.scrollableElement.onScroll;
  }
  focusItemByElement(element) {
    const lastFocusedItem = this.focusedItem;
    this.setFocusedItem(element);
    if (lastFocusedItem !== this.focusedItem) {
      this.updateFocus();
    }
  }
  setFocusedItem(element) {
    for (let i = 0; i < this.actionsList.children.length; i++) {
      const elem = this.actionsList.children[i];
      if (element === elem) {
        this.focusedItem = i;
        break;
      }
    }
  }
  updateFocus(fromRight) {
    super.updateFocus(fromRight, true, true);
    if (typeof this.focusedItem !== "undefined") {
      this.scrollableElement.setScrollPosition({
        scrollTop: Math.round(this.menuElement.scrollTop)
      });
    }
  }
  doGetActionViewItem(action, options, parentData) {
    if (action instanceof Separator) {
      return new MenuSeparatorActionViewItem(options.context, action, { icon: true }, this.menuStyles);
    } else if (action instanceof SubmenuAction) {
      const menuActionViewItem = new SubmenuMenuActionViewItem(action, action.actions, parentData, Object.assign(Object.assign({}, options), { submenuIds: /* @__PURE__ */ new Set([...options.submenuIds || [], action.id]) }), this.menuStyles);
      if (options.enableMnemonics) {
        const mnemonic = menuActionViewItem.getMnemonic();
        if (mnemonic && menuActionViewItem.isEnabled()) {
          let actionViewItems = [];
          if (this.mnemonics.has(mnemonic)) {
            actionViewItems = this.mnemonics.get(mnemonic);
          }
          actionViewItems.push(menuActionViewItem);
          this.mnemonics.set(mnemonic, actionViewItems);
        }
      }
      return menuActionViewItem;
    } else {
      const menuItemOptions = { enableMnemonics: options.enableMnemonics, useEventAsContext: options.useEventAsContext };
      if (options.getKeyBinding) {
        const keybinding = options.getKeyBinding(action);
        if (keybinding) {
          const keybindingLabel2 = keybinding.getLabel();
          if (keybindingLabel2) {
            menuItemOptions.keybinding = keybindingLabel2;
          }
        }
      }
      const menuActionViewItem = new BaseMenuActionViewItem(options.context, action, menuItemOptions, this.menuStyles);
      if (options.enableMnemonics) {
        const mnemonic = menuActionViewItem.getMnemonic();
        if (mnemonic && menuActionViewItem.isEnabled()) {
          let actionViewItems = [];
          if (this.mnemonics.has(mnemonic)) {
            actionViewItems = this.mnemonics.get(mnemonic);
          }
          actionViewItems.push(menuActionViewItem);
          this.mnemonics.set(mnemonic, actionViewItems);
        }
      }
      return menuActionViewItem;
    }
  }
}
class BaseMenuActionViewItem extends BaseActionViewItem {
  constructor(ctx, action, options, menuStyle) {
    options.isMenu = true;
    super(action, action, options);
    this.menuStyle = menuStyle;
    this.options = options;
    this.options.icon = options.icon !== void 0 ? options.icon : false;
    this.options.label = options.label !== void 0 ? options.label : true;
    this.cssClass = "";
    if (this.options.label && options.enableMnemonics) {
      const label = this.action.label;
      if (label) {
        const matches = MENU_MNEMONIC_REGEX.exec(label);
        if (matches) {
          this.mnemonic = (!!matches[1] ? matches[1] : matches[3]).toLocaleLowerCase();
        }
      }
    }
    this.runOnceToEnableMouseUp = new RunOnceScheduler(() => {
      if (!this.element) {
        return;
      }
      this._register(addDisposableListener(this.element, EventType$1.MOUSE_UP, (e) => {
        EventHelper.stop(e, true);
        if (isFirefox$1) {
          const mouseEvent = new StandardMouseEvent(e);
          if (mouseEvent.rightButton) {
            return;
          }
          this.onClick(e);
        } else {
          setTimeout(() => {
            this.onClick(e);
          }, 0);
        }
      }));
      this._register(addDisposableListener(this.element, EventType$1.CONTEXT_MENU, (e) => {
        EventHelper.stop(e, true);
      }));
    }, 100);
    this._register(this.runOnceToEnableMouseUp);
  }
  render(container2) {
    super.render(container2);
    if (!this.element) {
      return;
    }
    this.container = container2;
    this.item = append$1(this.element, $$d("a.action-menu-item"));
    if (this._action.id === Separator.ID) {
      this.item.setAttribute("role", "presentation");
    } else {
      this.item.setAttribute("role", "menuitem");
      if (this.mnemonic) {
        this.item.setAttribute("aria-keyshortcuts", `${this.mnemonic}`);
      }
    }
    this.check = append$1(this.item, $$d("span.menu-item-check" + ThemeIcon.asCSSSelector(Codicon.menuSelection)));
    this.check.setAttribute("role", "none");
    this.label = append$1(this.item, $$d("span.action-label"));
    if (this.options.label && this.options.keybinding) {
      append$1(this.item, $$d("span.keybinding")).textContent = this.options.keybinding;
    }
    this.runOnceToEnableMouseUp.schedule();
    this.updateClass();
    this.updateLabel();
    this.updateTooltip();
    this.updateEnabled();
    this.updateChecked();
    this.applyStyle();
  }
  blur() {
    super.blur();
    this.applyStyle();
  }
  focus() {
    var _a2;
    super.focus();
    (_a2 = this.item) === null || _a2 === void 0 ? void 0 : _a2.focus();
    this.applyStyle();
  }
  updatePositionInSet(pos, setSize) {
    if (this.item) {
      this.item.setAttribute("aria-posinset", `${pos}`);
      this.item.setAttribute("aria-setsize", `${setSize}`);
    }
  }
  updateLabel() {
    var _a2;
    if (!this.label) {
      return;
    }
    if (this.options.label) {
      clearNode(this.label);
      let label = stripIcons(this.action.label);
      if (label) {
        const cleanLabel = cleanMnemonic(label);
        if (!this.options.enableMnemonics) {
          label = cleanLabel;
        }
        this.label.setAttribute("aria-label", cleanLabel.replace(/&&/g, "&"));
        const matches = MENU_MNEMONIC_REGEX.exec(label);
        if (matches) {
          label = escape$1(label);
          MENU_ESCAPED_MNEMONIC_REGEX.lastIndex = 0;
          let escMatch = MENU_ESCAPED_MNEMONIC_REGEX.exec(label);
          while (escMatch && escMatch[1]) {
            escMatch = MENU_ESCAPED_MNEMONIC_REGEX.exec(label);
          }
          const replaceDoubleEscapes = (str2) => str2.replace(/&amp;&amp;/g, "&amp;");
          if (escMatch) {
            this.label.append(ltrim(replaceDoubleEscapes(label.substr(0, escMatch.index)), " "), $$d("u", { "aria-hidden": "true" }, escMatch[3]), rtrim(replaceDoubleEscapes(label.substr(escMatch.index + escMatch[0].length)), " "));
          } else {
            this.label.innerText = replaceDoubleEscapes(label).trim();
          }
          (_a2 = this.item) === null || _a2 === void 0 ? void 0 : _a2.setAttribute("aria-keyshortcuts", (!!matches[1] ? matches[1] : matches[3]).toLocaleLowerCase());
        } else {
          this.label.innerText = label.replace(/&&/g, "&").trim();
        }
      }
    }
  }
  updateTooltip() {
  }
  updateClass() {
    if (this.cssClass && this.item) {
      this.item.classList.remove(...this.cssClass.split(" "));
    }
    if (this.options.icon && this.label) {
      this.cssClass = this.action.class || "";
      this.label.classList.add("icon");
      if (this.cssClass) {
        this.label.classList.add(...this.cssClass.split(" "));
      }
      this.updateEnabled();
    } else if (this.label) {
      this.label.classList.remove("icon");
    }
  }
  updateEnabled() {
    if (this.action.enabled) {
      if (this.element) {
        this.element.classList.remove("disabled");
        this.element.removeAttribute("aria-disabled");
      }
      if (this.item) {
        this.item.classList.remove("disabled");
        this.item.removeAttribute("aria-disabled");
        this.item.tabIndex = 0;
      }
    } else {
      if (this.element) {
        this.element.classList.add("disabled");
        this.element.setAttribute("aria-disabled", "true");
      }
      if (this.item) {
        this.item.classList.add("disabled");
        this.item.setAttribute("aria-disabled", "true");
      }
    }
  }
  updateChecked() {
    if (!this.item) {
      return;
    }
    const checked2 = this.action.checked;
    this.item.classList.toggle("checked", !!checked2);
    if (checked2 !== void 0) {
      this.item.setAttribute("role", "menuitemcheckbox");
      this.item.setAttribute("aria-checked", checked2 ? "true" : "false");
    } else {
      this.item.setAttribute("role", "menuitem");
      this.item.setAttribute("aria-checked", "");
    }
  }
  getMnemonic() {
    return this.mnemonic;
  }
  applyStyle() {
    const isSelected = this.element && this.element.classList.contains("focused");
    const fgColor = isSelected && this.menuStyle.selectionForegroundColor ? this.menuStyle.selectionForegroundColor : this.menuStyle.foregroundColor;
    const bgColor = isSelected && this.menuStyle.selectionBackgroundColor ? this.menuStyle.selectionBackgroundColor : void 0;
    const outline = isSelected && this.menuStyle.selectionBorderColor ? `1px solid ${this.menuStyle.selectionBorderColor}` : "";
    const outlineOffset = isSelected && this.menuStyle.selectionBorderColor ? `-1px` : "";
    if (this.item) {
      this.item.style.color = fgColor !== null && fgColor !== void 0 ? fgColor : "";
      this.item.style.backgroundColor = bgColor !== null && bgColor !== void 0 ? bgColor : "";
      this.item.style.outline = outline;
      this.item.style.outlineOffset = outlineOffset;
    }
    if (this.check) {
      this.check.style.color = fgColor !== null && fgColor !== void 0 ? fgColor : "";
    }
  }
}
class SubmenuMenuActionViewItem extends BaseMenuActionViewItem {
  constructor(action, submenuActions, parentData, submenuOptions, menuStyles) {
    super(action, action, submenuOptions, menuStyles);
    this.submenuActions = submenuActions;
    this.parentData = parentData;
    this.submenuOptions = submenuOptions;
    this.mysubmenu = null;
    this.submenuDisposables = this._register(new DisposableStore());
    this.mouseOver = false;
    this.expandDirection = submenuOptions && submenuOptions.expandDirection !== void 0 ? submenuOptions.expandDirection : Direction.Right;
    this.showScheduler = new RunOnceScheduler(() => {
      if (this.mouseOver) {
        this.cleanupExistingSubmenu(false);
        this.createSubmenu(false);
      }
    }, 250);
    this.hideScheduler = new RunOnceScheduler(() => {
      if (this.element && (!isAncestor$1(getActiveElement(), this.element) && this.parentData.submenu === this.mysubmenu)) {
        this.parentData.parent.focus(false);
        this.cleanupExistingSubmenu(true);
      }
    }, 750);
  }
  render(container2) {
    super.render(container2);
    if (!this.element) {
      return;
    }
    if (this.item) {
      this.item.classList.add("monaco-submenu-item");
      this.item.tabIndex = 0;
      this.item.setAttribute("aria-haspopup", "true");
      this.updateAriaExpanded("false");
      this.submenuIndicator = append$1(this.item, $$d("span.submenu-indicator" + ThemeIcon.asCSSSelector(Codicon.menuSubmenu)));
      this.submenuIndicator.setAttribute("aria-hidden", "true");
    }
    this._register(addDisposableListener(this.element, EventType$1.KEY_UP, (e) => {
      const event = new StandardKeyboardEvent(e);
      if (event.equals(
        17
        /* KeyCode.RightArrow */
      ) || event.equals(
        3
        /* KeyCode.Enter */
      )) {
        EventHelper.stop(e, true);
        this.createSubmenu(true);
      }
    }));
    this._register(addDisposableListener(this.element, EventType$1.KEY_DOWN, (e) => {
      const event = new StandardKeyboardEvent(e);
      if (getActiveElement() === this.item) {
        if (event.equals(
          17
          /* KeyCode.RightArrow */
        ) || event.equals(
          3
          /* KeyCode.Enter */
        )) {
          EventHelper.stop(e, true);
        }
      }
    }));
    this._register(addDisposableListener(this.element, EventType$1.MOUSE_OVER, (e) => {
      if (!this.mouseOver) {
        this.mouseOver = true;
        this.showScheduler.schedule();
      }
    }));
    this._register(addDisposableListener(this.element, EventType$1.MOUSE_LEAVE, (e) => {
      this.mouseOver = false;
    }));
    this._register(addDisposableListener(this.element, EventType$1.FOCUS_OUT, (e) => {
      if (this.element && !isAncestor$1(getActiveElement(), this.element)) {
        this.hideScheduler.schedule();
      }
    }));
    this._register(this.parentData.parent.onScroll(() => {
      if (this.parentData.submenu === this.mysubmenu) {
        this.parentData.parent.focus(false);
        this.cleanupExistingSubmenu(true);
      }
    }));
  }
  updateEnabled() {
  }
  onClick(e) {
    EventHelper.stop(e, true);
    this.cleanupExistingSubmenu(false);
    this.createSubmenu(true);
  }
  cleanupExistingSubmenu(force) {
    if (this.parentData.submenu && (force || this.parentData.submenu !== this.mysubmenu)) {
      try {
        this.parentData.submenu.dispose();
      } catch (_a2) {
      }
      this.parentData.submenu = void 0;
      this.updateAriaExpanded("false");
      if (this.submenuContainer) {
        this.submenuDisposables.clear();
        this.submenuContainer = void 0;
      }
    }
  }
  calculateSubmenuMenuLayout(windowDimensions, submenu, entry, expandDirection) {
    const ret = { top: 0, left: 0 };
    ret.left = layout(windowDimensions.width, submenu.width, { position: expandDirection === Direction.Right ? 0 : 1, offset: entry.left, size: entry.width });
    if (ret.left >= entry.left && ret.left < entry.left + entry.width) {
      if (entry.left + 10 + submenu.width <= windowDimensions.width) {
        ret.left = entry.left + 10;
      }
      entry.top += 10;
      entry.height = 0;
    }
    ret.top = layout(windowDimensions.height, submenu.height, { position: 0, offset: entry.top, size: 0 });
    if (ret.top + submenu.height === entry.top && ret.top + entry.height + submenu.height <= windowDimensions.height) {
      ret.top += entry.height;
    }
    return ret;
  }
  createSubmenu(selectFirstItem = true) {
    if (!this.element) {
      return;
    }
    if (!this.parentData.submenu) {
      this.updateAriaExpanded("true");
      this.submenuContainer = append$1(this.element, $$d("div.monaco-submenu"));
      this.submenuContainer.classList.add("menubar-menu-items-holder", "context-view");
      const computedStyles = getComputedStyle(this.parentData.parent.domNode);
      const paddingTop = parseFloat(computedStyles.paddingTop || "0") || 0;
      this.submenuContainer.style.zIndex = "1";
      this.submenuContainer.style.position = "fixed";
      this.submenuContainer.style.top = "0";
      this.submenuContainer.style.left = "0";
      this.parentData.submenu = new Menu(this.submenuContainer, this.submenuActions.length ? this.submenuActions : [new EmptySubmenuAction()], this.submenuOptions, this.menuStyle);
      const entryBox = this.element.getBoundingClientRect();
      const entryBoxUpdated = {
        top: entryBox.top - paddingTop,
        left: entryBox.left,
        height: entryBox.height + 2 * paddingTop,
        width: entryBox.width
      };
      const viewBox = this.submenuContainer.getBoundingClientRect();
      const { top, left } = this.calculateSubmenuMenuLayout(new Dimension(window.innerWidth, window.innerHeight), Dimension.lift(viewBox), entryBoxUpdated, this.expandDirection);
      this.submenuContainer.style.left = `${left - viewBox.left}px`;
      this.submenuContainer.style.top = `${top - viewBox.top}px`;
      this.submenuDisposables.add(addDisposableListener(this.submenuContainer, EventType$1.KEY_UP, (e) => {
        const event = new StandardKeyboardEvent(e);
        if (event.equals(
          15
          /* KeyCode.LeftArrow */
        )) {
          EventHelper.stop(e, true);
          this.parentData.parent.focus();
          this.cleanupExistingSubmenu(true);
        }
      }));
      this.submenuDisposables.add(addDisposableListener(this.submenuContainer, EventType$1.KEY_DOWN, (e) => {
        const event = new StandardKeyboardEvent(e);
        if (event.equals(
          15
          /* KeyCode.LeftArrow */
        )) {
          EventHelper.stop(e, true);
        }
      }));
      this.submenuDisposables.add(this.parentData.submenu.onDidCancel(() => {
        this.parentData.parent.focus();
        this.cleanupExistingSubmenu(true);
      }));
      this.parentData.submenu.focus(selectFirstItem);
      this.mysubmenu = this.parentData.submenu;
    } else {
      this.parentData.submenu.focus(false);
    }
  }
  updateAriaExpanded(value) {
    var _a2;
    if (this.item) {
      (_a2 = this.item) === null || _a2 === void 0 ? void 0 : _a2.setAttribute("aria-expanded", value);
    }
  }
  applyStyle() {
    super.applyStyle();
    const isSelected = this.element && this.element.classList.contains("focused");
    const fgColor = isSelected && this.menuStyle.selectionForegroundColor ? this.menuStyle.selectionForegroundColor : this.menuStyle.foregroundColor;
    if (this.submenuIndicator) {
      this.submenuIndicator.style.color = fgColor !== null && fgColor !== void 0 ? fgColor : "";
    }
  }
  dispose() {
    super.dispose();
    this.hideScheduler.dispose();
    if (this.mysubmenu) {
      this.mysubmenu.dispose();
      this.mysubmenu = null;
    }
    if (this.submenuContainer) {
      this.submenuContainer = void 0;
    }
  }
}
class MenuSeparatorActionViewItem extends ActionViewItem {
  constructor(context, action, options, menuStyles) {
    super(context, action, options);
    this.menuStyles = menuStyles;
  }
  render(container2) {
    super.render(container2);
    if (this.label) {
      this.label.style.borderBottomColor = this.menuStyles.separatorColor ? `${this.menuStyles.separatorColor}` : "";
    }
  }
}
function cleanMnemonic(label) {
  const regex = MENU_MNEMONIC_REGEX;
  const matches = regex.exec(label);
  if (!matches) {
    return label;
  }
  const mnemonicInText = !matches[1];
  return label.replace(regex, mnemonicInText ? "$2$3" : "").trim();
}
function formatRule(c) {
  const fontCharacter = getCodiconFontCharacters()[c.id];
  return `.codicon-${c.id}:before { content: '\\${fontCharacter.toString(16)}'; }`;
}
function getMenuWidgetCSS(style2, isForShadowDom) {
  let result2 = (
    /* css */
    `
.monaco-menu {
	font-size: 13px;
	border-radius: 5px;
	min-width: 160px;
}

${formatRule(Codicon.menuSelection)}
${formatRule(Codicon.menuSubmenu)}

.monaco-menu .monaco-action-bar {
	text-align: right;
	overflow: hidden;
	white-space: nowrap;
}

.monaco-menu .monaco-action-bar .actions-container {
	display: flex;
	margin: 0 auto;
	padding: 0;
	width: 100%;
	justify-content: flex-end;
}

.monaco-menu .monaco-action-bar.vertical .actions-container {
	display: inline-block;
}

.monaco-menu .monaco-action-bar.reverse .actions-container {
	flex-direction: row-reverse;
}

.monaco-menu .monaco-action-bar .action-item {
	cursor: pointer;
	display: inline-block;
	transition: transform 50ms ease;
	position: relative;  /* DO NOT REMOVE - this is the key to preventing the ghosting icon bug in Chrome 42 */
}

.monaco-menu .monaco-action-bar .action-item.disabled {
	cursor: default;
}

.monaco-menu .monaco-action-bar.animated .action-item.active {
	transform: scale(1.272019649, 1.272019649); /* 1.272019649 = √φ */
}

.monaco-menu .monaco-action-bar .action-item .icon,
.monaco-menu .monaco-action-bar .action-item .codicon {
	display: inline-block;
}

.monaco-menu .monaco-action-bar .action-item .codicon {
	display: flex;
	align-items: center;
}

.monaco-menu .monaco-action-bar .action-label {
	font-size: 11px;
	margin-right: 4px;
}

.monaco-menu .monaco-action-bar .action-item.disabled .action-label,
.monaco-menu .monaco-action-bar .action-item.disabled .action-label:hover {
	color: var(--vscode-disabledForeground);
}

/* Vertical actions */

.monaco-menu .monaco-action-bar.vertical {
	text-align: left;
}

.monaco-menu .monaco-action-bar.vertical .action-item {
	display: block;
}

.monaco-menu .monaco-action-bar.vertical .action-label.separator {
	display: block;
	border-bottom: 1px solid var(--vscode-menu-separatorBackground);
	padding-top: 1px;
	padding: 30px;
}

.monaco-menu .secondary-actions .monaco-action-bar .action-label {
	margin-left: 6px;
}

/* Action Items */
.monaco-menu .monaco-action-bar .action-item.select-container {
	overflow: hidden; /* somehow the dropdown overflows its container, we prevent it here to not push */
	flex: 1;
	max-width: 170px;
	min-width: 60px;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 10px;
}

.monaco-menu .monaco-action-bar.vertical {
	margin-left: 0;
	overflow: visible;
}

.monaco-menu .monaco-action-bar.vertical .actions-container {
	display: block;
}

.monaco-menu .monaco-action-bar.vertical .action-item {
	padding: 0;
	transform: none;
	display: flex;
}

.monaco-menu .monaco-action-bar.vertical .action-item.active {
	transform: none;
}

.monaco-menu .monaco-action-bar.vertical .action-menu-item {
	flex: 1 1 auto;
	display: flex;
	height: 2em;
	align-items: center;
	position: relative;
	margin: 0 4px;
	border-radius: 4px;
}

.monaco-menu .monaco-action-bar.vertical .action-menu-item:hover .keybinding,
.monaco-menu .monaco-action-bar.vertical .action-menu-item:focus .keybinding {
	opacity: unset;
}

.monaco-menu .monaco-action-bar.vertical .action-label {
	flex: 1 1 auto;
	text-decoration: none;
	padding: 0 1em;
	background: none;
	font-size: 12px;
	line-height: 1;
}

.monaco-menu .monaco-action-bar.vertical .keybinding,
.monaco-menu .monaco-action-bar.vertical .submenu-indicator {
	display: inline-block;
	flex: 2 1 auto;
	padding: 0 1em;
	text-align: right;
	font-size: 12px;
	line-height: 1;
}

.monaco-menu .monaco-action-bar.vertical .submenu-indicator {
	height: 100%;
}

.monaco-menu .monaco-action-bar.vertical .submenu-indicator.codicon {
	font-size: 16px !important;
	display: flex;
	align-items: center;
}

.monaco-menu .monaco-action-bar.vertical .submenu-indicator.codicon::before {
	margin-left: auto;
	margin-right: -20px;
}

.monaco-menu .monaco-action-bar.vertical .action-item.disabled .keybinding,
.monaco-menu .monaco-action-bar.vertical .action-item.disabled .submenu-indicator {
	opacity: 0.4;
}

.monaco-menu .monaco-action-bar.vertical .action-label:not(.separator) {
	display: inline-block;
	box-sizing: border-box;
	margin: 0;
}

.monaco-menu .monaco-action-bar.vertical .action-item {
	position: static;
	overflow: visible;
}

.monaco-menu .monaco-action-bar.vertical .action-item .monaco-submenu {
	position: absolute;
}

.monaco-menu .monaco-action-bar.vertical .action-label.separator {
	width: 100%;
	height: 0px !important;
	opacity: 1;
}

.monaco-menu .monaco-action-bar.vertical .action-label.separator.text {
	padding: 0.7em 1em 0.1em 1em;
	font-weight: bold;
	opacity: 1;
}

.monaco-menu .monaco-action-bar.vertical .action-label:hover {
	color: inherit;
}

.monaco-menu .monaco-action-bar.vertical .menu-item-check {
	position: absolute;
	visibility: hidden;
	width: 1em;
	height: 100%;
}

.monaco-menu .monaco-action-bar.vertical .action-menu-item.checked .menu-item-check {
	visibility: visible;
	display: flex;
	align-items: center;
	justify-content: center;
}

/* Context Menu */

.context-view.monaco-menu-container {
	outline: 0;
	border: none;
	animation: fadeIn 0.083s linear;
	-webkit-app-region: no-drag;
}

.context-view.monaco-menu-container :focus,
.context-view.monaco-menu-container .monaco-action-bar.vertical:focus,
.context-view.monaco-menu-container .monaco-action-bar.vertical :focus {
	outline: 0;
}

.hc-black .context-view.monaco-menu-container,
.hc-light .context-view.monaco-menu-container,
:host-context(.hc-black) .context-view.monaco-menu-container,
:host-context(.hc-light) .context-view.monaco-menu-container {
	box-shadow: none;
}

.hc-black .monaco-menu .monaco-action-bar.vertical .action-item.focused,
.hc-light .monaco-menu .monaco-action-bar.vertical .action-item.focused,
:host-context(.hc-black) .monaco-menu .monaco-action-bar.vertical .action-item.focused,
:host-context(.hc-light) .monaco-menu .monaco-action-bar.vertical .action-item.focused {
	background: none;
}

/* Vertical Action Bar Styles */

.monaco-menu .monaco-action-bar.vertical {
	padding: 4px 0;
}

.monaco-menu .monaco-action-bar.vertical .action-menu-item {
	height: 2em;
}

.monaco-menu .monaco-action-bar.vertical .action-label:not(.separator),
.monaco-menu .monaco-action-bar.vertical .keybinding {
	font-size: inherit;
	padding: 0 2em;
}

.monaco-menu .monaco-action-bar.vertical .menu-item-check {
	font-size: inherit;
	width: 2em;
}

.monaco-menu .monaco-action-bar.vertical .action-label.separator {
	font-size: inherit;
	margin: 5px 0 !important;
	padding: 0;
	border-radius: 0;
}

.linux .monaco-menu .monaco-action-bar.vertical .action-label.separator,
:host-context(.linux) .monaco-menu .monaco-action-bar.vertical .action-label.separator {
	margin-left: 0;
	margin-right: 0;
}

.monaco-menu .monaco-action-bar.vertical .submenu-indicator {
	font-size: 60%;
	padding: 0 1.8em;
}

.linux .monaco-menu .monaco-action-bar.vertical .submenu-indicator {
:host-context(.linux) .monaco-menu .monaco-action-bar.vertical .submenu-indicator {
	height: 100%;
	mask-size: 10px 10px;
	-webkit-mask-size: 10px 10px;
}

.monaco-menu .action-item {
	cursor: default;
}`
  );
  if (isForShadowDom) {
    result2 += `
			/* Arrows */
			.monaco-scrollable-element > .scrollbar > .scra {
				cursor: pointer;
				font-size: 11px !important;
			}

			.monaco-scrollable-element > .visible {
				opacity: 1;

				/* Background rule added for IE9 - to allow clicks on dom node */
				background:rgba(0,0,0,0);

				transition: opacity 100ms linear;
			}
			.monaco-scrollable-element > .invisible {
				opacity: 0;
				pointer-events: none;
			}
			.monaco-scrollable-element > .invisible.fade {
				transition: opacity 800ms linear;
			}

			/* Scrollable Content Inset Shadow */
			.monaco-scrollable-element > .shadow {
				position: absolute;
				display: none;
			}
			.monaco-scrollable-element > .shadow.top {
				display: block;
				top: 0;
				left: 3px;
				height: 3px;
				width: 100%;
			}
			.monaco-scrollable-element > .shadow.left {
				display: block;
				top: 3px;
				left: 0;
				height: 100%;
				width: 3px;
			}
			.monaco-scrollable-element > .shadow.top-left-corner {
				display: block;
				top: 0;
				left: 0;
				height: 3px;
				width: 3px;
			}
		`;
    const scrollbarShadowColor = style2.scrollbarShadow;
    if (scrollbarShadowColor) {
      result2 += `
				.monaco-scrollable-element > .shadow.top {
					box-shadow: ${scrollbarShadowColor} 0 6px 6px -6px inset;
				}

				.monaco-scrollable-element > .shadow.left {
					box-shadow: ${scrollbarShadowColor} 6px 0 6px -6px inset;
				}

				.monaco-scrollable-element > .shadow.top.left {
					box-shadow: ${scrollbarShadowColor} 6px 6px 6px -6px inset;
				}
			`;
    }
    const scrollbarSliderBackgroundColor = style2.scrollbarSliderBackground;
    if (scrollbarSliderBackgroundColor) {
      result2 += `
				.monaco-scrollable-element > .scrollbar > .slider {
					background: ${scrollbarSliderBackgroundColor};
				}
			`;
    }
    const scrollbarSliderHoverBackgroundColor = style2.scrollbarSliderHoverBackground;
    if (scrollbarSliderHoverBackgroundColor) {
      result2 += `
				.monaco-scrollable-element > .scrollbar > .slider:hover {
					background: ${scrollbarSliderHoverBackgroundColor};
				}
			`;
    }
    const scrollbarSliderActiveBackgroundColor = style2.scrollbarSliderActiveBackground;
    if (scrollbarSliderActiveBackgroundColor) {
      result2 += `
				.monaco-scrollable-element > .scrollbar > .slider.active {
					background: ${scrollbarSliderActiveBackgroundColor};
				}
			`;
    }
  }
  return result2;
}
class ContextMenuHandler {
  constructor(contextViewService, telemetryService, notificationService, keybindingService) {
    this.contextViewService = contextViewService;
    this.telemetryService = telemetryService;
    this.notificationService = notificationService;
    this.keybindingService = keybindingService;
    this.focusToReturn = null;
    this.lastContainer = null;
    this.block = null;
    this.blockDisposable = null;
    this.options = { blockMouse: true };
  }
  configure(options) {
    this.options = options;
  }
  showContextMenu(delegate) {
    const actions = delegate.getActions();
    if (!actions.length) {
      return;
    }
    this.focusToReturn = document.activeElement;
    let menu;
    const shadowRootElement = isHTMLElement(delegate.domForShadowRoot) ? delegate.domForShadowRoot : void 0;
    this.contextViewService.showContextView({
      getAnchor: () => delegate.getAnchor(),
      canRelayout: false,
      anchorAlignment: delegate.anchorAlignment,
      anchorAxisAlignment: delegate.anchorAxisAlignment,
      render: (container2) => {
        var _a2;
        this.lastContainer = container2;
        const className3 = delegate.getMenuClassName ? delegate.getMenuClassName() : "";
        if (className3) {
          container2.className += " " + className3;
        }
        if (this.options.blockMouse) {
          this.block = container2.appendChild($$d(".context-view-block"));
          this.block.style.position = "fixed";
          this.block.style.cursor = "initial";
          this.block.style.left = "0";
          this.block.style.top = "0";
          this.block.style.width = "100%";
          this.block.style.height = "100%";
          this.block.style.zIndex = "-1";
          (_a2 = this.blockDisposable) === null || _a2 === void 0 ? void 0 : _a2.dispose();
          this.blockDisposable = addDisposableListener(this.block, EventType$1.MOUSE_DOWN, (e) => e.stopPropagation());
        }
        const menuDisposables = new DisposableStore();
        const actionRunner = delegate.actionRunner || new ActionRunner();
        actionRunner.onWillRun((evt) => this.onActionRun(evt, !delegate.skipTelemetry), this, menuDisposables);
        actionRunner.onDidRun(this.onDidActionRun, this, menuDisposables);
        menu = new Menu(container2, actions, {
          actionViewItemProvider: delegate.getActionViewItem,
          context: delegate.getActionsContext ? delegate.getActionsContext() : null,
          actionRunner,
          getKeyBinding: delegate.getKeyBinding ? delegate.getKeyBinding : (action) => this.keybindingService.lookupKeybinding(action.id)
        }, defaultMenuStyles);
        menu.onDidCancel(() => this.contextViewService.hideContextView(true), null, menuDisposables);
        menu.onDidBlur(() => this.contextViewService.hideContextView(true), null, menuDisposables);
        menuDisposables.add(addDisposableListener(window, EventType$1.BLUR, () => this.contextViewService.hideContextView(true)));
        menuDisposables.add(addDisposableListener(window, EventType$1.MOUSE_DOWN, (e) => {
          if (e.defaultPrevented) {
            return;
          }
          const event = new StandardMouseEvent(e);
          let element = event.target;
          if (event.rightButton) {
            return;
          }
          while (element) {
            if (element === container2) {
              return;
            }
            element = element.parentElement;
          }
          this.contextViewService.hideContextView(true);
        }));
        return combinedDisposable(menuDisposables, menu);
      },
      focus: () => {
        menu === null || menu === void 0 ? void 0 : menu.focus(!!delegate.autoSelectFirstItem);
      },
      onHide: (didCancel) => {
        var _a2, _b2, _c2;
        (_a2 = delegate.onHide) === null || _a2 === void 0 ? void 0 : _a2.call(delegate, !!didCancel);
        if (this.block) {
          this.block.remove();
          this.block = null;
        }
        (_b2 = this.blockDisposable) === null || _b2 === void 0 ? void 0 : _b2.dispose();
        this.blockDisposable = null;
        if (!!this.lastContainer && (getActiveElement() === this.lastContainer || isAncestor$1(getActiveElement(), this.lastContainer))) {
          (_c2 = this.focusToReturn) === null || _c2 === void 0 ? void 0 : _c2.focus();
        }
        this.lastContainer = null;
      }
    }, shadowRootElement, !!shadowRootElement);
  }
  onActionRun(e, logTelemetry) {
    if (logTelemetry) {
      this.telemetryService.publicLog2("workbenchActionExecuted", { id: e.action.id, from: "contextMenu" });
    }
    this.contextViewService.hideContextView(false);
  }
  onDidActionRun(e) {
    if (e.error && !isCancellationError(e.error)) {
      this.notificationService.error(e.error);
    }
  }
}
var __decorate$j = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$h = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let ContextMenuService = class ContextMenuService2 extends Disposable {
  get contextMenuHandler() {
    if (!this._contextMenuHandler) {
      this._contextMenuHandler = new ContextMenuHandler(this.contextViewService, this.telemetryService, this.notificationService, this.keybindingService);
    }
    return this._contextMenuHandler;
  }
  constructor(telemetryService, notificationService, contextViewService, keybindingService, menuService, contextKeyService) {
    super();
    this.telemetryService = telemetryService;
    this.notificationService = notificationService;
    this.contextViewService = contextViewService;
    this.keybindingService = keybindingService;
    this.menuService = menuService;
    this.contextKeyService = contextKeyService;
    this._contextMenuHandler = void 0;
    this._onDidShowContextMenu = this._store.add(new Emitter$1());
    this._onDidHideContextMenu = this._store.add(new Emitter$1());
  }
  configure(options) {
    this.contextMenuHandler.configure(options);
  }
  // ContextMenu
  showContextMenu(delegate) {
    delegate = ContextMenuMenuDelegate.transform(delegate, this.menuService, this.contextKeyService);
    this.contextMenuHandler.showContextMenu(Object.assign(Object.assign({}, delegate), { onHide: (didCancel) => {
      var _a2;
      (_a2 = delegate.onHide) === null || _a2 === void 0 ? void 0 : _a2.call(delegate, didCancel);
      this._onDidHideContextMenu.fire();
    } }));
    ModifierKeyEmitter.getInstance().resetKeyStatus();
    this._onDidShowContextMenu.fire();
  }
};
ContextMenuService = __decorate$j([
  __param$h(0, ITelemetryService),
  __param$h(1, INotificationService),
  __param$h(2, IContextViewService),
  __param$h(3, IKeybindingService),
  __param$h(4, IMenuService),
  __param$h(5, IContextKeyService)
], ContextMenuService);
var ContextMenuMenuDelegate;
(function(ContextMenuMenuDelegate2) {
  function is(thing) {
    return thing && thing.menuId instanceof MenuId;
  }
  function transform(delegate, menuService, globalContextKeyService) {
    if (!is(delegate)) {
      return delegate;
    }
    const { menuId, menuActionOptions, contextKeyService } = delegate;
    return Object.assign(Object.assign({}, delegate), { getActions: () => {
      const target = [];
      if (menuId) {
        const menu = menuService.createMenu(menuId, contextKeyService !== null && contextKeyService !== void 0 ? contextKeyService : globalContextKeyService);
        createAndFillInContextMenuActions(menu, menuActionOptions, target);
        menu.dispose();
      }
      if (!delegate.getActions) {
        return target;
      } else {
        return Separator.join(delegate.getActions(), target);
      }
    } });
  }
  ContextMenuMenuDelegate2.transform = transform;
})(ContextMenuMenuDelegate || (ContextMenuMenuDelegate = {}));
var EditorOpenSource;
(function(EditorOpenSource2) {
  EditorOpenSource2[EditorOpenSource2["API"] = 0] = "API";
  EditorOpenSource2[EditorOpenSource2["USER"] = 1] = "USER";
})(EditorOpenSource || (EditorOpenSource = {}));
var __decorate$i = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$g = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$9 = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
let CommandOpener = class CommandOpener2 {
  constructor(_commandService) {
    this._commandService = _commandService;
  }
  open(target, options) {
    return __awaiter$9(this, void 0, void 0, function* () {
      if (!matchesScheme(target, Schemas.command)) {
        return false;
      }
      if (!(options === null || options === void 0 ? void 0 : options.allowCommands)) {
        return true;
      }
      if (typeof target === "string") {
        target = URI.parse(target);
      }
      if (Array.isArray(options.allowCommands)) {
        if (!options.allowCommands.includes(target.path)) {
          return true;
        }
      }
      let args = [];
      try {
        args = parse$b(decodeURIComponent(target.query));
      } catch (_a2) {
        try {
          args = parse$b(target.query);
        } catch (_b2) {
        }
      }
      if (!Array.isArray(args)) {
        args = [args];
      }
      yield this._commandService.executeCommand(target.path, ...args);
      return true;
    });
  }
};
CommandOpener = __decorate$i([
  __param$g(0, ICommandService)
], CommandOpener);
let EditorOpener = class EditorOpener2 {
  constructor(_editorService) {
    this._editorService = _editorService;
  }
  open(target, options) {
    return __awaiter$9(this, void 0, void 0, function* () {
      if (typeof target === "string") {
        target = URI.parse(target);
      }
      const { selection, uri } = extractSelection(target);
      target = uri;
      if (target.scheme === Schemas.file) {
        target = normalizePath(target);
      }
      yield this._editorService.openCodeEditor({
        resource: target,
        options: Object.assign({ selection, source: (options === null || options === void 0 ? void 0 : options.fromUserGesture) ? EditorOpenSource.USER : EditorOpenSource.API }, options === null || options === void 0 ? void 0 : options.editorOptions)
      }, this._editorService.getFocusedCodeEditor(), options === null || options === void 0 ? void 0 : options.openToSide);
      return true;
    });
  }
};
EditorOpener = __decorate$i([
  __param$g(0, ICodeEditorService)
], EditorOpener);
let OpenerService = class OpenerService2 {
  constructor(editorService, commandService) {
    this._openers = new LinkedList();
    this._validators = new LinkedList();
    this._resolvers = new LinkedList();
    this._resolvedUriTargets = new ResourceMap((uri) => uri.with({ path: null, fragment: null, query: null }).toString());
    this._externalOpeners = new LinkedList();
    this._defaultExternalOpener = {
      openExternal: (href) => __awaiter$9(this, void 0, void 0, function* () {
        if (matchesSomeScheme(href, Schemas.http, Schemas.https)) {
          windowOpenNoOpener(href);
        } else {
          window.location.href = href;
        }
        return true;
      })
    };
    this._openers.push({
      open: (target, options) => __awaiter$9(this, void 0, void 0, function* () {
        if ((options === null || options === void 0 ? void 0 : options.openExternal) || matchesSomeScheme(target, Schemas.mailto, Schemas.http, Schemas.https, Schemas.vsls)) {
          yield this._doOpenExternal(target, options);
          return true;
        }
        return false;
      })
    });
    this._openers.push(new CommandOpener(commandService));
    this._openers.push(new EditorOpener(editorService));
  }
  registerOpener(opener) {
    const remove2 = this._openers.unshift(opener);
    return { dispose: remove2 };
  }
  open(target, options) {
    var _a2;
    return __awaiter$9(this, void 0, void 0, function* () {
      const targetURI = typeof target === "string" ? URI.parse(target) : target;
      const validationTarget = (_a2 = this._resolvedUriTargets.get(targetURI)) !== null && _a2 !== void 0 ? _a2 : target;
      for (const validator of this._validators) {
        if (!(yield validator.shouldOpen(validationTarget, options))) {
          return false;
        }
      }
      for (const opener of this._openers) {
        const handled = yield opener.open(target, options);
        if (handled) {
          return true;
        }
      }
      return false;
    });
  }
  resolveExternalUri(resource, options) {
    return __awaiter$9(this, void 0, void 0, function* () {
      for (const resolver of this._resolvers) {
        try {
          const result2 = yield resolver.resolveExternalUri(resource, options);
          if (result2) {
            if (!this._resolvedUriTargets.has(result2.resolved)) {
              this._resolvedUriTargets.set(result2.resolved, resource);
            }
            return result2;
          }
        } catch (_a2) {
        }
      }
      throw new Error("Could not resolve external URI: " + resource.toString());
    });
  }
  _doOpenExternal(resource, options) {
    return __awaiter$9(this, void 0, void 0, function* () {
      const uri = typeof resource === "string" ? URI.parse(resource) : resource;
      let externalUri;
      try {
        externalUri = (yield this.resolveExternalUri(uri, options)).resolved;
      } catch (_a2) {
        externalUri = uri;
      }
      let href;
      if (typeof resource === "string" && uri.toString() === externalUri.toString()) {
        href = resource;
      } else {
        href = encodeURI(externalUri.toString(true));
      }
      if (options === null || options === void 0 ? void 0 : options.allowContributedOpeners) {
        const preferredOpenerId = typeof (options === null || options === void 0 ? void 0 : options.allowContributedOpeners) === "string" ? options === null || options === void 0 ? void 0 : options.allowContributedOpeners : void 0;
        for (const opener of this._externalOpeners) {
          const didOpen = yield opener.openExternal(href, {
            sourceUri: uri,
            preferredOpenerId
          }, CancellationToken.None);
          if (didOpen) {
            return true;
          }
        }
      }
      return this._defaultExternalOpener.openExternal(href, { sourceUri: uri }, CancellationToken.None);
    });
  }
  dispose() {
    this._validators.clear();
  }
};
OpenerService = __decorate$i([
  __param$g(0, ICodeEditorService),
  __param$g(1, ICommandService)
], OpenerService);
var __decorate$h = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$f = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
class MarkerDecorations extends Disposable {
  constructor(model) {
    super();
    this.model = model;
    this._markersData = /* @__PURE__ */ new Map();
    this._register(toDisposable(() => {
      this.model.deltaDecorations([...this._markersData.keys()], []);
      this._markersData.clear();
    }));
  }
  update(markers, newDecorations) {
    const oldIds = [...this._markersData.keys()];
    this._markersData.clear();
    const ids = this.model.deltaDecorations(oldIds, newDecorations);
    for (let index = 0; index < ids.length; index++) {
      this._markersData.set(ids[index], markers[index]);
    }
    return oldIds.length !== 0 || ids.length !== 0;
  }
  getMarker(decoration2) {
    return this._markersData.get(decoration2.id);
  }
}
let MarkerDecorationsService = class MarkerDecorationsService2 extends Disposable {
  constructor(modelService, _markerService) {
    super();
    this._markerService = _markerService;
    this._onDidChangeMarker = this._register(new Emitter$1());
    this._markerDecorations = new ResourceMap();
    modelService.getModels().forEach((model) => this._onModelAdded(model));
    this._register(modelService.onModelAdded(this._onModelAdded, this));
    this._register(modelService.onModelRemoved(this._onModelRemoved, this));
    this._register(this._markerService.onMarkerChanged(this._handleMarkerChange, this));
  }
  dispose() {
    super.dispose();
    this._markerDecorations.forEach((value) => value.dispose());
    this._markerDecorations.clear();
  }
  getMarker(uri, decoration2) {
    const markerDecorations = this._markerDecorations.get(uri);
    return markerDecorations ? markerDecorations.getMarker(decoration2) || null : null;
  }
  _handleMarkerChange(changedResources) {
    changedResources.forEach((resource) => {
      const markerDecorations = this._markerDecorations.get(resource);
      if (markerDecorations) {
        this._updateDecorations(markerDecorations);
      }
    });
  }
  _onModelAdded(model) {
    const markerDecorations = new MarkerDecorations(model);
    this._markerDecorations.set(model.uri, markerDecorations);
    this._updateDecorations(markerDecorations);
  }
  _onModelRemoved(model) {
    var _a2;
    const markerDecorations = this._markerDecorations.get(model.uri);
    if (markerDecorations) {
      markerDecorations.dispose();
      this._markerDecorations.delete(model.uri);
    }
    if (model.uri.scheme === Schemas.inMemory || model.uri.scheme === Schemas.internal || model.uri.scheme === Schemas.vscode) {
      (_a2 = this._markerService) === null || _a2 === void 0 ? void 0 : _a2.read({ resource: model.uri }).map((marker) => marker.owner).forEach((owner) => this._markerService.remove(owner, [model.uri]));
    }
  }
  _updateDecorations(markerDecorations) {
    const markers = this._markerService.read({ resource: markerDecorations.model.uri, take: 500 });
    const newModelDecorations = markers.map((marker) => {
      return {
        range: this._createDecorationRange(markerDecorations.model, marker),
        options: this._createDecorationOption(marker)
      };
    });
    if (markerDecorations.update(markers, newModelDecorations)) {
      this._onDidChangeMarker.fire(markerDecorations.model);
    }
  }
  _createDecorationRange(model, rawMarker) {
    let ret = Range$2.lift(rawMarker);
    if (rawMarker.severity === MarkerSeverity$2.Hint && !this._hasMarkerTag(
      rawMarker,
      1
      /* MarkerTag.Unnecessary */
    ) && !this._hasMarkerTag(
      rawMarker,
      2
      /* MarkerTag.Deprecated */
    )) {
      ret = ret.setEndPosition(ret.startLineNumber, ret.startColumn + 2);
    }
    ret = model.validateRange(ret);
    if (ret.isEmpty()) {
      const maxColumn = model.getLineLastNonWhitespaceColumn(ret.startLineNumber) || model.getLineMaxColumn(ret.startLineNumber);
      if (maxColumn === 1 || ret.endColumn >= maxColumn) {
        return ret;
      }
      const word2 = model.getWordAtPosition(ret.getStartPosition());
      if (word2) {
        ret = new Range$2(ret.startLineNumber, word2.startColumn, ret.endLineNumber, word2.endColumn);
      }
    } else if (rawMarker.endColumn === Number.MAX_VALUE && rawMarker.startColumn === 1 && ret.startLineNumber === ret.endLineNumber) {
      const minColumn = model.getLineFirstNonWhitespaceColumn(rawMarker.startLineNumber);
      if (minColumn < ret.endColumn) {
        ret = new Range$2(ret.startLineNumber, minColumn, ret.endLineNumber, ret.endColumn);
        rawMarker.startColumn = minColumn;
      }
    }
    return ret;
  }
  _createDecorationOption(marker) {
    let className3;
    let color = void 0;
    let zIndex;
    let inlineClassName = void 0;
    let minimap2;
    switch (marker.severity) {
      case MarkerSeverity$2.Hint:
        if (this._hasMarkerTag(
          marker,
          2
          /* MarkerTag.Deprecated */
        )) {
          className3 = void 0;
        } else if (this._hasMarkerTag(
          marker,
          1
          /* MarkerTag.Unnecessary */
        )) {
          className3 = "squiggly-unnecessary";
        } else {
          className3 = "squiggly-hint";
        }
        zIndex = 0;
        break;
      case MarkerSeverity$2.Warning:
        className3 = "squiggly-warning";
        color = themeColorFromId(overviewRulerWarning);
        zIndex = 20;
        minimap2 = {
          color: themeColorFromId(minimapWarning),
          position: MinimapPosition$1.Inline
        };
        break;
      case MarkerSeverity$2.Info:
        className3 = "squiggly-info";
        color = themeColorFromId(overviewRulerInfo);
        zIndex = 10;
        break;
      case MarkerSeverity$2.Error:
      default:
        className3 = "squiggly-error";
        color = themeColorFromId(overviewRulerError);
        zIndex = 30;
        minimap2 = {
          color: themeColorFromId(minimapError),
          position: MinimapPosition$1.Inline
        };
        break;
    }
    if (marker.tags) {
      if (marker.tags.indexOf(
        1
        /* MarkerTag.Unnecessary */
      ) !== -1) {
        inlineClassName = "squiggly-inline-unnecessary";
      }
      if (marker.tags.indexOf(
        2
        /* MarkerTag.Deprecated */
      ) !== -1) {
        inlineClassName = "squiggly-inline-deprecated";
      }
    }
    return {
      description: "marker-decoration",
      stickiness: 1,
      className: className3,
      showIfCollapsed: true,
      overviewRuler: {
        color,
        position: OverviewRulerLane$1.Right
      },
      minimap: minimap2,
      zIndex,
      inlineClassName
    };
  }
  _hasMarkerTag(marker, tag3) {
    if (marker.tags) {
      return marker.tags.indexOf(tag3) >= 0;
    }
    return false;
  }
};
MarkerDecorationsService = __decorate$h([
  __param$f(0, IModelService),
  __param$f(1, IMarkerService)
], MarkerDecorationsService);
var __decorate$g = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$e = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
function MODEL_ID(resource) {
  return resource.toString();
}
function computeModelSha1(model) {
  const shaComputer = new StringSHA1();
  const snapshot = model.createSnapshot();
  let text2;
  while (text2 = snapshot.read()) {
    shaComputer.update(text2);
  }
  return shaComputer.digest();
}
class ModelData2 {
  constructor(model, onWillDispose, onDidChangeLanguage) {
    this.model = model;
    this._modelEventListeners = new DisposableStore();
    this.model = model;
    this._modelEventListeners.add(model.onWillDispose(() => onWillDispose(model)));
    this._modelEventListeners.add(model.onDidChangeLanguage((e) => onDidChangeLanguage(model, e)));
  }
  dispose() {
    this._modelEventListeners.dispose();
  }
}
const DEFAULT_EOL = isLinux || isMacintosh ? 1 : 2;
class DisposedModelInfo {
  constructor(uri, initialUndoRedoSnapshot, time, sharesUndoRedoStack, heapSize, sha1, versionId, alternativeVersionId) {
    this.uri = uri;
    this.initialUndoRedoSnapshot = initialUndoRedoSnapshot;
    this.time = time;
    this.sharesUndoRedoStack = sharesUndoRedoStack;
    this.heapSize = heapSize;
    this.sha1 = sha1;
    this.versionId = versionId;
    this.alternativeVersionId = alternativeVersionId;
  }
}
let ModelService = class ModelService2 extends Disposable {
  constructor(_configurationService, _resourcePropertiesService, _undoRedoService, _languageService, _languageConfigurationService) {
    super();
    this._configurationService = _configurationService;
    this._resourcePropertiesService = _resourcePropertiesService;
    this._undoRedoService = _undoRedoService;
    this._languageService = _languageService;
    this._languageConfigurationService = _languageConfigurationService;
    this._onModelAdded = this._register(new Emitter$1());
    this.onModelAdded = this._onModelAdded.event;
    this._onModelRemoved = this._register(new Emitter$1());
    this.onModelRemoved = this._onModelRemoved.event;
    this._onModelModeChanged = this._register(new Emitter$1());
    this.onModelLanguageChanged = this._onModelModeChanged.event;
    this._modelCreationOptionsByLanguageAndResource = /* @__PURE__ */ Object.create(null);
    this._models = {};
    this._disposedModels = /* @__PURE__ */ new Map();
    this._disposedModelsHeapSize = 0;
    this._register(this._configurationService.onDidChangeConfiguration((e) => this._updateModelOptions(e)));
    this._updateModelOptions(void 0);
  }
  static _readModelOptions(config2, isForSimpleWidget) {
    var _a2;
    let tabSize = EDITOR_MODEL_DEFAULTS.tabSize;
    if (config2.editor && typeof config2.editor.tabSize !== "undefined") {
      const parsedTabSize = parseInt(config2.editor.tabSize, 10);
      if (!isNaN(parsedTabSize)) {
        tabSize = parsedTabSize;
      }
      if (tabSize < 1) {
        tabSize = 1;
      }
    }
    let indentSize = "tabSize";
    if (config2.editor && typeof config2.editor.indentSize !== "undefined" && config2.editor.indentSize !== "tabSize") {
      const parsedIndentSize = parseInt(config2.editor.indentSize, 10);
      if (!isNaN(parsedIndentSize)) {
        indentSize = Math.max(parsedIndentSize, 1);
      }
    }
    let insertSpaces = EDITOR_MODEL_DEFAULTS.insertSpaces;
    if (config2.editor && typeof config2.editor.insertSpaces !== "undefined") {
      insertSpaces = config2.editor.insertSpaces === "false" ? false : Boolean(config2.editor.insertSpaces);
    }
    let newDefaultEOL = DEFAULT_EOL;
    const eol = config2.eol;
    if (eol === "\r\n") {
      newDefaultEOL = 2;
    } else if (eol === "\n") {
      newDefaultEOL = 1;
    }
    let trimAutoWhitespace = EDITOR_MODEL_DEFAULTS.trimAutoWhitespace;
    if (config2.editor && typeof config2.editor.trimAutoWhitespace !== "undefined") {
      trimAutoWhitespace = config2.editor.trimAutoWhitespace === "false" ? false : Boolean(config2.editor.trimAutoWhitespace);
    }
    let detectIndentation = EDITOR_MODEL_DEFAULTS.detectIndentation;
    if (config2.editor && typeof config2.editor.detectIndentation !== "undefined") {
      detectIndentation = config2.editor.detectIndentation === "false" ? false : Boolean(config2.editor.detectIndentation);
    }
    let largeFileOptimizations = EDITOR_MODEL_DEFAULTS.largeFileOptimizations;
    if (config2.editor && typeof config2.editor.largeFileOptimizations !== "undefined") {
      largeFileOptimizations = config2.editor.largeFileOptimizations === "false" ? false : Boolean(config2.editor.largeFileOptimizations);
    }
    let bracketPairColorizationOptions = EDITOR_MODEL_DEFAULTS.bracketPairColorizationOptions;
    if (((_a2 = config2.editor) === null || _a2 === void 0 ? void 0 : _a2.bracketPairColorization) && typeof config2.editor.bracketPairColorization === "object") {
      bracketPairColorizationOptions = {
        enabled: !!config2.editor.bracketPairColorization.enabled,
        independentColorPoolPerBracketType: !!config2.editor.bracketPairColorization.independentColorPoolPerBracketType
      };
    }
    return {
      isForSimpleWidget,
      tabSize,
      indentSize,
      insertSpaces,
      detectIndentation,
      defaultEOL: newDefaultEOL,
      trimAutoWhitespace,
      largeFileOptimizations,
      bracketPairColorizationOptions
    };
  }
  _getEOL(resource, language2) {
    if (resource) {
      return this._resourcePropertiesService.getEOL(resource, language2);
    }
    const eol = this._configurationService.getValue("files.eol", { overrideIdentifier: language2 });
    if (eol && typeof eol === "string" && eol !== "auto") {
      return eol;
    }
    return OS === 3 || OS === 2 ? "\n" : "\r\n";
  }
  _shouldRestoreUndoStack() {
    const result2 = this._configurationService.getValue("files.restoreUndoStack");
    if (typeof result2 === "boolean") {
      return result2;
    }
    return true;
  }
  getCreationOptions(languageIdOrSelection, resource, isForSimpleWidget) {
    const language2 = typeof languageIdOrSelection === "string" ? languageIdOrSelection : languageIdOrSelection.languageId;
    let creationOptions = this._modelCreationOptionsByLanguageAndResource[language2 + resource];
    if (!creationOptions) {
      const editor2 = this._configurationService.getValue("editor", { overrideIdentifier: language2, resource });
      const eol = this._getEOL(resource, language2);
      creationOptions = ModelService2._readModelOptions({ editor: editor2, eol }, isForSimpleWidget);
      this._modelCreationOptionsByLanguageAndResource[language2 + resource] = creationOptions;
    }
    return creationOptions;
  }
  _updateModelOptions(e) {
    const oldOptionsByLanguageAndResource = this._modelCreationOptionsByLanguageAndResource;
    this._modelCreationOptionsByLanguageAndResource = /* @__PURE__ */ Object.create(null);
    const keys = Object.keys(this._models);
    for (let i = 0, len = keys.length; i < len; i++) {
      const modelId = keys[i];
      const modelData = this._models[modelId];
      const language2 = modelData.model.getLanguageId();
      const uri = modelData.model.uri;
      if (e && !e.affectsConfiguration("editor", { overrideIdentifier: language2, resource: uri }) && !e.affectsConfiguration("files.eol", { overrideIdentifier: language2, resource: uri })) {
        continue;
      }
      const oldOptions = oldOptionsByLanguageAndResource[language2 + uri];
      const newOptions = this.getCreationOptions(language2, uri, modelData.model.isForSimpleWidget);
      ModelService2._setModelOptionsForModel(modelData.model, newOptions, oldOptions);
    }
  }
  static _setModelOptionsForModel(model, newOptions, currentOptions) {
    if (currentOptions && currentOptions.defaultEOL !== newOptions.defaultEOL && model.getLineCount() === 1) {
      model.setEOL(
        newOptions.defaultEOL === 1 ? 0 : 1
        /* EndOfLineSequence.CRLF */
      );
    }
    if (currentOptions && currentOptions.detectIndentation === newOptions.detectIndentation && currentOptions.insertSpaces === newOptions.insertSpaces && currentOptions.tabSize === newOptions.tabSize && currentOptions.indentSize === newOptions.indentSize && currentOptions.trimAutoWhitespace === newOptions.trimAutoWhitespace && equals$2(currentOptions.bracketPairColorizationOptions, newOptions.bracketPairColorizationOptions)) {
      return;
    }
    if (newOptions.detectIndentation) {
      model.detectIndentation(newOptions.insertSpaces, newOptions.tabSize);
      model.updateOptions({
        trimAutoWhitespace: newOptions.trimAutoWhitespace,
        bracketColorizationOptions: newOptions.bracketPairColorizationOptions
      });
    } else {
      model.updateOptions({
        insertSpaces: newOptions.insertSpaces,
        tabSize: newOptions.tabSize,
        indentSize: newOptions.indentSize,
        trimAutoWhitespace: newOptions.trimAutoWhitespace,
        bracketColorizationOptions: newOptions.bracketPairColorizationOptions
      });
    }
  }
  // --- begin IModelService
  _insertDisposedModel(disposedModelData) {
    this._disposedModels.set(MODEL_ID(disposedModelData.uri), disposedModelData);
    this._disposedModelsHeapSize += disposedModelData.heapSize;
  }
  _removeDisposedModel(resource) {
    const disposedModelData = this._disposedModels.get(MODEL_ID(resource));
    if (disposedModelData) {
      this._disposedModelsHeapSize -= disposedModelData.heapSize;
    }
    this._disposedModels.delete(MODEL_ID(resource));
    return disposedModelData;
  }
  _ensureDisposedModelsHeapSize(maxModelsHeapSize) {
    if (this._disposedModelsHeapSize > maxModelsHeapSize) {
      const disposedModels = [];
      this._disposedModels.forEach((entry) => {
        if (!entry.sharesUndoRedoStack) {
          disposedModels.push(entry);
        }
      });
      disposedModels.sort((a, b) => a.time - b.time);
      while (disposedModels.length > 0 && this._disposedModelsHeapSize > maxModelsHeapSize) {
        const disposedModel = disposedModels.shift();
        this._removeDisposedModel(disposedModel.uri);
        if (disposedModel.initialUndoRedoSnapshot !== null) {
          this._undoRedoService.restoreSnapshot(disposedModel.initialUndoRedoSnapshot);
        }
      }
    }
  }
  _createModelData(value, languageIdOrSelection, resource, isForSimpleWidget) {
    const options = this.getCreationOptions(languageIdOrSelection, resource, isForSimpleWidget);
    const model = new TextModel(value, languageIdOrSelection, options, resource, this._undoRedoService, this._languageService, this._languageConfigurationService);
    if (resource && this._disposedModels.has(MODEL_ID(resource))) {
      const disposedModelData = this._removeDisposedModel(resource);
      const elements = this._undoRedoService.getElements(resource);
      const sha1IsEqual = computeModelSha1(model) === disposedModelData.sha1;
      if (sha1IsEqual || disposedModelData.sharesUndoRedoStack) {
        for (const element of elements.past) {
          if (isEditStackElement(element) && element.matchesResource(resource)) {
            element.setModel(model);
          }
        }
        for (const element of elements.future) {
          if (isEditStackElement(element) && element.matchesResource(resource)) {
            element.setModel(model);
          }
        }
        this._undoRedoService.setElementsValidFlag(resource, true, (element) => isEditStackElement(element) && element.matchesResource(resource));
        if (sha1IsEqual) {
          model._overwriteVersionId(disposedModelData.versionId);
          model._overwriteAlternativeVersionId(disposedModelData.alternativeVersionId);
          model._overwriteInitialUndoRedoSnapshot(disposedModelData.initialUndoRedoSnapshot);
        }
      } else {
        if (disposedModelData.initialUndoRedoSnapshot !== null) {
          this._undoRedoService.restoreSnapshot(disposedModelData.initialUndoRedoSnapshot);
        }
      }
    }
    const modelId = MODEL_ID(model.uri);
    if (this._models[modelId]) {
      throw new Error("ModelService: Cannot add model because it already exists!");
    }
    const modelData = new ModelData2(model, (model2) => this._onWillDispose(model2), (model2, e) => this._onDidChangeLanguage(model2, e));
    this._models[modelId] = modelData;
    return modelData;
  }
  createModel(value, languageSelection, resource, isForSimpleWidget = false) {
    let modelData;
    if (languageSelection) {
      modelData = this._createModelData(value, languageSelection, resource, isForSimpleWidget);
    } else {
      modelData = this._createModelData(value, PLAINTEXT_LANGUAGE_ID, resource, isForSimpleWidget);
    }
    this._onModelAdded.fire(modelData.model);
    return modelData.model;
  }
  getModels() {
    const ret = [];
    const keys = Object.keys(this._models);
    for (let i = 0, len = keys.length; i < len; i++) {
      const modelId = keys[i];
      ret.push(this._models[modelId].model);
    }
    return ret;
  }
  getModel(resource) {
    const modelId = MODEL_ID(resource);
    const modelData = this._models[modelId];
    if (!modelData) {
      return null;
    }
    return modelData.model;
  }
  // --- end IModelService
  _schemaShouldMaintainUndoRedoElements(resource) {
    return resource.scheme === Schemas.file || resource.scheme === Schemas.vscodeRemote || resource.scheme === Schemas.vscodeUserData || resource.scheme === Schemas.vscodeNotebookCell || resource.scheme === "fake-fs";
  }
  _onWillDispose(model) {
    const modelId = MODEL_ID(model.uri);
    const modelData = this._models[modelId];
    const sharesUndoRedoStack = this._undoRedoService.getUriComparisonKey(model.uri) !== model.uri.toString();
    let maintainUndoRedoStack = false;
    let heapSize = 0;
    if (sharesUndoRedoStack || this._shouldRestoreUndoStack() && this._schemaShouldMaintainUndoRedoElements(model.uri)) {
      const elements = this._undoRedoService.getElements(model.uri);
      if (elements.past.length > 0 || elements.future.length > 0) {
        for (const element of elements.past) {
          if (isEditStackElement(element) && element.matchesResource(model.uri)) {
            maintainUndoRedoStack = true;
            heapSize += element.heapSize(model.uri);
            element.setModel(model.uri);
          }
        }
        for (const element of elements.future) {
          if (isEditStackElement(element) && element.matchesResource(model.uri)) {
            maintainUndoRedoStack = true;
            heapSize += element.heapSize(model.uri);
            element.setModel(model.uri);
          }
        }
      }
    }
    const maxMemory = ModelService2.MAX_MEMORY_FOR_CLOSED_FILES_UNDO_STACK;
    if (!maintainUndoRedoStack) {
      if (!sharesUndoRedoStack) {
        const initialUndoRedoSnapshot = modelData.model.getInitialUndoRedoSnapshot();
        if (initialUndoRedoSnapshot !== null) {
          this._undoRedoService.restoreSnapshot(initialUndoRedoSnapshot);
        }
      }
    } else if (!sharesUndoRedoStack && heapSize > maxMemory) {
      const initialUndoRedoSnapshot = modelData.model.getInitialUndoRedoSnapshot();
      if (initialUndoRedoSnapshot !== null) {
        this._undoRedoService.restoreSnapshot(initialUndoRedoSnapshot);
      }
    } else {
      this._ensureDisposedModelsHeapSize(maxMemory - heapSize);
      this._undoRedoService.setElementsValidFlag(model.uri, false, (element) => isEditStackElement(element) && element.matchesResource(model.uri));
      this._insertDisposedModel(new DisposedModelInfo(model.uri, modelData.model.getInitialUndoRedoSnapshot(), Date.now(), sharesUndoRedoStack, heapSize, computeModelSha1(model), model.getVersionId(), model.getAlternativeVersionId()));
    }
    delete this._models[modelId];
    modelData.dispose();
    delete this._modelCreationOptionsByLanguageAndResource[model.getLanguageId() + model.uri];
    this._onModelRemoved.fire(model);
  }
  _onDidChangeLanguage(model, e) {
    const oldLanguageId = e.oldLanguage;
    const newLanguageId = model.getLanguageId();
    const oldOptions = this.getCreationOptions(oldLanguageId, model.uri, model.isForSimpleWidget);
    const newOptions = this.getCreationOptions(newLanguageId, model.uri, model.isForSimpleWidget);
    ModelService2._setModelOptionsForModel(model, newOptions, oldOptions);
    this._onModelModeChanged.fire({ model, oldLanguageId });
  }
};
ModelService.MAX_MEMORY_FOR_CLOSED_FILES_UNDO_STACK = 20 * 1024 * 1024;
ModelService = __decorate$g([
  __param$e(0, IConfigurationService),
  __param$e(1, ITextResourcePropertiesService),
  __param$e(2, IUndoRedoService),
  __param$e(3, ILanguageService),
  __param$e(4, ILanguageConfigurationService)
], ModelService);
const standaloneQuickInput = "";
var __decorate$f = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$d = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let QuickAccessController = class QuickAccessController2 extends Disposable {
  constructor(quickInputService, instantiationService) {
    super();
    this.quickInputService = quickInputService;
    this.instantiationService = instantiationService;
    this.registry = Registry.as(Extensions.Quickaccess);
    this.mapProviderToDescriptor = /* @__PURE__ */ new Map();
    this.lastAcceptedPickerValues = /* @__PURE__ */ new Map();
    this.visibleQuickAccess = void 0;
  }
  show(value = "", options) {
    this.doShowOrPick(value, false, options);
  }
  doShowOrPick(value, pick, options) {
    var _a2;
    const [provider, descriptor] = this.getOrInstantiateProvider(value);
    const visibleQuickAccess = this.visibleQuickAccess;
    const visibleDescriptor = visibleQuickAccess === null || visibleQuickAccess === void 0 ? void 0 : visibleQuickAccess.descriptor;
    if (visibleQuickAccess && descriptor && visibleDescriptor === descriptor) {
      if (value !== descriptor.prefix && !(options === null || options === void 0 ? void 0 : options.preserveValue)) {
        visibleQuickAccess.picker.value = value;
      }
      this.adjustValueSelection(visibleQuickAccess.picker, descriptor, options);
      return;
    }
    if (descriptor && !(options === null || options === void 0 ? void 0 : options.preserveValue)) {
      let newValue = void 0;
      if (visibleQuickAccess && visibleDescriptor && visibleDescriptor !== descriptor) {
        const newValueCandidateWithoutPrefix = visibleQuickAccess.value.substr(visibleDescriptor.prefix.length);
        if (newValueCandidateWithoutPrefix) {
          newValue = `${descriptor.prefix}${newValueCandidateWithoutPrefix}`;
        }
      }
      if (!newValue) {
        const defaultFilterValue = provider === null || provider === void 0 ? void 0 : provider.defaultFilterValue;
        if (defaultFilterValue === DefaultQuickAccessFilterValue.LAST) {
          newValue = this.lastAcceptedPickerValues.get(descriptor);
        } else if (typeof defaultFilterValue === "string") {
          newValue = `${descriptor.prefix}${defaultFilterValue}`;
        }
      }
      if (typeof newValue === "string") {
        value = newValue;
      }
    }
    const disposables = new DisposableStore();
    const picker = disposables.add(this.quickInputService.createQuickPick());
    picker.value = value;
    this.adjustValueSelection(picker, descriptor, options);
    picker.placeholder = descriptor === null || descriptor === void 0 ? void 0 : descriptor.placeholder;
    picker.quickNavigate = options === null || options === void 0 ? void 0 : options.quickNavigateConfiguration;
    picker.hideInput = !!picker.quickNavigate && !visibleQuickAccess;
    if (typeof (options === null || options === void 0 ? void 0 : options.itemActivation) === "number" || (options === null || options === void 0 ? void 0 : options.quickNavigateConfiguration)) {
      picker.itemActivation = (_a2 = options === null || options === void 0 ? void 0 : options.itemActivation) !== null && _a2 !== void 0 ? _a2 : ItemActivation.SECOND;
    }
    picker.contextKey = descriptor === null || descriptor === void 0 ? void 0 : descriptor.contextKey;
    picker.filterValue = (value2) => value2.substring(descriptor ? descriptor.prefix.length : 0);
    let pickPromise = void 0;
    if (pick) {
      pickPromise = new DeferredPromise();
      disposables.add(once$2(picker.onWillAccept)((e) => {
        e.veto();
        picker.hide();
      }));
    }
    disposables.add(this.registerPickerListeners(picker, provider, descriptor, value, options === null || options === void 0 ? void 0 : options.providerOptions));
    const cts = disposables.add(new CancellationTokenSource$1());
    if (provider) {
      disposables.add(provider.provide(picker, cts.token, options === null || options === void 0 ? void 0 : options.providerOptions));
    }
    once$2(picker.onDidHide)(() => {
      if (picker.selectedItems.length === 0) {
        cts.cancel();
      }
      disposables.dispose();
      pickPromise === null || pickPromise === void 0 ? void 0 : pickPromise.complete(picker.selectedItems.slice(0));
    });
    picker.show();
    if (pick) {
      return pickPromise === null || pickPromise === void 0 ? void 0 : pickPromise.p;
    }
  }
  adjustValueSelection(picker, descriptor, options) {
    var _a2;
    let valueSelection;
    if (options === null || options === void 0 ? void 0 : options.preserveValue) {
      valueSelection = [picker.value.length, picker.value.length];
    } else {
      valueSelection = [(_a2 = descriptor === null || descriptor === void 0 ? void 0 : descriptor.prefix.length) !== null && _a2 !== void 0 ? _a2 : 0, picker.value.length];
    }
    picker.valueSelection = valueSelection;
  }
  registerPickerListeners(picker, provider, descriptor, value, providerOptions) {
    const disposables = new DisposableStore();
    const visibleQuickAccess = this.visibleQuickAccess = { picker, descriptor, value };
    disposables.add(toDisposable(() => {
      if (visibleQuickAccess === this.visibleQuickAccess) {
        this.visibleQuickAccess = void 0;
      }
    }));
    disposables.add(picker.onDidChangeValue((value2) => {
      const [providerForValue] = this.getOrInstantiateProvider(value2);
      if (providerForValue !== provider) {
        this.show(value2, {
          // do not rewrite value from user typing!
          preserveValue: true,
          // persist the value of the providerOptions from the original showing
          providerOptions
        });
      } else {
        visibleQuickAccess.value = value2;
      }
    }));
    if (descriptor) {
      disposables.add(picker.onDidAccept(() => {
        this.lastAcceptedPickerValues.set(descriptor, picker.value);
      }));
    }
    return disposables;
  }
  getOrInstantiateProvider(value) {
    const providerDescriptor = this.registry.getQuickAccessProvider(value);
    if (!providerDescriptor) {
      return [void 0, void 0];
    }
    let provider = this.mapProviderToDescriptor.get(providerDescriptor);
    if (!provider) {
      provider = this.instantiationService.createInstance(providerDescriptor.ctor);
      this.mapProviderToDescriptor.set(providerDescriptor, provider);
    }
    return [provider, providerDescriptor];
  }
};
QuickAccessController = __decorate$f([
  __param$d(0, IQuickInputService),
  __param$d(1, IInstantiationService)
], QuickAccessController);
const progressbar = "";
const CSS_DONE = "done";
const CSS_ACTIVE = "active";
const CSS_INFINITE = "infinite";
const CSS_INFINITE_LONG_RUNNING = "infinite-long-running";
const CSS_DISCRETE = "discrete";
class ProgressBar extends Disposable {
  constructor(container2, options) {
    super();
    this.workedVal = 0;
    this.showDelayedScheduler = this._register(new RunOnceScheduler(() => show(this.element), 0));
    this.longRunningScheduler = this._register(new RunOnceScheduler(() => this.infiniteLongRunning(), ProgressBar.LONG_RUNNING_INFINITE_THRESHOLD));
    this.create(container2, options);
  }
  create(container2, options) {
    this.element = document.createElement("div");
    this.element.classList.add("monaco-progress-container");
    this.element.setAttribute("role", "progressbar");
    this.element.setAttribute("aria-valuemin", "0");
    container2.appendChild(this.element);
    this.bit = document.createElement("div");
    this.bit.classList.add("progress-bit");
    this.bit.style.backgroundColor = (options === null || options === void 0 ? void 0 : options.progressBarBackground) || "#0E70C0";
    this.element.appendChild(this.bit);
  }
  off() {
    this.bit.style.width = "inherit";
    this.bit.style.opacity = "1";
    this.element.classList.remove(CSS_ACTIVE, CSS_INFINITE, CSS_INFINITE_LONG_RUNNING, CSS_DISCRETE);
    this.workedVal = 0;
    this.totalWork = void 0;
    this.longRunningScheduler.cancel();
  }
  /**
   * Stops the progressbar from showing any progress instantly without fading out.
   */
  stop() {
    return this.doDone(false);
  }
  doDone(delayed) {
    this.element.classList.add(CSS_DONE);
    if (!this.element.classList.contains(CSS_INFINITE)) {
      this.bit.style.width = "inherit";
      if (delayed) {
        setTimeout(() => this.off(), 200);
      } else {
        this.off();
      }
    } else {
      this.bit.style.opacity = "0";
      if (delayed) {
        setTimeout(() => this.off(), 200);
      } else {
        this.off();
      }
    }
    return this;
  }
  /**
   * Use this mode to indicate progress that has no total number of work units.
   */
  infinite() {
    this.bit.style.width = "2%";
    this.bit.style.opacity = "1";
    this.element.classList.remove(CSS_DISCRETE, CSS_DONE, CSS_INFINITE_LONG_RUNNING);
    this.element.classList.add(CSS_ACTIVE, CSS_INFINITE);
    this.longRunningScheduler.schedule();
    return this;
  }
  infiniteLongRunning() {
    this.element.classList.add(CSS_INFINITE_LONG_RUNNING);
  }
  getContainer() {
    return this.element;
  }
}
ProgressBar.LONG_RUNNING_INFINITE_THRESHOLD = 1e4;
const quickInput = "";
const $$2 = $$d;
class QuickInputBox extends Disposable {
  constructor(parent, inputBoxStyles, toggleStyles) {
    super();
    this.parent = parent;
    this.onKeyDown = (handler) => {
      return addDisposableListener(this.findInput.inputBox.inputElement, EventType$1.KEY_DOWN, (e) => {
        handler(new StandardKeyboardEvent(e));
      });
    };
    this.onMouseDown = (handler) => {
      return addDisposableListener(this.findInput.inputBox.inputElement, EventType$1.MOUSE_DOWN, (e) => {
        handler(new StandardMouseEvent(e));
      });
    };
    this.onDidChange = (handler) => {
      return this.findInput.onDidChange(handler);
    };
    this.container = append$1(this.parent, $$2(".quick-input-box"));
    this.findInput = this._register(new FindInput(this.container, void 0, { label: "", inputBoxStyles, toggleStyles }));
    const input2 = this.findInput.inputBox.inputElement;
    input2.role = "combobox";
    input2.ariaHasPopup = "menu";
    input2.ariaAutoComplete = "list";
    input2.ariaExpanded = "true";
  }
  get value() {
    return this.findInput.getValue();
  }
  set value(value) {
    this.findInput.setValue(value);
  }
  select(range2 = null) {
    this.findInput.inputBox.select(range2);
  }
  isSelectionAtEnd() {
    return this.findInput.inputBox.isSelectionAtEnd();
  }
  get placeholder() {
    return this.findInput.inputBox.inputElement.getAttribute("placeholder") || "";
  }
  set placeholder(placeholder) {
    this.findInput.inputBox.setPlaceHolder(placeholder);
  }
  get password() {
    return this.findInput.inputBox.inputElement.type === "password";
  }
  set password(password) {
    this.findInput.inputBox.inputElement.type = password ? "password" : "text";
  }
  set enabled(enabled) {
    this.findInput.inputBox.inputElement.toggleAttribute("readonly", !enabled);
  }
  set toggles(toggles) {
    this.findInput.setAdditionalToggles(toggles);
  }
  setAttribute(name, value) {
    this.findInput.inputBox.inputElement.setAttribute(name, value);
  }
  showDecoration(decoration2) {
    if (decoration2 === Severity$2.Ignore) {
      this.findInput.clearMessage();
    } else {
      this.findInput.showMessage({ type: decoration2 === Severity$2.Info ? 1 : decoration2 === Severity$2.Warning ? 2 : 3, content: "" });
    }
  }
  stylesForType(decoration2) {
    return this.findInput.inputBox.stylesForType(
      decoration2 === Severity$2.Info ? 1 : decoration2 === Severity$2.Warning ? 2 : 3
      /* MessageType.ERROR */
    );
  }
  setFocus() {
    this.findInput.focus();
  }
  layout() {
    this.findInput.inputBox.layout();
  }
}
const intlFileNameCollatorBaseNumeric = new Lazy(() => {
  const collator = new Intl.Collator(void 0, { numeric: true, sensitivity: "base" });
  return {
    collator,
    collatorIsNumeric: collator.resolvedOptions().numeric
  };
});
function compareFileNames(one, other, caseSensitive = false) {
  const a = one || "";
  const b = other || "";
  const result2 = intlFileNameCollatorBaseNumeric.value.collator.compare(a, b);
  if (intlFileNameCollatorBaseNumeric.value.collatorIsNumeric && result2 === 0 && a !== b) {
    return a < b ? -1 : 1;
  }
  return result2;
}
function compareAnything(one, other, lookFor) {
  const elementAName = one.toLowerCase();
  const elementBName = other.toLowerCase();
  const prefixCompare = compareByPrefix(one, other, lookFor);
  if (prefixCompare) {
    return prefixCompare;
  }
  const elementASuffixMatch = elementAName.endsWith(lookFor);
  const elementBSuffixMatch = elementBName.endsWith(lookFor);
  if (elementASuffixMatch !== elementBSuffixMatch) {
    return elementASuffixMatch ? -1 : 1;
  }
  const r = compareFileNames(elementAName, elementBName);
  if (r !== 0) {
    return r;
  }
  return elementAName.localeCompare(elementBName);
}
function compareByPrefix(one, other, lookFor) {
  const elementAName = one.toLowerCase();
  const elementBName = other.toLowerCase();
  const elementAPrefixMatch = elementAName.startsWith(lookFor);
  const elementBPrefixMatch = elementBName.startsWith(lookFor);
  if (elementAPrefixMatch !== elementBPrefixMatch) {
    return elementAPrefixMatch ? -1 : 1;
  } else if (elementAPrefixMatch && elementBPrefixMatch) {
    if (elementAName.length < elementBName.length) {
      return -1;
    }
    if (elementAName.length > elementBName.length) {
      return 1;
    }
  }
  return 0;
}
var __decorate$e = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
class LinkedText {
  constructor(nodes) {
    this.nodes = nodes;
  }
  toString() {
    return this.nodes.map((node2) => typeof node2 === "string" ? node2 : node2.label).join("");
  }
}
__decorate$e([
  memoize
], LinkedText.prototype, "toString", null);
const LINK_REGEX = /\[([^\]]+)\]\(((?:https?:\/\/|command:|file:)[^\)\s]+)(?: (["'])(.+?)(\3))?\)/gi;
function parseLinkedText(text2) {
  const result2 = [];
  let index = 0;
  let match2;
  while (match2 = LINK_REGEX.exec(text2)) {
    if (match2.index - index > 0) {
      result2.push(text2.substring(index, match2.index));
    }
    const [, label, href, , title2] = match2;
    if (title2) {
      result2.push({ label, href, title: title2 });
    } else {
      result2.push({ label, href });
    }
    index = match2.index + match2[0].length;
  }
  if (index < text2.length) {
    result2.push(text2.substring(index));
  }
  return new LinkedText(result2);
}
const iconPathToClass = {};
const iconClassGenerator = new IdGenerator("quick-input-button-icon-");
function getIconClass(iconPath) {
  if (!iconPath) {
    return void 0;
  }
  let iconClass;
  const key = iconPath.dark.toString();
  if (iconPathToClass[key]) {
    iconClass = iconPathToClass[key];
  } else {
    iconClass = iconClassGenerator.nextId();
    createCSSRule(`.${iconClass}, .hc-light .${iconClass}`, `background-image: ${asCSSUrl(iconPath.light || iconPath.dark)}`);
    createCSSRule(`.vs-dark .${iconClass}, .hc-black .${iconClass}`, `background-image: ${asCSSUrl(iconPath.dark)}`);
    iconPathToClass[key] = iconClass;
  }
  return iconClass;
}
function renderQuickInputDescription(description, container2, actionHandler) {
  reset(container2);
  const parsed = parseLinkedText(description);
  let tabIndex = 0;
  for (const node2 of parsed.nodes) {
    if (typeof node2 === "string") {
      container2.append(...renderLabelWithIcons(node2));
    } else {
      let title2 = node2.title;
      if (!title2 && node2.href.startsWith("command:")) {
        title2 = localize("executeCommand", "Click to execute command '{0}'", node2.href.substring("command:".length));
      } else if (!title2) {
        title2 = node2.href;
      }
      const anchor = $$d("a", { href: node2.href, title: title2, tabIndex: tabIndex++ }, node2.label);
      anchor.style.textDecoration = "underline";
      const handleOpen = (e) => {
        if (isEventLike(e)) {
          EventHelper.stop(e, true);
        }
        actionHandler.callback(node2.href);
      };
      const onClick = actionHandler.disposables.add(new DomEmitter(anchor, EventType$1.CLICK)).event;
      const onKeydown = actionHandler.disposables.add(new DomEmitter(anchor, EventType$1.KEY_DOWN)).event;
      const onSpaceOrEnter = actionHandler.disposables.add(Event$1.chain(onKeydown)).filter((e) => {
        const event = new StandardKeyboardEvent(e);
        return event.equals(
          10
          /* KeyCode.Space */
        ) || event.equals(
          3
          /* KeyCode.Enter */
        );
      }).event;
      actionHandler.disposables.add(Gesture.addTarget(anchor));
      const onTap = actionHandler.disposables.add(new DomEmitter(anchor, EventType.Tap)).event;
      Event$1.any(onClick, onTap, onSpaceOrEnter)(handleOpen, null, actionHandler.disposables);
      container2.appendChild(anchor);
    }
  }
}
var __decorate$d = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __awaiter$8 = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
const $$1 = $$d;
class ListElement {
  constructor(mainItem, previous, index, hasCheckbox, fireButtonTriggered, fireSeparatorButtonTriggered, onCheckedEmitter) {
    var _a2, _b2, _c2;
    this._checked = false;
    this._hidden = false;
    this.hasCheckbox = hasCheckbox;
    this.index = index;
    this.fireButtonTriggered = fireButtonTriggered;
    this.fireSeparatorButtonTriggered = fireSeparatorButtonTriggered;
    this._onChecked = onCheckedEmitter;
    this.onChecked = hasCheckbox ? Event$1.map(Event$1.filter(this._onChecked.event, (e) => e.listElement === this), (e) => e.checked) : Event$1.None;
    if (mainItem.type === "separator") {
      this._separator = mainItem;
    } else {
      this.item = mainItem;
      if (previous && previous.type === "separator" && !previous.buttons) {
        this._separator = previous;
      }
      this.saneDescription = this.item.description;
      this.saneDetail = this.item.detail;
      this._labelHighlights = (_a2 = this.item.highlights) === null || _a2 === void 0 ? void 0 : _a2.label;
      this._descriptionHighlights = (_b2 = this.item.highlights) === null || _b2 === void 0 ? void 0 : _b2.description;
      this._detailHighlights = (_c2 = this.item.highlights) === null || _c2 === void 0 ? void 0 : _c2.detail;
      this.saneTooltip = this.item.tooltip;
    }
    this._init = new Lazy(() => {
      var _a3;
      const saneLabel = (_a3 = mainItem.label) !== null && _a3 !== void 0 ? _a3 : "";
      const saneSortLabel = parseLabelWithIcons(saneLabel).text.trim();
      const saneAriaLabel = mainItem.ariaLabel || [saneLabel, this.saneDescription, this.saneDetail].map((s) => getCodiconAriaLabel(s)).filter((s) => !!s).join(", ");
      return {
        saneLabel,
        saneSortLabel,
        saneAriaLabel
      };
    });
  }
  // #region Lazy Getters
  get saneLabel() {
    return this._init.value.saneLabel;
  }
  get saneSortLabel() {
    return this._init.value.saneSortLabel;
  }
  get saneAriaLabel() {
    return this._init.value.saneAriaLabel;
  }
  // #endregion
  // #region Getters and Setters
  get element() {
    return this._element;
  }
  set element(value) {
    this._element = value;
  }
  get hidden() {
    return this._hidden;
  }
  set hidden(value) {
    this._hidden = value;
  }
  get checked() {
    return this._checked;
  }
  set checked(value) {
    if (value !== this._checked) {
      this._checked = value;
      this._onChecked.fire({ listElement: this, checked: value });
    }
  }
  get separator() {
    return this._separator;
  }
  set separator(value) {
    this._separator = value;
  }
  get labelHighlights() {
    return this._labelHighlights;
  }
  set labelHighlights(value) {
    this._labelHighlights = value;
  }
  get descriptionHighlights() {
    return this._descriptionHighlights;
  }
  set descriptionHighlights(value) {
    this._descriptionHighlights = value;
  }
  get detailHighlights() {
    return this._detailHighlights;
  }
  set detailHighlights(value) {
    this._detailHighlights = value;
  }
}
class ListElementRenderer {
  constructor(colorScheme) {
    this.colorScheme = colorScheme;
  }
  get templateId() {
    return ListElementRenderer.ID;
  }
  renderTemplate(container2) {
    const data = /* @__PURE__ */ Object.create(null);
    data.toDisposeElement = [];
    data.toDisposeTemplate = [];
    data.entry = append$1(container2, $$1(".quick-input-list-entry"));
    const label = append$1(data.entry, $$1("label.quick-input-list-label"));
    data.toDisposeTemplate.push(addStandardDisposableListener(label, EventType$1.CLICK, (e) => {
      if (!data.checkbox.offsetParent) {
        e.preventDefault();
      }
    }));
    data.checkbox = append$1(label, $$1("input.quick-input-list-checkbox"));
    data.checkbox.type = "checkbox";
    data.toDisposeTemplate.push(addStandardDisposableListener(data.checkbox, EventType$1.CHANGE, (e) => {
      data.element.checked = data.checkbox.checked;
    }));
    const rows = append$1(label, $$1(".quick-input-list-rows"));
    const row1 = append$1(rows, $$1(".quick-input-list-row"));
    const row2 = append$1(rows, $$1(".quick-input-list-row"));
    data.label = new IconLabel(row1, { supportHighlights: true, supportDescriptionHighlights: true, supportIcons: true });
    data.icon = prepend$1(data.label.element, $$1(".quick-input-list-icon"));
    const keybindingContainer = append$1(row1, $$1(".quick-input-list-entry-keybinding"));
    data.keybinding = new KeybindingLabel(keybindingContainer, OS);
    const detailContainer = append$1(row2, $$1(".quick-input-list-label-meta"));
    data.detail = new IconLabel(detailContainer, { supportHighlights: true, supportIcons: true });
    data.separator = append$1(data.entry, $$1(".quick-input-list-separator"));
    data.actionBar = new ActionBar(data.entry);
    data.actionBar.domNode.classList.add("quick-input-list-entry-action-bar");
    data.toDisposeTemplate.push(data.actionBar);
    return data;
  }
  renderElement(element, index, data) {
    var _a2, _b2, _c2;
    data.element = element;
    element.element = withNullAsUndefined(data.entry);
    const mainItem = element.item ? element.item : element.separator;
    data.checkbox.checked = element.checked;
    data.toDisposeElement.push(element.onChecked((checked2) => data.checkbox.checked = checked2));
    const { labelHighlights, descriptionHighlights, detailHighlights } = element;
    if ((_a2 = element.item) === null || _a2 === void 0 ? void 0 : _a2.iconPath) {
      const icon = isDark(this.colorScheme) ? element.item.iconPath.dark : (_b2 = element.item.iconPath.light) !== null && _b2 !== void 0 ? _b2 : element.item.iconPath.dark;
      const iconUrl = URI.revive(icon);
      data.icon.className = "quick-input-list-icon";
      data.icon.style.backgroundImage = asCSSUrl(iconUrl);
    } else {
      data.icon.style.backgroundImage = "";
      data.icon.className = ((_c2 = element.item) === null || _c2 === void 0 ? void 0 : _c2.iconClass) ? `quick-input-list-icon ${element.item.iconClass}` : "";
    }
    const options = {
      matches: labelHighlights || [],
      descriptionTitle: element.saneDescription,
      descriptionMatches: descriptionHighlights || [],
      labelEscapeNewLines: true
    };
    if (mainItem.type !== "separator") {
      options.extraClasses = mainItem.iconClasses;
      options.italic = mainItem.italic;
      options.strikethrough = mainItem.strikethrough;
      data.entry.classList.remove("quick-input-list-separator-as-item");
    } else {
      data.entry.classList.add("quick-input-list-separator-as-item");
    }
    data.label.setLabel(element.saneLabel, element.saneDescription, options);
    data.keybinding.set(mainItem.type === "separator" ? void 0 : mainItem.keybinding);
    if (element.saneDetail) {
      data.detail.element.style.display = "";
      data.detail.setLabel(element.saneDetail, void 0, {
        matches: detailHighlights,
        title: element.saneDetail,
        labelEscapeNewLines: true
      });
    } else {
      data.detail.element.style.display = "none";
    }
    if (element.item && element.separator && element.separator.label) {
      data.separator.textContent = element.separator.label;
      data.separator.style.display = "";
    } else {
      data.separator.style.display = "none";
    }
    data.entry.classList.toggle("quick-input-list-separator-border", !!element.separator);
    const buttons = mainItem.buttons;
    if (buttons && buttons.length) {
      data.actionBar.push(buttons.map((button2, index2) => {
        let cssClasses = button2.iconClass || (button2.iconPath ? getIconClass(button2.iconPath) : void 0);
        if (button2.alwaysVisible) {
          cssClasses = cssClasses ? `${cssClasses} always-visible` : "always-visible";
        }
        return {
          id: `id-${index2}`,
          class: cssClasses,
          enabled: true,
          label: "",
          tooltip: button2.tooltip || "",
          run: () => {
            mainItem.type !== "separator" ? element.fireButtonTriggered({
              button: button2,
              item: mainItem
            }) : element.fireSeparatorButtonTriggered({
              button: button2,
              separator: mainItem
            });
          }
        };
      }), { icon: true, label: false });
      data.entry.classList.add("has-actions");
    } else {
      data.entry.classList.remove("has-actions");
    }
  }
  disposeElement(element, index, data) {
    data.toDisposeElement = dispose(data.toDisposeElement);
    data.actionBar.clear();
  }
  disposeTemplate(data) {
    data.toDisposeElement = dispose(data.toDisposeElement);
    data.toDisposeTemplate = dispose(data.toDisposeTemplate);
  }
}
ListElementRenderer.ID = "listelement";
class ListElementDelegate {
  getHeight(element) {
    if (!element.item) {
      return 24;
    }
    return element.saneDetail ? 44 : 22;
  }
  getTemplateId(element) {
    return ListElementRenderer.ID;
  }
}
var QuickInputListFocus;
(function(QuickInputListFocus2) {
  QuickInputListFocus2[QuickInputListFocus2["First"] = 1] = "First";
  QuickInputListFocus2[QuickInputListFocus2["Second"] = 2] = "Second";
  QuickInputListFocus2[QuickInputListFocus2["Last"] = 3] = "Last";
  QuickInputListFocus2[QuickInputListFocus2["Next"] = 4] = "Next";
  QuickInputListFocus2[QuickInputListFocus2["Previous"] = 5] = "Previous";
  QuickInputListFocus2[QuickInputListFocus2["NextPage"] = 6] = "NextPage";
  QuickInputListFocus2[QuickInputListFocus2["PreviousPage"] = 7] = "PreviousPage";
})(QuickInputListFocus || (QuickInputListFocus = {}));
class QuickInputList {
  constructor(parent, id3, options) {
    this.parent = parent;
    this.options = options;
    this.inputElements = [];
    this.elements = [];
    this.elementsToIndexes = /* @__PURE__ */ new Map();
    this.matchOnDescription = false;
    this.matchOnDetail = false;
    this.matchOnLabel = true;
    this.matchOnLabelMode = "fuzzy";
    this.sortByLabel = true;
    this._onChangedAllVisibleChecked = new Emitter$1();
    this.onChangedAllVisibleChecked = this._onChangedAllVisibleChecked.event;
    this._onChangedCheckedCount = new Emitter$1();
    this.onChangedCheckedCount = this._onChangedCheckedCount.event;
    this._onChangedVisibleCount = new Emitter$1();
    this.onChangedVisibleCount = this._onChangedVisibleCount.event;
    this._onChangedCheckedElements = new Emitter$1();
    this.onChangedCheckedElements = this._onChangedCheckedElements.event;
    this._onButtonTriggered = new Emitter$1();
    this.onButtonTriggered = this._onButtonTriggered.event;
    this._onSeparatorButtonTriggered = new Emitter$1();
    this.onSeparatorButtonTriggered = this._onSeparatorButtonTriggered.event;
    this._onKeyDown = new Emitter$1();
    this.onKeyDown = this._onKeyDown.event;
    this._onLeave = new Emitter$1();
    this.onLeave = this._onLeave.event;
    this._listElementChecked = new Emitter$1();
    this._fireCheckedEvents = true;
    this.elementDisposables = [];
    this.disposables = [];
    this.id = id3;
    this.container = append$1(this.parent, $$1(".quick-input-list"));
    const delegate = new ListElementDelegate();
    const accessibilityProvider = new QuickInputAccessibilityProvider();
    this.list = options.createList("QuickInput", this.container, delegate, [new ListElementRenderer(this.options.styles.colorScheme)], {
      identityProvider: {
        getId: (element) => {
          var _a2, _b2, _c2, _d2, _e2, _f2, _g2, _h2;
          return (_h2 = (_f2 = (_d2 = (_b2 = (_a2 = element.item) === null || _a2 === void 0 ? void 0 : _a2.id) !== null && _b2 !== void 0 ? _b2 : (_c2 = element.item) === null || _c2 === void 0 ? void 0 : _c2.label) !== null && _d2 !== void 0 ? _d2 : (_e2 = element.separator) === null || _e2 === void 0 ? void 0 : _e2.id) !== null && _f2 !== void 0 ? _f2 : (_g2 = element.separator) === null || _g2 === void 0 ? void 0 : _g2.label) !== null && _h2 !== void 0 ? _h2 : "";
        }
      },
      setRowLineHeight: false,
      multipleSelectionSupport: false,
      horizontalScrolling: false,
      accessibilityProvider
    });
    this.list.getHTMLElement().id = id3;
    this.disposables.push(this.list);
    this.disposables.push(this.list.onKeyDown((e) => {
      const event = new StandardKeyboardEvent(e);
      switch (event.keyCode) {
        case 10:
          this.toggleCheckbox();
          break;
        case 31:
          if (isMacintosh ? e.metaKey : e.ctrlKey) {
            this.list.setFocus(range$1(this.list.length));
          }
          break;
        case 16: {
          const focus1 = this.list.getFocus();
          if (focus1.length === 1 && focus1[0] === 0) {
            this._onLeave.fire();
          }
          break;
        }
        case 18: {
          const focus2 = this.list.getFocus();
          if (focus2.length === 1 && focus2[0] === this.list.length - 1) {
            this._onLeave.fire();
          }
          break;
        }
      }
      this._onKeyDown.fire(event);
    }));
    this.disposables.push(this.list.onMouseDown((e) => {
      if (e.browserEvent.button !== 2) {
        e.browserEvent.preventDefault();
      }
    }));
    this.disposables.push(addDisposableListener(this.container, EventType$1.CLICK, (e) => {
      if (e.x || e.y) {
        this._onLeave.fire();
      }
    }));
    this.disposables.push(this.list.onMouseMiddleClick((e) => {
      this._onLeave.fire();
    }));
    this.disposables.push(this.list.onContextMenu((e) => {
      if (typeof e.index === "number") {
        e.browserEvent.preventDefault();
        this.list.setSelection([e.index]);
      }
    }));
    const delayer2 = new ThrottledDelayer(options.hoverDelegate.delay);
    this.disposables.push(this.list.onMouseOver((e) => __awaiter$8(this, void 0, void 0, function* () {
      var _a2;
      if (e.browserEvent.target instanceof HTMLAnchorElement) {
        delayer2.cancel();
        return;
      }
      if (
        // anchors are an exception as called out above so we skip them here
        !(e.browserEvent.relatedTarget instanceof HTMLAnchorElement) && // check if the mouse is still over the same element
        isAncestor$1(e.browserEvent.relatedTarget, (_a2 = e.element) === null || _a2 === void 0 ? void 0 : _a2.element)
      ) {
        return;
      }
      try {
        yield delayer2.trigger(() => __awaiter$8(this, void 0, void 0, function* () {
          if (e.element) {
            this.showHover(e.element);
          }
        }));
      } catch (e2) {
        if (!isCancellationError(e2)) {
          throw e2;
        }
      }
    })));
    this.disposables.push(this.list.onMouseOut((e) => {
      var _a2;
      if (isAncestor$1(e.browserEvent.relatedTarget, (_a2 = e.element) === null || _a2 === void 0 ? void 0 : _a2.element)) {
        return;
      }
      delayer2.cancel();
    }));
    this.disposables.push(this._listElementChecked.event((_) => this.fireCheckedEvents()));
    this.disposables.push(this._onChangedAllVisibleChecked, this._onChangedCheckedCount, this._onChangedVisibleCount, this._onChangedCheckedElements, this._onButtonTriggered, this._onSeparatorButtonTriggered, this._onLeave, this._onKeyDown, delayer2);
  }
  get onDidChangeFocus() {
    return Event$1.map(this.list.onDidChangeFocus, (e) => e.elements.map((e2) => e2.item));
  }
  get onDidChangeSelection() {
    return Event$1.map(this.list.onDidChangeSelection, (e) => ({ items: e.elements.map((e2) => e2.item), event: e.browserEvent }));
  }
  get scrollTop() {
    return this.list.scrollTop;
  }
  set scrollTop(scrollTop) {
    this.list.scrollTop = scrollTop;
  }
  get ariaLabel() {
    return this.list.getHTMLElement().ariaLabel;
  }
  set ariaLabel(label) {
    this.list.getHTMLElement().ariaLabel = label;
  }
  getAllVisibleChecked() {
    return this.allVisibleChecked(this.elements, false);
  }
  allVisibleChecked(elements, whenNoneVisible = true) {
    for (let i = 0, n2 = elements.length; i < n2; i++) {
      const element = elements[i];
      if (!element.hidden) {
        if (!element.checked) {
          return false;
        } else {
          whenNoneVisible = true;
        }
      }
    }
    return whenNoneVisible;
  }
  getCheckedCount() {
    let count = 0;
    const elements = this.elements;
    for (let i = 0, n2 = elements.length; i < n2; i++) {
      if (elements[i].checked) {
        count++;
      }
    }
    return count;
  }
  getVisibleCount() {
    let count = 0;
    const elements = this.elements;
    for (let i = 0, n2 = elements.length; i < n2; i++) {
      if (!elements[i].hidden) {
        count++;
      }
    }
    return count;
  }
  setAllVisibleChecked(checked2) {
    try {
      this._fireCheckedEvents = false;
      this.elements.forEach((element) => {
        if (!element.hidden) {
          element.checked = checked2;
        }
      });
    } finally {
      this._fireCheckedEvents = true;
      this.fireCheckedEvents();
    }
  }
  setElements(inputElements) {
    this.elementDisposables = dispose(this.elementDisposables);
    const fireButtonTriggered = (event) => this.fireButtonTriggered(event);
    const fireSeparatorButtonTriggered = (event) => this.fireSeparatorButtonTriggered(event);
    this.inputElements = inputElements;
    const elementsToIndexes = /* @__PURE__ */ new Map();
    const hasCheckbox = this.parent.classList.contains("show-checkboxes");
    this.elements = inputElements.reduce((result2, item, index) => {
      var _a2;
      const previous = index > 0 ? inputElements[index - 1] : void 0;
      if (item.type === "separator") {
        if (!item.buttons) {
          return result2;
        }
      }
      const element = new ListElement(item, previous, index, hasCheckbox, fireButtonTriggered, fireSeparatorButtonTriggered, this._listElementChecked);
      const resultIndex = result2.length;
      result2.push(element);
      elementsToIndexes.set((_a2 = element.item) !== null && _a2 !== void 0 ? _a2 : element.separator, resultIndex);
      return result2;
    }, []);
    this.elementsToIndexes = elementsToIndexes;
    this.list.splice(0, this.list.length);
    this.list.splice(0, this.list.length, this.elements);
    this._onChangedVisibleCount.fire(this.elements.length);
  }
  getFocusedElements() {
    return this.list.getFocusedElements().map((e) => e.item);
  }
  setFocusedElements(items) {
    this.list.setFocus(items.filter((item) => this.elementsToIndexes.has(item)).map((item) => this.elementsToIndexes.get(item)));
    if (items.length > 0) {
      const focused = this.list.getFocus()[0];
      if (typeof focused === "number") {
        this.list.reveal(focused);
      }
    }
  }
  getActiveDescendant() {
    return this.list.getHTMLElement().getAttribute("aria-activedescendant");
  }
  setSelectedElements(items) {
    this.list.setSelection(items.filter((item) => this.elementsToIndexes.has(item)).map((item) => this.elementsToIndexes.get(item)));
  }
  getCheckedElements() {
    return this.elements.filter((e) => e.checked).map((e) => e.item).filter((e) => !!e);
  }
  setCheckedElements(items) {
    try {
      this._fireCheckedEvents = false;
      const checked2 = /* @__PURE__ */ new Set();
      for (const item of items) {
        checked2.add(item);
      }
      for (const element of this.elements) {
        element.checked = checked2.has(element.item);
      }
    } finally {
      this._fireCheckedEvents = true;
      this.fireCheckedEvents();
    }
  }
  set enabled(value) {
    this.list.getHTMLElement().style.pointerEvents = value ? "" : "none";
  }
  focus(what) {
    if (!this.list.length) {
      return;
    }
    if (what === QuickInputListFocus.Second && this.list.length < 2) {
      what = QuickInputListFocus.First;
    }
    switch (what) {
      case QuickInputListFocus.First:
        this.list.scrollTop = 0;
        this.list.focusFirst(void 0, (e) => !!e.item);
        break;
      case QuickInputListFocus.Second:
        this.list.scrollTop = 0;
        this.list.focusNth(1, void 0, (e) => !!e.item);
        break;
      case QuickInputListFocus.Last:
        this.list.scrollTop = this.list.scrollHeight;
        this.list.focusLast(void 0, (e) => !!e.item);
        break;
      case QuickInputListFocus.Next: {
        this.list.focusNext(void 0, true, void 0, (e) => !!e.item);
        const index = this.list.getFocus()[0];
        if (index !== 0 && !this.elements[index - 1].item && this.list.firstVisibleIndex > index - 1) {
          this.list.reveal(index - 1);
        }
        break;
      }
      case QuickInputListFocus.Previous: {
        this.list.focusPrevious(void 0, true, void 0, (e) => !!e.item);
        const index = this.list.getFocus()[0];
        if (index !== 0 && !this.elements[index - 1].item && this.list.firstVisibleIndex > index - 1) {
          this.list.reveal(index - 1);
        }
        break;
      }
      case QuickInputListFocus.NextPage:
        this.list.focusNextPage(void 0, (e) => !!e.item);
        break;
      case QuickInputListFocus.PreviousPage:
        this.list.focusPreviousPage(void 0, (e) => !!e.item);
        break;
    }
    const focused = this.list.getFocus()[0];
    if (typeof focused === "number") {
      this.list.reveal(focused);
    }
  }
  clearFocus() {
    this.list.setFocus([]);
  }
  domFocus() {
    this.list.domFocus();
  }
  /**
   * Disposes of the hover and shows a new one for the given index if it has a tooltip.
   * @param element The element to show the hover for
   */
  showHover(element) {
    var _a2, _b2, _c2;
    if (this._lastHover && !this._lastHover.isDisposed) {
      (_b2 = (_a2 = this.options.hoverDelegate).onDidHideHover) === null || _b2 === void 0 ? void 0 : _b2.call(_a2);
      (_c2 = this._lastHover) === null || _c2 === void 0 ? void 0 : _c2.dispose();
    }
    if (!element.element || !element.saneTooltip) {
      return;
    }
    this._lastHover = this.options.hoverDelegate.showHover({
      content: element.saneTooltip,
      target: element.element,
      linkHandler: (url) => {
        this.options.linkOpenerDelegate(url);
      },
      showPointer: true,
      container: this.container,
      hoverPosition: 1
      /* HoverPosition.RIGHT */
    }, false);
  }
  layout(maxHeight) {
    this.list.getHTMLElement().style.maxHeight = maxHeight ? `${// Make sure height aligns with list item heights
    Math.floor(maxHeight / 44) * 44 + 6}px` : "";
    this.list.layout();
  }
  filter(query) {
    if (!(this.sortByLabel || this.matchOnLabel || this.matchOnDescription || this.matchOnDetail)) {
      this.list.layout();
      return false;
    }
    const queryWithWhitespace = query;
    query = query.trim();
    if (!query || !(this.matchOnLabel || this.matchOnDescription || this.matchOnDetail)) {
      this.elements.forEach((element) => {
        element.labelHighlights = void 0;
        element.descriptionHighlights = void 0;
        element.detailHighlights = void 0;
        element.hidden = false;
        const previous = element.index && this.inputElements[element.index - 1];
        if (element.item) {
          element.separator = previous && previous.type === "separator" && !previous.buttons ? previous : void 0;
        }
      });
    } else {
      let currentSeparator;
      this.elements.forEach((element) => {
        let labelHighlights;
        if (this.matchOnLabelMode === "fuzzy") {
          labelHighlights = this.matchOnLabel ? withNullAsUndefined(matchesFuzzyIconAware(query, parseLabelWithIcons(element.saneLabel))) : void 0;
        } else {
          labelHighlights = this.matchOnLabel ? withNullAsUndefined(matchesContiguousIconAware(queryWithWhitespace, parseLabelWithIcons(element.saneLabel))) : void 0;
        }
        const descriptionHighlights = this.matchOnDescription ? withNullAsUndefined(matchesFuzzyIconAware(query, parseLabelWithIcons(element.saneDescription || ""))) : void 0;
        const detailHighlights = this.matchOnDetail ? withNullAsUndefined(matchesFuzzyIconAware(query, parseLabelWithIcons(element.saneDetail || ""))) : void 0;
        if (labelHighlights || descriptionHighlights || detailHighlights) {
          element.labelHighlights = labelHighlights;
          element.descriptionHighlights = descriptionHighlights;
          element.detailHighlights = detailHighlights;
          element.hidden = false;
        } else {
          element.labelHighlights = void 0;
          element.descriptionHighlights = void 0;
          element.detailHighlights = void 0;
          element.hidden = element.item ? !element.item.alwaysShow : true;
        }
        if (element.item) {
          element.separator = void 0;
        } else if (element.separator) {
          element.hidden = true;
        }
        if (!this.sortByLabel) {
          const previous = element.index && this.inputElements[element.index - 1];
          currentSeparator = previous && previous.type === "separator" ? previous : currentSeparator;
          if (currentSeparator && !element.hidden) {
            element.separator = currentSeparator;
            currentSeparator = void 0;
          }
        }
      });
    }
    const shownElements = this.elements.filter((element) => !element.hidden);
    if (this.sortByLabel && query) {
      const normalizedSearchValue = query.toLowerCase();
      shownElements.sort((a, b) => {
        return compareEntries(a, b, normalizedSearchValue);
      });
    }
    this.elementsToIndexes = shownElements.reduce((map2, element, index) => {
      var _a2;
      map2.set((_a2 = element.item) !== null && _a2 !== void 0 ? _a2 : element.separator, index);
      return map2;
    }, /* @__PURE__ */ new Map());
    this.list.splice(0, this.list.length, shownElements);
    this.list.setFocus([]);
    this.list.layout();
    this._onChangedAllVisibleChecked.fire(this.getAllVisibleChecked());
    this._onChangedVisibleCount.fire(shownElements.length);
    return true;
  }
  toggleCheckbox() {
    try {
      this._fireCheckedEvents = false;
      const elements = this.list.getFocusedElements();
      const allChecked = this.allVisibleChecked(elements);
      for (const element of elements) {
        element.checked = !allChecked;
      }
    } finally {
      this._fireCheckedEvents = true;
      this.fireCheckedEvents();
    }
  }
  display(display) {
    this.container.style.display = display ? "" : "none";
  }
  isDisplayed() {
    return this.container.style.display !== "none";
  }
  dispose() {
    this.elementDisposables = dispose(this.elementDisposables);
    this.disposables = dispose(this.disposables);
  }
  fireCheckedEvents() {
    if (this._fireCheckedEvents) {
      this._onChangedAllVisibleChecked.fire(this.getAllVisibleChecked());
      this._onChangedCheckedCount.fire(this.getCheckedCount());
      this._onChangedCheckedElements.fire(this.getCheckedElements());
    }
  }
  fireButtonTriggered(event) {
    this._onButtonTriggered.fire(event);
  }
  fireSeparatorButtonTriggered(event) {
    this._onSeparatorButtonTriggered.fire(event);
  }
  style(styles) {
    this.list.style(styles);
  }
  toggleHover() {
    const element = this.list.getFocusedElements()[0];
    if (!(element === null || element === void 0 ? void 0 : element.saneTooltip)) {
      return;
    }
    if (this._lastHover && !this._lastHover.isDisposed) {
      this._lastHover.dispose();
      return;
    }
    const focused = this.list.getFocusedElements()[0];
    if (!focused) {
      return;
    }
    this.showHover(focused);
    const store = new DisposableStore();
    store.add(this.list.onDidChangeFocus((e) => {
      if (e.indexes.length) {
        this.showHover(e.elements[0]);
      }
    }));
    if (this._lastHover) {
      store.add(this._lastHover);
    }
    this._toggleHover = store;
    this.elementDisposables.push(this._toggleHover);
  }
}
__decorate$d([
  memoize
], QuickInputList.prototype, "onDidChangeFocus", null);
__decorate$d([
  memoize
], QuickInputList.prototype, "onDidChangeSelection", null);
function matchesContiguousIconAware(query, target) {
  const { text: text2, iconOffsets } = target;
  if (!iconOffsets || iconOffsets.length === 0) {
    return matchesContiguous(query, text2);
  }
  const wordToMatchAgainstWithoutIconsTrimmed = ltrim(text2, " ");
  const leadingWhitespaceOffset = text2.length - wordToMatchAgainstWithoutIconsTrimmed.length;
  const matches = matchesContiguous(query, wordToMatchAgainstWithoutIconsTrimmed);
  if (matches) {
    for (const match2 of matches) {
      const iconOffset = iconOffsets[match2.start + leadingWhitespaceOffset] + leadingWhitespaceOffset;
      match2.start += iconOffset;
      match2.end += iconOffset;
    }
  }
  return matches;
}
function matchesContiguous(word2, wordToMatchAgainst) {
  const matchIndex = wordToMatchAgainst.toLowerCase().indexOf(word2.toLowerCase());
  if (matchIndex !== -1) {
    return [{ start: matchIndex, end: matchIndex + word2.length }];
  }
  return null;
}
function compareEntries(elementA, elementB, lookFor) {
  const labelHighlightsA = elementA.labelHighlights || [];
  const labelHighlightsB = elementB.labelHighlights || [];
  if (labelHighlightsA.length && !labelHighlightsB.length) {
    return -1;
  }
  if (!labelHighlightsA.length && labelHighlightsB.length) {
    return 1;
  }
  if (labelHighlightsA.length === 0 && labelHighlightsB.length === 0) {
    return 0;
  }
  return compareAnything(elementA.saneSortLabel, elementB.saneSortLabel, lookFor);
}
class QuickInputAccessibilityProvider {
  getWidgetAriaLabel() {
    return localize("quickInput", "Quick Input");
  }
  getAriaLabel(element) {
    var _a2;
    return ((_a2 = element.separator) === null || _a2 === void 0 ? void 0 : _a2.label) ? `${element.saneAriaLabel}, ${element.separator.label}` : element.saneAriaLabel;
  }
  getWidgetRole() {
    return "listbox";
  }
  getRole(element) {
    return element.hasCheckbox ? "checkbox" : "option";
  }
  isChecked(element) {
    if (!element.hasCheckbox) {
      return void 0;
    }
    return {
      value: element.checked,
      onDidChange: element.onChecked
    };
  }
}
var __awaiter$7 = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
const $ = $$d;
const backButton = {
  iconClass: ThemeIcon.asClassName(Codicon.quickInputBack),
  tooltip: localize("quickInput.back", "Back"),
  handle: -1
  // TODO
};
class QuickInput extends Disposable {
  constructor(ui) {
    super();
    this.ui = ui;
    this._widgetUpdated = false;
    this.visible = false;
    this._enabled = true;
    this._busy = false;
    this._ignoreFocusOut = false;
    this._buttons = [];
    this.buttonsUpdated = false;
    this._toggles = [];
    this.togglesUpdated = false;
    this.noValidationMessage = QuickInput.noPromptMessage;
    this._severity = Severity$2.Ignore;
    this.onDidTriggerButtonEmitter = this._register(new Emitter$1());
    this.onDidHideEmitter = this._register(new Emitter$1());
    this.onDisposeEmitter = this._register(new Emitter$1());
    this.visibleDisposables = this._register(new DisposableStore());
    this.onDidHide = this.onDidHideEmitter.event;
  }
  get title() {
    return this._title;
  }
  set title(title2) {
    this._title = title2;
    this.update();
  }
  get description() {
    return this._description;
  }
  set description(description) {
    this._description = description;
    this.update();
  }
  get step() {
    return this._steps;
  }
  set step(step) {
    this._steps = step;
    this.update();
  }
  get totalSteps() {
    return this._totalSteps;
  }
  set totalSteps(totalSteps) {
    this._totalSteps = totalSteps;
    this.update();
  }
  get enabled() {
    return this._enabled;
  }
  set enabled(enabled) {
    this._enabled = enabled;
    this.update();
  }
  get contextKey() {
    return this._contextKey;
  }
  set contextKey(contextKey) {
    this._contextKey = contextKey;
    this.update();
  }
  get busy() {
    return this._busy;
  }
  set busy(busy) {
    this._busy = busy;
    this.update();
  }
  get ignoreFocusOut() {
    return this._ignoreFocusOut;
  }
  set ignoreFocusOut(ignoreFocusOut) {
    const shouldUpdate = this._ignoreFocusOut !== ignoreFocusOut && !isIOS;
    this._ignoreFocusOut = ignoreFocusOut && !isIOS;
    if (shouldUpdate) {
      this.update();
    }
  }
  get buttons() {
    return this._buttons;
  }
  set buttons(buttons) {
    this._buttons = buttons;
    this.buttonsUpdated = true;
    this.update();
  }
  get toggles() {
    return this._toggles;
  }
  set toggles(toggles) {
    this._toggles = toggles !== null && toggles !== void 0 ? toggles : [];
    this.togglesUpdated = true;
    this.update();
  }
  get validationMessage() {
    return this._validationMessage;
  }
  set validationMessage(validationMessage) {
    this._validationMessage = validationMessage;
    this.update();
  }
  get severity() {
    return this._severity;
  }
  set severity(severity) {
    this._severity = severity;
    this.update();
  }
  show() {
    if (this.visible) {
      return;
    }
    this.visibleDisposables.add(this.ui.onDidTriggerButton((button2) => {
      if (this.buttons.indexOf(button2) !== -1) {
        this.onDidTriggerButtonEmitter.fire(button2);
      }
    }));
    this.ui.show(this);
    this.visible = true;
    this._lastValidationMessage = void 0;
    this._lastSeverity = void 0;
    if (this.buttons.length) {
      this.buttonsUpdated = true;
    }
    if (this.toggles.length) {
      this.togglesUpdated = true;
    }
    this.update();
  }
  hide() {
    if (!this.visible) {
      return;
    }
    this.ui.hide();
  }
  didHide(reason = QuickInputHideReason.Other) {
    this.visible = false;
    this.visibleDisposables.clear();
    this.onDidHideEmitter.fire({ reason });
  }
  update() {
    var _a2, _b2;
    if (!this.visible) {
      return;
    }
    const title2 = this.getTitle();
    if (title2 && this.ui.title.textContent !== title2) {
      this.ui.title.textContent = title2;
    } else if (!title2 && this.ui.title.innerHTML !== "&nbsp;") {
      this.ui.title.innerText = " ";
    }
    const description = this.getDescription();
    if (this.ui.description1.textContent !== description) {
      this.ui.description1.textContent = description;
    }
    if (this.ui.description2.textContent !== description) {
      this.ui.description2.textContent = description;
    }
    if (this._widgetUpdated) {
      this._widgetUpdated = false;
      if (this._widget) {
        reset(this.ui.widget, this._widget);
      } else {
        reset(this.ui.widget);
      }
    }
    if (this.busy && !this.busyDelay) {
      this.busyDelay = new TimeoutTimer();
      this.busyDelay.setIfNotSet(() => {
        if (this.visible) {
          this.ui.progressBar.infinite();
        }
      }, 800);
    }
    if (!this.busy && this.busyDelay) {
      this.ui.progressBar.stop();
      this.busyDelay.cancel();
      this.busyDelay = void 0;
    }
    if (this.buttonsUpdated) {
      this.buttonsUpdated = false;
      this.ui.leftActionBar.clear();
      const leftButtons = this.buttons.filter((button2) => button2 === backButton);
      this.ui.leftActionBar.push(leftButtons.map((button2, index) => {
        const action = new Action(`id-${index}`, "", button2.iconClass || getIconClass(button2.iconPath), true, () => __awaiter$7(this, void 0, void 0, function* () {
          this.onDidTriggerButtonEmitter.fire(button2);
        }));
        action.tooltip = button2.tooltip || "";
        return action;
      }), { icon: true, label: false });
      this.ui.rightActionBar.clear();
      const rightButtons = this.buttons.filter((button2) => button2 !== backButton);
      this.ui.rightActionBar.push(rightButtons.map((button2, index) => {
        const action = new Action(`id-${index}`, "", button2.iconClass || getIconClass(button2.iconPath), true, () => __awaiter$7(this, void 0, void 0, function* () {
          this.onDidTriggerButtonEmitter.fire(button2);
        }));
        action.tooltip = button2.tooltip || "";
        return action;
      }), { icon: true, label: false });
    }
    if (this.togglesUpdated) {
      this.togglesUpdated = false;
      const concreteToggles = (_b2 = (_a2 = this.toggles) === null || _a2 === void 0 ? void 0 : _a2.filter((opts) => opts instanceof Toggle)) !== null && _b2 !== void 0 ? _b2 : [];
      this.ui.inputBox.toggles = concreteToggles;
    }
    this.ui.ignoreFocusOut = this.ignoreFocusOut;
    this.ui.setEnabled(this.enabled);
    this.ui.setContextKey(this.contextKey);
    const validationMessage = this.validationMessage || this.noValidationMessage;
    if (this._lastValidationMessage !== validationMessage) {
      this._lastValidationMessage = validationMessage;
      reset(this.ui.message);
      renderQuickInputDescription(validationMessage, this.ui.message, {
        callback: (content) => {
          this.ui.linkOpenerDelegate(content);
        },
        disposables: this.visibleDisposables
      });
    }
    if (this._lastSeverity !== this.severity) {
      this._lastSeverity = this.severity;
      this.showMessageDecoration(this.severity);
    }
  }
  getTitle() {
    if (this.title && this.step) {
      return `${this.title} (${this.getSteps()})`;
    }
    if (this.title) {
      return this.title;
    }
    if (this.step) {
      return this.getSteps();
    }
    return "";
  }
  getDescription() {
    return this.description || "";
  }
  getSteps() {
    if (this.step && this.totalSteps) {
      return localize("quickInput.steps", "{0}/{1}", this.step, this.totalSteps);
    }
    if (this.step) {
      return String(this.step);
    }
    return "";
  }
  showMessageDecoration(severity) {
    this.ui.inputBox.showDecoration(severity);
    if (severity !== Severity$2.Ignore) {
      const styles = this.ui.inputBox.stylesForType(severity);
      this.ui.message.style.color = styles.foreground ? `${styles.foreground}` : "";
      this.ui.message.style.backgroundColor = styles.background ? `${styles.background}` : "";
      this.ui.message.style.border = styles.border ? `1px solid ${styles.border}` : "";
      this.ui.message.style.marginBottom = "-2px";
    } else {
      this.ui.message.style.color = "";
      this.ui.message.style.backgroundColor = "";
      this.ui.message.style.border = "";
      this.ui.message.style.marginBottom = "";
    }
  }
  dispose() {
    this.hide();
    this.onDisposeEmitter.fire();
    super.dispose();
  }
}
QuickInput.noPromptMessage = localize("inputModeEntry", "Press 'Enter' to confirm your input or 'Escape' to cancel");
class QuickPick extends QuickInput {
  constructor() {
    super(...arguments);
    this._value = "";
    this.onDidChangeValueEmitter = this._register(new Emitter$1());
    this.onWillAcceptEmitter = this._register(new Emitter$1());
    this.onDidAcceptEmitter = this._register(new Emitter$1());
    this.onDidCustomEmitter = this._register(new Emitter$1());
    this._items = [];
    this.itemsUpdated = false;
    this._canSelectMany = false;
    this._canAcceptInBackground = false;
    this._matchOnDescription = false;
    this._matchOnDetail = false;
    this._matchOnLabel = true;
    this._matchOnLabelMode = "fuzzy";
    this._sortByLabel = true;
    this._autoFocusOnList = true;
    this._keepScrollPosition = false;
    this._itemActivation = ItemActivation.FIRST;
    this._activeItems = [];
    this.activeItemsUpdated = false;
    this.activeItemsToConfirm = [];
    this.onDidChangeActiveEmitter = this._register(new Emitter$1());
    this._selectedItems = [];
    this.selectedItemsUpdated = false;
    this.selectedItemsToConfirm = [];
    this.onDidChangeSelectionEmitter = this._register(new Emitter$1());
    this.onDidTriggerItemButtonEmitter = this._register(new Emitter$1());
    this.onDidTriggerSeparatorButtonEmitter = this._register(new Emitter$1());
    this.valueSelectionUpdated = true;
    this._ok = "default";
    this._customButton = false;
    this.filterValue = (value) => value;
    this.onDidChangeValue = this.onDidChangeValueEmitter.event;
    this.onWillAccept = this.onWillAcceptEmitter.event;
    this.onDidAccept = this.onDidAcceptEmitter.event;
    this.onDidChangeActive = this.onDidChangeActiveEmitter.event;
    this.onDidChangeSelection = this.onDidChangeSelectionEmitter.event;
    this.onDidTriggerItemButton = this.onDidTriggerItemButtonEmitter.event;
    this.onDidTriggerSeparatorButton = this.onDidTriggerSeparatorButtonEmitter.event;
  }
  get quickNavigate() {
    return this._quickNavigate;
  }
  set quickNavigate(quickNavigate) {
    this._quickNavigate = quickNavigate;
    this.update();
  }
  get value() {
    return this._value;
  }
  set value(value) {
    this.doSetValue(value);
  }
  doSetValue(value, skipUpdate) {
    if (this._value !== value) {
      this._value = value;
      if (!skipUpdate) {
        this.update();
      }
      if (this.visible) {
        const didFilter = this.ui.list.filter(this.filterValue(this._value));
        if (didFilter) {
          this.trySelectFirst();
        }
      }
      this.onDidChangeValueEmitter.fire(this._value);
    }
  }
  set ariaLabel(ariaLabel) {
    this._ariaLabel = ariaLabel;
    this.update();
  }
  get ariaLabel() {
    return this._ariaLabel;
  }
  get placeholder() {
    return this._placeholder;
  }
  set placeholder(placeholder) {
    this._placeholder = placeholder;
    this.update();
  }
  get items() {
    return this._items;
  }
  get scrollTop() {
    return this.ui.list.scrollTop;
  }
  set scrollTop(scrollTop) {
    this.ui.list.scrollTop = scrollTop;
  }
  set items(items) {
    this._items = items;
    this.itemsUpdated = true;
    this.update();
  }
  get canSelectMany() {
    return this._canSelectMany;
  }
  set canSelectMany(canSelectMany) {
    this._canSelectMany = canSelectMany;
    this.update();
  }
  get canAcceptInBackground() {
    return this._canAcceptInBackground;
  }
  set canAcceptInBackground(canAcceptInBackground) {
    this._canAcceptInBackground = canAcceptInBackground;
  }
  get matchOnDescription() {
    return this._matchOnDescription;
  }
  set matchOnDescription(matchOnDescription) {
    this._matchOnDescription = matchOnDescription;
    this.update();
  }
  get matchOnDetail() {
    return this._matchOnDetail;
  }
  set matchOnDetail(matchOnDetail) {
    this._matchOnDetail = matchOnDetail;
    this.update();
  }
  get matchOnLabel() {
    return this._matchOnLabel;
  }
  set matchOnLabel(matchOnLabel) {
    this._matchOnLabel = matchOnLabel;
    this.update();
  }
  get matchOnLabelMode() {
    return this._matchOnLabelMode;
  }
  set matchOnLabelMode(matchOnLabelMode) {
    this._matchOnLabelMode = matchOnLabelMode;
    this.update();
  }
  get sortByLabel() {
    return this._sortByLabel;
  }
  set sortByLabel(sortByLabel) {
    this._sortByLabel = sortByLabel;
    this.update();
  }
  get autoFocusOnList() {
    return this._autoFocusOnList;
  }
  set autoFocusOnList(autoFocusOnList) {
    this._autoFocusOnList = autoFocusOnList;
    this.update();
  }
  get keepScrollPosition() {
    return this._keepScrollPosition;
  }
  set keepScrollPosition(keepScrollPosition) {
    this._keepScrollPosition = keepScrollPosition;
  }
  get itemActivation() {
    return this._itemActivation;
  }
  set itemActivation(itemActivation) {
    this._itemActivation = itemActivation;
  }
  get activeItems() {
    return this._activeItems;
  }
  set activeItems(activeItems) {
    this._activeItems = activeItems;
    this.activeItemsUpdated = true;
    this.update();
  }
  get selectedItems() {
    return this._selectedItems;
  }
  set selectedItems(selectedItems) {
    this._selectedItems = selectedItems;
    this.selectedItemsUpdated = true;
    this.update();
  }
  get keyMods() {
    if (this._quickNavigate) {
      return NO_KEY_MODS;
    }
    return this.ui.keyMods;
  }
  set valueSelection(valueSelection) {
    this._valueSelection = valueSelection;
    this.valueSelectionUpdated = true;
    this.update();
  }
  get customButton() {
    return this._customButton;
  }
  set customButton(showCustomButton) {
    this._customButton = showCustomButton;
    this.update();
  }
  get customLabel() {
    return this._customButtonLabel;
  }
  set customLabel(label) {
    this._customButtonLabel = label;
    this.update();
  }
  get customHover() {
    return this._customButtonHover;
  }
  set customHover(hover2) {
    this._customButtonHover = hover2;
    this.update();
  }
  get ok() {
    return this._ok;
  }
  set ok(showOkButton) {
    this._ok = showOkButton;
    this.update();
  }
  get hideInput() {
    return !!this._hideInput;
  }
  set hideInput(hideInput) {
    this._hideInput = hideInput;
    this.update();
  }
  trySelectFirst() {
    if (this.autoFocusOnList) {
      if (!this.canSelectMany) {
        this.ui.list.focus(QuickInputListFocus.First);
      }
    }
  }
  show() {
    if (!this.visible) {
      this.visibleDisposables.add(this.ui.inputBox.onDidChange((value) => {
        this.doSetValue(
          value,
          true
          /* skip update since this originates from the UI */
        );
      }));
      this.visibleDisposables.add(this.ui.inputBox.onMouseDown((event) => {
        if (!this.autoFocusOnList) {
          this.ui.list.clearFocus();
        }
      }));
      this.visibleDisposables.add((this._hideInput ? this.ui.list : this.ui.inputBox).onKeyDown((event) => {
        switch (event.keyCode) {
          case 18:
            this.ui.list.focus(QuickInputListFocus.Next);
            if (this.canSelectMany) {
              this.ui.list.domFocus();
            }
            EventHelper.stop(event, true);
            break;
          case 16:
            if (this.ui.list.getFocusedElements().length) {
              this.ui.list.focus(QuickInputListFocus.Previous);
            } else {
              this.ui.list.focus(QuickInputListFocus.Last);
            }
            if (this.canSelectMany) {
              this.ui.list.domFocus();
            }
            EventHelper.stop(event, true);
            break;
          case 12:
            this.ui.list.focus(QuickInputListFocus.NextPage);
            if (this.canSelectMany) {
              this.ui.list.domFocus();
            }
            EventHelper.stop(event, true);
            break;
          case 11:
            this.ui.list.focus(QuickInputListFocus.PreviousPage);
            if (this.canSelectMany) {
              this.ui.list.domFocus();
            }
            EventHelper.stop(event, true);
            break;
          case 17:
            if (!this._canAcceptInBackground) {
              return;
            }
            if (!this.ui.inputBox.isSelectionAtEnd()) {
              return;
            }
            if (this.activeItems[0]) {
              this._selectedItems = [this.activeItems[0]];
              this.onDidChangeSelectionEmitter.fire(this.selectedItems);
              this.handleAccept(true);
            }
            break;
          case 14:
            if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey) {
              this.ui.list.focus(QuickInputListFocus.First);
              EventHelper.stop(event, true);
            }
            break;
          case 13:
            if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey) {
              this.ui.list.focus(QuickInputListFocus.Last);
              EventHelper.stop(event, true);
            }
            break;
        }
      }));
      this.visibleDisposables.add(this.ui.onDidAccept(() => {
        if (this.canSelectMany) {
          if (!this.ui.list.getCheckedElements().length) {
            this._selectedItems = [];
            this.onDidChangeSelectionEmitter.fire(this.selectedItems);
          }
        } else if (this.activeItems[0]) {
          this._selectedItems = [this.activeItems[0]];
          this.onDidChangeSelectionEmitter.fire(this.selectedItems);
        }
        this.handleAccept(false);
      }));
      this.visibleDisposables.add(this.ui.onDidCustom(() => {
        this.onDidCustomEmitter.fire();
      }));
      this.visibleDisposables.add(this.ui.list.onDidChangeFocus((focusedItems) => {
        if (this.activeItemsUpdated) {
          return;
        }
        if (this.activeItemsToConfirm !== this._activeItems && equals$3(focusedItems, this._activeItems, (a, b) => a === b)) {
          return;
        }
        this._activeItems = focusedItems;
        this.onDidChangeActiveEmitter.fire(focusedItems);
      }));
      this.visibleDisposables.add(this.ui.list.onDidChangeSelection(({ items: selectedItems, event }) => {
        if (this.canSelectMany) {
          if (selectedItems.length) {
            this.ui.list.setSelectedElements([]);
          }
          return;
        }
        if (this.selectedItemsToConfirm !== this._selectedItems && equals$3(selectedItems, this._selectedItems, (a, b) => a === b)) {
          return;
        }
        this._selectedItems = selectedItems;
        this.onDidChangeSelectionEmitter.fire(selectedItems);
        if (selectedItems.length) {
          this.handleAccept(
            event instanceof MouseEvent && event.button === 1
            /* mouse middle click */
          );
        }
      }));
      this.visibleDisposables.add(this.ui.list.onChangedCheckedElements((checkedItems) => {
        if (!this.canSelectMany) {
          return;
        }
        if (this.selectedItemsToConfirm !== this._selectedItems && equals$3(checkedItems, this._selectedItems, (a, b) => a === b)) {
          return;
        }
        this._selectedItems = checkedItems;
        this.onDidChangeSelectionEmitter.fire(checkedItems);
      }));
      this.visibleDisposables.add(this.ui.list.onButtonTriggered((event) => this.onDidTriggerItemButtonEmitter.fire(event)));
      this.visibleDisposables.add(this.ui.list.onSeparatorButtonTriggered((event) => this.onDidTriggerSeparatorButtonEmitter.fire(event)));
      this.visibleDisposables.add(this.registerQuickNavigation());
      this.valueSelectionUpdated = true;
    }
    super.show();
  }
  handleAccept(inBackground) {
    let veto = false;
    this.onWillAcceptEmitter.fire({ veto: () => veto = true });
    if (!veto) {
      this.onDidAcceptEmitter.fire({ inBackground });
    }
  }
  registerQuickNavigation() {
    return addDisposableListener(this.ui.container, EventType$1.KEY_UP, (e) => {
      if (this.canSelectMany || !this._quickNavigate) {
        return;
      }
      const keyboardEvent = new StandardKeyboardEvent(e);
      const keyCode = keyboardEvent.keyCode;
      const quickNavKeys = this._quickNavigate.keybindings;
      const wasTriggerKeyPressed = quickNavKeys.some((k) => {
        const chords = k.getChords();
        if (chords.length > 1) {
          return false;
        }
        if (chords[0].shiftKey && keyCode === 4) {
          if (keyboardEvent.ctrlKey || keyboardEvent.altKey || keyboardEvent.metaKey) {
            return false;
          }
          return true;
        }
        if (chords[0].altKey && keyCode === 6) {
          return true;
        }
        if (chords[0].ctrlKey && keyCode === 5) {
          return true;
        }
        if (chords[0].metaKey && keyCode === 57) {
          return true;
        }
        return false;
      });
      if (wasTriggerKeyPressed) {
        if (this.activeItems[0]) {
          this._selectedItems = [this.activeItems[0]];
          this.onDidChangeSelectionEmitter.fire(this.selectedItems);
          this.handleAccept(false);
        }
        this._quickNavigate = void 0;
      }
    });
  }
  update() {
    if (!this.visible) {
      return;
    }
    const scrollTopBefore = this.keepScrollPosition ? this.scrollTop : 0;
    const hasDescription = !!this.description;
    const visibilities = {
      title: !!this.title || !!this.step || !!this.buttons.length,
      description: hasDescription,
      checkAll: this.canSelectMany && !this._hideCheckAll,
      checkBox: this.canSelectMany,
      inputBox: !this._hideInput,
      progressBar: !this._hideInput || hasDescription,
      visibleCount: true,
      count: this.canSelectMany && !this._hideCountBadge,
      ok: this.ok === "default" ? this.canSelectMany : this.ok,
      list: true,
      message: !!this.validationMessage,
      customButton: this.customButton
    };
    this.ui.setVisibilities(visibilities);
    super.update();
    if (this.ui.inputBox.value !== this.value) {
      this.ui.inputBox.value = this.value;
    }
    if (this.valueSelectionUpdated) {
      this.valueSelectionUpdated = false;
      this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] });
    }
    if (this.ui.inputBox.placeholder !== (this.placeholder || "")) {
      this.ui.inputBox.placeholder = this.placeholder || "";
    }
    let ariaLabel = this.ariaLabel;
    if (!ariaLabel && visibilities.inputBox) {
      ariaLabel = this.placeholder || QuickPick.DEFAULT_ARIA_LABEL;
      if (this.title) {
        ariaLabel += ` - ${this.title}`;
      }
    }
    if (this.ui.list.ariaLabel !== ariaLabel) {
      this.ui.list.ariaLabel = withUndefinedAsNull(ariaLabel);
    }
    this.ui.list.matchOnDescription = this.matchOnDescription;
    this.ui.list.matchOnDetail = this.matchOnDetail;
    this.ui.list.matchOnLabel = this.matchOnLabel;
    this.ui.list.matchOnLabelMode = this.matchOnLabelMode;
    this.ui.list.sortByLabel = this.sortByLabel;
    if (this.itemsUpdated) {
      this.itemsUpdated = false;
      this.ui.list.setElements(this.items);
      this.ui.list.filter(this.filterValue(this.ui.inputBox.value));
      this.ui.checkAll.checked = this.ui.list.getAllVisibleChecked();
      this.ui.visibleCount.setCount(this.ui.list.getVisibleCount());
      this.ui.count.setCount(this.ui.list.getCheckedCount());
      switch (this._itemActivation) {
        case ItemActivation.NONE:
          this._itemActivation = ItemActivation.FIRST;
          break;
        case ItemActivation.SECOND:
          this.ui.list.focus(QuickInputListFocus.Second);
          this._itemActivation = ItemActivation.FIRST;
          break;
        case ItemActivation.LAST:
          this.ui.list.focus(QuickInputListFocus.Last);
          this._itemActivation = ItemActivation.FIRST;
          break;
        default:
          this.trySelectFirst();
          break;
      }
    }
    if (this.ui.container.classList.contains("show-checkboxes") !== !!this.canSelectMany) {
      if (this.canSelectMany) {
        this.ui.list.clearFocus();
      } else {
        this.trySelectFirst();
      }
    }
    if (this.activeItemsUpdated) {
      this.activeItemsUpdated = false;
      this.activeItemsToConfirm = this._activeItems;
      this.ui.list.setFocusedElements(this.activeItems);
      if (this.activeItemsToConfirm === this._activeItems) {
        this.activeItemsToConfirm = null;
      }
    }
    if (this.selectedItemsUpdated) {
      this.selectedItemsUpdated = false;
      this.selectedItemsToConfirm = this._selectedItems;
      if (this.canSelectMany) {
        this.ui.list.setCheckedElements(this.selectedItems);
      } else {
        this.ui.list.setSelectedElements(this.selectedItems);
      }
      if (this.selectedItemsToConfirm === this._selectedItems) {
        this.selectedItemsToConfirm = null;
      }
    }
    this.ui.customButton.label = this.customLabel || "";
    this.ui.customButton.element.title = this.customHover || "";
    if (!visibilities.inputBox) {
      this.ui.list.domFocus();
      if (this.canSelectMany) {
        this.ui.list.focus(QuickInputListFocus.First);
      }
    }
    if (this.keepScrollPosition) {
      this.scrollTop = scrollTopBefore;
    }
  }
}
QuickPick.DEFAULT_ARIA_LABEL = localize("quickInputBox.ariaLabel", "Type to narrow down results.");
class InputBox2 extends QuickInput {
  constructor() {
    super(...arguments);
    this._value = "";
    this.valueSelectionUpdated = true;
    this._password = false;
    this.onDidValueChangeEmitter = this._register(new Emitter$1());
    this.onDidAcceptEmitter = this._register(new Emitter$1());
    this.onDidChangeValue = this.onDidValueChangeEmitter.event;
    this.onDidAccept = this.onDidAcceptEmitter.event;
  }
  get value() {
    return this._value;
  }
  set value(value) {
    this._value = value || "";
    this.update();
  }
  get placeholder() {
    return this._placeholder;
  }
  set placeholder(placeholder) {
    this._placeholder = placeholder;
    this.update();
  }
  get password() {
    return this._password;
  }
  set password(password) {
    this._password = password;
    this.update();
  }
  show() {
    if (!this.visible) {
      this.visibleDisposables.add(this.ui.inputBox.onDidChange((value) => {
        if (value === this.value) {
          return;
        }
        this._value = value;
        this.onDidValueChangeEmitter.fire(value);
      }));
      this.visibleDisposables.add(this.ui.onDidAccept(() => this.onDidAcceptEmitter.fire()));
      this.valueSelectionUpdated = true;
    }
    super.show();
  }
  update() {
    if (!this.visible) {
      return;
    }
    this.ui.container.classList.remove("hidden-input");
    const visibilities = {
      title: !!this.title || !!this.step || !!this.buttons.length,
      description: !!this.description || !!this.step,
      inputBox: true,
      message: true,
      progressBar: true
    };
    this.ui.setVisibilities(visibilities);
    super.update();
    if (this.ui.inputBox.value !== this.value) {
      this.ui.inputBox.value = this.value;
    }
    if (this.valueSelectionUpdated) {
      this.valueSelectionUpdated = false;
      this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] });
    }
    if (this.ui.inputBox.placeholder !== (this.placeholder || "")) {
      this.ui.inputBox.placeholder = this.placeholder || "";
    }
    if (this.ui.inputBox.password !== this.password) {
      this.ui.inputBox.password = this.password;
    }
  }
}
class QuickInputController extends Disposable {
  constructor(options) {
    super();
    this.options = options;
    this.enabled = true;
    this.onDidAcceptEmitter = this._register(new Emitter$1());
    this.onDidCustomEmitter = this._register(new Emitter$1());
    this.onDidTriggerButtonEmitter = this._register(new Emitter$1());
    this.keyMods = { ctrlCmd: false, alt: false };
    this.controller = null;
    this.onShowEmitter = this._register(new Emitter$1());
    this.onShow = this.onShowEmitter.event;
    this.onHideEmitter = this._register(new Emitter$1());
    this.onHide = this.onHideEmitter.event;
    this.idPrefix = options.idPrefix;
    this.parentElement = options.container;
    this.styles = options.styles;
    this.registerKeyModsListeners();
  }
  registerKeyModsListeners() {
    const listener = (e) => {
      this.keyMods.ctrlCmd = e.ctrlKey || e.metaKey;
      this.keyMods.alt = e.altKey;
    };
    this._register(addDisposableListener(window, EventType$1.KEY_DOWN, listener, true));
    this._register(addDisposableListener(window, EventType$1.KEY_UP, listener, true));
    this._register(addDisposableListener(window, EventType$1.MOUSE_DOWN, listener, true));
  }
  getUI() {
    if (this.ui) {
      return this.ui;
    }
    const container2 = append$1(this.parentElement, $(".quick-input-widget.show-file-icons"));
    container2.tabIndex = -1;
    container2.style.display = "none";
    const styleSheet = createStyleSheet(container2);
    const titleBar = append$1(container2, $(".quick-input-titlebar"));
    const leftActionBar = this._register(new ActionBar(titleBar));
    leftActionBar.domNode.classList.add("quick-input-left-action-bar");
    const title2 = append$1(titleBar, $(".quick-input-title"));
    const rightActionBar = this._register(new ActionBar(titleBar));
    rightActionBar.domNode.classList.add("quick-input-right-action-bar");
    const headerContainer = append$1(container2, $(".quick-input-header"));
    const checkAll = append$1(headerContainer, $("input.quick-input-check-all"));
    checkAll.type = "checkbox";
    checkAll.setAttribute("aria-label", localize("quickInput.checkAll", "Toggle all checkboxes"));
    this._register(addStandardDisposableListener(checkAll, EventType$1.CHANGE, (e) => {
      const checked2 = checkAll.checked;
      list2.setAllVisibleChecked(checked2);
    }));
    this._register(addDisposableListener(checkAll, EventType$1.CLICK, (e) => {
      if (e.x || e.y) {
        inputBox2.setFocus();
      }
    }));
    const description2 = append$1(headerContainer, $(".quick-input-description"));
    const inputContainer = append$1(headerContainer, $(".quick-input-and-message"));
    const filterContainer = append$1(inputContainer, $(".quick-input-filter"));
    const inputBox2 = this._register(new QuickInputBox(filterContainer, this.styles.inputBox, this.styles.toggle));
    inputBox2.setAttribute("aria-describedby", `${this.idPrefix}message`);
    const visibleCountContainer = append$1(filterContainer, $(".quick-input-visible-count"));
    visibleCountContainer.setAttribute("aria-live", "polite");
    visibleCountContainer.setAttribute("aria-atomic", "true");
    const visibleCount = new CountBadge(visibleCountContainer, { countFormat: localize({ key: "quickInput.visibleCount", comment: ["This tells the user how many items are shown in a list of items to select from. The items can be anything. Currently not visible, but read by screen readers."] }, "{0} Results") }, this.styles.countBadge);
    const countContainer = append$1(filterContainer, $(".quick-input-count"));
    countContainer.setAttribute("aria-live", "polite");
    const count = new CountBadge(countContainer, { countFormat: localize({ key: "quickInput.countSelected", comment: ["This tells the user how many items are selected in a list of items to select from. The items can be anything."] }, "{0} Selected") }, this.styles.countBadge);
    const okContainer = append$1(headerContainer, $(".quick-input-action"));
    const ok2 = new Button(okContainer, this.styles.button);
    ok2.label = localize("ok", "OK");
    this._register(ok2.onDidClick((e) => {
      this.onDidAcceptEmitter.fire();
    }));
    const customButtonContainer = append$1(headerContainer, $(".quick-input-action"));
    const customButton = new Button(customButtonContainer, this.styles.button);
    customButton.label = localize("custom", "Custom");
    this._register(customButton.onDidClick((e) => {
      this.onDidCustomEmitter.fire();
    }));
    const message = append$1(inputContainer, $(`#${this.idPrefix}message.quick-input-message`));
    const progressBar = new ProgressBar(container2, this.styles.progressBar);
    progressBar.getContainer().classList.add("quick-input-progress");
    const widget = append$1(container2, $(".quick-input-html-widget"));
    widget.tabIndex = -1;
    const description1 = append$1(container2, $(".quick-input-description"));
    const listId = this.idPrefix + "list";
    const list2 = this._register(new QuickInputList(container2, listId, this.options));
    inputBox2.setAttribute("aria-controls", listId);
    this._register(list2.onDidChangeFocus(() => {
      var _a2;
      inputBox2.setAttribute("aria-activedescendant", (_a2 = list2.getActiveDescendant()) !== null && _a2 !== void 0 ? _a2 : "");
    }));
    this._register(list2.onChangedAllVisibleChecked((checked2) => {
      checkAll.checked = checked2;
    }));
    this._register(list2.onChangedVisibleCount((c) => {
      visibleCount.setCount(c);
    }));
    this._register(list2.onChangedCheckedCount((c) => {
      count.setCount(c);
    }));
    this._register(list2.onLeave(() => {
      setTimeout(() => {
        inputBox2.setFocus();
        if (this.controller instanceof QuickPick && this.controller.canSelectMany) {
          list2.clearFocus();
        }
      }, 0);
    }));
    const focusTracker = trackFocus(container2);
    this._register(focusTracker);
    this._register(addDisposableListener(container2, EventType$1.FOCUS, (e) => {
      this.previousFocusElement = e.relatedTarget instanceof HTMLElement ? e.relatedTarget : void 0;
    }, true));
    this._register(focusTracker.onDidBlur(() => {
      if (!this.getUI().ignoreFocusOut && !this.options.ignoreFocusOut()) {
        this.hide(QuickInputHideReason.Blur);
      }
      this.previousFocusElement = void 0;
    }));
    this._register(addDisposableListener(container2, EventType$1.FOCUS, (e) => {
      inputBox2.setFocus();
    }));
    this._register(addDisposableListener(container2, EventType$1.KEY_DOWN, (e) => {
      const event = new StandardKeyboardEvent(e);
      switch (event.keyCode) {
        case 3:
          EventHelper.stop(e, true);
          if (this.enabled) {
            this.onDidAcceptEmitter.fire();
          }
          break;
        case 9:
          EventHelper.stop(e, true);
          this.hide(QuickInputHideReason.Gesture);
          break;
        case 2:
          if (!event.altKey && !event.ctrlKey && !event.metaKey) {
            const selectors2 = [
              ".quick-input-list .monaco-action-bar .always-visible",
              ".quick-input-list-entry:hover .monaco-action-bar",
              ".monaco-list-row.focused .monaco-action-bar"
            ];
            if (container2.classList.contains("show-checkboxes")) {
              selectors2.push("input");
            } else {
              selectors2.push("input[type=text]");
            }
            if (this.getUI().list.isDisplayed()) {
              selectors2.push(".monaco-list");
            }
            if (this.getUI().message) {
              selectors2.push(".quick-input-message a");
            }
            if (this.getUI().widget) {
              if (isAncestor$1(event.target, this.getUI().widget)) {
                break;
              }
              selectors2.push(".quick-input-html-widget");
            }
            const stops = container2.querySelectorAll(selectors2.join(", "));
            if (event.shiftKey && event.target === stops[0]) {
              EventHelper.stop(e, true);
              list2.clearFocus();
            } else if (!event.shiftKey && isAncestor$1(event.target, stops[stops.length - 1])) {
              EventHelper.stop(e, true);
              stops[0].focus();
            }
          }
          break;
        case 10:
          if (event.ctrlKey) {
            EventHelper.stop(e, true);
            this.getUI().list.toggleHover();
          }
          break;
      }
    }));
    this.ui = {
      container: container2,
      styleSheet,
      leftActionBar,
      titleBar,
      title: title2,
      description1,
      description2,
      widget,
      rightActionBar,
      checkAll,
      inputContainer,
      filterContainer,
      inputBox: inputBox2,
      visibleCountContainer,
      visibleCount,
      countContainer,
      count,
      okContainer,
      ok: ok2,
      message,
      customButtonContainer,
      customButton,
      list: list2,
      progressBar,
      onDidAccept: this.onDidAcceptEmitter.event,
      onDidCustom: this.onDidCustomEmitter.event,
      onDidTriggerButton: this.onDidTriggerButtonEmitter.event,
      ignoreFocusOut: false,
      keyMods: this.keyMods,
      show: (controller) => this.show(controller),
      hide: () => this.hide(),
      setVisibilities: (visibilities) => this.setVisibilities(visibilities),
      setEnabled: (enabled) => this.setEnabled(enabled),
      setContextKey: (contextKey) => this.options.setContextKey(contextKey),
      linkOpenerDelegate: (content) => this.options.linkOpenerDelegate(content)
    };
    this.updateStyles();
    return this.ui;
  }
  pick(picks, options = {}, token = CancellationToken.None) {
    return new Promise((doResolve, reject) => {
      let resolve2 = (result2) => {
        var _a2;
        resolve2 = doResolve;
        (_a2 = options.onKeyMods) === null || _a2 === void 0 ? void 0 : _a2.call(options, input2.keyMods);
        doResolve(result2);
      };
      if (token.isCancellationRequested) {
        resolve2(void 0);
        return;
      }
      const input2 = this.createQuickPick();
      let activeItem;
      const disposables = [
        input2,
        input2.onDidAccept(() => {
          if (input2.canSelectMany) {
            resolve2(input2.selectedItems.slice());
            input2.hide();
          } else {
            const result2 = input2.activeItems[0];
            if (result2) {
              resolve2(result2);
              input2.hide();
            }
          }
        }),
        input2.onDidChangeActive((items) => {
          const focused = items[0];
          if (focused && options.onDidFocus) {
            options.onDidFocus(focused);
          }
        }),
        input2.onDidChangeSelection((items) => {
          if (!input2.canSelectMany) {
            const result2 = items[0];
            if (result2) {
              resolve2(result2);
              input2.hide();
            }
          }
        }),
        input2.onDidTriggerItemButton((event) => options.onDidTriggerItemButton && options.onDidTriggerItemButton(Object.assign(Object.assign({}, event), { removeItem: () => {
          const index = input2.items.indexOf(event.item);
          if (index !== -1) {
            const items = input2.items.slice();
            const removed = items.splice(index, 1);
            const activeItems = input2.activeItems.filter((activeItem2) => activeItem2 !== removed[0]);
            const keepScrollPositionBefore = input2.keepScrollPosition;
            input2.keepScrollPosition = true;
            input2.items = items;
            if (activeItems) {
              input2.activeItems = activeItems;
            }
            input2.keepScrollPosition = keepScrollPositionBefore;
          }
        } }))),
        input2.onDidTriggerSeparatorButton((event) => {
          var _a2;
          return (_a2 = options.onDidTriggerSeparatorButton) === null || _a2 === void 0 ? void 0 : _a2.call(options, event);
        }),
        input2.onDidChangeValue((value) => {
          if (activeItem && !value && (input2.activeItems.length !== 1 || input2.activeItems[0] !== activeItem)) {
            input2.activeItems = [activeItem];
          }
        }),
        token.onCancellationRequested(() => {
          input2.hide();
        }),
        input2.onDidHide(() => {
          dispose(disposables);
          resolve2(void 0);
        })
      ];
      input2.title = options.title;
      input2.canSelectMany = !!options.canPickMany;
      input2.placeholder = options.placeHolder;
      input2.ignoreFocusOut = !!options.ignoreFocusLost;
      input2.matchOnDescription = !!options.matchOnDescription;
      input2.matchOnDetail = !!options.matchOnDetail;
      input2.matchOnLabel = options.matchOnLabel === void 0 || options.matchOnLabel;
      input2.autoFocusOnList = options.autoFocusOnList === void 0 || options.autoFocusOnList;
      input2.quickNavigate = options.quickNavigate;
      input2.hideInput = !!options.hideInput;
      input2.contextKey = options.contextKey;
      input2.busy = true;
      Promise.all([picks, options.activeItem]).then(([items, _activeItem]) => {
        activeItem = _activeItem;
        input2.busy = false;
        input2.items = items;
        if (input2.canSelectMany) {
          input2.selectedItems = items.filter((item) => item.type !== "separator" && item.picked);
        }
        if (activeItem) {
          input2.activeItems = [activeItem];
        }
      });
      input2.show();
      Promise.resolve(picks).then(void 0, (err) => {
        reject(err);
        input2.hide();
      });
    });
  }
  createQuickPick() {
    const ui = this.getUI();
    return new QuickPick(ui);
  }
  createInputBox() {
    const ui = this.getUI();
    return new InputBox2(ui);
  }
  show(controller) {
    const ui = this.getUI();
    this.onShowEmitter.fire();
    const oldController = this.controller;
    this.controller = controller;
    oldController === null || oldController === void 0 ? void 0 : oldController.didHide();
    this.setEnabled(true);
    ui.leftActionBar.clear();
    ui.title.textContent = "";
    ui.description1.textContent = "";
    ui.description2.textContent = "";
    reset(ui.widget);
    ui.rightActionBar.clear();
    ui.checkAll.checked = false;
    ui.inputBox.placeholder = "";
    ui.inputBox.password = false;
    ui.inputBox.showDecoration(Severity$2.Ignore);
    ui.visibleCount.setCount(0);
    ui.count.setCount(0);
    reset(ui.message);
    ui.progressBar.stop();
    ui.list.setElements([]);
    ui.list.matchOnDescription = false;
    ui.list.matchOnDetail = false;
    ui.list.matchOnLabel = true;
    ui.list.sortByLabel = true;
    ui.ignoreFocusOut = false;
    ui.inputBox.toggles = void 0;
    const backKeybindingLabel = this.options.backKeybindingLabel();
    backButton.tooltip = backKeybindingLabel ? localize("quickInput.backWithKeybinding", "Back ({0})", backKeybindingLabel) : localize("quickInput.back", "Back");
    ui.container.style.display = "";
    this.updateLayout();
    ui.inputBox.setFocus();
  }
  setVisibilities(visibilities) {
    const ui = this.getUI();
    ui.title.style.display = visibilities.title ? "" : "none";
    ui.description1.style.display = visibilities.description && (visibilities.inputBox || visibilities.checkAll) ? "" : "none";
    ui.description2.style.display = visibilities.description && !(visibilities.inputBox || visibilities.checkAll) ? "" : "none";
    ui.checkAll.style.display = visibilities.checkAll ? "" : "none";
    ui.inputContainer.style.display = visibilities.inputBox ? "" : "none";
    ui.filterContainer.style.display = visibilities.inputBox ? "" : "none";
    ui.visibleCountContainer.style.display = visibilities.visibleCount ? "" : "none";
    ui.countContainer.style.display = visibilities.count ? "" : "none";
    ui.okContainer.style.display = visibilities.ok ? "" : "none";
    ui.customButtonContainer.style.display = visibilities.customButton ? "" : "none";
    ui.message.style.display = visibilities.message ? "" : "none";
    ui.progressBar.getContainer().style.display = visibilities.progressBar ? "" : "none";
    ui.list.display(!!visibilities.list);
    ui.container.classList.toggle("show-checkboxes", !!visibilities.checkBox);
    ui.container.classList.toggle("hidden-input", !visibilities.inputBox && !visibilities.description);
    this.updateLayout();
  }
  setEnabled(enabled) {
    if (enabled !== this.enabled) {
      this.enabled = enabled;
      for (const item of this.getUI().leftActionBar.viewItems) {
        item.action.enabled = enabled;
      }
      for (const item of this.getUI().rightActionBar.viewItems) {
        item.action.enabled = enabled;
      }
      this.getUI().checkAll.disabled = !enabled;
      this.getUI().inputBox.enabled = enabled;
      this.getUI().ok.enabled = enabled;
      this.getUI().list.enabled = enabled;
    }
  }
  hide(reason) {
    var _a2;
    const controller = this.controller;
    if (controller) {
      const focusChanged = !((_a2 = this.ui) === null || _a2 === void 0 ? void 0 : _a2.container.contains(document.activeElement));
      this.controller = null;
      this.onHideEmitter.fire();
      this.getUI().container.style.display = "none";
      if (!focusChanged) {
        let currentElement = this.previousFocusElement;
        while (currentElement && !currentElement.offsetParent) {
          currentElement = withNullAsUndefined(currentElement.parentElement);
        }
        if (currentElement === null || currentElement === void 0 ? void 0 : currentElement.offsetParent) {
          currentElement.focus();
          this.previousFocusElement = void 0;
        } else {
          this.options.returnFocus();
        }
      }
      controller.didHide(reason);
    }
  }
  layout(dimension, titleBarOffset) {
    this.dimension = dimension;
    this.titleBarOffset = titleBarOffset;
    this.updateLayout();
  }
  updateLayout() {
    if (this.ui && this.isDisplayed()) {
      this.ui.container.style.top = `${this.titleBarOffset}px`;
      const style2 = this.ui.container.style;
      const width = Math.min(this.dimension.width * 0.62, QuickInputController.MAX_WIDTH);
      style2.width = width + "px";
      style2.marginLeft = "-" + width / 2 + "px";
      this.ui.inputBox.layout();
      this.ui.list.layout(this.dimension && this.dimension.height * 0.4);
    }
  }
  applyStyles(styles) {
    this.styles = styles;
    this.updateStyles();
  }
  updateStyles() {
    if (this.ui) {
      const { quickInputTitleBackground: quickInputTitleBackground2, quickInputBackground: quickInputBackground2, quickInputForeground: quickInputForeground2, widgetBorder: widgetBorder2, widgetShadow: widgetShadow2 } = this.styles.widget;
      this.ui.titleBar.style.backgroundColor = quickInputTitleBackground2 !== null && quickInputTitleBackground2 !== void 0 ? quickInputTitleBackground2 : "";
      this.ui.container.style.backgroundColor = quickInputBackground2 !== null && quickInputBackground2 !== void 0 ? quickInputBackground2 : "";
      this.ui.container.style.color = quickInputForeground2 !== null && quickInputForeground2 !== void 0 ? quickInputForeground2 : "";
      this.ui.container.style.border = widgetBorder2 ? `1px solid ${widgetBorder2}` : "";
      this.ui.container.style.boxShadow = widgetShadow2 ? `0 0 8px 2px ${widgetShadow2}` : "";
      this.ui.list.style(this.styles.list);
      const content = [];
      if (this.styles.pickerGroup.pickerGroupBorder) {
        content.push(`.quick-input-list .quick-input-list-entry { border-top-color:  ${this.styles.pickerGroup.pickerGroupBorder}; }`);
      }
      if (this.styles.pickerGroup.pickerGroupForeground) {
        content.push(`.quick-input-list .quick-input-list-separator { color:  ${this.styles.pickerGroup.pickerGroupForeground}; }`);
      }
      if (this.styles.pickerGroup.pickerGroupForeground) {
        content.push(`.quick-input-list .quick-input-list-separator-as-item { color:  ${this.styles.pickerGroup.pickerGroupForeground}; }`);
      }
      if (this.styles.keybindingLabel.keybindingLabelBackground || this.styles.keybindingLabel.keybindingLabelBorder || this.styles.keybindingLabel.keybindingLabelBottomBorder || this.styles.keybindingLabel.keybindingLabelShadow || this.styles.keybindingLabel.keybindingLabelForeground) {
        content.push(".quick-input-list .monaco-keybinding > .monaco-keybinding-key {");
        if (this.styles.keybindingLabel.keybindingLabelBackground) {
          content.push(`background-color: ${this.styles.keybindingLabel.keybindingLabelBackground};`);
        }
        if (this.styles.keybindingLabel.keybindingLabelBorder) {
          content.push(`border-color: ${this.styles.keybindingLabel.keybindingLabelBorder};`);
        }
        if (this.styles.keybindingLabel.keybindingLabelBottomBorder) {
          content.push(`border-bottom-color: ${this.styles.keybindingLabel.keybindingLabelBottomBorder};`);
        }
        if (this.styles.keybindingLabel.keybindingLabelShadow) {
          content.push(`box-shadow: inset 0 -1px 0 ${this.styles.keybindingLabel.keybindingLabelShadow};`);
        }
        if (this.styles.keybindingLabel.keybindingLabelForeground) {
          content.push(`color: ${this.styles.keybindingLabel.keybindingLabelForeground};`);
        }
        content.push("}");
      }
      const newStyles = content.join("\n");
      if (newStyles !== this.ui.styleSheet.textContent) {
        this.ui.styleSheet.textContent = newStyles;
      }
    }
  }
  isDisplayed() {
    return this.ui && this.ui.container.style.display !== "none";
  }
}
QuickInputController.MAX_WIDTH = 600;
var __decorate$c = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$c = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let QuickInputService = class QuickInputService2 extends Themable {
  get controller() {
    if (!this._controller) {
      this._controller = this._register(this.createController());
    }
    return this._controller;
  }
  get hasController() {
    return !!this._controller;
  }
  get quickAccess() {
    if (!this._quickAccess) {
      this._quickAccess = this._register(this.instantiationService.createInstance(QuickAccessController));
    }
    return this._quickAccess;
  }
  constructor(instantiationService, contextKeyService, themeService, layoutService) {
    super(themeService);
    this.instantiationService = instantiationService;
    this.contextKeyService = contextKeyService;
    this.layoutService = layoutService;
    this._onShow = this._register(new Emitter$1());
    this._onHide = this._register(new Emitter$1());
    this.contexts = /* @__PURE__ */ new Map();
  }
  createController(host = this.layoutService, options) {
    const defaultOptions2 = {
      idPrefix: "quickInput_",
      container: host.container,
      ignoreFocusOut: () => false,
      backKeybindingLabel: () => void 0,
      setContextKey: (id3) => this.setContextKey(id3),
      linkOpenerDelegate: (content) => {
        this.instantiationService.invokeFunction((accessor) => {
          const openerService = accessor.get(IOpenerService);
          openerService.open(content, { allowCommands: true, fromUserGesture: true });
        });
      },
      returnFocus: () => host.focus(),
      createList: (user, container2, delegate, renderers, options2) => this.instantiationService.createInstance(WorkbenchList, user, container2, delegate, renderers, options2),
      hoverDelegate: {
        showHover(options2, focus) {
          return void 0;
        },
        delay: 200
      },
      styles: this.computeStyles()
    };
    const controller = this._register(new QuickInputController(Object.assign(Object.assign({}, defaultOptions2), options)));
    controller.layout(host.dimension, host.offset.quickPickTop);
    this._register(host.onDidLayout((dimension) => controller.layout(dimension, host.offset.quickPickTop)));
    this._register(controller.onShow(() => {
      this.resetContextKeys();
      this._onShow.fire();
    }));
    this._register(controller.onHide(() => {
      this.resetContextKeys();
      this._onHide.fire();
    }));
    return controller;
  }
  setContextKey(id3) {
    let key;
    if (id3) {
      key = this.contexts.get(id3);
      if (!key) {
        key = new RawContextKey(id3, false).bindTo(this.contextKeyService);
        this.contexts.set(id3, key);
      }
    }
    if (key && key.get()) {
      return;
    }
    this.resetContextKeys();
    key === null || key === void 0 ? void 0 : key.set(true);
  }
  resetContextKeys() {
    this.contexts.forEach((context) => {
      if (context.get()) {
        context.reset();
      }
    });
  }
  pick(picks, options = {}, token = CancellationToken.None) {
    return this.controller.pick(picks, options, token);
  }
  createQuickPick() {
    return this.controller.createQuickPick();
  }
  createInputBox() {
    return this.controller.createInputBox();
  }
  updateStyles() {
    if (this.hasController) {
      this.controller.applyStyles(this.computeStyles());
    }
  }
  computeStyles() {
    return {
      widget: {
        quickInputBackground: asCssVariable(quickInputBackground),
        quickInputForeground: asCssVariable(quickInputForeground),
        quickInputTitleBackground: asCssVariable(quickInputTitleBackground),
        widgetBorder: asCssVariable(widgetBorder),
        widgetShadow: asCssVariable(widgetShadow)
      },
      inputBox: defaultInputBoxStyles,
      toggle: defaultToggleStyles,
      countBadge: defaultCountBadgeStyles,
      button: defaultButtonStyles,
      progressBar: defaultProgressBarStyles,
      keybindingLabel: defaultKeybindingLabelStyles,
      list: getListStyles({
        listBackground: quickInputBackground,
        listFocusBackground: quickInputListFocusBackground,
        listFocusForeground: quickInputListFocusForeground,
        // Look like focused when inactive.
        listInactiveFocusForeground: quickInputListFocusForeground,
        listInactiveSelectionIconForeground: quickInputListFocusIconForeground,
        listInactiveFocusBackground: quickInputListFocusBackground,
        listFocusOutline: activeContrastBorder,
        listInactiveFocusOutline: activeContrastBorder
      }),
      pickerGroup: {
        pickerGroupBorder: asCssVariable(pickerGroupBorder),
        pickerGroupForeground: asCssVariable(pickerGroupForeground)
      },
      colorScheme: this.themeService.getColorTheme().type
    };
  }
};
QuickInputService = __decorate$c([
  __param$c(0, IInstantiationService),
  __param$c(1, IContextKeyService),
  __param$c(2, IThemeService),
  __param$c(3, ILayoutService)
], QuickInputService);
var __decorate$b = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$b = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let EditorScopedQuickInputService = class EditorScopedQuickInputService2 extends QuickInputService {
  constructor(editor2, instantiationService, contextKeyService, themeService, codeEditorService) {
    super(instantiationService, contextKeyService, themeService, new EditorScopedLayoutService(editor2.getContainerDomNode(), codeEditorService));
    this.host = void 0;
    const contribution = QuickInputEditorContribution.get(editor2);
    if (contribution) {
      const widget = contribution.widget;
      this.host = {
        _serviceBrand: void 0,
        get hasContainer() {
          return true;
        },
        get container() {
          return widget.getDomNode();
        },
        get dimension() {
          return editor2.getLayoutInfo();
        },
        get onDidLayout() {
          return editor2.onDidLayoutChange;
        },
        focus: () => editor2.focus(),
        offset: { top: 0, quickPickTop: 0 }
      };
    } else {
      this.host = void 0;
    }
  }
  createController() {
    return super.createController(this.host);
  }
};
EditorScopedQuickInputService = __decorate$b([
  __param$b(1, IInstantiationService),
  __param$b(2, IContextKeyService),
  __param$b(3, IThemeService),
  __param$b(4, ICodeEditorService)
], EditorScopedQuickInputService);
let StandaloneQuickInputService = class StandaloneQuickInputService2 {
  get activeService() {
    const editor2 = this.codeEditorService.getFocusedCodeEditor();
    if (!editor2) {
      throw new Error("Quick input service needs a focused editor to work.");
    }
    let quickInputService = this.mapEditorToService.get(editor2);
    if (!quickInputService) {
      const newQuickInputService = quickInputService = this.instantiationService.createInstance(EditorScopedQuickInputService, editor2);
      this.mapEditorToService.set(editor2, quickInputService);
      once$2(editor2.onDidDispose)(() => {
        newQuickInputService.dispose();
        this.mapEditorToService.delete(editor2);
      });
    }
    return quickInputService;
  }
  get quickAccess() {
    return this.activeService.quickAccess;
  }
  constructor(instantiationService, codeEditorService) {
    this.instantiationService = instantiationService;
    this.codeEditorService = codeEditorService;
    this.mapEditorToService = /* @__PURE__ */ new Map();
  }
  pick(picks, options = {}, token = CancellationToken.None) {
    return this.activeService.pick(picks, options, token);
  }
  createQuickPick() {
    return this.activeService.createQuickPick();
  }
  createInputBox() {
    return this.activeService.createInputBox();
  }
};
StandaloneQuickInputService = __decorate$b([
  __param$b(0, IInstantiationService),
  __param$b(1, ICodeEditorService)
], StandaloneQuickInputService);
class QuickInputEditorContribution {
  static get(editor2) {
    return editor2.getContribution(QuickInputEditorContribution.ID);
  }
  constructor(editor2) {
    this.editor = editor2;
    this.widget = new QuickInputEditorWidget(this.editor);
  }
  dispose() {
    this.widget.dispose();
  }
}
QuickInputEditorContribution.ID = "editor.controller.quickInput";
class QuickInputEditorWidget {
  constructor(codeEditor) {
    this.codeEditor = codeEditor;
    this.domNode = document.createElement("div");
    this.codeEditor.addOverlayWidget(this);
  }
  getId() {
    return QuickInputEditorWidget.ID;
  }
  getDomNode() {
    return this.domNode;
  }
  getPosition() {
    return {
      preference: 2
      /* OverlayWidgetPositionPreference.TOP_CENTER */
    };
  }
  dispose() {
    this.codeEditor.removeOverlayWidget(this);
  }
}
QuickInputEditorWidget.ID = "editor.contrib.quickInputWidget";
registerEditorContribution(
  QuickInputEditorContribution.ID,
  QuickInputEditorContribution,
  4
  /* EditorContributionInstantiation.Lazy */
);
var __decorate$a = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$a = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let AccessibilityService = class AccessibilityService2 extends Disposable {
  constructor(_contextKeyService, _layoutService, _configurationService) {
    super();
    this._contextKeyService = _contextKeyService;
    this._layoutService = _layoutService;
    this._configurationService = _configurationService;
    this._accessibilitySupport = 0;
    this._onDidChangeScreenReaderOptimized = new Emitter$1();
    this._onDidChangeReducedMotion = new Emitter$1();
    this._accessibilityModeEnabledContext = CONTEXT_ACCESSIBILITY_MODE_ENABLED.bindTo(this._contextKeyService);
    const updateContextKey = () => this._accessibilityModeEnabledContext.set(this.isScreenReaderOptimized());
    this._register(this._configurationService.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration("editor.accessibilitySupport")) {
        updateContextKey();
        this._onDidChangeScreenReaderOptimized.fire();
      }
      if (e.affectsConfiguration("workbench.reduceMotion")) {
        this._configMotionReduced = this._configurationService.getValue("workbench.reduceMotion");
        this._onDidChangeReducedMotion.fire();
      }
    }));
    updateContextKey();
    this._register(this.onDidChangeScreenReaderOptimized(() => updateContextKey()));
    const reduceMotionMatcher = window.matchMedia(`(prefers-reduced-motion: reduce)`);
    this._systemMotionReduced = reduceMotionMatcher.matches;
    this._configMotionReduced = this._configurationService.getValue("workbench.reduceMotion");
    this.initReducedMotionListeners(reduceMotionMatcher);
  }
  initReducedMotionListeners(reduceMotionMatcher) {
    if (!this._layoutService.hasContainer) {
      return;
    }
    this._register(addDisposableListener(reduceMotionMatcher, "change", () => {
      this._systemMotionReduced = reduceMotionMatcher.matches;
      if (this._configMotionReduced === "auto") {
        this._onDidChangeReducedMotion.fire();
      }
    }));
    const updateRootClasses = () => {
      const reduce = this.isMotionReduced();
      this._layoutService.container.classList.toggle("reduce-motion", reduce);
      this._layoutService.container.classList.toggle("enable-motion", !reduce);
    };
    updateRootClasses();
    this._register(this.onDidChangeReducedMotion(() => updateRootClasses()));
  }
  get onDidChangeScreenReaderOptimized() {
    return this._onDidChangeScreenReaderOptimized.event;
  }
  isScreenReaderOptimized() {
    const config2 = this._configurationService.getValue("editor.accessibilitySupport");
    return config2 === "on" || config2 === "auto" && this._accessibilitySupport === 2;
  }
  get onDidChangeReducedMotion() {
    return this._onDidChangeReducedMotion.event;
  }
  isMotionReduced() {
    const config2 = this._configMotionReduced;
    return config2 === "on" || config2 === "auto" && this._systemMotionReduced;
  }
  getAccessibilitySupport() {
    return this._accessibilitySupport;
  }
};
AccessibilityService = __decorate$a([
  __param$a(0, IContextKeyService),
  __param$a(1, ILayoutService),
  __param$a(2, IConfigurationService)
], AccessibilityService);
var __decorate$9 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$9 = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let MenuService = class MenuService2 {
  constructor(_commandService, storageService) {
    this._commandService = _commandService;
    this._hiddenStates = new PersistedMenuHideState(storageService);
  }
  createMenu(id3, contextKeyService, options) {
    return new MenuImpl(id3, this._hiddenStates, Object.assign({ emitEventsForSubmenuChanges: false, eventDebounceDelay: 50 }, options), this._commandService, contextKeyService);
  }
  resetHiddenStates(ids) {
    this._hiddenStates.reset(ids);
  }
};
MenuService = __decorate$9([
  __param$9(0, ICommandService),
  __param$9(1, IStorageService)
], MenuService);
let PersistedMenuHideState = class PersistedMenuHideState2 {
  constructor(_storageService) {
    this._storageService = _storageService;
    this._disposables = new DisposableStore();
    this._onDidChange = new Emitter$1();
    this.onDidChange = this._onDidChange.event;
    this._ignoreChangeEvent = false;
    this._hiddenByDefaultCache = /* @__PURE__ */ new Map();
    try {
      const raw = _storageService.get(PersistedMenuHideState2._key, 0, "{}");
      this._data = JSON.parse(raw);
    } catch (err) {
      this._data = /* @__PURE__ */ Object.create(null);
    }
    this._disposables.add(_storageService.onDidChangeValue((e) => {
      if (e.key !== PersistedMenuHideState2._key) {
        return;
      }
      if (!this._ignoreChangeEvent) {
        try {
          const raw = _storageService.get(PersistedMenuHideState2._key, 0, "{}");
          this._data = JSON.parse(raw);
        } catch (err) {
          console.log("FAILED to read storage after UPDATE", err);
        }
      }
      this._onDidChange.fire();
    }));
  }
  dispose() {
    this._onDidChange.dispose();
    this._disposables.dispose();
  }
  _isHiddenByDefault(menu, commandId) {
    var _a2;
    return (_a2 = this._hiddenByDefaultCache.get(`${menu.id}/${commandId}`)) !== null && _a2 !== void 0 ? _a2 : false;
  }
  setDefaultState(menu, commandId, hidden) {
    this._hiddenByDefaultCache.set(`${menu.id}/${commandId}`, hidden);
  }
  isHidden(menu, commandId) {
    var _a2, _b2;
    const hiddenByDefault = this._isHiddenByDefault(menu, commandId);
    const state = (_b2 = (_a2 = this._data[menu.id]) === null || _a2 === void 0 ? void 0 : _a2.includes(commandId)) !== null && _b2 !== void 0 ? _b2 : false;
    return hiddenByDefault ? !state : state;
  }
  updateHidden(menu, commandId, hidden) {
    const hiddenByDefault = this._isHiddenByDefault(menu, commandId);
    if (hiddenByDefault) {
      hidden = !hidden;
    }
    const entries = this._data[menu.id];
    if (!hidden) {
      if (entries) {
        const idx = entries.indexOf(commandId);
        if (idx >= 0) {
          removeFastWithoutKeepingOrder(entries, idx);
        }
        if (entries.length === 0) {
          delete this._data[menu.id];
        }
      }
    } else {
      if (!entries) {
        this._data[menu.id] = [commandId];
      } else {
        const idx = entries.indexOf(commandId);
        if (idx < 0) {
          entries.push(commandId);
        }
      }
    }
    this._persist();
  }
  reset(menus) {
    if (menus === void 0) {
      this._data = /* @__PURE__ */ Object.create(null);
      this._persist();
    } else {
      for (const { id: id3 } of menus) {
        if (this._data[id3]) {
          delete this._data[id3];
        }
      }
      this._persist();
    }
  }
  _persist() {
    try {
      this._ignoreChangeEvent = true;
      const raw = JSON.stringify(this._data);
      this._storageService.store(
        PersistedMenuHideState2._key,
        raw,
        0,
        0
        /* StorageTarget.USER */
      );
    } finally {
      this._ignoreChangeEvent = false;
    }
  }
};
PersistedMenuHideState._key = "menu.hiddenCommands";
PersistedMenuHideState = __decorate$9([
  __param$9(0, IStorageService)
], PersistedMenuHideState);
let MenuInfo = class MenuInfo2 {
  constructor(_id2, _hiddenStates, _collectContextKeysForSubmenus, _commandService, _contextKeyService) {
    this._id = _id2;
    this._hiddenStates = _hiddenStates;
    this._collectContextKeysForSubmenus = _collectContextKeysForSubmenus;
    this._commandService = _commandService;
    this._contextKeyService = _contextKeyService;
    this._menuGroups = [];
    this._structureContextKeys = /* @__PURE__ */ new Set();
    this._preconditionContextKeys = /* @__PURE__ */ new Set();
    this._toggledContextKeys = /* @__PURE__ */ new Set();
    this.refresh();
  }
  get structureContextKeys() {
    return this._structureContextKeys;
  }
  get preconditionContextKeys() {
    return this._preconditionContextKeys;
  }
  get toggledContextKeys() {
    return this._toggledContextKeys;
  }
  refresh() {
    this._menuGroups.length = 0;
    this._structureContextKeys.clear();
    this._preconditionContextKeys.clear();
    this._toggledContextKeys.clear();
    const menuItems = MenuRegistry.getMenuItems(this._id);
    let group2;
    menuItems.sort(MenuInfo2._compareMenuItems);
    for (const item of menuItems) {
      const groupName = item.group || "";
      if (!group2 || group2[0] !== groupName) {
        group2 = [groupName, []];
        this._menuGroups.push(group2);
      }
      group2[1].push(item);
      this._collectContextKeys(item);
    }
  }
  _collectContextKeys(item) {
    MenuInfo2._fillInKbExprKeys(item.when, this._structureContextKeys);
    if (isIMenuItem(item)) {
      if (item.command.precondition) {
        MenuInfo2._fillInKbExprKeys(item.command.precondition, this._preconditionContextKeys);
      }
      if (item.command.toggled) {
        const toggledExpression = item.command.toggled.condition || item.command.toggled;
        MenuInfo2._fillInKbExprKeys(toggledExpression, this._toggledContextKeys);
      }
    } else if (this._collectContextKeysForSubmenus) {
      MenuRegistry.getMenuItems(item.submenu).forEach(this._collectContextKeys, this);
    }
  }
  createActionGroups(options) {
    const result2 = [];
    for (const group2 of this._menuGroups) {
      const [id3, items] = group2;
      const activeActions = [];
      for (const item of items) {
        if (this._contextKeyService.contextMatchesRules(item.when)) {
          const isMenuItem = isIMenuItem(item);
          if (isMenuItem) {
            this._hiddenStates.setDefaultState(this._id, item.command.id, !!item.isHiddenByDefault);
          }
          const menuHide = createMenuHide(this._id, isMenuItem ? item.command : item, this._hiddenStates);
          if (isMenuItem) {
            activeActions.push(new MenuItemAction(item.command, item.alt, options, menuHide, this._contextKeyService, this._commandService));
          } else {
            const groups = new MenuInfo2(item.submenu, this._hiddenStates, this._collectContextKeysForSubmenus, this._commandService, this._contextKeyService).createActionGroups(options);
            const submenuActions = Separator.join(...groups.map((g) => g[1]));
            if (submenuActions.length > 0) {
              activeActions.push(new SubmenuItemAction(item, menuHide, submenuActions));
            }
          }
        }
      }
      if (activeActions.length > 0) {
        result2.push([id3, activeActions]);
      }
    }
    return result2;
  }
  static _fillInKbExprKeys(exp, set2) {
    if (exp) {
      for (const key of exp.keys()) {
        set2.add(key);
      }
    }
  }
  static _compareMenuItems(a, b) {
    const aGroup = a.group;
    const bGroup = b.group;
    if (aGroup !== bGroup) {
      if (!aGroup) {
        return 1;
      } else if (!bGroup) {
        return -1;
      }
      if (aGroup === "navigation") {
        return -1;
      } else if (bGroup === "navigation") {
        return 1;
      }
      const value = aGroup.localeCompare(bGroup);
      if (value !== 0) {
        return value;
      }
    }
    const aPrio = a.order || 0;
    const bPrio = b.order || 0;
    if (aPrio < bPrio) {
      return -1;
    } else if (aPrio > bPrio) {
      return 1;
    }
    return MenuInfo2._compareTitles(isIMenuItem(a) ? a.command.title : a.title, isIMenuItem(b) ? b.command.title : b.title);
  }
  static _compareTitles(a, b) {
    const aStr = typeof a === "string" ? a : a.original;
    const bStr = typeof b === "string" ? b : b.original;
    return aStr.localeCompare(bStr);
  }
};
MenuInfo = __decorate$9([
  __param$9(3, ICommandService),
  __param$9(4, IContextKeyService)
], MenuInfo);
let MenuImpl = class MenuImpl2 {
  constructor(id3, hiddenStates, options, commandService, contextKeyService) {
    this._disposables = new DisposableStore();
    this._menuInfo = new MenuInfo(id3, hiddenStates, options.emitEventsForSubmenuChanges, commandService, contextKeyService);
    const rebuildMenuSoon = new RunOnceScheduler(() => {
      this._menuInfo.refresh();
      this._onDidChange.fire({ menu: this, isStructuralChange: true, isEnablementChange: true, isToggleChange: true });
    }, options.eventDebounceDelay);
    this._disposables.add(rebuildMenuSoon);
    this._disposables.add(MenuRegistry.onDidChangeMenu((e) => {
      if (e.has(id3)) {
        rebuildMenuSoon.schedule();
      }
    }));
    const lazyListener = this._disposables.add(new DisposableStore());
    const merge2 = (events) => {
      let isStructuralChange = false;
      let isEnablementChange = false;
      let isToggleChange = false;
      for (const item of events) {
        isStructuralChange = isStructuralChange || item.isStructuralChange;
        isEnablementChange = isEnablementChange || item.isEnablementChange;
        isToggleChange = isToggleChange || item.isToggleChange;
        if (isStructuralChange && isEnablementChange && isToggleChange) {
          break;
        }
      }
      return { menu: this, isStructuralChange, isEnablementChange, isToggleChange };
    };
    const startLazyListener = () => {
      lazyListener.add(contextKeyService.onDidChangeContext((e) => {
        const isStructuralChange = e.affectsSome(this._menuInfo.structureContextKeys);
        const isEnablementChange = e.affectsSome(this._menuInfo.preconditionContextKeys);
        const isToggleChange = e.affectsSome(this._menuInfo.toggledContextKeys);
        if (isStructuralChange || isEnablementChange || isToggleChange) {
          this._onDidChange.fire({ menu: this, isStructuralChange, isEnablementChange, isToggleChange });
        }
      }));
      lazyListener.add(hiddenStates.onDidChange((e) => {
        this._onDidChange.fire({ menu: this, isStructuralChange: true, isEnablementChange: false, isToggleChange: false });
      }));
    };
    this._onDidChange = new DebounceEmitter({
      // start/stop context key listener
      onWillAddFirstListener: startLazyListener,
      onDidRemoveLastListener: lazyListener.clear.bind(lazyListener),
      delay: options.eventDebounceDelay,
      merge: merge2
    });
    this.onDidChange = this._onDidChange.event;
  }
  getActions(options) {
    return this._menuInfo.createActionGroups(options);
  }
  dispose() {
    this._disposables.dispose();
    this._onDidChange.dispose();
  }
};
MenuImpl = __decorate$9([
  __param$9(3, ICommandService),
  __param$9(4, IContextKeyService)
], MenuImpl);
function createMenuHide(menu, command, states) {
  const id3 = isISubmenuItem(command) ? command.submenu.id : command.id;
  const title2 = typeof command.title === "string" ? command.title : command.title.value;
  const hide2 = toAction({
    id: `hide/${menu.id}/${id3}`,
    label: localize("hide.label", "Hide '{0}'", title2),
    run() {
      states.updateHidden(menu, id3, true);
    }
  });
  const toggle2 = toAction({
    id: `toggle/${menu.id}/${id3}`,
    label: title2,
    get checked() {
      return !states.isHidden(menu, id3);
    },
    run() {
      states.updateHidden(menu, id3, !!this.checked);
    }
  });
  return {
    hide: hide2,
    toggle: toggle2,
    get isHidden() {
      return !toggle2.checked;
    }
  };
}
var __decorate$8 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$8 = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$6 = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
let BrowserClipboardService = class BrowserClipboardService2 extends Disposable {
  constructor(layoutService, logService) {
    super();
    this.layoutService = layoutService;
    this.logService = logService;
    this.mapTextToType = /* @__PURE__ */ new Map();
    this.findText = "";
    this.resources = [];
    if (isSafari$1 || isWebkitWebView) {
      this.installWebKitWriteTextWorkaround();
    }
  }
  // In Safari, it has the following note:
  //
  // "The request to write to the clipboard must be triggered during a user gesture.
  // A call to clipboard.write or clipboard.writeText outside the scope of a user
  // gesture(such as "click" or "touch" event handlers) will result in the immediate
  // rejection of the promise returned by the API call."
  // From: https://webkit.org/blog/10855/async-clipboard-api/
  //
  // Since extensions run in a web worker, and handle gestures in an asynchronous way,
  // they are not classified by Safari as "in response to a user gesture" and will reject.
  //
  // This function sets up some handlers to work around that behavior.
  installWebKitWriteTextWorkaround() {
    const handler = () => {
      const currentWritePromise = new DeferredPromise();
      if (this.webKitPendingClipboardWritePromise && !this.webKitPendingClipboardWritePromise.isSettled) {
        this.webKitPendingClipboardWritePromise.cancel();
      }
      this.webKitPendingClipboardWritePromise = currentWritePromise;
      navigator.clipboard.write([new ClipboardItem({
        "text/plain": currentWritePromise.p
      })]).catch((err) => __awaiter$6(this, void 0, void 0, function* () {
        if (!(err instanceof Error) || err.name !== "NotAllowedError" || !currentWritePromise.isRejected) {
          this.logService.error(err);
        }
      }));
    };
    if (this.layoutService.hasContainer) {
      this._register(addDisposableListener(this.layoutService.container, "click", handler));
      this._register(addDisposableListener(this.layoutService.container, "keydown", handler));
    }
  }
  writeText(text2, type) {
    return __awaiter$6(this, void 0, void 0, function* () {
      if (type) {
        this.mapTextToType.set(type, text2);
        return;
      }
      if (this.webKitPendingClipboardWritePromise) {
        return this.webKitPendingClipboardWritePromise.complete(text2);
      }
      try {
        return yield navigator.clipboard.writeText(text2);
      } catch (error2) {
        console.error(error2);
      }
      const activeElement = document.activeElement;
      const textArea = document.body.appendChild($$d("textarea", { "aria-hidden": true }));
      textArea.style.height = "1px";
      textArea.style.width = "1px";
      textArea.style.position = "absolute";
      textArea.value = text2;
      textArea.focus();
      textArea.select();
      document.execCommand("copy");
      if (activeElement instanceof HTMLElement) {
        activeElement.focus();
      }
      document.body.removeChild(textArea);
      return;
    });
  }
  readText(type) {
    return __awaiter$6(this, void 0, void 0, function* () {
      if (type) {
        return this.mapTextToType.get(type) || "";
      }
      try {
        return yield navigator.clipboard.readText();
      } catch (error2) {
        console.error(error2);
        return "";
      }
    });
  }
  readFindText() {
    return __awaiter$6(this, void 0, void 0, function* () {
      return this.findText;
    });
  }
  writeFindText(text2) {
    return __awaiter$6(this, void 0, void 0, function* () {
      this.findText = text2;
    });
  }
  writeResources(resources) {
    return __awaiter$6(this, void 0, void 0, function* () {
      this.resources = resources;
    });
  }
  readResources() {
    return __awaiter$6(this, void 0, void 0, function* () {
      return this.resources;
    });
  }
};
BrowserClipboardService = __decorate$8([
  __param$8(0, ILayoutService),
  __param$8(1, ILogService)
], BrowserClipboardService);
var __decorate$7 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$7 = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
const KEYBINDING_CONTEXT_ATTR = "data-keybinding-context";
class Context {
  constructor(id3, parent) {
    this._id = id3;
    this._parent = parent;
    this._value = /* @__PURE__ */ Object.create(null);
    this._value["_contextId"] = id3;
  }
  get value() {
    return Object.assign({}, this._value);
  }
  setValue(key, value) {
    if (this._value[key] !== value) {
      this._value[key] = value;
      return true;
    }
    return false;
  }
  removeValue(key) {
    if (key in this._value) {
      delete this._value[key];
      return true;
    }
    return false;
  }
  getValue(key) {
    const ret = this._value[key];
    if (typeof ret === "undefined" && this._parent) {
      return this._parent.getValue(key);
    }
    return ret;
  }
}
class NullContext extends Context {
  constructor() {
    super(-1, null);
  }
  setValue(key, value) {
    return false;
  }
  removeValue(key) {
    return false;
  }
  getValue(key) {
    return void 0;
  }
}
NullContext.INSTANCE = new NullContext();
class ConfigAwareContextValuesContainer extends Context {
  constructor(id3, _configurationService, emitter) {
    super(id3, null);
    this._configurationService = _configurationService;
    this._values = TernarySearchTree.forConfigKeys();
    this._listener = this._configurationService.onDidChangeConfiguration((event) => {
      if (event.source === 7) {
        const allKeys = Array.from(this._values, ([k]) => k);
        this._values.clear();
        emitter.fire(new ArrayContextKeyChangeEvent(allKeys));
      } else {
        const changedKeys = [];
        for (const configKey of event.affectedKeys) {
          const contextKey = `config.${configKey}`;
          const cachedItems = this._values.findSuperstr(contextKey);
          if (cachedItems !== void 0) {
            changedKeys.push(...Iterable.map(cachedItems, ([key]) => key));
            this._values.deleteSuperstr(contextKey);
          }
          if (this._values.has(contextKey)) {
            changedKeys.push(contextKey);
            this._values.delete(contextKey);
          }
        }
        emitter.fire(new ArrayContextKeyChangeEvent(changedKeys));
      }
    });
  }
  dispose() {
    this._listener.dispose();
  }
  getValue(key) {
    if (key.indexOf(ConfigAwareContextValuesContainer._keyPrefix) !== 0) {
      return super.getValue(key);
    }
    if (this._values.has(key)) {
      return this._values.get(key);
    }
    const configKey = key.substr(ConfigAwareContextValuesContainer._keyPrefix.length);
    const configValue = this._configurationService.getValue(configKey);
    let value = void 0;
    switch (typeof configValue) {
      case "number":
      case "boolean":
      case "string":
        value = configValue;
        break;
      default:
        if (Array.isArray(configValue)) {
          value = JSON.stringify(configValue);
        } else {
          value = configValue;
        }
    }
    this._values.set(key, value);
    return value;
  }
  setValue(key, value) {
    return super.setValue(key, value);
  }
  removeValue(key) {
    return super.removeValue(key);
  }
}
ConfigAwareContextValuesContainer._keyPrefix = "config.";
class ContextKey {
  constructor(service, key, defaultValue) {
    this._service = service;
    this._key = key;
    this._defaultValue = defaultValue;
    this.reset();
  }
  set(value) {
    this._service.setContext(this._key, value);
  }
  reset() {
    if (typeof this._defaultValue === "undefined") {
      this._service.removeContext(this._key);
    } else {
      this._service.setContext(this._key, this._defaultValue);
    }
  }
  get() {
    return this._service.getContextKeyValue(this._key);
  }
}
class SimpleContextKeyChangeEvent {
  constructor(key) {
    this.key = key;
  }
  affectsSome(keys) {
    return keys.has(this.key);
  }
  allKeysContainedIn(keys) {
    return this.affectsSome(keys);
  }
}
class ArrayContextKeyChangeEvent {
  constructor(keys) {
    this.keys = keys;
  }
  affectsSome(keys) {
    for (const key of this.keys) {
      if (keys.has(key)) {
        return true;
      }
    }
    return false;
  }
  allKeysContainedIn(keys) {
    return this.keys.every((key) => keys.has(key));
  }
}
class CompositeContextKeyChangeEvent {
  constructor(events) {
    this.events = events;
  }
  affectsSome(keys) {
    for (const e of this.events) {
      if (e.affectsSome(keys)) {
        return true;
      }
    }
    return false;
  }
  allKeysContainedIn(keys) {
    return this.events.every((evt) => evt.allKeysContainedIn(keys));
  }
}
function allEventKeysInContext(event, context) {
  return event.allKeysContainedIn(new Set(Object.keys(context)));
}
class AbstractContextKeyService {
  constructor(myContextId) {
    this._onDidChangeContext = new PauseableEmitter({ merge: (input2) => new CompositeContextKeyChangeEvent(input2) });
    this.onDidChangeContext = this._onDidChangeContext.event;
    this._isDisposed = false;
    this._myContextId = myContextId;
  }
  createKey(key, defaultValue) {
    if (this._isDisposed) {
      throw new Error(`AbstractContextKeyService has been disposed`);
    }
    return new ContextKey(this, key, defaultValue);
  }
  bufferChangeEvents(callback) {
    this._onDidChangeContext.pause();
    try {
      callback();
    } finally {
      this._onDidChangeContext.resume();
    }
  }
  createScoped(domNode) {
    if (this._isDisposed) {
      throw new Error(`AbstractContextKeyService has been disposed`);
    }
    return new ScopedContextKeyService(this, domNode);
  }
  contextMatchesRules(rules) {
    if (this._isDisposed) {
      throw new Error(`AbstractContextKeyService has been disposed`);
    }
    const context = this.getContextValuesContainer(this._myContextId);
    const result2 = rules ? rules.evaluate(context) : true;
    return result2;
  }
  getContextKeyValue(key) {
    if (this._isDisposed) {
      return void 0;
    }
    return this.getContextValuesContainer(this._myContextId).getValue(key);
  }
  setContext(key, value) {
    if (this._isDisposed) {
      return;
    }
    const myContext = this.getContextValuesContainer(this._myContextId);
    if (!myContext) {
      return;
    }
    if (myContext.setValue(key, value)) {
      this._onDidChangeContext.fire(new SimpleContextKeyChangeEvent(key));
    }
  }
  removeContext(key) {
    if (this._isDisposed) {
      return;
    }
    if (this.getContextValuesContainer(this._myContextId).removeValue(key)) {
      this._onDidChangeContext.fire(new SimpleContextKeyChangeEvent(key));
    }
  }
  getContext(target) {
    if (this._isDisposed) {
      return NullContext.INSTANCE;
    }
    return this.getContextValuesContainer(findContextAttr(target));
  }
}
let ContextKeyService = class ContextKeyService2 extends AbstractContextKeyService {
  constructor(configurationService) {
    super(0);
    this._contexts = /* @__PURE__ */ new Map();
    this._toDispose = new DisposableStore();
    this._lastContextId = 0;
    const myContext = new ConfigAwareContextValuesContainer(this._myContextId, configurationService, this._onDidChangeContext);
    this._contexts.set(this._myContextId, myContext);
    this._toDispose.add(myContext);
  }
  dispose() {
    this._onDidChangeContext.dispose();
    this._isDisposed = true;
    this._toDispose.dispose();
  }
  getContextValuesContainer(contextId) {
    if (this._isDisposed) {
      return NullContext.INSTANCE;
    }
    return this._contexts.get(contextId) || NullContext.INSTANCE;
  }
  createChildContext(parentContextId = this._myContextId) {
    if (this._isDisposed) {
      throw new Error(`ContextKeyService has been disposed`);
    }
    const id3 = ++this._lastContextId;
    this._contexts.set(id3, new Context(id3, this.getContextValuesContainer(parentContextId)));
    return id3;
  }
  disposeContext(contextId) {
    if (!this._isDisposed) {
      this._contexts.delete(contextId);
    }
  }
};
ContextKeyService = __decorate$7([
  __param$7(0, IConfigurationService)
], ContextKeyService);
class ScopedContextKeyService extends AbstractContextKeyService {
  constructor(parent, domNode) {
    super(parent.createChildContext());
    this._parentChangeListener = new MutableDisposable();
    this._parent = parent;
    this._updateParentChangeListener();
    this._domNode = domNode;
    if (this._domNode.hasAttribute(KEYBINDING_CONTEXT_ATTR)) {
      let extraInfo = "";
      if (this._domNode.classList) {
        extraInfo = Array.from(this._domNode.classList.values()).join(", ");
      }
      console.error(`Element already has context attribute${extraInfo ? ": " + extraInfo : ""}`);
    }
    this._domNode.setAttribute(KEYBINDING_CONTEXT_ATTR, String(this._myContextId));
  }
  _updateParentChangeListener() {
    this._parentChangeListener.value = this._parent.onDidChangeContext((e) => {
      const thisContainer = this._parent.getContextValuesContainer(this._myContextId);
      const thisContextValues = thisContainer.value;
      if (!allEventKeysInContext(e, thisContextValues)) {
        this._onDidChangeContext.fire(e);
      }
    });
  }
  dispose() {
    if (this._isDisposed) {
      return;
    }
    this._onDidChangeContext.dispose();
    this._parent.disposeContext(this._myContextId);
    this._parentChangeListener.dispose();
    this._domNode.removeAttribute(KEYBINDING_CONTEXT_ATTR);
    this._isDisposed = true;
  }
  getContextValuesContainer(contextId) {
    if (this._isDisposed) {
      return NullContext.INSTANCE;
    }
    return this._parent.getContextValuesContainer(contextId);
  }
  createChildContext(parentContextId = this._myContextId) {
    if (this._isDisposed) {
      throw new Error(`ScopedContextKeyService has been disposed`);
    }
    return this._parent.createChildContext(parentContextId);
  }
  disposeContext(contextId) {
    if (this._isDisposed) {
      return;
    }
    this._parent.disposeContext(contextId);
  }
}
function findContextAttr(domNode) {
  while (domNode) {
    if (domNode.hasAttribute(KEYBINDING_CONTEXT_ATTR)) {
      const attr = domNode.getAttribute(KEYBINDING_CONTEXT_ATTR);
      if (attr) {
        return parseInt(attr, 10);
      }
      return NaN;
    }
    domNode = domNode.parentElement;
  }
  return 0;
}
function setContext(accessor, contextKey, contextValue) {
  const contextKeyService = accessor.get(IContextKeyService);
  contextKeyService.createKey(String(contextKey), stringifyURIs(contextValue));
}
function stringifyURIs(contextValue) {
  return cloneAndChange(contextValue, (obj) => {
    if (typeof obj === "object" && obj.$mid === 1) {
      return URI.revive(obj).toString();
    }
    if (obj instanceof URI) {
      return obj.toString();
    }
    return void 0;
  });
}
CommandsRegistry.registerCommand("_setContext", setContext);
CommandsRegistry.registerCommand({
  id: "getContextKeyInfo",
  handler() {
    return [...RawContextKey.all()].sort((a, b) => a.key.localeCompare(b.key));
  },
  description: {
    description: localize("getContextKeyInfo", "A command that returns information about context keys"),
    args: []
  }
});
CommandsRegistry.registerCommand("_generateContextKeyInfo", function() {
  const result2 = [];
  const seen2 = /* @__PURE__ */ new Set();
  for (const info of RawContextKey.all()) {
    if (!seen2.has(info.key)) {
      seen2.add(info.key);
      result2.push(info);
    }
  }
  result2.sort((a, b) => a.key.localeCompare(b.key));
  console.log(JSON.stringify(result2, void 0, 2));
});
let Node$7 = class Node3 {
  constructor(key, data) {
    this.key = key;
    this.data = data;
    this.incoming = /* @__PURE__ */ new Map();
    this.outgoing = /* @__PURE__ */ new Map();
  }
};
class Graph {
  constructor(_hashFn) {
    this._hashFn = _hashFn;
    this._nodes = /* @__PURE__ */ new Map();
  }
  roots() {
    const ret = [];
    for (const node2 of this._nodes.values()) {
      if (node2.outgoing.size === 0) {
        ret.push(node2);
      }
    }
    return ret;
  }
  insertEdge(from2, to) {
    const fromNode = this.lookupOrInsertNode(from2);
    const toNode = this.lookupOrInsertNode(to);
    fromNode.outgoing.set(toNode.key, toNode);
    toNode.incoming.set(fromNode.key, fromNode);
  }
  removeNode(data) {
    const key = this._hashFn(data);
    this._nodes.delete(key);
    for (const node2 of this._nodes.values()) {
      node2.outgoing.delete(key);
      node2.incoming.delete(key);
    }
  }
  lookupOrInsertNode(data) {
    const key = this._hashFn(data);
    let node2 = this._nodes.get(key);
    if (!node2) {
      node2 = new Node$7(key, data);
      this._nodes.set(key, node2);
    }
    return node2;
  }
  isEmpty() {
    return this._nodes.size === 0;
  }
  toString() {
    const data = [];
    for (const [key, value] of this._nodes) {
      data.push(`${key}
	(-> incoming)[${[...value.incoming.keys()].join(", ")}]
	(outgoing ->)[${[...value.outgoing.keys()].join(",")}]
`);
    }
    return data.join("\n");
  }
  /**
   * This is brute force and slow and **only** be used
   * to trouble shoot.
   */
  findCycleSlow() {
    for (const [id3, node2] of this._nodes) {
      const seen2 = /* @__PURE__ */ new Set([id3]);
      const res = this._findCycle(node2, seen2);
      if (res) {
        return res;
      }
    }
    return void 0;
  }
  _findCycle(node2, seen2) {
    for (const [id3, outgoing] of node2.outgoing) {
      if (seen2.has(id3)) {
        return [...seen2, id3].join(" -> ");
      }
      seen2.add(id3);
      const value = this._findCycle(outgoing, seen2);
      if (value) {
        return value;
      }
      seen2.delete(id3);
    }
    return void 0;
  }
}
const _enableAllTracing = false;
class CyclicDependencyError extends Error {
  constructor(graph) {
    var _a2;
    super("cyclic dependency between services");
    this.message = (_a2 = graph.findCycleSlow()) !== null && _a2 !== void 0 ? _a2 : `UNABLE to detect cycle, dumping graph: 
${graph.toString()}`;
  }
}
class InstantiationService {
  constructor(_services = new ServiceCollection(), _strict = false, _parent, _enableTracing = _enableAllTracing) {
    var _a2;
    this._services = _services;
    this._strict = _strict;
    this._parent = _parent;
    this._enableTracing = _enableTracing;
    this._activeInstantiations = /* @__PURE__ */ new Set();
    this._services.set(IInstantiationService, this);
    this._globalGraph = _enableTracing ? (_a2 = _parent === null || _parent === void 0 ? void 0 : _parent._globalGraph) !== null && _a2 !== void 0 ? _a2 : new Graph((e) => e) : void 0;
  }
  createChild(services) {
    return new InstantiationService(services, this._strict, this, this._enableTracing);
  }
  invokeFunction(fn, ...args) {
    const _trace = Trace.traceInvocation(this._enableTracing, fn);
    let _done = false;
    try {
      const accessor = {
        get: (id3) => {
          if (_done) {
            throw illegalState("service accessor is only valid during the invocation of its target method");
          }
          const result2 = this._getOrCreateServiceInstance(id3, _trace);
          if (!result2) {
            throw new Error(`[invokeFunction] unknown service '${id3}'`);
          }
          return result2;
        }
      };
      return fn(accessor, ...args);
    } finally {
      _done = true;
      _trace.stop();
    }
  }
  createInstance(ctorOrDescriptor, ...rest) {
    let _trace;
    let result2;
    if (ctorOrDescriptor instanceof SyncDescriptor) {
      _trace = Trace.traceCreation(this._enableTracing, ctorOrDescriptor.ctor);
      result2 = this._createInstance(ctorOrDescriptor.ctor, ctorOrDescriptor.staticArguments.concat(rest), _trace);
    } else {
      _trace = Trace.traceCreation(this._enableTracing, ctorOrDescriptor);
      result2 = this._createInstance(ctorOrDescriptor, rest, _trace);
    }
    _trace.stop();
    return result2;
  }
  _createInstance(ctor, args = [], _trace) {
    const serviceDependencies = _util.getServiceDependencies(ctor).sort((a, b) => a.index - b.index);
    const serviceArgs = [];
    for (const dependency of serviceDependencies) {
      const service = this._getOrCreateServiceInstance(dependency.id, _trace);
      if (!service) {
        this._throwIfStrict(`[createInstance] ${ctor.name} depends on UNKNOWN service ${dependency.id}.`, false);
      }
      serviceArgs.push(service);
    }
    const firstServiceArgPos = serviceDependencies.length > 0 ? serviceDependencies[0].index : args.length;
    if (args.length !== firstServiceArgPos) {
      console.trace(`[createInstance] First service dependency of ${ctor.name} at position ${firstServiceArgPos + 1} conflicts with ${args.length} static arguments`);
      const delta = firstServiceArgPos - args.length;
      if (delta > 0) {
        args = args.concat(new Array(delta));
      } else {
        args = args.slice(0, firstServiceArgPos);
      }
    }
    return Reflect.construct(ctor, args.concat(serviceArgs));
  }
  _setServiceInstance(id3, instance) {
    if (this._services.get(id3) instanceof SyncDescriptor) {
      this._services.set(id3, instance);
    } else if (this._parent) {
      this._parent._setServiceInstance(id3, instance);
    } else {
      throw new Error("illegalState - setting UNKNOWN service instance");
    }
  }
  _getServiceInstanceOrDescriptor(id3) {
    const instanceOrDesc = this._services.get(id3);
    if (!instanceOrDesc && this._parent) {
      return this._parent._getServiceInstanceOrDescriptor(id3);
    } else {
      return instanceOrDesc;
    }
  }
  _getOrCreateServiceInstance(id3, _trace) {
    if (this._globalGraph && this._globalGraphImplicitDependency) {
      this._globalGraph.insertEdge(this._globalGraphImplicitDependency, String(id3));
    }
    const thing = this._getServiceInstanceOrDescriptor(id3);
    if (thing instanceof SyncDescriptor) {
      return this._safeCreateAndCacheServiceInstance(id3, thing, _trace.branch(id3, true));
    } else {
      _trace.branch(id3, false);
      return thing;
    }
  }
  _safeCreateAndCacheServiceInstance(id3, desc, _trace) {
    if (this._activeInstantiations.has(id3)) {
      throw new Error(`illegal state - RECURSIVELY instantiating service '${id3}'`);
    }
    this._activeInstantiations.add(id3);
    try {
      return this._createAndCacheServiceInstance(id3, desc, _trace);
    } finally {
      this._activeInstantiations.delete(id3);
    }
  }
  _createAndCacheServiceInstance(id3, desc, _trace) {
    var _a2;
    const graph = new Graph((data) => data.id.toString());
    let cycleCount = 0;
    const stack = [{ id: id3, desc, _trace }];
    while (stack.length) {
      const item = stack.pop();
      graph.lookupOrInsertNode(item);
      if (cycleCount++ > 1e3) {
        throw new CyclicDependencyError(graph);
      }
      for (const dependency of _util.getServiceDependencies(item.desc.ctor)) {
        const instanceOrDesc = this._getServiceInstanceOrDescriptor(dependency.id);
        if (!instanceOrDesc) {
          this._throwIfStrict(`[createInstance] ${id3} depends on ${dependency.id} which is NOT registered.`, true);
        }
        (_a2 = this._globalGraph) === null || _a2 === void 0 ? void 0 : _a2.insertEdge(String(item.id), String(dependency.id));
        if (instanceOrDesc instanceof SyncDescriptor) {
          const d = { id: dependency.id, desc: instanceOrDesc, _trace: item._trace.branch(dependency.id, true) };
          graph.insertEdge(item, d);
          stack.push(d);
        }
      }
    }
    while (true) {
      const roots = graph.roots();
      if (roots.length === 0) {
        if (!graph.isEmpty()) {
          throw new CyclicDependencyError(graph);
        }
        break;
      }
      for (const { data } of roots) {
        const instanceOrDesc = this._getServiceInstanceOrDescriptor(data.id);
        if (instanceOrDesc instanceof SyncDescriptor) {
          const instance = this._createServiceInstanceWithOwner(data.id, data.desc.ctor, data.desc.staticArguments, data.desc.supportsDelayedInstantiation, data._trace);
          this._setServiceInstance(data.id, instance);
        }
        graph.removeNode(data);
      }
    }
    return this._getServiceInstanceOrDescriptor(id3);
  }
  _createServiceInstanceWithOwner(id3, ctor, args = [], supportsDelayedInstantiation, _trace) {
    if (this._services.get(id3) instanceof SyncDescriptor) {
      return this._createServiceInstance(id3, ctor, args, supportsDelayedInstantiation, _trace);
    } else if (this._parent) {
      return this._parent._createServiceInstanceWithOwner(id3, ctor, args, supportsDelayedInstantiation, _trace);
    } else {
      throw new Error(`illegalState - creating UNKNOWN service instance ${ctor.name}`);
    }
  }
  _createServiceInstance(id3, ctor, args = [], supportsDelayedInstantiation, _trace) {
    if (!supportsDelayedInstantiation) {
      return this._createInstance(ctor, args, _trace);
    } else {
      const child = new InstantiationService(void 0, this._strict, this, this._enableTracing);
      child._globalGraphImplicitDependency = String(id3);
      const earlyListeners = /* @__PURE__ */ new Map();
      const idle = new IdleValue(() => {
        const result2 = child._createInstance(ctor, args, _trace);
        for (const [key, values] of earlyListeners) {
          const candidate = result2[key];
          if (typeof candidate === "function") {
            for (const listener of values) {
              candidate.apply(result2, listener);
            }
          }
        }
        earlyListeners.clear();
        return result2;
      });
      return new Proxy(/* @__PURE__ */ Object.create(null), {
        get(target, key) {
          if (!idle.isInitialized) {
            if (typeof key === "string" && (key.startsWith("onDid") || key.startsWith("onWill"))) {
              let list2 = earlyListeners.get(key);
              if (!list2) {
                list2 = new LinkedList();
                earlyListeners.set(key, list2);
              }
              const event = (callback, thisArg, disposables) => {
                const rm = list2.push([callback, thisArg, disposables]);
                return toDisposable(rm);
              };
              return event;
            }
          }
          if (key in target) {
            return target[key];
          }
          const obj = idle.value;
          let prop = obj[key];
          if (typeof prop !== "function") {
            return prop;
          }
          prop = prop.bind(obj);
          target[key] = prop;
          return prop;
        },
        set(_target, p2, value) {
          idle.value[p2] = value;
          return true;
        },
        getPrototypeOf(_target) {
          return ctor.prototype;
        }
      });
    }
  }
  _throwIfStrict(msg, printWarning) {
    if (printWarning) {
      console.warn(msg);
    }
    if (this._strict) {
      throw new Error(msg);
    }
  }
}
class Trace {
  static traceInvocation(_enableTracing, ctor) {
    return !_enableTracing ? Trace._None : new Trace(2, ctor.name || new Error().stack.split("\n").slice(3, 4).join("\n"));
  }
  static traceCreation(_enableTracing, ctor) {
    return !_enableTracing ? Trace._None : new Trace(1, ctor.name);
  }
  constructor(type, name) {
    this.type = type;
    this.name = name;
    this._start = Date.now();
    this._dep = [];
  }
  branch(id3, first2) {
    const child = new Trace(3, id3.toString());
    this._dep.push([id3, first2, child]);
    return child;
  }
  stop() {
    const dur = Date.now() - this._start;
    Trace._totals += dur;
    let causedCreation = false;
    function printChild(n2, trace) {
      const res = [];
      const prefix2 = new Array(n2 + 1).join("	");
      for (const [id3, first2, child] of trace._dep) {
        if (first2 && child) {
          causedCreation = true;
          res.push(`${prefix2}CREATES -> ${id3}`);
          const nested = printChild(n2 + 1, child);
          if (nested) {
            res.push(nested);
          }
        } else {
          res.push(`${prefix2}uses -> ${id3}`);
        }
      }
      return res.join("\n");
    }
    const lines = [
      `${this.type === 1 ? "CREATE" : "CALL"} ${this.name}`,
      `${printChild(1, this)}`,
      `DONE, took ${dur.toFixed(2)}ms (grand total ${Trace._totals.toFixed(2)}ms)`
    ];
    if (dur > 2 || causedCreation) {
      Trace.all.add(lines.join("\n"));
    }
  }
}
Trace.all = /* @__PURE__ */ new Set();
Trace._None = new class extends Trace {
  constructor() {
    super(0, null);
  }
  stop() {
  }
  branch() {
    return this;
  }
}();
Trace._totals = 0;
const unsupportedSchemas = /* @__PURE__ */ new Set([Schemas.inMemory, Schemas.vscodeSourceControl, Schemas.walkThrough, Schemas.walkThroughSnippet]);
class DoubleResourceMap {
  constructor() {
    this._byResource = new ResourceMap();
    this._byOwner = /* @__PURE__ */ new Map();
  }
  set(resource, owner, value) {
    let ownerMap = this._byResource.get(resource);
    if (!ownerMap) {
      ownerMap = /* @__PURE__ */ new Map();
      this._byResource.set(resource, ownerMap);
    }
    ownerMap.set(owner, value);
    let resourceMap = this._byOwner.get(owner);
    if (!resourceMap) {
      resourceMap = new ResourceMap();
      this._byOwner.set(owner, resourceMap);
    }
    resourceMap.set(resource, value);
  }
  get(resource, owner) {
    const ownerMap = this._byResource.get(resource);
    return ownerMap === null || ownerMap === void 0 ? void 0 : ownerMap.get(owner);
  }
  delete(resource, owner) {
    let removedA = false;
    let removedB = false;
    const ownerMap = this._byResource.get(resource);
    if (ownerMap) {
      removedA = ownerMap.delete(owner);
    }
    const resourceMap = this._byOwner.get(owner);
    if (resourceMap) {
      removedB = resourceMap.delete(resource);
    }
    if (removedA !== removedB) {
      throw new Error("illegal state");
    }
    return removedA && removedB;
  }
  values(key) {
    var _a2, _b2, _c2, _d2;
    if (typeof key === "string") {
      return (_b2 = (_a2 = this._byOwner.get(key)) === null || _a2 === void 0 ? void 0 : _a2.values()) !== null && _b2 !== void 0 ? _b2 : Iterable.empty();
    }
    if (URI.isUri(key)) {
      return (_d2 = (_c2 = this._byResource.get(key)) === null || _c2 === void 0 ? void 0 : _c2.values()) !== null && _d2 !== void 0 ? _d2 : Iterable.empty();
    }
    return Iterable.map(Iterable.concat(...this._byOwner.values()), (map2) => map2[1]);
  }
}
class MarkerStats {
  constructor(service) {
    this.errors = 0;
    this.infos = 0;
    this.warnings = 0;
    this.unknowns = 0;
    this._data = new ResourceMap();
    this._service = service;
    this._subscription = service.onMarkerChanged(this._update, this);
  }
  dispose() {
    this._subscription.dispose();
  }
  _update(resources) {
    for (const resource of resources) {
      const oldStats = this._data.get(resource);
      if (oldStats) {
        this._substract(oldStats);
      }
      const newStats = this._resourceStats(resource);
      this._add(newStats);
      this._data.set(resource, newStats);
    }
  }
  _resourceStats(resource) {
    const result2 = { errors: 0, warnings: 0, infos: 0, unknowns: 0 };
    if (unsupportedSchemas.has(resource.scheme)) {
      return result2;
    }
    for (const { severity } of this._service.read({ resource })) {
      if (severity === MarkerSeverity$2.Error) {
        result2.errors += 1;
      } else if (severity === MarkerSeverity$2.Warning) {
        result2.warnings += 1;
      } else if (severity === MarkerSeverity$2.Info) {
        result2.infos += 1;
      } else {
        result2.unknowns += 1;
      }
    }
    return result2;
  }
  _substract(op) {
    this.errors -= op.errors;
    this.warnings -= op.warnings;
    this.infos -= op.infos;
    this.unknowns -= op.unknowns;
  }
  _add(op) {
    this.errors += op.errors;
    this.warnings += op.warnings;
    this.infos += op.infos;
    this.unknowns += op.unknowns;
  }
}
class MarkerService {
  constructor() {
    this._onMarkerChanged = new DebounceEmitter({
      delay: 0,
      merge: MarkerService._merge
    });
    this.onMarkerChanged = this._onMarkerChanged.event;
    this._data = new DoubleResourceMap();
    this._stats = new MarkerStats(this);
  }
  dispose() {
    this._stats.dispose();
    this._onMarkerChanged.dispose();
  }
  remove(owner, resources) {
    for (const resource of resources || []) {
      this.changeOne(owner, resource, []);
    }
  }
  changeOne(owner, resource, markerData) {
    if (isFalsyOrEmpty(markerData)) {
      const removed = this._data.delete(resource, owner);
      if (removed) {
        this._onMarkerChanged.fire([resource]);
      }
    } else {
      const markers = [];
      for (const data of markerData) {
        const marker = MarkerService._toMarker(owner, resource, data);
        if (marker) {
          markers.push(marker);
        }
      }
      this._data.set(resource, owner, markers);
      this._onMarkerChanged.fire([resource]);
    }
  }
  static _toMarker(owner, resource, data) {
    let { code, severity, message, source, startLineNumber, startColumn, endLineNumber, endColumn, relatedInformation, tags } = data;
    if (!message) {
      return void 0;
    }
    startLineNumber = startLineNumber > 0 ? startLineNumber : 1;
    startColumn = startColumn > 0 ? startColumn : 1;
    endLineNumber = endLineNumber >= startLineNumber ? endLineNumber : startLineNumber;
    endColumn = endColumn > 0 ? endColumn : startColumn;
    return {
      resource,
      owner,
      code,
      severity,
      message,
      source,
      startLineNumber,
      startColumn,
      endLineNumber,
      endColumn,
      relatedInformation,
      tags
    };
  }
  changeAll(owner, data) {
    const changes = [];
    const existing = this._data.values(owner);
    if (existing) {
      for (const data2 of existing) {
        const first2 = Iterable.first(data2);
        if (first2) {
          changes.push(first2.resource);
          this._data.delete(first2.resource, owner);
        }
      }
    }
    if (isNonEmptyArray(data)) {
      const groups = new ResourceMap();
      for (const { resource, marker: markerData } of data) {
        const marker = MarkerService._toMarker(owner, resource, markerData);
        if (!marker) {
          continue;
        }
        const array2 = groups.get(resource);
        if (!array2) {
          groups.set(resource, [marker]);
          changes.push(resource);
        } else {
          array2.push(marker);
        }
      }
      for (const [resource, value] of groups) {
        this._data.set(resource, owner, value);
      }
    }
    if (changes.length > 0) {
      this._onMarkerChanged.fire(changes);
    }
  }
  read(filter2 = /* @__PURE__ */ Object.create(null)) {
    let { owner, resource, severities, take } = filter2;
    if (!take || take < 0) {
      take = -1;
    }
    if (owner && resource) {
      const data = this._data.get(resource, owner);
      if (!data) {
        return [];
      } else {
        const result2 = [];
        for (const marker of data) {
          if (MarkerService._accept(marker, severities)) {
            const newLen = result2.push(marker);
            if (take > 0 && newLen === take) {
              break;
            }
          }
        }
        return result2;
      }
    } else if (!owner && !resource) {
      const result2 = [];
      for (const markers of this._data.values()) {
        for (const data of markers) {
          if (MarkerService._accept(data, severities)) {
            const newLen = result2.push(data);
            if (take > 0 && newLen === take) {
              return result2;
            }
          }
        }
      }
      return result2;
    } else {
      const iterable = this._data.values(resource !== null && resource !== void 0 ? resource : owner);
      const result2 = [];
      for (const markers of iterable) {
        for (const data of markers) {
          if (MarkerService._accept(data, severities)) {
            const newLen = result2.push(data);
            if (take > 0 && newLen === take) {
              return result2;
            }
          }
        }
      }
      return result2;
    }
  }
  static _accept(marker, severities) {
    return severities === void 0 || (severities & marker.severity) === marker.severity;
  }
  // --- event debounce logic
  static _merge(all) {
    const set2 = new ResourceMap();
    for (const array2 of all) {
      for (const item of array2) {
        set2.set(item, true);
      }
    }
    return Array.from(set2.keys());
  }
}
class DefaultConfiguration extends Disposable {
  constructor() {
    super(...arguments);
    this._configurationModel = new ConfigurationModel();
  }
  get configurationModel() {
    return this._configurationModel;
  }
  reload() {
    this.resetConfigurationModel();
    return this.configurationModel;
  }
  getConfigurationDefaultOverrides() {
    return {};
  }
  resetConfigurationModel() {
    this._configurationModel = new ConfigurationModel();
    const properties = Registry.as(Extensions$6.Configuration).getConfigurationProperties();
    this.updateConfigurationModel(Object.keys(properties), properties);
  }
  updateConfigurationModel(properties, configurationProperties) {
    const configurationDefaultsOverrides = this.getConfigurationDefaultOverrides();
    for (const key of properties) {
      const defaultOverrideValue = configurationDefaultsOverrides[key];
      const propertySchema = configurationProperties[key];
      if (defaultOverrideValue !== void 0) {
        this._configurationModel.addValue(key, defaultOverrideValue);
      } else if (propertySchema) {
        this._configurationModel.addValue(key, propertySchema.default);
      } else {
        this._configurationModel.removeValue(key);
      }
    }
  }
}
class LogService extends Disposable {
  constructor(primaryLogger, otherLoggers = []) {
    super();
    this.logger = new MultiplexLogger([primaryLogger, ...otherLoggers]);
    this._register(primaryLogger.onDidChangeLogLevel((level) => this.setLevel(level)));
  }
  get onDidChangeLogLevel() {
    return this.logger.onDidChangeLogLevel;
  }
  setLevel(level) {
    this.logger.setLevel(level);
  }
  getLevel() {
    return this.logger.getLevel();
  }
  trace(message, ...args) {
    this.logger.trace(message, ...args);
  }
  debug(message, ...args) {
    this.logger.debug(message, ...args);
  }
  info(message, ...args) {
    this.logger.info(message, ...args);
  }
  warn(message, ...args) {
    this.logger.warn(message, ...args);
  }
  error(message, ...args) {
    this.logger.error(message, ...args);
  }
}
var __decorate$6 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$6 = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$5 = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class SimpleModel {
  constructor(model) {
    this.disposed = false;
    this.model = model;
    this._onWillDispose = new Emitter$1();
  }
  get textEditorModel() {
    return this.model;
  }
  dispose() {
    this.disposed = true;
    this._onWillDispose.fire();
  }
}
let StandaloneTextModelService = class StandaloneTextModelService2 {
  constructor(modelService) {
    this.modelService = modelService;
  }
  createModelReference(resource) {
    const model = this.modelService.getModel(resource);
    if (!model) {
      return Promise.reject(new Error(`Model not found`));
    }
    return Promise.resolve(new ImmortalReference(new SimpleModel(model)));
  }
};
StandaloneTextModelService = __decorate$6([
  __param$6(0, IModelService)
], StandaloneTextModelService);
class StandaloneEditorProgressService {
  show() {
    return StandaloneEditorProgressService.NULL_PROGRESS_RUNNER;
  }
  showWhile(promise, delay) {
    return __awaiter$5(this, void 0, void 0, function* () {
      yield promise;
    });
  }
}
StandaloneEditorProgressService.NULL_PROGRESS_RUNNER = {
  done: () => {
  },
  total: () => {
  },
  worked: () => {
  }
};
class StandaloneProgressService {
  withProgress(_options, task, onDidCancel) {
    return task({
      report: () => {
      }
    });
  }
}
class StandaloneEnvironmentService {
  constructor() {
    this.isExtensionDevelopment = false;
    this.isBuilt = false;
  }
}
class StandaloneDialogService {
  confirm(confirmation) {
    return __awaiter$5(this, void 0, void 0, function* () {
      const confirmed = this.doConfirm(confirmation.message, confirmation.detail);
      return {
        confirmed,
        checkboxChecked: false
        // unsupported
      };
    });
  }
  doConfirm(message, detail) {
    let messageText = message;
    if (detail) {
      messageText = messageText + "\n\n" + detail;
    }
    return window.confirm(messageText);
  }
  prompt(prompt) {
    var _a2, _b2;
    return __awaiter$5(this, void 0, void 0, function* () {
      let result2 = void 0;
      const confirmed = this.doConfirm(prompt.message, prompt.detail);
      if (confirmed) {
        const promptButtons = [...(_a2 = prompt.buttons) !== null && _a2 !== void 0 ? _a2 : []];
        if (prompt.cancelButton && typeof prompt.cancelButton !== "string" && typeof prompt.cancelButton !== "boolean") {
          promptButtons.push(prompt.cancelButton);
        }
        result2 = yield (_b2 = promptButtons[0]) === null || _b2 === void 0 ? void 0 : _b2.run({ checkboxChecked: false });
      }
      return { result: result2 };
    });
  }
  error(message, detail) {
    return __awaiter$5(this, void 0, void 0, function* () {
      yield this.prompt({ type: Severity$2.Error, message, detail });
    });
  }
}
class StandaloneNotificationService {
  info(message) {
    return this.notify({ severity: Severity$2.Info, message });
  }
  warn(message) {
    return this.notify({ severity: Severity$2.Warning, message });
  }
  error(error2) {
    return this.notify({ severity: Severity$2.Error, message: error2 });
  }
  notify(notification) {
    switch (notification.severity) {
      case Severity$2.Error:
        console.error(notification.message);
        break;
      case Severity$2.Warning:
        console.warn(notification.message);
        break;
      default:
        console.log(notification.message);
        break;
    }
    return StandaloneNotificationService.NO_OP;
  }
  prompt(severity, message, choices, options) {
    return StandaloneNotificationService.NO_OP;
  }
  status(message, options) {
    return Disposable.None;
  }
}
StandaloneNotificationService.NO_OP = new NoOpNotification();
let StandaloneCommandService = class StandaloneCommandService2 {
  constructor(instantiationService) {
    this._onWillExecuteCommand = new Emitter$1();
    this._onDidExecuteCommand = new Emitter$1();
    this.onDidExecuteCommand = this._onDidExecuteCommand.event;
    this._instantiationService = instantiationService;
  }
  executeCommand(id3, ...args) {
    const command = CommandsRegistry.getCommand(id3);
    if (!command) {
      return Promise.reject(new Error(`command '${id3}' not found`));
    }
    try {
      this._onWillExecuteCommand.fire({ commandId: id3, args });
      const result2 = this._instantiationService.invokeFunction.apply(this._instantiationService, [command.handler, ...args]);
      this._onDidExecuteCommand.fire({ commandId: id3, args });
      return Promise.resolve(result2);
    } catch (err) {
      return Promise.reject(err);
    }
  }
};
StandaloneCommandService = __decorate$6([
  __param$6(0, IInstantiationService)
], StandaloneCommandService);
let StandaloneKeybindingService = class StandaloneKeybindingService2 extends AbstractKeybindingService {
  constructor(contextKeyService, commandService, telemetryService, notificationService, logService, codeEditorService) {
    super(contextKeyService, commandService, telemetryService, notificationService, logService);
    this._cachedResolver = null;
    this._dynamicKeybindings = [];
    this._domNodeListeners = [];
    const addContainer = (domNode) => {
      const disposables = new DisposableStore();
      disposables.add(addDisposableListener(domNode, EventType$1.KEY_DOWN, (e) => {
        const keyEvent = new StandardKeyboardEvent(e);
        const shouldPreventDefault = this._dispatch(keyEvent, keyEvent.target);
        if (shouldPreventDefault) {
          keyEvent.preventDefault();
          keyEvent.stopPropagation();
        }
      }));
      disposables.add(addDisposableListener(domNode, EventType$1.KEY_UP, (e) => {
        const keyEvent = new StandardKeyboardEvent(e);
        const shouldPreventDefault = this._singleModifierDispatch(keyEvent, keyEvent.target);
        if (shouldPreventDefault) {
          keyEvent.preventDefault();
        }
      }));
      this._domNodeListeners.push(new DomNodeListeners(domNode, disposables));
    };
    const removeContainer = (domNode) => {
      for (let i = 0; i < this._domNodeListeners.length; i++) {
        const domNodeListeners = this._domNodeListeners[i];
        if (domNodeListeners.domNode === domNode) {
          this._domNodeListeners.splice(i, 1);
          domNodeListeners.dispose();
        }
      }
    };
    const addCodeEditor = (codeEditor) => {
      if (codeEditor.getOption(
        60
        /* EditorOption.inDiffEditor */
      )) {
        return;
      }
      addContainer(codeEditor.getContainerDomNode());
    };
    const removeCodeEditor = (codeEditor) => {
      if (codeEditor.getOption(
        60
        /* EditorOption.inDiffEditor */
      )) {
        return;
      }
      removeContainer(codeEditor.getContainerDomNode());
    };
    this._register(codeEditorService.onCodeEditorAdd(addCodeEditor));
    this._register(codeEditorService.onCodeEditorRemove(removeCodeEditor));
    codeEditorService.listCodeEditors().forEach(addCodeEditor);
    const addDiffEditor = (diffEditor2) => {
      addContainer(diffEditor2.getContainerDomNode());
    };
    const removeDiffEditor = (diffEditor2) => {
      removeContainer(diffEditor2.getContainerDomNode());
    };
    this._register(codeEditorService.onDiffEditorAdd(addDiffEditor));
    this._register(codeEditorService.onDiffEditorRemove(removeDiffEditor));
    codeEditorService.listDiffEditors().forEach(addDiffEditor);
  }
  addDynamicKeybinding(command, keybinding, handler, when) {
    return combinedDisposable(CommandsRegistry.registerCommand(command, handler), this.addDynamicKeybindings([{
      keybinding,
      command,
      when
    }]));
  }
  addDynamicKeybindings(rules) {
    const entries = rules.map((rule2) => {
      var _a2;
      const keybinding = decodeKeybinding(rule2.keybinding, OS);
      return {
        keybinding,
        command: (_a2 = rule2.command) !== null && _a2 !== void 0 ? _a2 : null,
        commandArgs: rule2.commandArgs,
        when: rule2.when,
        weight1: 1e3,
        weight2: 0,
        extensionId: null,
        isBuiltinExtension: false
      };
    });
    this._dynamicKeybindings = this._dynamicKeybindings.concat(entries);
    this.updateResolver();
    return toDisposable(() => {
      for (let i = 0; i < this._dynamicKeybindings.length; i++) {
        if (this._dynamicKeybindings[i] === entries[0]) {
          this._dynamicKeybindings.splice(i, entries.length);
          this.updateResolver();
          return;
        }
      }
    });
  }
  updateResolver() {
    this._cachedResolver = null;
    this._onDidUpdateKeybindings.fire();
  }
  _getResolver() {
    if (!this._cachedResolver) {
      const defaults = this._toNormalizedKeybindingItems(KeybindingsRegistry.getDefaultKeybindings(), true);
      const overrides = this._toNormalizedKeybindingItems(this._dynamicKeybindings, false);
      this._cachedResolver = new KeybindingResolver(defaults, overrides, (str2) => this._log(str2));
    }
    return this._cachedResolver;
  }
  _documentHasFocus() {
    return document.hasFocus();
  }
  _toNormalizedKeybindingItems(items, isDefault) {
    const result2 = [];
    let resultLen = 0;
    for (const item of items) {
      const when = item.when || void 0;
      const keybinding = item.keybinding;
      if (!keybinding) {
        result2[resultLen++] = new ResolvedKeybindingItem(void 0, item.command, item.commandArgs, when, isDefault, null, false);
      } else {
        const resolvedKeybindings = USLayoutResolvedKeybinding.resolveKeybinding(keybinding, OS);
        for (const resolvedKeybinding of resolvedKeybindings) {
          result2[resultLen++] = new ResolvedKeybindingItem(resolvedKeybinding, item.command, item.commandArgs, when, isDefault, null, false);
        }
      }
    }
    return result2;
  }
  resolveKeyboardEvent(keyboardEvent) {
    const chord = new KeyCodeChord(keyboardEvent.ctrlKey, keyboardEvent.shiftKey, keyboardEvent.altKey, keyboardEvent.metaKey, keyboardEvent.keyCode);
    return new USLayoutResolvedKeybinding([chord], OS);
  }
};
StandaloneKeybindingService = __decorate$6([
  __param$6(0, IContextKeyService),
  __param$6(1, ICommandService),
  __param$6(2, ITelemetryService),
  __param$6(3, INotificationService),
  __param$6(4, ILogService),
  __param$6(5, ICodeEditorService)
], StandaloneKeybindingService);
class DomNodeListeners extends Disposable {
  constructor(domNode, disposables) {
    super();
    this.domNode = domNode;
    this._register(disposables);
  }
}
function isConfigurationOverrides(thing) {
  return thing && typeof thing === "object" && (!thing.overrideIdentifier || typeof thing.overrideIdentifier === "string") && (!thing.resource || thing.resource instanceof URI);
}
class StandaloneConfigurationService {
  constructor() {
    this._onDidChangeConfiguration = new Emitter$1();
    this.onDidChangeConfiguration = this._onDidChangeConfiguration.event;
    const defaultConfiguration = new DefaultConfiguration();
    this._configuration = new Configuration(defaultConfiguration.reload(), new ConfigurationModel(), new ConfigurationModel(), new ConfigurationModel());
    defaultConfiguration.dispose();
  }
  getValue(arg1, arg2) {
    const section = typeof arg1 === "string" ? arg1 : void 0;
    const overrides = isConfigurationOverrides(arg1) ? arg1 : isConfigurationOverrides(arg2) ? arg2 : {};
    return this._configuration.getValue(section, overrides, void 0);
  }
  updateValues(values) {
    const previous = { data: this._configuration.toData() };
    const changedKeys = [];
    for (const entry of values) {
      const [key, value] = entry;
      if (this.getValue(key) === value) {
        continue;
      }
      this._configuration.updateValue(key, value);
      changedKeys.push(key);
    }
    if (changedKeys.length > 0) {
      const configurationChangeEvent = new ConfigurationChangeEvent({ keys: changedKeys, overrides: [] }, previous, this._configuration);
      configurationChangeEvent.source = 8;
      configurationChangeEvent.sourceConfig = null;
      this._onDidChangeConfiguration.fire(configurationChangeEvent);
    }
    return Promise.resolve();
  }
  updateValue(key, value, arg3, arg4) {
    return this.updateValues([[key, value]]);
  }
  inspect(key, options = {}) {
    return this._configuration.inspect(key, options, void 0);
  }
}
let StandaloneResourceConfigurationService = class StandaloneResourceConfigurationService2 {
  constructor(configurationService, modelService, languageService) {
    this.configurationService = configurationService;
    this.modelService = modelService;
    this.languageService = languageService;
    this._onDidChangeConfiguration = new Emitter$1();
    this.configurationService.onDidChangeConfiguration((e) => {
      this._onDidChangeConfiguration.fire({ affectedKeys: e.affectedKeys, affectsConfiguration: (resource, configuration) => e.affectsConfiguration(configuration) });
    });
  }
  getValue(resource, arg2, arg3) {
    const position = Position$2.isIPosition(arg2) ? arg2 : null;
    const section = position ? typeof arg3 === "string" ? arg3 : void 0 : typeof arg2 === "string" ? arg2 : void 0;
    const language2 = resource ? this.getLanguage(resource, position) : void 0;
    if (typeof section === "undefined") {
      return this.configurationService.getValue({
        resource,
        overrideIdentifier: language2
      });
    }
    return this.configurationService.getValue(section, {
      resource,
      overrideIdentifier: language2
    });
  }
  getLanguage(resource, position) {
    const model = this.modelService.getModel(resource);
    if (model) {
      return position ? model.getLanguageIdAtPosition(position.lineNumber, position.column) : model.getLanguageId();
    }
    return this.languageService.guessLanguageIdByFilepathOrFirstLine(resource);
  }
};
StandaloneResourceConfigurationService = __decorate$6([
  __param$6(0, IConfigurationService),
  __param$6(1, IModelService),
  __param$6(2, ILanguageService)
], StandaloneResourceConfigurationService);
let StandaloneResourcePropertiesService = class StandaloneResourcePropertiesService2 {
  constructor(configurationService) {
    this.configurationService = configurationService;
  }
  getEOL(resource, language2) {
    const eol = this.configurationService.getValue("files.eol", { overrideIdentifier: language2, resource });
    if (eol && typeof eol === "string" && eol !== "auto") {
      return eol;
    }
    return isLinux || isMacintosh ? "\n" : "\r\n";
  }
};
StandaloneResourcePropertiesService = __decorate$6([
  __param$6(0, IConfigurationService)
], StandaloneResourcePropertiesService);
class StandaloneTelemetryService {
  publicLog2() {
  }
}
class StandaloneWorkspaceContextService {
  constructor() {
    const resource = URI.from({ scheme: StandaloneWorkspaceContextService.SCHEME, authority: "model", path: "/" });
    this.workspace = { id: STANDALONE_EDITOR_WORKSPACE_ID, folders: [new WorkspaceFolder({ uri: resource, name: "", index: 0 })] };
  }
  getWorkspace() {
    return this.workspace;
  }
  getWorkspaceFolder(resource) {
    return resource && resource.scheme === StandaloneWorkspaceContextService.SCHEME ? this.workspace.folders[0] : null;
  }
}
StandaloneWorkspaceContextService.SCHEME = "inmemory";
function updateConfigurationService(configurationService, source, isDiffEditor2) {
  if (!source) {
    return;
  }
  if (!(configurationService instanceof StandaloneConfigurationService)) {
    return;
  }
  const toUpdate = [];
  Object.keys(source).forEach((key) => {
    if (isEditorConfigurationKey(key)) {
      toUpdate.push([`editor.${key}`, source[key]]);
    }
    if (isDiffEditor2 && isDiffEditorConfigurationKey(key)) {
      toUpdate.push([`diffEditor.${key}`, source[key]]);
    }
  });
  if (toUpdate.length > 0) {
    configurationService.updateValues(toUpdate);
  }
}
let StandaloneBulkEditService = class StandaloneBulkEditService2 {
  constructor(_modelService) {
    this._modelService = _modelService;
  }
  hasPreviewHandler() {
    return false;
  }
  apply(editsIn, _options) {
    return __awaiter$5(this, void 0, void 0, function* () {
      const edits = Array.isArray(editsIn) ? editsIn : ResourceEdit.convert(editsIn);
      const textEdits = /* @__PURE__ */ new Map();
      for (const edit of edits) {
        if (!(edit instanceof ResourceTextEdit)) {
          throw new Error("bad edit - only text edits are supported");
        }
        const model = this._modelService.getModel(edit.resource);
        if (!model) {
          throw new Error("bad edit - model not found");
        }
        if (typeof edit.versionId === "number" && model.getVersionId() !== edit.versionId) {
          throw new Error("bad state - model changed in the meantime");
        }
        let array2 = textEdits.get(model);
        if (!array2) {
          array2 = [];
          textEdits.set(model, array2);
        }
        array2.push(EditOperation.replaceMove(Range$2.lift(edit.textEdit.range), edit.textEdit.text));
      }
      let totalEdits = 0;
      let totalFiles = 0;
      for (const [model, edits2] of textEdits) {
        model.pushStackElement();
        model.pushEditOperations([], edits2, () => []);
        model.pushStackElement();
        totalFiles += 1;
        totalEdits += edits2.length;
      }
      return {
        ariaSummary: format$2(StandaloneServicesNLS.bulkEditServiceSummary, totalEdits, totalFiles),
        isApplied: totalEdits > 0
      };
    });
  }
};
StandaloneBulkEditService = __decorate$6([
  __param$6(0, IModelService)
], StandaloneBulkEditService);
class StandaloneUriLabelService {
  getUriLabel(resource, options) {
    if (resource.scheme === "file") {
      return resource.fsPath;
    }
    return resource.path;
  }
  getUriBasenameLabel(resource) {
    return basename$1(resource);
  }
}
let StandaloneContextViewService = class StandaloneContextViewService2 extends ContextViewService {
  constructor(layoutService, _codeEditorService) {
    super(layoutService);
    this._codeEditorService = _codeEditorService;
  }
  showContextView(delegate, container2, shadowRoot) {
    if (!container2) {
      const codeEditor = this._codeEditorService.getFocusedCodeEditor() || this._codeEditorService.getActiveCodeEditor();
      if (codeEditor) {
        container2 = codeEditor.getContainerDomNode();
      }
    }
    return super.showContextView(delegate, container2, shadowRoot);
  }
};
StandaloneContextViewService = __decorate$6([
  __param$6(0, ILayoutService),
  __param$6(1, ICodeEditorService)
], StandaloneContextViewService);
class StandaloneWorkspaceTrustManagementService {
  constructor() {
    this._neverEmitter = new Emitter$1();
    this.onDidChangeTrust = this._neverEmitter.event;
  }
  isWorkspaceTrusted() {
    return true;
  }
}
class StandaloneLanguageService extends LanguageService {
  constructor() {
    super();
  }
}
class StandaloneLogService extends LogService {
  constructor() {
    super(new ConsoleLogger());
  }
}
let StandaloneContextMenuService = class StandaloneContextMenuService2 extends ContextMenuService {
  constructor(telemetryService, notificationService, contextViewService, keybindingService, menuService, contextKeyService) {
    super(telemetryService, notificationService, contextViewService, keybindingService, menuService, contextKeyService);
    this.configure({ blockMouse: false });
  }
};
StandaloneContextMenuService = __decorate$6([
  __param$6(0, ITelemetryService),
  __param$6(1, INotificationService),
  __param$6(2, IContextViewService),
  __param$6(3, IKeybindingService),
  __param$6(4, IMenuService),
  __param$6(5, IContextKeyService)
], StandaloneContextMenuService);
class StandaloneAudioService {
  playAudioCue(cue, allowManyInParallel) {
    return __awaiter$5(this, void 0, void 0, function* () {
    });
  }
}
registerSingleton(
  IConfigurationService,
  StandaloneConfigurationService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  ITextResourceConfigurationService,
  StandaloneResourceConfigurationService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  ITextResourcePropertiesService,
  StandaloneResourcePropertiesService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  IWorkspaceContextService,
  StandaloneWorkspaceContextService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  ILabelService,
  StandaloneUriLabelService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  ITelemetryService,
  StandaloneTelemetryService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  IDialogService,
  StandaloneDialogService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  IEnvironmentService,
  StandaloneEnvironmentService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  INotificationService,
  StandaloneNotificationService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  IMarkerService,
  MarkerService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  ILanguageService,
  StandaloneLanguageService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  IStandaloneThemeService,
  StandaloneThemeService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  ILogService,
  StandaloneLogService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  IModelService,
  ModelService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  IMarkerDecorationsService,
  MarkerDecorationsService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  IContextKeyService,
  ContextKeyService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  IProgressService,
  StandaloneProgressService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  IEditorProgressService,
  StandaloneEditorProgressService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  IStorageService,
  InMemoryStorageService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  IEditorWorkerService,
  EditorWorkerService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  IBulkEditService,
  StandaloneBulkEditService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  IWorkspaceTrustManagementService,
  StandaloneWorkspaceTrustManagementService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  ITextModelService,
  StandaloneTextModelService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  IAccessibilityService,
  AccessibilityService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  IListService,
  ListService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  ICommandService,
  StandaloneCommandService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  IKeybindingService,
  StandaloneKeybindingService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  IQuickInputService,
  StandaloneQuickInputService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  IContextViewService,
  StandaloneContextViewService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  IOpenerService,
  OpenerService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  IClipboardService,
  BrowserClipboardService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  IContextMenuService,
  StandaloneContextMenuService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  IMenuService,
  MenuService,
  0
  /* InstantiationType.Eager */
);
registerSingleton(
  IAudioCueService,
  StandaloneAudioService,
  0
  /* InstantiationType.Eager */
);
var StandaloneServices;
(function(StandaloneServices2) {
  const serviceCollection = new ServiceCollection();
  for (const [id3, descriptor] of getSingletonServiceDescriptors()) {
    serviceCollection.set(id3, descriptor);
  }
  const instantiationService = new InstantiationService(serviceCollection, true);
  serviceCollection.set(IInstantiationService, instantiationService);
  function get2(serviceId) {
    const r = serviceCollection.get(serviceId);
    if (!r) {
      throw new Error("Missing service " + serviceId);
    }
    if (r instanceof SyncDescriptor) {
      return instantiationService.invokeFunction((accessor) => accessor.get(serviceId));
    } else {
      return r;
    }
  }
  StandaloneServices2.get = get2;
  let initialized = false;
  const onDidInitialize = new Emitter$1();
  function initialize2(overrides) {
    if (initialized) {
      return instantiationService;
    }
    initialized = true;
    for (const [id3, descriptor] of getSingletonServiceDescriptors()) {
      if (!serviceCollection.get(id3)) {
        serviceCollection.set(id3, descriptor);
      }
    }
    for (const serviceId in overrides) {
      if (overrides.hasOwnProperty(serviceId)) {
        const serviceIdentifier = createDecorator(serviceId);
        const r = serviceCollection.get(serviceIdentifier);
        if (r instanceof SyncDescriptor) {
          serviceCollection.set(serviceIdentifier, overrides[serviceId]);
        }
      }
    }
    const editorFeatures2 = getEditorFeatures();
    for (const feature of editorFeatures2) {
      try {
        instantiationService.createInstance(feature);
      } catch (err) {
        onUnexpectedError(err);
      }
    }
    onDidInitialize.fire();
    return instantiationService;
  }
  StandaloneServices2.initialize = initialize2;
  function withServices(callback) {
    if (initialized) {
      return callback();
    }
    const disposable = new DisposableStore();
    const listener = disposable.add(onDidInitialize.event(() => {
      listener.dispose();
      disposable.add(callback());
    }));
    return disposable;
  }
  StandaloneServices2.withServices = withServices;
})(StandaloneServices || (StandaloneServices = {}));
const style = "";
const diffInsertIcon = registerIcon("diff-insert", Codicon.add, localize("diffInsertIcon", "Line decoration for inserts in the diff editor."));
const diffRemoveIcon = registerIcon("diff-remove", Codicon.remove, localize("diffRemoveIcon", "Line decoration for removals in the diff editor."));
const diffLineAddDecorationBackgroundWithIndicator = ModelDecorationOptions.register({
  className: "line-insert",
  description: "line-insert",
  isWholeLine: true,
  linesDecorationsClassName: "insert-sign " + ThemeIcon.asClassName(diffInsertIcon),
  marginClassName: "gutter-insert"
});
const diffLineDeleteDecorationBackgroundWithIndicator = ModelDecorationOptions.register({
  className: "line-delete",
  description: "line-delete",
  isWholeLine: true,
  linesDecorationsClassName: "delete-sign " + ThemeIcon.asClassName(diffRemoveIcon),
  marginClassName: "gutter-delete"
});
const diffLineAddDecorationBackground = ModelDecorationOptions.register({
  className: "line-insert",
  description: "line-insert",
  isWholeLine: true,
  marginClassName: "gutter-insert"
});
const diffLineDeleteDecorationBackground = ModelDecorationOptions.register({
  className: "line-delete",
  description: "line-delete",
  isWholeLine: true,
  marginClassName: "gutter-delete"
});
const diffAddDecoration = ModelDecorationOptions.register({
  className: "char-insert",
  description: "char-insert",
  shouldFillLineOnLineBreak: true
});
const diffWholeLineAddDecoration = ModelDecorationOptions.register({
  className: "char-insert",
  description: "char-insert",
  isWholeLine: true
});
const diffAddDecorationEmpty = ModelDecorationOptions.register({
  className: "char-insert diff-range-empty",
  description: "char-insert diff-range-empty"
});
const diffDeleteDecoration = ModelDecorationOptions.register({
  className: "char-delete",
  description: "char-delete",
  shouldFillLineOnLineBreak: true
});
const diffWholeLineDeleteDecoration = ModelDecorationOptions.register({
  className: "char-delete",
  description: "char-delete",
  isWholeLine: true
});
const diffDeleteDecorationEmpty = ModelDecorationOptions.register({
  className: "char-delete diff-range-empty",
  description: "char-delete diff-range-empty"
});
const arrowRevertChange = ModelDecorationOptions.register({
  description: "diff-editor-arrow-revert-change",
  glyphMarginHoverMessage: new MarkdownString(void 0, { isTrusted: true, supportThemeIcons: true }).appendMarkdown(localize("revertChangeHoverMessage", "Click to revert change")),
  glyphMarginClassName: "arrow-revert-change " + ThemeIcon.asClassName(Codicon.arrowRight),
  zIndex: 10001
});
class MovedBlocksLinesPart extends Disposable {
  constructor(_rootElement, _diffModel, _originalEditorLayoutInfo, _modifiedEditorLayoutInfo, _editors) {
    super();
    this._rootElement = _rootElement;
    this._diffModel = _diffModel;
    this._originalEditorLayoutInfo = _originalEditorLayoutInfo;
    this._modifiedEditorLayoutInfo = _modifiedEditorLayoutInfo;
    this._editors = _editors;
    const element = document.createElementNS("http://www.w3.org/2000/svg", "svg");
    element.setAttribute("class", "moved-blocks-lines");
    this._rootElement.appendChild(element);
    this._register(autorun("update", (reader) => {
      const info = this._originalEditorLayoutInfo.read(reader);
      const info2 = this._modifiedEditorLayoutInfo.read(reader);
      if (!info || !info2) {
        return;
      }
      element.style.left = `${info.width - info.verticalScrollbarWidth}px`;
      element.style.height = `${info.height}px`;
      element.style.width = `${info.verticalScrollbarWidth + info.contentLeft - MovedBlocksLinesPart.movedCodeBlockPadding}px`;
    }));
    const originalScrollTop = observableFromEvent(this._editors.original.onDidScrollChange, () => this._editors.original.getScrollTop());
    const modifiedScrollTop = observableFromEvent(this._editors.modified.onDidScrollChange, () => this._editors.modified.getScrollTop());
    const viewZonesChanged = observableSignalFromEvent("onDidChangeViewZones", this._editors.modified.onDidChangeViewZones);
    this._register(autorun("update", (reader) => {
      var _a2, _b2;
      element.replaceChildren();
      viewZonesChanged.read(reader);
      const info = this._originalEditorLayoutInfo.read(reader);
      const info2 = this._modifiedEditorLayoutInfo.read(reader);
      if (!info || !info2) {
        return;
      }
      const width = info.verticalScrollbarWidth + info.contentLeft - MovedBlocksLinesPart.movedCodeBlockPadding;
      const moves = (_b2 = (_a2 = this._diffModel.read(reader)) === null || _a2 === void 0 ? void 0 : _a2.diff.read(reader)) === null || _b2 === void 0 ? void 0 : _b2.movedTexts;
      if (!moves) {
        return;
      }
      let idx = 0;
      for (const m of moves) {
        let computeLineStart = function(range2, editor2) {
          const t1 = editor2.getTopForLineNumber(range2.startLineNumber);
          const t2 = editor2.getTopForLineNumber(range2.endLineNumberExclusive);
          return (t1 + t2) / 2;
        };
        const start = computeLineStart(m.lineRangeMapping.original, this._editors.original);
        const startOffset = originalScrollTop.read(reader);
        const end = computeLineStart(m.lineRangeMapping.modified, this._editors.modified);
        const endOffset = modifiedScrollTop.read(reader);
        const top = start - startOffset;
        const bottom = end - endOffset;
        const center = width / 2 - moves.length * 5 + idx * 10;
        idx++;
        const path2 = document.createElementNS("http://www.w3.org/2000/svg", "path");
        path2.setAttribute("d", `M ${0} ${top} L ${center} ${top} L ${center} ${bottom} L ${width} ${bottom}`);
        path2.setAttribute("fill", "none");
        element.appendChild(path2);
      }
    }));
  }
}
MovedBlocksLinesPart.movedCodeBlockPadding = 4;
function joinCombine(arr1, arr2, keySelector, combine) {
  if (arr1.length === 0) {
    return arr2;
  }
  if (arr2.length === 0) {
    return arr1;
  }
  const result2 = [];
  let i = 0;
  let j = 0;
  while (i < arr1.length && j < arr2.length) {
    const val1 = arr1[i];
    const val2 = arr2[j];
    const key1 = keySelector(val1);
    const key2 = keySelector(val2);
    if (key1 < key2) {
      result2.push(val1);
      i++;
    } else if (key1 > key2) {
      result2.push(val2);
      j++;
    } else {
      result2.push(combine(val1, val2));
      i++;
      j++;
    }
  }
  while (i < arr1.length) {
    result2.push(arr1[i]);
    i++;
  }
  while (j < arr2.length) {
    result2.push(arr2[j]);
    j++;
  }
  return result2;
}
function applyObservableDecorations(editor2, decorations2) {
  const d = new DisposableStore();
  const decorationsCollection = editor2.createDecorationsCollection();
  d.add(autorun(`Apply decorations from ${decorations2.debugName}`, (reader) => {
    const d2 = decorations2.read(reader);
    decorationsCollection.set(d2);
  }));
  d.add({
    dispose: () => {
      decorationsCollection.clear();
    }
  });
  return d;
}
function appendRemoveOnDispose(parent, child) {
  parent.appendChild(child);
  return toDisposable(() => {
    parent.removeChild(child);
  });
}
class ObservableElementSizeObserver extends Disposable {
  get width() {
    return this._width;
  }
  get height() {
    return this._height;
  }
  constructor(element, dimension) {
    super();
    this.elementSizeObserver = this._register(new ElementSizeObserver(element, dimension));
    this._width = observableValue("width", this.elementSizeObserver.getWidth());
    this._height = observableValue("height", this.elementSizeObserver.getHeight());
    this._register(this.elementSizeObserver.onDidChange((e) => transaction((tx) => {
      this._width.set(this.elementSizeObserver.getWidth(), tx);
      this._height.set(this.elementSizeObserver.getHeight(), tx);
    })));
  }
  observe(dimension) {
    this.elementSizeObserver.observe(dimension);
  }
  setAutomaticLayout(automaticLayout) {
    if (automaticLayout) {
      this.elementSizeObserver.startObserving();
    } else {
      this.elementSizeObserver.stopObserving();
    }
  }
}
function animatedObservable(base2, store) {
  let targetVal = base2.get();
  let startVal = targetVal;
  let curVal = targetVal;
  const result2 = observableValue("animatedValue", targetVal);
  let animationStartMs = -1;
  const durationMs = 300;
  let animationFrame = void 0;
  store.add(autorunHandleChanges("update value", {
    createEmptyChangeSummary: () => ({ animate: false }),
    handleChange: (ctx, s) => {
      if (ctx.didChange(base2)) {
        s.animate = s.animate || ctx.change;
      }
      return true;
    }
  }, (reader, s) => {
    if (animationFrame !== void 0) {
      cancelAnimationFrame(animationFrame);
      animationFrame = void 0;
    }
    startVal = curVal;
    targetVal = base2.read(reader);
    animationStartMs = Date.now() - (s.animate ? 0 : durationMs);
    update();
  }));
  function update() {
    const passedMs = Date.now() - animationStartMs;
    curVal = Math.floor(easeOutExpo(passedMs, startVal, targetVal - startVal, durationMs));
    if (passedMs < durationMs) {
      animationFrame = requestAnimationFrame(update);
    } else {
      curVal = targetVal;
    }
    result2.set(curVal, void 0);
  }
  return result2;
}
function easeOutExpo(t, b, c, d) {
  return t === d ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b;
}
class ViewZoneOverlayWidget extends Disposable {
  constructor(editor2, viewZone, htmlElement) {
    super();
    this._register(new ManagedOverlayWidget(editor2, htmlElement));
    this._register(applyStyle(htmlElement, {
      height: viewZone.actualHeight,
      top: viewZone.actualTop
    }));
  }
}
class PlaceholderViewZone {
  get afterLineNumber() {
    return this._afterLineNumber.get();
  }
  constructor(_afterLineNumber, heightInPx) {
    this._afterLineNumber = _afterLineNumber;
    this.heightInPx = heightInPx;
    this.domNode = document.createElement("div");
    this._actualTop = observableValue("actualTop", void 0);
    this._actualHeight = observableValue("actualHeight", void 0);
    this.actualTop = this._actualTop;
    this.actualHeight = this._actualHeight;
    this.showInHiddenAreas = true;
    this.onChange = this._afterLineNumber;
    this.onDomNodeTop = (top) => {
      this._actualTop.set(top, void 0);
    };
    this.onComputedHeight = (height) => {
      this._actualHeight.set(height, void 0);
    };
  }
}
class ManagedOverlayWidget {
  constructor(_editor, _domElement) {
    this._editor = _editor;
    this._domElement = _domElement;
    this._overlayWidgetId = `managedOverlayWidget-${ManagedOverlayWidget._counter++}`;
    this._overlayWidget = {
      getId: () => this._overlayWidgetId,
      getDomNode: () => this._domElement,
      getPosition: () => null
    };
    this._editor.addOverlayWidget(this._overlayWidget);
  }
  dispose() {
    this._editor.removeOverlayWidget(this._overlayWidget);
  }
}
ManagedOverlayWidget._counter = 0;
function applyStyle(domNode, style2) {
  return autorun("applyStyle", (reader) => {
    for (let [key, val] of Object.entries(style2)) {
      if (val && typeof val === "object" && "read" in val) {
        val = val.read(reader);
      }
      if (typeof val === "number") {
        val = `${val}px`;
      }
      domNode.style[key] = val;
    }
  });
}
function readHotReloadableExport(value, reader) {
  observeHotReloadableExports([value], reader);
  return value;
}
function observeHotReloadableExports(values, reader) {
  const hotReload_deprecateExports = globalThis.$hotReload_deprecateExports;
  if (!hotReload_deprecateExports) {
    return;
  }
  const o = observableSignalFromEvent("reload", (e) => {
    function handleExports(oldExports, _newExports) {
      if ([...Object.values(oldExports)].some((v) => values.includes(v))) {
        e(void 0);
        return true;
      }
      return false;
    }
    hotReload_deprecateExports.add(handleExports);
    return {
      dispose() {
        hotReload_deprecateExports.delete(handleExports);
      }
    };
  });
  o.read(reader);
}
function applyViewZones(editor2, viewZones, setIsUpdating) {
  const store = new DisposableStore();
  const lastViewZoneIds = [];
  store.add(autorun("applyViewZones", (reader) => {
    const curViewZones = viewZones.read(reader);
    const viewZonIdsPerViewZone = /* @__PURE__ */ new Map();
    const viewZoneIdPerOnChangeObservable = /* @__PURE__ */ new Map();
    if (setIsUpdating) {
      setIsUpdating(true);
    }
    editor2.changeViewZones((a) => {
      for (const id3 of lastViewZoneIds) {
        a.removeZone(id3);
      }
      lastViewZoneIds.length = 0;
      for (const z of curViewZones) {
        const id3 = a.addZone(z);
        lastViewZoneIds.push(id3);
        viewZonIdsPerViewZone.set(z, id3);
      }
    });
    if (setIsUpdating) {
      setIsUpdating(false);
    }
    store.add(autorunHandleChanges("layoutZone on change", {
      createEmptyChangeSummary() {
        return [];
      },
      handleChange(context, changeSummary) {
        const id3 = viewZoneIdPerOnChangeObservable.get(context.changedObservable);
        if (id3 !== void 0) {
          changeSummary.push(id3);
        }
        return true;
      }
    }, (reader2, changeSummary) => {
      for (const vz of curViewZones) {
        if (vz.onChange) {
          viewZoneIdPerOnChangeObservable.set(vz.onChange, viewZonIdsPerViewZone.get(vz));
          vz.onChange.read(reader2);
        }
      }
      if (setIsUpdating) {
        setIsUpdating(true);
      }
      editor2.changeViewZones((a) => {
        for (const id3 of changeSummary) {
          a.layoutZone(id3);
        }
      });
      if (setIsUpdating) {
        setIsUpdating(false);
      }
    }));
  }));
  store.add({
    dispose() {
      if (setIsUpdating) {
        setIsUpdating(true);
      }
      editor2.changeViewZones((a) => {
        for (const id3 of lastViewZoneIds) {
          a.removeZone(id3);
        }
      });
      if (setIsUpdating) {
        setIsUpdating(false);
      }
    }
  });
  return store;
}
class DiffEditorDecorations extends Disposable {
  constructor(_editors, _diffModel, _options) {
    super();
    this._editors = _editors;
    this._diffModel = _diffModel;
    this._options = _options;
    this._decorations = derived("decorations", (reader) => {
      var _a2;
      const diff = (_a2 = this._diffModel.read(reader)) === null || _a2 === void 0 ? void 0 : _a2.diff.read(reader);
      if (!diff) {
        return null;
      }
      const currentMove = this._diffModel.read(reader).syncedMovedTexts.read(reader);
      const renderIndicators = this._options.renderIndicators.read(reader);
      const showEmptyDecorations = this._options.showEmptyDecorations.read(reader);
      const originalDecorations = [];
      const modifiedDecorations = [];
      for (const m of diff.mappings) {
        const fullRangeOriginal = LineRange2.subtract(m.lineRangeMapping.originalRange, currentMove === null || currentMove === void 0 ? void 0 : currentMove.lineRangeMapping.original).map((i) => i.toInclusiveRange()).filter(isDefined);
        for (const range2 of fullRangeOriginal) {
          originalDecorations.push({ range: range2, options: renderIndicators ? diffLineDeleteDecorationBackgroundWithIndicator : diffLineDeleteDecorationBackground });
        }
        const fullRangeModified = LineRange2.subtract(m.lineRangeMapping.modifiedRange, currentMove === null || currentMove === void 0 ? void 0 : currentMove.lineRangeMapping.modified).map((i) => i.toInclusiveRange()).filter(isDefined);
        for (const range2 of fullRangeModified) {
          modifiedDecorations.push({ range: range2, options: renderIndicators ? diffLineAddDecorationBackgroundWithIndicator : diffLineAddDecorationBackground });
        }
        if (m.lineRangeMapping.modifiedRange.isEmpty || m.lineRangeMapping.originalRange.isEmpty) {
          for (const range2 of fullRangeOriginal) {
            originalDecorations.push({ range: range2, options: diffWholeLineDeleteDecoration });
          }
          for (const range2 of fullRangeModified) {
            modifiedDecorations.push({ range: range2, options: diffWholeLineAddDecoration });
          }
        } else {
          for (const i of m.lineRangeMapping.innerChanges || []) {
            if (currentMove && (currentMove.lineRangeMapping.original.intersect(new LineRange2(i.originalRange.startLineNumber, i.originalRange.endLineNumber)) || currentMove.lineRangeMapping.modified.intersect(new LineRange2(i.modifiedRange.startLineNumber, i.modifiedRange.endLineNumber)))) {
              continue;
            }
            if (m.lineRangeMapping.originalRange.contains(i.originalRange.startLineNumber)) {
              originalDecorations.push({ range: i.originalRange, options: i.originalRange.isEmpty() && showEmptyDecorations ? diffDeleteDecorationEmpty : diffDeleteDecoration });
            }
            if (m.lineRangeMapping.modifiedRange.contains(i.modifiedRange.startLineNumber)) {
              modifiedDecorations.push({ range: i.modifiedRange, options: i.modifiedRange.isEmpty() && showEmptyDecorations ? diffAddDecorationEmpty : diffAddDecoration });
            }
          }
        }
        if (!m.lineRangeMapping.modifiedRange.isEmpty && this._options.shouldRenderRevertArrows.read(reader) && !currentMove) {
          modifiedDecorations.push({ range: Range$2.fromPositions(new Position$2(m.lineRangeMapping.modifiedRange.startLineNumber, 1)), options: arrowRevertChange });
        }
      }
      if (currentMove) {
        for (const m of currentMove.changes) {
          const fullRangeOriginal = m.originalRange.toInclusiveRange();
          if (fullRangeOriginal) {
            originalDecorations.push({ range: fullRangeOriginal, options: renderIndicators ? diffLineDeleteDecorationBackgroundWithIndicator : diffLineDeleteDecorationBackground });
          }
          const fullRangeModified = m.modifiedRange.toInclusiveRange();
          if (fullRangeModified) {
            modifiedDecorations.push({ range: fullRangeModified, options: renderIndicators ? diffLineAddDecorationBackgroundWithIndicator : diffLineAddDecorationBackground });
          }
          for (const i of m.innerChanges || []) {
            originalDecorations.push({ range: i.originalRange, options: diffDeleteDecoration });
            modifiedDecorations.push({ range: i.modifiedRange, options: diffAddDecoration });
          }
        }
      }
      for (const m of diff.movedTexts) {
        originalDecorations.push({
          range: m.lineRangeMapping.original.toInclusiveRange(),
          options: {
            description: "moved",
            blockClassName: "movedOriginal",
            blockPadding: [MovedBlocksLinesPart.movedCodeBlockPadding, 0, MovedBlocksLinesPart.movedCodeBlockPadding, MovedBlocksLinesPart.movedCodeBlockPadding]
          }
        });
        modifiedDecorations.push({
          range: m.lineRangeMapping.modified.toInclusiveRange(),
          options: {
            description: "moved",
            blockClassName: "movedModified",
            blockPadding: [4, 0, 4, 4]
          }
        });
      }
      return { originalDecorations, modifiedDecorations };
    });
    this._register(applyObservableDecorations(this._editors.original, this._decorations.map((d) => (d === null || d === void 0 ? void 0 : d.originalDecorations) || [])));
    this._register(applyObservableDecorations(this._editors.modified, this._decorations.map((d) => (d === null || d === void 0 ? void 0 : d.modifiedDecorations) || [])));
  }
}
class DiffEditorSash extends Disposable {
  constructor(_options, _domNode, _dimensions) {
    super();
    this._options = _options;
    this._domNode = _domNode;
    this._dimensions = _dimensions;
    this._sashRatio = observableValue("sashRatio", void 0);
    this.sashLeft = derived("sashLeft", (reader) => {
      var _a2;
      const ratio = (_a2 = this._sashRatio.read(reader)) !== null && _a2 !== void 0 ? _a2 : this._options.splitViewDefaultRatio.read(reader);
      return this._computeSashLeft(ratio, reader);
    });
    this._sash = this._register(new Sash(this._domNode, {
      getVerticalSashTop: (_sash) => 0,
      getVerticalSashLeft: (_sash) => this.sashLeft.get(),
      getVerticalSashHeight: (_sash) => this._dimensions.height.get()
    }, {
      orientation: 0
      /* Orientation.VERTICAL */
    }));
    this._startSashPosition = void 0;
    this._register(this._sash.onDidStart(() => {
      this._startSashPosition = this.sashLeft.get();
    }));
    this._register(this._sash.onDidChange((e) => {
      const contentWidth = this._dimensions.width.get();
      const sashPosition = this._computeSashLeft((this._startSashPosition + (e.currentX - e.startX)) / contentWidth, void 0);
      this._sashRatio.set(sashPosition / contentWidth, void 0);
    }));
    this._register(this._sash.onDidEnd(() => this._sash.layout()));
    this._register(this._sash.onDidReset(() => this._sashRatio.set(void 0, void 0)));
    this._register(autorun("update sash layout", (reader) => {
      const enabled = this._options.enableSplitViewResizing.read(reader);
      this._sash.state = enabled ? 3 : 0;
      this.sashLeft.read(reader);
      this._sash.layout();
    }));
  }
  setBoundarySashes(sashes) {
    this._sash.orthogonalEndSash = sashes.bottom;
  }
  _computeSashLeft(desiredRatio, reader) {
    const contentWidth = this._dimensions.width.read(reader);
    const midPoint = Math.floor(this._options.splitViewDefaultRatio.read(reader) * contentWidth);
    const sashLeft = this._options.enableSplitViewResizing.read(reader) ? Math.floor(desiredRatio * contentWidth) : midPoint;
    const MINIMUM_EDITOR_WIDTH = 100;
    if (contentWidth <= MINIMUM_EDITOR_WIDTH * 2) {
      return midPoint;
    }
    if (sashLeft < MINIMUM_EDITOR_WIDTH) {
      return MINIMUM_EDITOR_WIDTH;
    }
    if (sashLeft > contentWidth - MINIMUM_EDITOR_WIDTH) {
      return contentWidth - MINIMUM_EDITOR_WIDTH;
    }
    return sashLeft;
  }
}
var __awaiter$4 = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class DiffEditorViewModel extends Disposable {
  constructor(model, _options, documentDiffProvider) {
    super();
    this.model = model;
    this._options = _options;
    this._isDiffUpToDate = observableValue("isDiffUpToDate", false);
    this.isDiffUpToDate = this._isDiffUpToDate;
    this._diff = observableValue("diff", void 0);
    this.diff = this._diff;
    this._unchangedRegions = observableValue("unchangedRegion", { regions: [], originalDecorationIds: [], modifiedDecorationIds: [] });
    this.unchangedRegions = derived("unchangedRegions", (r) => {
      if (this._options.collapseUnchangedRegions.read(r)) {
        return this._unchangedRegions.read(r).regions;
      } else {
        transaction((tx) => {
          for (const r2 of this._unchangedRegions.get().regions) {
            r2.setState(0, 0, tx);
          }
        });
        return [];
      }
    });
    this.syncedMovedTexts = observableValue("syncedMovedText", void 0);
    const contentChangedSignal = observableSignal("contentChangedSignal");
    const debouncer = this._register(new RunOnceScheduler(() => contentChangedSignal.trigger(void 0), 200));
    const updateUnchangedRegions = (result2, tx) => {
      const newUnchangedRegions = UnchangedRegion.fromDiffs(result2.changes, model.original.getLineCount(), model.modified.getLineCount());
      const lastUnchangedRegions = this._unchangedRegions.get();
      const lastUnchangedRegionsOrigRanges = lastUnchangedRegions.originalDecorationIds.map((id3) => model.original.getDecorationRange(id3)).filter((r) => !!r).map((r) => LineRange2.fromRange(r));
      const lastUnchangedRegionsModRanges = lastUnchangedRegions.modifiedDecorationIds.map((id3) => model.modified.getDecorationRange(id3)).filter((r) => !!r).map((r) => LineRange2.fromRange(r));
      const originalDecorationIds = model.original.deltaDecorations(lastUnchangedRegions.originalDecorationIds, newUnchangedRegions.map((r) => ({ range: r.originalRange.toInclusiveRange(), options: { description: "unchanged" } })));
      const modifiedDecorationIds = model.modified.deltaDecorations(lastUnchangedRegions.modifiedDecorationIds, newUnchangedRegions.map((r) => ({ range: r.modifiedRange.toInclusiveRange(), options: { description: "unchanged" } })));
      for (const r of newUnchangedRegions) {
        for (let i = 0; i < lastUnchangedRegions.regions.length; i++) {
          if (r.originalRange.intersectsStrict(lastUnchangedRegionsOrigRanges[i]) && r.modifiedRange.intersectsStrict(lastUnchangedRegionsModRanges[i])) {
            r.setHiddenModifiedRange(lastUnchangedRegions.regions[i].getHiddenModifiedRange(void 0), tx);
            break;
          }
        }
      }
      this._unchangedRegions.set({
        regions: newUnchangedRegions,
        originalDecorationIds,
        modifiedDecorationIds
      }, tx);
    };
    this._register(model.modified.onDidChangeContent((e) => {
      const diff = this._diff.get();
      if (!diff) {
        return;
      }
      const textEdits = TextEditInfo.fromModelContentChanges(e.changes);
      const result2 = applyModifiedEdits(this._lastDiff, textEdits, model.original, model.modified);
      if (result2) {
        this._lastDiff = result2;
        transaction((tx) => {
          this._diff.set(DiffState.fromDiffResult(this._lastDiff), tx);
          updateUnchangedRegions(result2, tx);
          const currentSyncedMovedText = this.syncedMovedTexts.get();
          this.syncedMovedTexts.set(currentSyncedMovedText ? this._lastDiff.moves.find((m) => m.lineRangeMapping.modified.intersect(currentSyncedMovedText.lineRangeMapping.modified)) : void 0, tx);
        });
      }
      debouncer.schedule();
    }));
    this._register(model.original.onDidChangeContent((e) => {
      const diff = this._diff.get();
      if (!diff) {
        return;
      }
      const textEdits = TextEditInfo.fromModelContentChanges(e.changes);
      const result2 = applyOriginalEdits(this._lastDiff, textEdits, model.original, model.modified);
      if (result2) {
        this._lastDiff = result2;
        transaction((tx) => {
          this._diff.set(DiffState.fromDiffResult(this._lastDiff), tx);
          updateUnchangedRegions(result2, tx);
          const currentSyncedMovedText = this.syncedMovedTexts.get();
          this.syncedMovedTexts.set(currentSyncedMovedText ? this._lastDiff.moves.find((m) => m.lineRangeMapping.modified.intersect(currentSyncedMovedText.lineRangeMapping.modified)) : void 0, tx);
        });
      }
      debouncer.schedule();
    }));
    const documentDiffProviderOptionChanged = observableSignalFromEvent("documentDiffProviderOptionChanged", documentDiffProvider.onDidChange);
    this._register(autorunWithStore2("compute diff", (reader, store) => __awaiter$4(this, void 0, void 0, function* () {
      var _a2, _b2;
      debouncer.cancel();
      contentChangedSignal.read(reader);
      documentDiffProviderOptionChanged.read(reader);
      this._isDiffUpToDate.set(false, void 0);
      let originalTextEditInfos = [];
      store.add(model.original.onDidChangeContent((e) => {
        const edits = TextEditInfo.fromModelContentChanges(e.changes);
        originalTextEditInfos = combineTextEditInfos(originalTextEditInfos, edits);
      }));
      let modifiedTextEditInfos = [];
      store.add(model.modified.onDidChangeContent((e) => {
        const edits = TextEditInfo.fromModelContentChanges(e.changes);
        modifiedTextEditInfos = combineTextEditInfos(modifiedTextEditInfos, edits);
      }));
      let result2 = yield documentDiffProvider.computeDiff(model.original, model.modified, {
        ignoreTrimWhitespace: this._options.ignoreTrimWhitespace.read(reader),
        maxComputationTimeMs: this._options.maxComputationTimeMs.read(reader),
        computeMoves: this._options.showMoves.read(reader)
      });
      result2 = (_a2 = applyOriginalEdits(result2, originalTextEditInfos, model.original, model.modified)) !== null && _a2 !== void 0 ? _a2 : result2;
      result2 = (_b2 = applyModifiedEdits(result2, modifiedTextEditInfos, model.original, model.modified)) !== null && _b2 !== void 0 ? _b2 : result2;
      transaction((tx) => {
        updateUnchangedRegions(result2, tx);
        this._lastDiff = result2;
        const state = DiffState.fromDiffResult(result2);
        this._diff.set(state, tx);
        this._isDiffUpToDate.set(true, tx);
        const currentSyncedMovedText = this.syncedMovedTexts.get();
        this.syncedMovedTexts.set(currentSyncedMovedText ? this._lastDiff.moves.find((m) => m.lineRangeMapping.modified.intersect(currentSyncedMovedText.lineRangeMapping.modified)) : void 0, tx);
      });
    })));
  }
  ensureModifiedLineIsVisible(lineNumber, tx) {
    var _a2;
    if (((_a2 = this.diff.get()) === null || _a2 === void 0 ? void 0 : _a2.mappings.length) === 0) {
      return;
    }
    const unchangedRegions = this._unchangedRegions.get().regions;
    for (const r of unchangedRegions) {
      if (r.getHiddenModifiedRange(void 0).contains(lineNumber)) {
        r.showAll(tx);
        return;
      }
    }
  }
  ensureOriginalLineIsVisible(lineNumber, tx) {
    var _a2;
    if (((_a2 = this.diff.get()) === null || _a2 === void 0 ? void 0 : _a2.mappings.length) === 0) {
      return;
    }
    const unchangedRegions = this._unchangedRegions.get().regions;
    for (const r of unchangedRegions) {
      if (r.getHiddenOriginalRange(void 0).contains(lineNumber)) {
        r.showAll(tx);
        return;
      }
    }
  }
  waitForDiff() {
    return __awaiter$4(this, void 0, void 0, function* () {
      yield waitForState(this.isDiffUpToDate, (s) => s);
    });
  }
  serializeState() {
    const regions = this._unchangedRegions.get();
    return {
      collapsedRegions: regions.regions.map((r) => ({ range: r.getHiddenModifiedRange(void 0).serialize() }))
    };
  }
  restoreSerializedState(state) {
    const ranges = state.collapsedRegions.map((r) => LineRange2.deserialize(r.range));
    const regions = this._unchangedRegions.get();
    transaction((tx) => {
      for (const r of regions.regions) {
        for (const range2 of ranges) {
          if (r.modifiedRange.intersect(range2)) {
            r.setHiddenModifiedRange(range2, tx);
            break;
          }
        }
      }
    });
  }
}
class DiffState {
  static fromDiffResult(result2) {
    return new DiffState(result2.changes.map((c) => new DiffMapping(c)), result2.moves || [], result2.identical, result2.quitEarly);
  }
  constructor(mappings, movedTexts, identical, quitEarly) {
    this.mappings = mappings;
    this.movedTexts = movedTexts;
    this.identical = identical;
    this.quitEarly = quitEarly;
  }
}
class DiffMapping {
  constructor(lineRangeMapping) {
    this.lineRangeMapping = lineRangeMapping;
  }
}
class UnchangedRegion {
  static fromDiffs(changes, originalLineCount, modifiedLineCount) {
    const inversedMappings = LineRangeMapping.inverse(changes, originalLineCount, modifiedLineCount);
    const result2 = [];
    const minHiddenLineCount = 3;
    const minContext = 3;
    for (const mapping of inversedMappings) {
      let origStart = mapping.originalRange.startLineNumber;
      let modStart = mapping.modifiedRange.startLineNumber;
      let length2 = mapping.originalRange.length;
      const atStart = origStart === 1 && modStart === 1;
      const atEnd = origStart + length2 === originalLineCount + 1 && modStart + length2 === modifiedLineCount + 1;
      if ((atStart || atEnd) && length2 > minContext + minHiddenLineCount) {
        if (atStart && !atEnd) {
          length2 -= minContext;
        }
        if (atEnd && !atStart) {
          origStart += minContext;
          modStart += minContext;
          length2 -= minContext;
        }
        result2.push(new UnchangedRegion(origStart, modStart, length2, 0, 0));
      } else if (length2 > minContext * 2 + minHiddenLineCount) {
        origStart += minContext;
        modStart += minContext;
        length2 -= minContext * 2;
        result2.push(new UnchangedRegion(origStart, modStart, length2, 0, 0));
      }
    }
    return result2;
  }
  get originalRange() {
    return LineRange2.ofLength(this.originalLineNumber, this.lineCount);
  }
  get modifiedRange() {
    return LineRange2.ofLength(this.modifiedLineNumber, this.lineCount);
  }
  constructor(originalLineNumber, modifiedLineNumber, lineCount, visibleLineCountTop, visibleLineCountBottom) {
    this.originalLineNumber = originalLineNumber;
    this.modifiedLineNumber = modifiedLineNumber;
    this.lineCount = lineCount;
    this._visibleLineCountTop = observableValue("visibleLineCountTop", 0);
    this.visibleLineCountTop = this._visibleLineCountTop;
    this._visibleLineCountBottom = observableValue("visibleLineCountBottom", 0);
    this.visibleLineCountBottom = this._visibleLineCountBottom;
    this._shouldHideControls = derived("isVisible", (reader) => this.visibleLineCountTop.read(reader) + this.visibleLineCountBottom.read(reader) === this.lineCount && !this.isDragged.read(reader));
    this.isDragged = observableValue("isDragged", false);
    this._visibleLineCountTop.set(visibleLineCountTop, void 0);
    this._visibleLineCountBottom.set(visibleLineCountBottom, void 0);
  }
  shouldHideControls(reader) {
    return this._shouldHideControls.read(reader);
  }
  getHiddenOriginalRange(reader) {
    return LineRange2.ofLength(this.originalLineNumber + this._visibleLineCountTop.read(reader), this.lineCount - this._visibleLineCountTop.read(reader) - this._visibleLineCountBottom.read(reader));
  }
  getHiddenModifiedRange(reader) {
    return LineRange2.ofLength(this.modifiedLineNumber + this._visibleLineCountTop.read(reader), this.lineCount - this._visibleLineCountTop.read(reader) - this._visibleLineCountBottom.read(reader));
  }
  setHiddenModifiedRange(range2, tx) {
    const visibleLineCountTop = range2.startLineNumber - this.modifiedLineNumber;
    const visibleLineCountBottom = this.modifiedLineNumber + this.lineCount - range2.endLineNumberExclusive;
    this.setState(visibleLineCountTop, visibleLineCountBottom, tx);
  }
  getMaxVisibleLineCountTop() {
    return this.lineCount - this._visibleLineCountBottom.get();
  }
  getMaxVisibleLineCountBottom() {
    return this.lineCount - this._visibleLineCountTop.get();
  }
  showMoreAbove(count = 10, tx) {
    const maxVisibleLineCountTop = this.getMaxVisibleLineCountTop();
    this._visibleLineCountTop.set(Math.min(this._visibleLineCountTop.get() + count, maxVisibleLineCountTop), tx);
  }
  showMoreBelow(count = 10, tx) {
    const maxVisibleLineCountBottom = this.lineCount - this._visibleLineCountTop.get();
    this._visibleLineCountBottom.set(Math.min(this._visibleLineCountBottom.get() + count, maxVisibleLineCountBottom), tx);
  }
  showAll(tx) {
    this._visibleLineCountBottom.set(this.lineCount - this._visibleLineCountTop.get(), tx);
  }
  setState(visibleLineCountTop, visibleLineCountBottom, tx) {
    visibleLineCountTop = Math.max(Math.min(visibleLineCountTop, this.lineCount), 0);
    visibleLineCountBottom = Math.max(Math.min(visibleLineCountBottom, this.lineCount - visibleLineCountTop), 0);
    this._visibleLineCountTop.set(visibleLineCountTop, tx);
    this._visibleLineCountBottom.set(visibleLineCountBottom, tx);
  }
}
function applyOriginalEdits(diff, textEdits, originalTextModel, modifiedTextModel) {
  if (textEdits.length === 0) {
    return diff;
  }
  const diff2 = flip(diff);
  const diff3 = applyModifiedEdits(diff2, textEdits, modifiedTextModel, originalTextModel);
  if (!diff3) {
    return void 0;
  }
  return flip(diff3);
}
function flip(diff) {
  return {
    changes: diff.changes.map((c) => c.flip()),
    moves: diff.moves.map((m) => m.flip()),
    identical: diff.identical,
    quitEarly: diff.quitEarly
  };
}
function applyModifiedEdits(diff, textEdits, originalTextModel, modifiedTextModel) {
  if (textEdits.length === 0) {
    return diff;
  }
  if (diff.changes.some((c) => !c.innerChanges) || diff.moves.length > 0) {
    return void 0;
  }
  const changes = applyModifiedEditsToLineRangeMappings(diff.changes, textEdits, originalTextModel, modifiedTextModel);
  const moves = diff.moves.map((m) => {
    const newModifiedRange = applyEditToLineRange(m.lineRangeMapping.modified, textEdits);
    return newModifiedRange ? new MovedText(new SimpleLineRangeMapping(m.lineRangeMapping.original, newModifiedRange), applyModifiedEditsToLineRangeMappings(m.changes, textEdits, originalTextModel, modifiedTextModel)) : void 0;
  }).filter(isDefined);
  return {
    identical: false,
    quitEarly: false,
    changes,
    moves
  };
}
function applyEditToLineRange(range2, textEdits) {
  let rangeStartLineNumber = range2.startLineNumber;
  let rangeEndLineNumberEx = range2.endLineNumberExclusive;
  for (let i = textEdits.length - 1; i >= 0; i--) {
    const textEdit = textEdits[i];
    const textEditStartLineNumber = lengthGetLineCount(textEdit.startOffset) + 1;
    const textEditEndLineNumber = lengthGetLineCount(textEdit.endOffset) + 1;
    const newLengthLineCount = lengthGetLineCount(textEdit.newLength);
    const delta = newLengthLineCount - (textEditEndLineNumber - textEditStartLineNumber);
    if (textEditEndLineNumber < rangeStartLineNumber) {
      rangeStartLineNumber += delta;
      rangeEndLineNumberEx += delta;
    } else if (textEditStartLineNumber > rangeEndLineNumberEx)
      ;
    else if (textEditStartLineNumber < rangeStartLineNumber && rangeEndLineNumberEx < textEditEndLineNumber) {
      return void 0;
    } else if (textEditStartLineNumber < rangeStartLineNumber && textEditEndLineNumber <= rangeEndLineNumberEx) {
      rangeStartLineNumber = textEditEndLineNumber + 1;
      rangeStartLineNumber += delta;
      rangeEndLineNumberEx += delta;
    } else if (rangeStartLineNumber <= textEditStartLineNumber && textEditEndLineNumber < rangeStartLineNumber) {
      rangeEndLineNumberEx = textEditStartLineNumber;
    } else {
      rangeEndLineNumberEx += delta;
    }
  }
  return new LineRange2(rangeStartLineNumber, rangeEndLineNumberEx);
}
function applyModifiedEditsToLineRangeMappings(changes, textEdits, originalTextModel, modifiedTextModel) {
  const diffTextEdits = changes.flatMap((c) => c.innerChanges.map((c2) => new TextEditInfo(positionToLength(c2.originalRange.getStartPosition()), positionToLength(c2.originalRange.getEndPosition()), lengthOfRange(c2.modifiedRange).toLength())));
  const combined = combineTextEditInfos(diffTextEdits, textEdits);
  let lastOriginalEndOffset = lengthZero;
  let lastModifiedEndOffset = lengthZero;
  const rangeMappings = combined.map((c) => {
    const modifiedStartOffset = lengthAdd(lastModifiedEndOffset, lengthDiffNonNegative(lastOriginalEndOffset, c.startOffset));
    lastOriginalEndOffset = c.endOffset;
    lastModifiedEndOffset = lengthAdd(modifiedStartOffset, c.newLength);
    return new RangeMapping(Range$2.fromPositions(lengthToPosition(c.startOffset), lengthToPosition(c.endOffset)), Range$2.fromPositions(lengthToPosition(modifiedStartOffset), lengthToPosition(lastModifiedEndOffset)));
  });
  const newChanges = lineRangeMappingFromRangeMappings(rangeMappings, originalTextModel.getLinesContent(), modifiedTextModel.getLinesContent());
  return newChanges;
}
var __awaiter$3 = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
class InlineDiffDeletedCodeMargin extends Disposable {
  get visibility() {
    return this._visibility;
  }
  set visibility(_visibility) {
    if (this._visibility !== _visibility) {
      this._visibility = _visibility;
      this._diffActions.style.visibility = _visibility ? "visible" : "hidden";
    }
  }
  constructor(_getViewZoneId, _marginDomNode, _modifiedEditor, _diff, _editor, _viewLineCounts, _originalTextModel, _contextMenuService, _clipboardService) {
    super();
    this._getViewZoneId = _getViewZoneId;
    this._marginDomNode = _marginDomNode;
    this._modifiedEditor = _modifiedEditor;
    this._diff = _diff;
    this._editor = _editor;
    this._viewLineCounts = _viewLineCounts;
    this._originalTextModel = _originalTextModel;
    this._contextMenuService = _contextMenuService;
    this._clipboardService = _clipboardService;
    this._visibility = false;
    this._marginDomNode.style.zIndex = "10";
    this._diffActions = document.createElement("div");
    this._diffActions.className = ThemeIcon.asClassName(Codicon.lightBulb) + " lightbulb-glyph";
    this._diffActions.style.position = "absolute";
    const lineHeight = this._modifiedEditor.getOption(
      65
      /* EditorOption.lineHeight */
    );
    this._diffActions.style.right = "0px";
    this._diffActions.style.visibility = "hidden";
    this._diffActions.style.height = `${lineHeight}px`;
    this._diffActions.style.lineHeight = `${lineHeight}px`;
    this._marginDomNode.appendChild(this._diffActions);
    let currentLineNumberOffset = 0;
    const useShadowDOM = _modifiedEditor.getOption(
      125
      /* EditorOption.useShadowDOM */
    ) && !isIOS;
    const showContextMenu = (x, y) => {
      var _a2;
      this._contextMenuService.showContextMenu({
        domForShadowRoot: useShadowDOM ? (_a2 = _modifiedEditor.getDomNode()) !== null && _a2 !== void 0 ? _a2 : void 0 : void 0,
        getAnchor: () => ({ x, y }),
        getActions: () => {
          const actions = [];
          const isDeletion = _diff.modifiedRange.isEmpty;
          actions.push(new Action("diff.clipboard.copyDeletedContent", isDeletion ? _diff.originalRange.length > 1 ? localize("diff.clipboard.copyDeletedLinesContent.label", "Copy deleted lines") : localize("diff.clipboard.copyDeletedLinesContent.single.label", "Copy deleted line") : _diff.originalRange.length > 1 ? localize("diff.clipboard.copyChangedLinesContent.label", "Copy changed lines") : localize("diff.clipboard.copyChangedLinesContent.single.label", "Copy changed line"), void 0, true, () => __awaiter$3(this, void 0, void 0, function* () {
            const originalText = this._originalTextModel.getValueInRange(_diff.originalRange.toExclusiveRange());
            yield this._clipboardService.writeText(originalText);
          })));
          if (_diff.originalRange.length > 1) {
            actions.push(new Action("diff.clipboard.copyDeletedLineContent", isDeletion ? localize("diff.clipboard.copyDeletedLineContent.label", "Copy deleted line ({0})", _diff.originalRange.startLineNumber + currentLineNumberOffset) : localize("diff.clipboard.copyChangedLineContent.label", "Copy changed line ({0})", _diff.originalRange.startLineNumber + currentLineNumberOffset), void 0, true, () => __awaiter$3(this, void 0, void 0, function* () {
              let lineContent = this._originalTextModel.getLineContent(_diff.originalRange.startLineNumber + currentLineNumberOffset);
              if (lineContent === "") {
                const eof = this._originalTextModel.getEndOfLineSequence();
                lineContent = eof === 0 ? "\n" : "\r\n";
              }
              yield this._clipboardService.writeText(lineContent);
            })));
          }
          const readOnly = _modifiedEditor.getOption(
            89
            /* EditorOption.readOnly */
          );
          if (!readOnly) {
            actions.push(new Action("diff.inline.revertChange", localize("diff.inline.revertChange.label", "Revert this change"), void 0, true, () => __awaiter$3(this, void 0, void 0, function* () {
              this._editor.revert(this._diff);
            })));
          }
          return actions;
        },
        autoSelectFirstItem: true
      });
    };
    this._register(addStandardDisposableListener(this._diffActions, "mousedown", (e) => {
      const { top, height } = getDomNodePagePosition(this._diffActions);
      const pad2 = Math.floor(lineHeight / 3);
      e.preventDefault();
      showContextMenu(e.posx, top + height + pad2);
    }));
    this._register(_modifiedEditor.onMouseMove((e) => {
      if ((e.target.type === 8 || e.target.type === 5) && e.target.detail.viewZoneId === this._getViewZoneId()) {
        currentLineNumberOffset = this._updateLightBulbPosition(this._marginDomNode, e.event.browserEvent.y, lineHeight);
        this.visibility = true;
      } else {
        this.visibility = false;
      }
    }));
    this._register(_modifiedEditor.onMouseDown((e) => {
      if (!e.event.rightButton) {
        return;
      }
      if (e.target.type === 8 || e.target.type === 5) {
        const viewZoneId = e.target.detail.viewZoneId;
        if (viewZoneId === this._getViewZoneId()) {
          e.event.preventDefault();
          currentLineNumberOffset = this._updateLightBulbPosition(this._marginDomNode, e.event.browserEvent.y, lineHeight);
          showContextMenu(e.event.posx, e.event.posy + lineHeight);
        }
      }
    }));
  }
  _updateLightBulbPosition(marginDomNode, y, lineHeight) {
    const { top } = getDomNodePagePosition(marginDomNode);
    const offset = y - top;
    const lineNumberOffset = Math.floor(offset / lineHeight);
    const newTop = lineNumberOffset * lineHeight;
    this._diffActions.style.top = `${newTop}px`;
    if (this._viewLineCounts) {
      let acc = 0;
      for (let i = 0; i < this._viewLineCounts.length; i++) {
        acc += this._viewLineCounts[i];
        if (lineNumberOffset < acc) {
          return i;
        }
      }
    }
    return lineNumberOffset;
  }
}
const ttPolicy = diffEditorWidgetTtPolicy;
function renderLines(source, options, decorations2, domNode) {
  applyFontInfo(domNode, options.fontInfo);
  const hasCharChanges = decorations2.length > 0;
  const sb = new StringBuilder(1e4);
  let maxCharsPerLine = 0;
  let renderedLineCount = 0;
  const viewLineCounts = [];
  for (let lineIndex = 0; lineIndex < source.lineTokens.length; lineIndex++) {
    const lineNumber = lineIndex + 1;
    const lineTokens = source.lineTokens[lineIndex];
    const lineBreakData = source.lineBreakData[lineIndex];
    const actualDecorations = LineDecoration.filter(decorations2, lineNumber, 1, Number.MAX_SAFE_INTEGER);
    if (lineBreakData) {
      let lastBreakOffset = 0;
      for (const breakOffset of lineBreakData.breakOffsets) {
        const viewLineTokens = lineTokens.sliceAndInflate(lastBreakOffset, breakOffset, 0);
        maxCharsPerLine = Math.max(maxCharsPerLine, renderOriginalLine(renderedLineCount, viewLineTokens, LineDecoration.extractWrapped(actualDecorations, lastBreakOffset, breakOffset), hasCharChanges, source.mightContainNonBasicASCII, source.mightContainRTL, options, sb));
        renderedLineCount++;
        lastBreakOffset = breakOffset;
      }
      viewLineCounts.push(lineBreakData.breakOffsets.length);
    } else {
      viewLineCounts.push(1);
      maxCharsPerLine = Math.max(maxCharsPerLine, renderOriginalLine(renderedLineCount, lineTokens, actualDecorations, hasCharChanges, source.mightContainNonBasicASCII, source.mightContainRTL, options, sb));
      renderedLineCount++;
    }
  }
  maxCharsPerLine += options.scrollBeyondLastColumn;
  const html2 = sb.build();
  const trustedhtml = ttPolicy ? ttPolicy.createHTML(html2) : html2;
  domNode.innerHTML = trustedhtml;
  const minWidthInPx = maxCharsPerLine * options.typicalHalfwidthCharacterWidth;
  return {
    heightInLines: renderedLineCount,
    minWidthInPx,
    viewLineCounts
  };
}
class LineSource {
  constructor(lineTokens, lineBreakData, mightContainNonBasicASCII, mightContainRTL) {
    this.lineTokens = lineTokens;
    this.lineBreakData = lineBreakData;
    this.mightContainNonBasicASCII = mightContainNonBasicASCII;
    this.mightContainRTL = mightContainRTL;
  }
}
class RenderOptions {
  static fromEditor(editor2) {
    var _a2;
    const modifiedEditorOptions = editor2.getOptions();
    const fontInfo = modifiedEditorOptions.get(
      49
      /* EditorOption.fontInfo */
    );
    const layoutInfo = modifiedEditorOptions.get(
      142
      /* EditorOption.layoutInfo */
    );
    return new RenderOptions(((_a2 = editor2.getModel()) === null || _a2 === void 0 ? void 0 : _a2.getOptions().tabSize) || 0, fontInfo, modifiedEditorOptions.get(
      32
      /* EditorOption.disableMonospaceOptimizations */
    ), fontInfo.typicalHalfwidthCharacterWidth, modifiedEditorOptions.get(
      102
      /* EditorOption.scrollBeyondLastColumn */
    ), modifiedEditorOptions.get(
      65
      /* EditorOption.lineHeight */
    ), layoutInfo.decorationsWidth, modifiedEditorOptions.get(
      115
      /* EditorOption.stopRenderingLineAfter */
    ), modifiedEditorOptions.get(
      97
      /* EditorOption.renderWhitespace */
    ), modifiedEditorOptions.get(
      92
      /* EditorOption.renderControlCharacters */
    ), modifiedEditorOptions.get(
      50
      /* EditorOption.fontLigatures */
    ));
  }
  constructor(tabSize, fontInfo, disableMonospaceOptimizations, typicalHalfwidthCharacterWidth, scrollBeyondLastColumn, lineHeight, lineDecorationsWidth, stopRenderingLineAfter, renderWhitespace, renderControlCharacters, fontLigatures) {
    this.tabSize = tabSize;
    this.fontInfo = fontInfo;
    this.disableMonospaceOptimizations = disableMonospaceOptimizations;
    this.typicalHalfwidthCharacterWidth = typicalHalfwidthCharacterWidth;
    this.scrollBeyondLastColumn = scrollBeyondLastColumn;
    this.lineHeight = lineHeight;
    this.lineDecorationsWidth = lineDecorationsWidth;
    this.stopRenderingLineAfter = stopRenderingLineAfter;
    this.renderWhitespace = renderWhitespace;
    this.renderControlCharacters = renderControlCharacters;
    this.fontLigatures = fontLigatures;
  }
}
function renderOriginalLine(viewLineIdx, lineTokens, decorations2, hasCharChanges, mightContainNonBasicASCII, mightContainRTL, options, sb) {
  sb.appendString('<div class="view-line');
  if (!hasCharChanges) {
    sb.appendString(" char-delete");
  }
  sb.appendString('" style="top:');
  sb.appendString(String(viewLineIdx * options.lineHeight));
  sb.appendString('px;width:1000000px;">');
  const lineContent = lineTokens.getLineContent();
  const isBasicASCII2 = ViewLineRenderingData.isBasicASCII(lineContent, mightContainNonBasicASCII);
  const containsRTL2 = ViewLineRenderingData.containsRTL(lineContent, isBasicASCII2, mightContainRTL);
  const output = renderViewLine(new RenderLineInput(
    options.fontInfo.isMonospace && !options.disableMonospaceOptimizations,
    options.fontInfo.canUseHalfwidthRightwardsArrow,
    lineContent,
    false,
    isBasicASCII2,
    containsRTL2,
    0,
    lineTokens,
    decorations2,
    options.tabSize,
    0,
    options.fontInfo.spaceWidth,
    options.fontInfo.middotWidth,
    options.fontInfo.wsmiddotWidth,
    options.stopRenderingLineAfter,
    options.renderWhitespace,
    options.renderControlCharacters,
    options.fontLigatures !== EditorFontLigatures.OFF,
    null
    // Send no selections, original line cannot be selected
  ), sb);
  sb.appendString("</div>");
  return output.characterMapping.getHorizontalOffset(output.characterMapping.length);
}
var __decorate$5 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$5 = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let ViewZoneManager = class ViewZoneManager2 extends Disposable {
  constructor(_editors, _diffModel, _options, _diffEditorWidget, _canIgnoreViewZoneUpdateEvent, _clipboardService, _contextMenuService) {
    super();
    this._editors = _editors;
    this._diffModel = _diffModel;
    this._options = _options;
    this._diffEditorWidget = _diffEditorWidget;
    this._canIgnoreViewZoneUpdateEvent = _canIgnoreViewZoneUpdateEvent;
    this._clipboardService = _clipboardService;
    this._contextMenuService = _contextMenuService;
    this._originalTopPadding = observableValue("originalTopPadding", 0);
    this._originalScrollOffset = observableValue("originalScrollOffset", 0);
    this._originalScrollOffsetAnimated = animatedObservable(this._originalScrollOffset, this._store);
    this._modifiedTopPadding = observableValue("modifiedTopPadding", 0);
    this._modifiedScrollOffset = observableValue("modifiedScrollOffset", 0);
    this._modifiedScrollOffsetAnimated = animatedObservable(this._modifiedScrollOffset, this._store);
    let isChangingViewZones = false;
    const state = observableValue("state", 0);
    const updateImmediately = this._register(new RunOnceScheduler(() => {
      state.set(state.get() + 1, void 0);
    }, 0));
    this._register(this._editors.original.onDidChangeViewZones((_args) => {
      if (!isChangingViewZones && !this._canIgnoreViewZoneUpdateEvent()) {
        updateImmediately.schedule();
      }
    }));
    this._register(this._editors.modified.onDidChangeViewZones((_args) => {
      if (!isChangingViewZones && !this._canIgnoreViewZoneUpdateEvent()) {
        updateImmediately.schedule();
      }
    }));
    this._register(this._editors.original.onDidChangeConfiguration((args) => {
      if (args.hasChanged(
        143
        /* EditorOption.wrappingInfo */
      )) {
        updateImmediately.schedule();
      }
    }));
    this._register(this._editors.modified.onDidChangeConfiguration((args) => {
      if (args.hasChanged(
        143
        /* EditorOption.wrappingInfo */
      )) {
        updateImmediately.schedule();
      }
    }));
    const originalModelTokenizationCompleted = this._diffModel.map((m) => m ? observableFromEvent(
      m.model.original.onDidChangeTokens,
      () => m.model.original.tokenization.backgroundTokenizationState === 2
      /* BackgroundTokenizationState.Completed */
    ) : void 0).map((m, reader) => m === null || m === void 0 ? void 0 : m.read(reader));
    const alignmentViewZoneIdsOrig = /* @__PURE__ */ new Set();
    const alignmentViewZoneIdsMod = /* @__PURE__ */ new Set();
    const alignments = derived("alignments", (reader) => {
      const diffModel = this._diffModel.read(reader);
      const diff = diffModel === null || diffModel === void 0 ? void 0 : diffModel.diff.read(reader);
      if (!diffModel || !diff) {
        return null;
      }
      state.read(reader);
      const renderSideBySide = this._options.renderSideBySide.read(reader);
      const innerHunkAlignment = renderSideBySide;
      return computeRangeAlignment(this._editors.original, this._editors.modified, diff.mappings, alignmentViewZoneIdsOrig, alignmentViewZoneIdsMod, innerHunkAlignment);
    });
    const alignmentsSyncedMovedText = derived("alignments", (reader) => {
      var _a2;
      const syncedMovedText = (_a2 = this._diffModel.read(reader)) === null || _a2 === void 0 ? void 0 : _a2.syncedMovedTexts.read(reader);
      if (!syncedMovedText) {
        return null;
      }
      state.read(reader);
      const mappings = syncedMovedText.changes.map((c) => new DiffMapping(c));
      return computeRangeAlignment(this._editors.original, this._editors.modified, mappings, alignmentViewZoneIdsOrig, alignmentViewZoneIdsMod, true);
    });
    function createFakeLinesDiv2() {
      const r = document.createElement("div");
      r.className = "diagonal-fill";
      return r;
    }
    const alignmentViewZonesDisposables = this._register(new DisposableStore());
    const alignmentViewZones = derived("alignment viewzones", (reader) => {
      var _a2, _b2, _c2, _d2, _e2, _f2, _g2, _h2;
      alignmentViewZonesDisposables.clear();
      const alignmentsVal = alignments.read(reader) || [];
      const origViewZones = [];
      const modViewZones = [];
      const modifiedTopPaddingVal = this._modifiedTopPadding.read(reader);
      if (modifiedTopPaddingVal > 0) {
        modViewZones.push({
          afterLineNumber: 0,
          domNode: document.createElement("div"),
          heightInPx: modifiedTopPaddingVal,
          showInHiddenAreas: true
        });
      }
      const originalTopPaddingVal = this._originalTopPadding.read(reader);
      if (originalTopPaddingVal > 0) {
        origViewZones.push({
          afterLineNumber: 0,
          domNode: document.createElement("div"),
          heightInPx: originalTopPaddingVal,
          showInHiddenAreas: true
        });
      }
      const renderSideBySide = this._options.renderSideBySide.read(reader);
      const deletedCodeLineBreaksComputer = !renderSideBySide ? (_a2 = this._editors.modified._getViewModel()) === null || _a2 === void 0 ? void 0 : _a2.createLineBreaksComputer() : void 0;
      if (deletedCodeLineBreaksComputer) {
        for (const a of alignmentsVal) {
          if (a.diff) {
            for (let i = a.originalRange.startLineNumber; i < a.originalRange.endLineNumberExclusive; i++) {
              deletedCodeLineBreaksComputer === null || deletedCodeLineBreaksComputer === void 0 ? void 0 : deletedCodeLineBreaksComputer.addRequest(this._editors.original.getModel().getLineContent(i), null, null);
            }
          }
        }
      }
      const lineBreakData = (_b2 = deletedCodeLineBreaksComputer === null || deletedCodeLineBreaksComputer === void 0 ? void 0 : deletedCodeLineBreaksComputer.finalize()) !== null && _b2 !== void 0 ? _b2 : [];
      let lineBreakDataIdx = 0;
      const modLineHeight = this._editors.modified.getOption(
        65
        /* EditorOption.lineHeight */
      );
      const syncedMovedText = (_c2 = this._diffModel.read(reader)) === null || _c2 === void 0 ? void 0 : _c2.syncedMovedTexts.read(reader);
      const mightContainNonBasicASCII = (_e2 = (_d2 = this._editors.original.getModel()) === null || _d2 === void 0 ? void 0 : _d2.mightContainNonBasicASCII()) !== null && _e2 !== void 0 ? _e2 : false;
      const mightContainRTL = (_g2 = (_f2 = this._editors.original.getModel()) === null || _f2 === void 0 ? void 0 : _f2.mightContainRTL()) !== null && _g2 !== void 0 ? _g2 : false;
      const renderOptions = RenderOptions.fromEditor(this._editors.modified);
      for (const a of alignmentsVal) {
        if (a.diff && !renderSideBySide) {
          if (!a.originalRange.isEmpty) {
            originalModelTokenizationCompleted.read(reader);
            const deletedCodeDomNode = document.createElement("div");
            deletedCodeDomNode.classList.add("view-lines", "line-delete", "monaco-mouse-cursor-text");
            const source = new LineSource(a.originalRange.mapToLineArray((l) => this._editors.original.getModel().tokenization.getLineTokens(l)), a.originalRange.mapToLineArray((_) => lineBreakData[lineBreakDataIdx++]), mightContainNonBasicASCII, mightContainRTL);
            const decorations2 = [];
            for (const i of a.diff.innerChanges || []) {
              decorations2.push(new InlineDecoration(
                i.originalRange.delta(-(a.diff.originalRange.startLineNumber - 1)),
                diffDeleteDecoration.className,
                0
                /* InlineDecorationType.Regular */
              ));
            }
            const result2 = renderLines(source, renderOptions, decorations2, deletedCodeDomNode);
            const marginDomNode2 = document.createElement("div");
            marginDomNode2.className = "inline-deleted-margin-view-zone";
            applyFontInfo(marginDomNode2, renderOptions.fontInfo);
            if (this._options.renderIndicators.read(reader)) {
              for (let i = 0; i < result2.heightInLines; i++) {
                const marginElement = document.createElement("div");
                marginElement.className = `delete-sign ${ThemeIcon.asClassName(diffRemoveIcon)}`;
                marginElement.setAttribute("style", `position:absolute;top:${i * modLineHeight}px;width:${renderOptions.lineDecorationsWidth}px;height:${modLineHeight}px;right:0;`);
                marginDomNode2.appendChild(marginElement);
              }
            }
            let zoneId = void 0;
            alignmentViewZonesDisposables.add(new InlineDiffDeletedCodeMargin(() => assertIsDefined(zoneId), marginDomNode2, this._editors.modified, a.diff, this._diffEditorWidget, result2.viewLineCounts, this._editors.original.getModel(), this._contextMenuService, this._clipboardService));
            for (let i = 0; i < result2.viewLineCounts.length; i++) {
              const count = result2.viewLineCounts[i];
              if (count > 1) {
                origViewZones.push({
                  afterLineNumber: a.originalRange.startLineNumber + i,
                  domNode: createFakeLinesDiv2(),
                  heightInPx: (count - 1) * modLineHeight,
                  showInHiddenAreas: true
                });
              }
            }
            modViewZones.push({
              afterLineNumber: a.modifiedRange.startLineNumber - 1,
              domNode: deletedCodeDomNode,
              heightInPx: result2.heightInLines * modLineHeight,
              minWidthInPx: result2.minWidthInPx,
              marginDomNode: marginDomNode2,
              setZoneId(id3) {
                zoneId = id3;
              },
              showInHiddenAreas: true
            });
          }
          const marginDomNode = document.createElement("div");
          marginDomNode.className = "gutter-delete";
          origViewZones.push({
            afterLineNumber: a.originalRange.endLineNumberExclusive - 1,
            domNode: createFakeLinesDiv2(),
            heightInPx: a.modifiedHeightInPx,
            marginDomNode,
            showInHiddenAreas: true
          });
        } else {
          const delta = a.modifiedHeightInPx - a.originalHeightInPx;
          if (delta > 0) {
            if (syncedMovedText === null || syncedMovedText === void 0 ? void 0 : syncedMovedText.lineRangeMapping.original.contains(a.originalRange.endLineNumberExclusive - 1)) {
              continue;
            }
            origViewZones.push({
              afterLineNumber: a.originalRange.endLineNumberExclusive - 1,
              domNode: createFakeLinesDiv2(),
              heightInPx: delta,
              showInHiddenAreas: true
            });
          } else {
            let createViewZoneMarginArrow2 = function() {
              const arrow = document.createElement("div");
              arrow.className = "arrow-revert-change " + ThemeIcon.asClassName(Codicon.arrowRight);
              return $$d("div", {}, arrow);
            };
            if (syncedMovedText === null || syncedMovedText === void 0 ? void 0 : syncedMovedText.lineRangeMapping.modified.contains(a.modifiedRange.endLineNumberExclusive - 1)) {
              continue;
            }
            let marginDomNode = void 0;
            if (a.diff && a.diff.modifiedRange.isEmpty && this._options.shouldRenderRevertArrows.read(reader)) {
              marginDomNode = createViewZoneMarginArrow2();
            }
            modViewZones.push({
              afterLineNumber: a.modifiedRange.endLineNumberExclusive - 1,
              domNode: createFakeLinesDiv2(),
              heightInPx: -delta,
              marginDomNode,
              showInHiddenAreas: true
            });
          }
        }
      }
      for (const a of (_h2 = alignmentsSyncedMovedText.read(reader)) !== null && _h2 !== void 0 ? _h2 : []) {
        if (!(syncedMovedText === null || syncedMovedText === void 0 ? void 0 : syncedMovedText.lineRangeMapping.original.intersect(a.originalRange)) && !(syncedMovedText === null || syncedMovedText === void 0 ? void 0 : syncedMovedText.lineRangeMapping.modified.intersect(a.modifiedRange))) {
          continue;
        }
        const delta = a.modifiedHeightInPx - a.originalHeightInPx;
        if (delta > 0) {
          origViewZones.push({
            afterLineNumber: a.originalRange.endLineNumberExclusive - 1,
            domNode: createFakeLinesDiv2(),
            heightInPx: delta,
            showInHiddenAreas: true
          });
        } else {
          modViewZones.push({
            afterLineNumber: a.modifiedRange.endLineNumberExclusive - 1,
            domNode: createFakeLinesDiv2(),
            heightInPx: -delta,
            showInHiddenAreas: true
          });
        }
      }
      return { orig: origViewZones, mod: modViewZones };
    });
    this._register(autorunWithStore2("alignment viewzones", (reader) => {
      const scrollState = StableEditorScrollState.capture(this._editors.modified);
      const alignmentViewZones_ = alignmentViewZones.read(reader);
      isChangingViewZones = true;
      this._editors.original.changeViewZones((aOrig) => {
        for (const id3 of alignmentViewZoneIdsOrig) {
          aOrig.removeZone(id3);
        }
        alignmentViewZoneIdsOrig.clear();
        for (const z of alignmentViewZones_.orig) {
          const id3 = aOrig.addZone(z);
          if (z.setZoneId) {
            z.setZoneId(id3);
          }
          alignmentViewZoneIdsOrig.add(id3);
        }
      });
      this._editors.modified.changeViewZones((aMod) => {
        for (const id3 of alignmentViewZoneIdsMod) {
          aMod.removeZone(id3);
        }
        alignmentViewZoneIdsMod.clear();
        for (const z of alignmentViewZones_.mod) {
          const id3 = aMod.addZone(z);
          if (z.setZoneId) {
            z.setZoneId(id3);
          }
          alignmentViewZoneIdsMod.add(id3);
        }
      });
      isChangingViewZones = false;
      scrollState.restore(this._editors.modified);
    }));
    this._register(toDisposable(() => {
      this._editors.original.changeViewZones((a) => {
        for (const id3 of alignmentViewZoneIdsOrig) {
          a.removeZone(id3);
        }
        alignmentViewZoneIdsOrig.clear();
      });
      this._editors.modified.changeViewZones((a) => {
        for (const id3 of alignmentViewZoneIdsMod) {
          a.removeZone(id3);
        }
        alignmentViewZoneIdsMod.clear();
      });
    }));
    let ignoreChange = false;
    this._register(this._editors.original.onDidScrollChange((e) => {
      if (e.scrollLeftChanged && !ignoreChange) {
        ignoreChange = true;
        this._editors.modified.setScrollLeft(e.scrollLeft);
        ignoreChange = false;
      }
    }));
    this._register(this._editors.modified.onDidScrollChange((e) => {
      if (e.scrollLeftChanged && !ignoreChange) {
        ignoreChange = true;
        this._editors.original.setScrollLeft(e.scrollLeft);
        ignoreChange = false;
      }
    }));
    this._originalScrollTop = observableFromEvent(this._editors.original.onDidScrollChange, () => this._editors.original.getScrollTop());
    this._modifiedScrollTop = observableFromEvent(this._editors.modified.onDidScrollChange, () => this._editors.modified.getScrollTop());
    this._register(autorun("update scroll modified", (reader) => {
      const newScrollTopModified = this._originalScrollTop.read(reader) - (this._originalScrollOffsetAnimated.get() - this._modifiedScrollOffsetAnimated.read(reader)) - (this._originalTopPadding.get() - this._modifiedTopPadding.read(reader));
      if (newScrollTopModified !== this._editors.modified.getScrollTop()) {
        this._editors.modified.setScrollTop(
          newScrollTopModified,
          1
          /* ScrollType.Immediate */
        );
      }
    }));
    this._register(autorun("update scroll original", (reader) => {
      const newScrollTopOriginal = this._modifiedScrollTop.read(reader) - (this._modifiedScrollOffsetAnimated.get() - this._originalScrollOffsetAnimated.read(reader)) - (this._modifiedTopPadding.get() - this._originalTopPadding.read(reader));
      if (newScrollTopOriginal !== this._editors.original.getScrollTop()) {
        this._editors.original.setScrollTop(
          newScrollTopOriginal,
          1
          /* ScrollType.Immediate */
        );
      }
    }));
    this._register(autorun("update", (reader) => {
      var _a2;
      const m = (_a2 = this._diffModel.read(reader)) === null || _a2 === void 0 ? void 0 : _a2.syncedMovedTexts.read(reader);
      let deltaOrigToMod = 0;
      if (m) {
        const trueTopOriginal = this._editors.original.getTopForLineNumber(m.lineRangeMapping.original.startLineNumber, true) - this._originalTopPadding.get();
        const trueTopModified = this._editors.modified.getTopForLineNumber(m.lineRangeMapping.modified.startLineNumber, true) - this._modifiedTopPadding.get();
        deltaOrigToMod = trueTopModified - trueTopOriginal;
      }
      if (deltaOrigToMod > 0) {
        this._modifiedTopPadding.set(0, void 0);
        this._originalTopPadding.set(deltaOrigToMod, void 0);
      } else if (deltaOrigToMod < 0) {
        this._modifiedTopPadding.set(-deltaOrigToMod, void 0);
        this._originalTopPadding.set(0, void 0);
      } else {
        setTimeout(() => {
          this._modifiedTopPadding.set(0, void 0);
          this._originalTopPadding.set(0, void 0);
        }, 400);
      }
      if (this._editors.modified.hasTextFocus()) {
        this._originalScrollOffset.set(this._modifiedScrollOffset.get() - deltaOrigToMod, void 0, true);
      } else {
        this._modifiedScrollOffset.set(this._originalScrollOffset.get() + deltaOrigToMod, void 0, true);
      }
    }));
  }
};
ViewZoneManager = __decorate$5([
  __param$5(5, IClipboardService),
  __param$5(6, IContextMenuService)
], ViewZoneManager);
function computeRangeAlignment(originalEditor, modifiedEditor, diffs, originalEditorAlignmentViewZones, modifiedEditorAlignmentViewZones, innerHunkAlignment) {
  const originalLineHeightOverrides = new ArrayQueue(getAdditionalLineHeights(originalEditor, originalEditorAlignmentViewZones));
  const modifiedLineHeightOverrides = new ArrayQueue(getAdditionalLineHeights(modifiedEditor, modifiedEditorAlignmentViewZones));
  const origLineHeight = originalEditor.getOption(
    65
    /* EditorOption.lineHeight */
  );
  const modLineHeight = modifiedEditor.getOption(
    65
    /* EditorOption.lineHeight */
  );
  const result2 = [];
  let lastOriginalLineNumber = 0;
  let lastModifiedLineNumber = 0;
  function handleAlignmentsOutsideOfDiffs(untilOriginalLineNumberExclusive, untilModifiedLineNumberExclusive) {
    while (true) {
      let origNext = originalLineHeightOverrides.peek();
      let modNext = modifiedLineHeightOverrides.peek();
      if (origNext && origNext.lineNumber >= untilOriginalLineNumberExclusive) {
        origNext = void 0;
      }
      if (modNext && modNext.lineNumber >= untilModifiedLineNumberExclusive) {
        modNext = void 0;
      }
      if (!origNext && !modNext) {
        break;
      }
      const distOrig = origNext ? origNext.lineNumber - lastOriginalLineNumber : Number.MAX_VALUE;
      const distNext = modNext ? modNext.lineNumber - lastModifiedLineNumber : Number.MAX_VALUE;
      if (distOrig < distNext) {
        originalLineHeightOverrides.dequeue();
        modNext = {
          lineNumber: origNext.lineNumber - lastOriginalLineNumber + lastModifiedLineNumber,
          heightInPx: 0
        };
      } else if (distOrig > distNext) {
        modifiedLineHeightOverrides.dequeue();
        origNext = {
          lineNumber: modNext.lineNumber - lastModifiedLineNumber + lastOriginalLineNumber,
          heightInPx: 0
        };
      } else {
        originalLineHeightOverrides.dequeue();
        modifiedLineHeightOverrides.dequeue();
      }
      result2.push({
        originalRange: LineRange2.ofLength(origNext.lineNumber, 1),
        modifiedRange: LineRange2.ofLength(modNext.lineNumber, 1),
        originalHeightInPx: origLineHeight + origNext.heightInPx,
        modifiedHeightInPx: modLineHeight + modNext.heightInPx,
        diff: void 0
      });
    }
  }
  for (const m of diffs) {
    let emitAlignment = function(origLineNumberExclusive, modLineNumberExclusive) {
      var _a2, _b2, _c2, _d2;
      if (origLineNumberExclusive < lastOrigLineNumber || modLineNumberExclusive < lastModLineNumber) {
        return;
      }
      if (first2) {
        first2 = false;
      } else if (origLineNumberExclusive === lastOrigLineNumber || modLineNumberExclusive === lastModLineNumber) {
        return;
      }
      const originalRange = new LineRange2(lastOrigLineNumber, origLineNumberExclusive);
      const modifiedRange = new LineRange2(lastModLineNumber, modLineNumberExclusive);
      if (originalRange.isEmpty && modifiedRange.isEmpty) {
        return;
      }
      const originalAdditionalHeight = (_b2 = (_a2 = originalLineHeightOverrides.takeWhile((v) => v.lineNumber < origLineNumberExclusive)) === null || _a2 === void 0 ? void 0 : _a2.reduce((p2, c2) => p2 + c2.heightInPx, 0)) !== null && _b2 !== void 0 ? _b2 : 0;
      const modifiedAdditionalHeight = (_d2 = (_c2 = modifiedLineHeightOverrides.takeWhile((v) => v.lineNumber < modLineNumberExclusive)) === null || _c2 === void 0 ? void 0 : _c2.reduce((p2, c2) => p2 + c2.heightInPx, 0)) !== null && _d2 !== void 0 ? _d2 : 0;
      result2.push({
        originalRange,
        modifiedRange,
        originalHeightInPx: originalRange.length * origLineHeight + originalAdditionalHeight,
        modifiedHeightInPx: modifiedRange.length * modLineHeight + modifiedAdditionalHeight,
        diff: m.lineRangeMapping
      });
      lastOrigLineNumber = origLineNumberExclusive;
      lastModLineNumber = modLineNumberExclusive;
    };
    const c = m.lineRangeMapping;
    handleAlignmentsOutsideOfDiffs(c.originalRange.startLineNumber, c.modifiedRange.startLineNumber);
    let first2 = true;
    let lastModLineNumber = c.modifiedRange.startLineNumber;
    let lastOrigLineNumber = c.originalRange.startLineNumber;
    if (innerHunkAlignment) {
      for (const i of c.innerChanges || []) {
        if (i.originalRange.startColumn > 1 && i.modifiedRange.startColumn > 1) {
          emitAlignment(i.originalRange.startLineNumber, i.modifiedRange.startLineNumber);
        }
        if (i.originalRange.endColumn < originalEditor.getModel().getLineMaxColumn(i.originalRange.endLineNumber)) {
          emitAlignment(i.originalRange.endLineNumber, i.modifiedRange.endLineNumber);
        }
      }
    }
    emitAlignment(c.originalRange.endLineNumberExclusive, c.modifiedRange.endLineNumberExclusive);
    lastOriginalLineNumber = c.originalRange.endLineNumberExclusive;
    lastModifiedLineNumber = c.modifiedRange.endLineNumberExclusive;
  }
  handleAlignmentsOutsideOfDiffs(Number.MAX_VALUE, Number.MAX_VALUE);
  return result2;
}
function getAdditionalLineHeights(editor2, viewZonesToIgnore) {
  const viewZoneHeights = [];
  const wrappingZoneHeights = [];
  const hasWrapping = editor2.getOption(
    143
    /* EditorOption.wrappingInfo */
  ).wrappingColumn !== -1;
  const coordinatesConverter = editor2._getViewModel().coordinatesConverter;
  const editorLineHeight = editor2.getOption(
    65
    /* EditorOption.lineHeight */
  );
  if (hasWrapping) {
    for (let i = 1; i <= editor2.getModel().getLineCount(); i++) {
      const lineCount = coordinatesConverter.getModelLineViewLineCount(i);
      if (lineCount > 1) {
        wrappingZoneHeights.push({ lineNumber: i, heightInPx: editorLineHeight * (lineCount - 1) });
      }
    }
  }
  for (const w of editor2.getWhitespaces()) {
    if (viewZonesToIgnore.has(w.id)) {
      continue;
    }
    const modelLineNumber = w.afterLineNumber === 0 ? 0 : coordinatesConverter.convertViewPositionToModelPosition(new Position$2(w.afterLineNumber, 1)).lineNumber;
    viewZoneHeights.push({ lineNumber: modelLineNumber, heightInPx: w.height });
  }
  const result2 = joinCombine(viewZoneHeights, wrappingZoneHeights, (v) => v.lineNumber, (v1, v2) => ({ lineNumber: v1.lineNumber, heightInPx: v1.heightInPx + v2.heightInPx }));
  return result2;
}
var __decorate$4 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$4 = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let OverviewRulerPart = class OverviewRulerPart2 extends Disposable {
  constructor(_editors, _rootElement, _diffModel, _rootWidth, _rootHeight, _modifiedEditorLayoutInfo, _options, _themeService) {
    super();
    this._editors = _editors;
    this._rootElement = _rootElement;
    this._diffModel = _diffModel;
    this._rootWidth = _rootWidth;
    this._rootHeight = _rootHeight;
    this._modifiedEditorLayoutInfo = _modifiedEditorLayoutInfo;
    this._options = _options;
    this._themeService = _themeService;
    const currentColorTheme = observableFromEvent(this._themeService.onDidColorThemeChange, () => this._themeService.getColorTheme());
    const currentColors = derived("colors", (reader) => {
      const theme = currentColorTheme.read(reader);
      const insertColor = theme.getColor(diffOverviewRulerInserted) || (theme.getColor(diffInserted) || defaultInsertColor).transparent(2);
      const removeColor = theme.getColor(diffOverviewRulerRemoved) || (theme.getColor(diffRemoved) || defaultRemoveColor).transparent(2);
      return { insertColor, removeColor };
    });
    const scrollTopObservable = observableFromEvent(this._editors.modified.onDidScrollChange, () => this._editors.modified.getScrollTop());
    const scrollHeightObservable = observableFromEvent(this._editors.modified.onDidScrollChange, () => this._editors.modified.getScrollHeight());
    this._register(autorunWithStore2("create diff editor overview ruler if enabled", (reader, store) => {
      if (!this._options.renderOverviewRuler.read(reader)) {
        return;
      }
      const viewportDomElement = createFastDomNode(document.createElement("div"));
      viewportDomElement.setClassName("diffViewport");
      viewportDomElement.setPosition("absolute");
      const diffOverviewRoot = h("div.diffOverview", {
        style: { position: "absolute", top: "0px", width: OverviewRulerPart2.ENTIRE_DIFF_OVERVIEW_WIDTH + "px" }
      }).root;
      store.add(appendRemoveOnDispose(diffOverviewRoot, viewportDomElement.domNode));
      store.add(addStandardDisposableListener(diffOverviewRoot, EventType$1.POINTER_DOWN, (e) => {
        this._editors.modified.delegateVerticalScrollbarPointerDown(e);
      }));
      store.add(addDisposableListener(diffOverviewRoot, EventType$1.MOUSE_WHEEL, (e) => {
        this._editors.modified.delegateScrollFromMouseWheelEvent(e);
      }, { passive: false }));
      store.add(appendRemoveOnDispose(this._rootElement, diffOverviewRoot));
      store.add(autorunWithStore2("recreate overview rules when model changes", (reader2, store2) => {
        const m = this._diffModel.read(reader2);
        const originalOverviewRuler = this._editors.original.createOverviewRuler("original diffOverviewRuler");
        if (originalOverviewRuler) {
          store2.add(originalOverviewRuler);
          store2.add(appendRemoveOnDispose(diffOverviewRoot, originalOverviewRuler.getDomNode()));
        }
        const modifiedOverviewRuler = this._editors.modified.createOverviewRuler("modified diffOverviewRuler");
        if (modifiedOverviewRuler) {
          store2.add(modifiedOverviewRuler);
          store2.add(appendRemoveOnDispose(diffOverviewRoot, modifiedOverviewRuler.getDomNode()));
        }
        if (!originalOverviewRuler || !modifiedOverviewRuler) {
          return;
        }
        const origViewZonesChanged = observableSignalFromEvent("viewZoneChanged", this._editors.original.onDidChangeViewZones);
        const modViewZonesChanged = observableSignalFromEvent("viewZoneChanged", this._editors.modified.onDidChangeViewZones);
        const origHiddenRangesChanged = observableSignalFromEvent("hiddenRangesChanged", this._editors.original.onDidChangeHiddenAreas);
        const modHiddenRangesChanged = observableSignalFromEvent("hiddenRangesChanged", this._editors.modified.onDidChangeHiddenAreas);
        store2.add(autorun("set overview ruler zones", (reader3) => {
          var _a2;
          origViewZonesChanged.read(reader3);
          modViewZonesChanged.read(reader3);
          origHiddenRangesChanged.read(reader3);
          modHiddenRangesChanged.read(reader3);
          const colors = currentColors.read(reader3);
          const diff = (_a2 = m === null || m === void 0 ? void 0 : m.diff.read(reader3)) === null || _a2 === void 0 ? void 0 : _a2.mappings;
          function createZones(ranges, color, editor2) {
            const vm = editor2._getViewModel();
            if (!vm) {
              return [];
            }
            return ranges.filter((d) => d.length > 0).map((r) => {
              const start = vm.coordinatesConverter.convertModelPositionToViewPosition(new Position$2(r.startLineNumber, 1));
              const end = vm.coordinatesConverter.convertModelPositionToViewPosition(new Position$2(r.endLineNumberExclusive, 1));
              return new OverviewRulerZone(start.lineNumber, end.lineNumber, 0, color.toString());
            });
          }
          originalOverviewRuler === null || originalOverviewRuler === void 0 ? void 0 : originalOverviewRuler.setZones(createZones((diff || []).map((d) => d.lineRangeMapping.originalRange), colors.removeColor, this._editors.original));
          modifiedOverviewRuler === null || modifiedOverviewRuler === void 0 ? void 0 : modifiedOverviewRuler.setZones(createZones((diff || []).map((d) => d.lineRangeMapping.modifiedRange), colors.insertColor, this._editors.modified));
        }));
        store2.add(autorun("layout overview ruler", (reader3) => {
          const height = this._rootHeight.read(reader3);
          const width = this._rootWidth.read(reader3);
          const layoutInfo = this._modifiedEditorLayoutInfo.read(reader3);
          if (layoutInfo) {
            const freeSpace = OverviewRulerPart2.ENTIRE_DIFF_OVERVIEW_WIDTH - 2 * OverviewRulerPart2.ONE_OVERVIEW_WIDTH;
            originalOverviewRuler.setLayout({
              top: 0,
              height,
              right: freeSpace + OverviewRulerPart2.ONE_OVERVIEW_WIDTH,
              width: OverviewRulerPart2.ONE_OVERVIEW_WIDTH
            });
            modifiedOverviewRuler.setLayout({
              top: 0,
              height,
              right: 0,
              width: OverviewRulerPart2.ONE_OVERVIEW_WIDTH
            });
            const scrollTop = scrollTopObservable.read(reader3);
            const scrollHeight = scrollHeightObservable.read(reader3);
            const scrollBarOptions = this._editors.modified.getOption(
              101
              /* EditorOption.scrollbar */
            );
            const state = new ScrollbarState(scrollBarOptions.verticalHasArrows ? scrollBarOptions.arrowSize : 0, scrollBarOptions.verticalScrollbarSize, 0, layoutInfo.height, scrollHeight, scrollTop);
            viewportDomElement.setTop(state.getSliderPosition());
            viewportDomElement.setHeight(state.getSliderSize());
          } else {
            viewportDomElement.setTop(0);
            viewportDomElement.setHeight(0);
          }
          diffOverviewRoot.style.height = height + "px";
          diffOverviewRoot.style.left = width - OverviewRulerPart2.ENTIRE_DIFF_OVERVIEW_WIDTH + "px";
          viewportDomElement.setWidth(OverviewRulerPart2.ENTIRE_DIFF_OVERVIEW_WIDTH);
        }));
      }));
    }));
  }
};
OverviewRulerPart.ONE_OVERVIEW_WIDTH = 15;
OverviewRulerPart.ENTIRE_DIFF_OVERVIEW_WIDTH = OverviewRulerPart.ONE_OVERVIEW_WIDTH * 2;
OverviewRulerPart = __decorate$4([
  __param$4(7, IThemeService)
], OverviewRulerPart);
class UnchangedRangesFeature extends Disposable {
  get isUpdatingViewZones() {
    return this._isUpdatingViewZones;
  }
  constructor(_editors, _diffModel, _options) {
    super();
    this._editors = _editors;
    this._diffModel = _diffModel;
    this._options = _options;
    this._isUpdatingViewZones = false;
    this._register(this._editors.original.onDidChangeCursorPosition((e) => {
      if (e.reason === 3) {
        const m = this._diffModel.get();
        transaction((tx) => {
          for (const s of this._editors.original.getSelections() || []) {
            m === null || m === void 0 ? void 0 : m.ensureOriginalLineIsVisible(s.getStartPosition().lineNumber, tx);
            m === null || m === void 0 ? void 0 : m.ensureOriginalLineIsVisible(s.getEndPosition().lineNumber, tx);
          }
        });
      }
    }));
    this._register(this._editors.modified.onDidChangeCursorPosition((e) => {
      if (e.reason === 3) {
        const m = this._diffModel.get();
        transaction((tx) => {
          for (const s of this._editors.modified.getSelections() || []) {
            m === null || m === void 0 ? void 0 : m.ensureModifiedLineIsVisible(s.getStartPosition().lineNumber, tx);
            m === null || m === void 0 ? void 0 : m.ensureModifiedLineIsVisible(s.getEndPosition().lineNumber, tx);
          }
        });
      }
    }));
    const unchangedRegions = this._diffModel.map((m, reader) => {
      var _a2, _b2;
      return ((_a2 = m === null || m === void 0 ? void 0 : m.diff.read(reader)) === null || _a2 === void 0 ? void 0 : _a2.mappings.length) === 0 ? [] : (_b2 = m === null || m === void 0 ? void 0 : m.unchangedRegions.read(reader)) !== null && _b2 !== void 0 ? _b2 : [];
    });
    const viewZones = derivedWithStore("view zones", (reader, store) => {
      const origViewZones = [];
      const modViewZones = [];
      const sideBySide = this._options.renderSideBySide.read(reader);
      const curUnchangedRegions = unchangedRegions.read(reader);
      for (const r of curUnchangedRegions) {
        if (r.shouldHideControls(reader)) {
          continue;
        }
        {
          const d = derived("hiddenOriginalRangeStart", (reader2) => r.getHiddenOriginalRange(reader2).startLineNumber - 1);
          const origVz = new PlaceholderViewZone(d, 24);
          origViewZones.push(origVz);
          store.add(new CollapsedCodeOverlayWidget(this._editors.original, origVz, r, !sideBySide));
        }
        {
          const d = derived("hiddenModifiedRangeStart", (reader2) => r.getHiddenModifiedRange(reader2).startLineNumber - 1);
          const modViewZone = new PlaceholderViewZone(d, 24);
          modViewZones.push(modViewZone);
          store.add(new CollapsedCodeOverlayWidget(this._editors.modified, modViewZone, r, false));
        }
      }
      return { origViewZones, modViewZones };
    });
    const unchangedLinesDecoration = {
      description: "unchanged lines",
      className: "diff-unchanged-lines",
      isWholeLine: true
    };
    const unchangedLinesDecorationShow = {
      description: "Fold Unchanged",
      glyphMarginHoverMessage: new MarkdownString(void 0, { isTrusted: true, supportThemeIcons: true }).appendMarkdown(localize("foldUnchanged", "Fold Unchanged Region")),
      glyphMarginClassName: "fold-unchanged " + ThemeIcon.asClassName(Codicon.fold),
      zIndex: 10001
    };
    this._register(applyObservableDecorations(this._editors.original, derived("decorations", (reader) => {
      const curUnchangedRegions = unchangedRegions.read(reader);
      const result2 = curUnchangedRegions.map((r) => ({
        range: r.originalRange.toInclusiveRange(),
        options: unchangedLinesDecoration
      }));
      for (const r of curUnchangedRegions) {
        if (r.shouldHideControls(reader)) {
          result2.push({
            range: Range$2.fromPositions(new Position$2(r.originalLineNumber, 1)),
            options: unchangedLinesDecorationShow
          });
        }
      }
      return result2;
    })));
    this._register(applyObservableDecorations(this._editors.modified, derived("decorations", (reader) => {
      const curUnchangedRegions = unchangedRegions.read(reader);
      const result2 = curUnchangedRegions.map((r) => ({
        range: r.modifiedRange.toInclusiveRange(),
        options: unchangedLinesDecoration
      }));
      for (const r of curUnchangedRegions) {
        if (r.shouldHideControls(reader)) {
          result2.push({
            range: LineRange2.ofLength(r.modifiedLineNumber, 1).toInclusiveRange(),
            options: unchangedLinesDecorationShow
          });
        }
      }
      return result2;
    })));
    this._register(applyViewZones(this._editors.original, viewZones.map((v) => v.origViewZones), (v) => this._isUpdatingViewZones = v));
    this._register(applyViewZones(this._editors.modified, viewZones.map((v) => v.modViewZones), (v) => this._isUpdatingViewZones = v));
    this._register(autorunWithStore2("update folded unchanged regions", (reader, store) => {
      const curUnchangedRegions = unchangedRegions.read(reader);
      this._editors.original.setHiddenAreas(curUnchangedRegions.map((r) => r.getHiddenOriginalRange(reader).toInclusiveRange()).filter(isDefined));
      this._editors.modified.setHiddenAreas(curUnchangedRegions.map((r) => r.getHiddenModifiedRange(reader).toInclusiveRange()).filter(isDefined));
    }));
    this._register(this._editors.modified.onMouseUp((event) => {
      var _a2;
      if (!event.event.rightButton && event.target.position && ((_a2 = event.target.element) === null || _a2 === void 0 ? void 0 : _a2.className.includes("fold-unchanged"))) {
        const lineNumber = event.target.position.lineNumber;
        const model = this._diffModel.get();
        if (!model) {
          return;
        }
        const region = model.unchangedRegions.get().find((r) => r.modifiedRange.includes(lineNumber));
        if (!region) {
          return;
        }
        region.setState(0, 0, void 0);
        event.event.stopPropagation();
        event.event.preventDefault();
      }
    }));
    this._register(this._editors.original.onMouseUp((event) => {
      var _a2;
      if (!event.event.rightButton && event.target.position && ((_a2 = event.target.element) === null || _a2 === void 0 ? void 0 : _a2.className.includes("fold-unchanged"))) {
        const lineNumber = event.target.position.lineNumber;
        const model = this._diffModel.get();
        if (!model) {
          return;
        }
        const region = model.unchangedRegions.get().find((r) => r.originalRange.includes(lineNumber));
        if (!region) {
          return;
        }
        region.setState(0, 0, void 0);
        event.event.stopPropagation();
        event.event.preventDefault();
      }
    }));
  }
}
class CollapsedCodeOverlayWidget extends ViewZoneOverlayWidget {
  constructor(_editor, _viewZone, _unchangedRegion, hide2) {
    const root3 = h("div.diff-hidden-lines-widget");
    super(_editor, _viewZone, root3.root);
    this._editor = _editor;
    this._unchangedRegion = _unchangedRegion;
    this.hide = hide2;
    this._nodes = h("div.diff-hidden-lines", [
      h("div.top@top", { title: "Click or drag to show more above" }),
      h("div.center@content", { style: { display: "flex" } }, [
        h("div@first", { style: { display: "flex", justifyContent: "center", alignItems: "center" } }, [$$d("a", { title: "Show all", role: "button", onclick: () => {
          this._unchangedRegion.showAll(void 0);
        } }, ...renderLabelWithIcons("$(unfold)"))]),
        h("div@others", { style: { display: "flex", justifyContent: "center", alignItems: "center" } })
      ]),
      h("div.bottom@bottom", { title: "Click or drag to show more below", role: "button" })
    ]);
    root3.root.appendChild(this._nodes.root);
    const layoutInfo = observableFromEvent(this._editor.onDidLayoutChange, () => this._editor.getLayoutInfo());
    if (!this.hide) {
      this._register(applyStyle(this._nodes.first, { width: layoutInfo.map((l) => l.contentLeft) }));
    } else {
      reset(this._nodes.first);
    }
    const editor2 = this._editor;
    this._register(addDisposableListener(this._nodes.top, "mousedown", (e) => {
      if (e.button !== 0) {
        return;
      }
      this._nodes.top.classList.toggle("dragging", true);
      this._nodes.root.classList.toggle("dragging", true);
      e.preventDefault();
      const startTop = e.clientY;
      let didMove = false;
      const cur = this._unchangedRegion.visibleLineCountTop.get();
      this._unchangedRegion.isDragged.set(true, void 0);
      const mouseMoveListener = addDisposableListener(window, "mousemove", (e2) => {
        const currentTop = e2.clientY;
        const delta = currentTop - startTop;
        didMove = didMove || Math.abs(delta) > 2;
        const lineDelta = Math.round(delta / editor2.getOption(
          65
          /* EditorOption.lineHeight */
        ));
        const newVal = Math.max(0, Math.min(cur + lineDelta, this._unchangedRegion.getMaxVisibleLineCountTop()));
        this._unchangedRegion.visibleLineCountTop.set(newVal, void 0);
      });
      const mouseUpListener = addDisposableListener(window, "mouseup", (e2) => {
        if (!didMove) {
          this._unchangedRegion.showMoreAbove(20, void 0);
        }
        this._nodes.top.classList.toggle("dragging", false);
        this._nodes.root.classList.toggle("dragging", false);
        this._unchangedRegion.isDragged.set(false, void 0);
        mouseMoveListener.dispose();
        mouseUpListener.dispose();
      });
    }));
    this._register(addDisposableListener(this._nodes.bottom, "mousedown", (e) => {
      if (e.button !== 0) {
        return;
      }
      this._nodes.bottom.classList.toggle("dragging", true);
      this._nodes.root.classList.toggle("dragging", true);
      e.preventDefault();
      const startTop = e.clientY;
      let didMove = false;
      const cur = this._unchangedRegion.visibleLineCountBottom.get();
      this._unchangedRegion.isDragged.set(true, void 0);
      const mouseMoveListener = addDisposableListener(window, "mousemove", (e2) => {
        const currentTop = e2.clientY;
        const delta = currentTop - startTop;
        didMove = didMove || Math.abs(delta) > 2;
        const lineDelta = Math.round(delta / editor2.getOption(
          65
          /* EditorOption.lineHeight */
        ));
        const newVal = Math.max(0, Math.min(cur - lineDelta, this._unchangedRegion.getMaxVisibleLineCountBottom()));
        const top = editor2.getTopForLineNumber(this._unchangedRegion.originalRange.endLineNumberExclusive);
        this._unchangedRegion.visibleLineCountBottom.set(newVal, void 0);
        const top2 = editor2.getTopForLineNumber(this._unchangedRegion.originalRange.endLineNumberExclusive);
        editor2.setScrollTop(editor2.getScrollTop() + (top2 - top));
      });
      const mouseUpListener = addDisposableListener(window, "mouseup", (e2) => {
        this._unchangedRegion.isDragged.set(false, void 0);
        if (!didMove) {
          const top = editor2.getTopForLineNumber(this._unchangedRegion.originalRange.endLineNumberExclusive);
          this._unchangedRegion.showMoreBelow(20, void 0);
          const top2 = editor2.getTopForLineNumber(this._unchangedRegion.originalRange.endLineNumberExclusive);
          editor2.setScrollTop(editor2.getScrollTop() + (top2 - top));
        }
        this._nodes.bottom.classList.toggle("dragging", false);
        this._nodes.root.classList.toggle("dragging", false);
        mouseMoveListener.dispose();
        mouseUpListener.dispose();
      });
    }));
    this._register(autorun("update labels", (reader) => {
      const children = [];
      if (!this.hide && true) {
        const lineCount = _unchangedRegion.getHiddenModifiedRange(reader).length;
        const linesHiddenText = `${lineCount} Hidden Lines`;
        children.push($$d("span", { title: linesHiddenText }, linesHiddenText));
      }
      reset(this._nodes.others, ...children);
    }));
  }
}
class DelegatingEditor extends Disposable {
  constructor() {
    super(...arguments);
    this._id = ++DelegatingEditor.idCounter;
    this._onDidDispose = this._register(new Emitter$1());
    this.onDidDispose = this._onDidDispose.event;
  }
  getId() {
    return this.getEditorType() + ":v2:" + this._id;
  }
  // #region editorBrowser.IDiffEditor: Delegating to modified Editor
  getVisibleColumnFromPosition(position) {
    return this._targetEditor.getVisibleColumnFromPosition(position);
  }
  getPosition() {
    return this._targetEditor.getPosition();
  }
  setPosition(position, source = "api") {
    this._targetEditor.setPosition(position, source);
  }
  revealLine(lineNumber, scrollType = 0) {
    this._targetEditor.revealLine(lineNumber, scrollType);
  }
  revealLineInCenter(lineNumber, scrollType = 0) {
    this._targetEditor.revealLineInCenter(lineNumber, scrollType);
  }
  revealLineInCenterIfOutsideViewport(lineNumber, scrollType = 0) {
    this._targetEditor.revealLineInCenterIfOutsideViewport(lineNumber, scrollType);
  }
  revealLineNearTop(lineNumber, scrollType = 0) {
    this._targetEditor.revealLineNearTop(lineNumber, scrollType);
  }
  revealPosition(position, scrollType = 0) {
    this._targetEditor.revealPosition(position, scrollType);
  }
  revealPositionInCenter(position, scrollType = 0) {
    this._targetEditor.revealPositionInCenter(position, scrollType);
  }
  revealPositionInCenterIfOutsideViewport(position, scrollType = 0) {
    this._targetEditor.revealPositionInCenterIfOutsideViewport(position, scrollType);
  }
  revealPositionNearTop(position, scrollType = 0) {
    this._targetEditor.revealPositionNearTop(position, scrollType);
  }
  getSelection() {
    return this._targetEditor.getSelection();
  }
  getSelections() {
    return this._targetEditor.getSelections();
  }
  setSelection(something, source = "api") {
    this._targetEditor.setSelection(something, source);
  }
  setSelections(ranges, source = "api") {
    this._targetEditor.setSelections(ranges, source);
  }
  revealLines(startLineNumber, endLineNumber, scrollType = 0) {
    this._targetEditor.revealLines(startLineNumber, endLineNumber, scrollType);
  }
  revealLinesInCenter(startLineNumber, endLineNumber, scrollType = 0) {
    this._targetEditor.revealLinesInCenter(startLineNumber, endLineNumber, scrollType);
  }
  revealLinesInCenterIfOutsideViewport(startLineNumber, endLineNumber, scrollType = 0) {
    this._targetEditor.revealLinesInCenterIfOutsideViewport(startLineNumber, endLineNumber, scrollType);
  }
  revealLinesNearTop(startLineNumber, endLineNumber, scrollType = 0) {
    this._targetEditor.revealLinesNearTop(startLineNumber, endLineNumber, scrollType);
  }
  revealRange(range2, scrollType = 0, revealVerticalInCenter = false, revealHorizontal = true) {
    this._targetEditor.revealRange(range2, scrollType, revealVerticalInCenter, revealHorizontal);
  }
  revealRangeInCenter(range2, scrollType = 0) {
    this._targetEditor.revealRangeInCenter(range2, scrollType);
  }
  revealRangeInCenterIfOutsideViewport(range2, scrollType = 0) {
    this._targetEditor.revealRangeInCenterIfOutsideViewport(range2, scrollType);
  }
  revealRangeNearTop(range2, scrollType = 0) {
    this._targetEditor.revealRangeNearTop(range2, scrollType);
  }
  revealRangeNearTopIfOutsideViewport(range2, scrollType = 0) {
    this._targetEditor.revealRangeNearTopIfOutsideViewport(range2, scrollType);
  }
  revealRangeAtTop(range2, scrollType = 0) {
    this._targetEditor.revealRangeAtTop(range2, scrollType);
  }
  getSupportedActions() {
    return this._targetEditor.getSupportedActions();
  }
  focus() {
    this._targetEditor.focus();
  }
  trigger(source, handlerId, payload) {
    this._targetEditor.trigger(source, handlerId, payload);
  }
  createDecorationsCollection(decorations2) {
    return this._targetEditor.createDecorationsCollection(decorations2);
  }
  changeDecorations(callback) {
    return this._targetEditor.changeDecorations(callback);
  }
}
DelegatingEditor.idCounter = 0;
var __decorate$3 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$3 = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let DiffEditorEditors = class DiffEditorEditors2 extends Disposable {
  constructor(originalEditorElement, modifiedEditorElement, _options, codeEditorWidgetOptions, _createInnerEditor, _instantiationService, _keybindingService) {
    super();
    this.originalEditorElement = originalEditorElement;
    this.modifiedEditorElement = modifiedEditorElement;
    this._options = _options;
    this._createInnerEditor = _createInnerEditor;
    this._instantiationService = _instantiationService;
    this._keybindingService = _keybindingService;
    this._onDidContentSizeChange = this._register(new Emitter$1());
    this.original = this._createLeftHandSideEditor(_options.editorOptions.get(), codeEditorWidgetOptions.originalEditor || {});
    this.modified = this._createRightHandSideEditor(_options.editorOptions.get(), codeEditorWidgetOptions.modifiedEditor || {});
    this._register(autorunHandleChanges("update editor options", {
      createEmptyChangeSummary: () => ({}),
      handleChange: (ctx, changeSummary) => {
        if (ctx.didChange(_options.editorOptions)) {
          Object.assign(changeSummary, ctx.change.changedOptions);
        }
        return true;
      }
    }, (reader, changeSummary) => {
      _options.editorOptions.read(reader);
      this.modified.updateOptions(this._adjustOptionsForRightHandSide(reader, changeSummary));
      this.original.updateOptions(this._adjustOptionsForLeftHandSide(reader, changeSummary));
    }));
  }
  _createLeftHandSideEditor(options, codeEditorWidgetOptions) {
    const leftHandSideOptions = this._adjustOptionsForLeftHandSide(void 0, options);
    const editor2 = this._constructInnerEditor(this._instantiationService, this.originalEditorElement, leftHandSideOptions, codeEditorWidgetOptions);
    editor2.setContextValue("isInDiffLeftEditor", true);
    return editor2;
  }
  _createRightHandSideEditor(options, codeEditorWidgetOptions) {
    const rightHandSideOptions = this._adjustOptionsForRightHandSide(void 0, options);
    const editor2 = this._constructInnerEditor(this._instantiationService, this.modifiedEditorElement, rightHandSideOptions, codeEditorWidgetOptions);
    editor2.setContextValue("isInDiffRightEditor", true);
    return editor2;
  }
  _constructInnerEditor(instantiationService, container2, options, editorWidgetOptions) {
    const editor2 = this._createInnerEditor(instantiationService, container2, options, editorWidgetOptions);
    this._register(editor2.onDidContentSizeChange((e) => {
      const width = this.original.getContentWidth() + this.modified.getContentWidth() + OverviewRulerPart.ENTIRE_DIFF_OVERVIEW_WIDTH;
      const height = Math.max(this.modified.getContentHeight(), this.original.getContentHeight());
      this._onDidContentSizeChange.fire({
        contentHeight: height,
        contentWidth: width,
        contentHeightChanged: e.contentHeightChanged,
        contentWidthChanged: e.contentWidthChanged
      });
    }));
    return editor2;
  }
  _adjustOptionsForLeftHandSide(_reader, changedOptions) {
    const result2 = this._adjustOptionsForSubEditor(changedOptions);
    if (!this._options.renderSideBySide.get()) {
      result2.wordWrapOverride1 = "off";
      result2.wordWrapOverride2 = "off";
      result2.stickyScroll = { enabled: false };
    } else {
      result2.wordWrapOverride1 = this._options.diffWordWrap.get();
    }
    if (changedOptions.originalAriaLabel) {
      result2.ariaLabel = changedOptions.originalAriaLabel;
    }
    result2.ariaLabel = this._updateAriaLabel(result2.ariaLabel);
    result2.readOnly = !this._options.originalEditable.get();
    result2.dropIntoEditor = { enabled: !result2.readOnly };
    result2.extraEditorClassName = "original-in-monaco-diff-editor";
    return result2;
  }
  _adjustOptionsForRightHandSide(reader, changedOptions) {
    const result2 = this._adjustOptionsForSubEditor(changedOptions);
    if (changedOptions.modifiedAriaLabel) {
      result2.ariaLabel = changedOptions.modifiedAriaLabel;
    }
    result2.ariaLabel = this._updateAriaLabel(result2.ariaLabel);
    result2.wordWrapOverride1 = this._options.diffWordWrap.get();
    result2.revealHorizontalRightPadding = EditorOptions.revealHorizontalRightPadding.defaultValue + OverviewRulerPart.ENTIRE_DIFF_OVERVIEW_WIDTH;
    result2.scrollbar.verticalHasArrows = false;
    result2.extraEditorClassName = "modified-in-monaco-diff-editor";
    return result2;
  }
  _adjustOptionsForSubEditor(options) {
    const clonedOptions = Object.assign(Object.assign({}, options), { dimension: {
      height: 0,
      width: 0
    } });
    clonedOptions.inDiffEditor = true;
    clonedOptions.automaticLayout = false;
    clonedOptions.scrollbar = Object.assign({}, clonedOptions.scrollbar || {});
    clonedOptions.scrollbar.vertical = "visible";
    clonedOptions.folding = false;
    clonedOptions.codeLens = this._options.diffCodeLens.get();
    clonedOptions.fixedOverflowWidgets = true;
    clonedOptions.minimap = Object.assign({}, clonedOptions.minimap || {});
    clonedOptions.minimap.enabled = false;
    if (this._options.collapseUnchangedRegions.get()) {
      clonedOptions.stickyScroll = { enabled: false };
    } else {
      clonedOptions.stickyScroll = this._options.editorOptions.get().stickyScroll;
    }
    return clonedOptions;
  }
  _updateAriaLabel(ariaLabel) {
    var _a2;
    if (!ariaLabel) {
      ariaLabel = "";
    }
    const ariaNavigationTip2 = localize("diff-aria-navigation-tip", " use {0} to open the accessibility help.", (_a2 = this._keybindingService.lookupKeybinding("editor.action.accessibilityHelp")) === null || _a2 === void 0 ? void 0 : _a2.getAriaLabel());
    if (this._options.accessibilityVerbose.get()) {
      return ariaLabel + ariaNavigationTip2;
    } else if (ariaLabel) {
      return ariaLabel.replaceAll(ariaNavigationTip2, "");
    }
    return "";
  }
};
DiffEditorEditors = __decorate$3([
  __param$3(5, IInstantiationService),
  __param$3(6, IKeybindingService)
], DiffEditorEditors);
class DiffEditorOptions {
  get editorOptions() {
    return this._options;
  }
  constructor(options) {
    this.renderOverviewRuler = derived("renderOverviewRuler", (reader) => this._options.read(reader).renderOverviewRuler);
    this.renderSideBySide = derived("renderSideBySide", (reader) => this._options.read(reader).renderSideBySide);
    this.readOnly = derived("readOnly", (reader) => this._options.read(reader).readOnly);
    this.shouldRenderRevertArrows = derived("shouldRenderRevertArrows", (reader) => {
      if (!this._options.read(reader).renderMarginRevertIcon) {
        return false;
      }
      if (!this.renderSideBySide.read(reader)) {
        return false;
      }
      if (this.readOnly.read(reader)) {
        return false;
      }
      return true;
    });
    this.renderIndicators = derived("renderIndicators", (reader) => this._options.read(reader).renderIndicators);
    this.enableSplitViewResizing = derived("enableSplitViewResizing", (reader) => this._options.read(reader).enableSplitViewResizing);
    this.collapseUnchangedRegions = derived("hideUnchangedRegions", (reader) => this._options.read(reader).experimental.collapseUnchangedRegions);
    this.splitViewDefaultRatio = derived("splitViewDefaultRatio", (reader) => this._options.read(reader).splitViewDefaultRatio);
    this.ignoreTrimWhitespace = derived("ignoreTrimWhitespace", (reader) => this._options.read(reader).ignoreTrimWhitespace);
    this.maxComputationTimeMs = derived("maxComputationTime", (reader) => this._options.read(reader).maxComputationTime);
    this.showMoves = derived("showMoves", (reader) => {
      const o = this._options.read(reader);
      return o.experimental.showMoves && o.renderSideBySide;
    });
    this.isInEmbeddedEditor = derived("isInEmbeddedEditor", (reader) => this._options.read(reader).isInEmbeddedEditor);
    this.diffWordWrap = derived("diffWordWrap", (reader) => this._options.read(reader).diffWordWrap);
    this.originalEditable = derived("originalEditable", (reader) => this._options.read(reader).originalEditable);
    this.diffCodeLens = derived("diffCodeLens", (reader) => this._options.read(reader).diffCodeLens);
    this.accessibilityVerbose = derived("accessibilityVerbose", (reader) => this._options.read(reader).accessibilityVerbose);
    this.diffAlgorithm = derived("diffAlgorithm", (reader) => this._options.read(reader).diffAlgorithm);
    this.showEmptyDecorations = derived("showEmptyDecorations", (reader) => this._options.read(reader).experimental.showEmptyDecorations);
    this.onlyShowAccessibleDiffViewer = derived("onlyShowAccessibleDiffViewer", (reader) => this._options.read(reader).onlyShowAccessibleDiffViewer);
    const optionsCopy = Object.assign(Object.assign({}, options), validateDiffEditorOptions(options, diffEditorDefaultOptions));
    this._options = observableValue("options", optionsCopy);
  }
  updateOptions(changedOptions) {
    const newDiffEditorOptions = validateDiffEditorOptions(changedOptions, this._options.get());
    const newOptions = Object.assign(Object.assign(Object.assign({}, this._options.get()), changedOptions), newDiffEditorOptions);
    this._options.set(newOptions, void 0, { changedOptions });
  }
}
const diffEditorDefaultOptions = {
  enableSplitViewResizing: true,
  splitViewDefaultRatio: 0.5,
  renderSideBySide: true,
  renderMarginRevertIcon: true,
  maxComputationTime: 5e3,
  maxFileSize: 50,
  ignoreTrimWhitespace: true,
  renderIndicators: true,
  originalEditable: false,
  diffCodeLens: false,
  renderOverviewRuler: true,
  diffWordWrap: "inherit",
  diffAlgorithm: "advanced",
  accessibilityVerbose: false,
  experimental: {
    collapseUnchangedRegions: false,
    showMoves: false,
    showEmptyDecorations: true
  },
  isInEmbeddedEditor: false,
  onlyShowAccessibleDiffViewer: false
};
function validateDiffEditorOptions(options, defaults) {
  var _a2, _b2, _c2;
  return {
    enableSplitViewResizing: boolean(options.enableSplitViewResizing, defaults.enableSplitViewResizing),
    splitViewDefaultRatio: clampedFloat(options.splitViewDefaultRatio, 0.5, 0.1, 0.9),
    renderSideBySide: boolean(options.renderSideBySide, defaults.renderSideBySide),
    renderMarginRevertIcon: boolean(options.renderMarginRevertIcon, defaults.renderMarginRevertIcon),
    maxComputationTime: clampedInt(
      options.maxComputationTime,
      defaults.maxComputationTime,
      0,
      1073741824
      /* Constants.MAX_SAFE_SMALL_INTEGER */
    ),
    maxFileSize: clampedInt(
      options.maxFileSize,
      defaults.maxFileSize,
      0,
      1073741824
      /* Constants.MAX_SAFE_SMALL_INTEGER */
    ),
    ignoreTrimWhitespace: boolean(options.ignoreTrimWhitespace, defaults.ignoreTrimWhitespace),
    renderIndicators: boolean(options.renderIndicators, defaults.renderIndicators),
    originalEditable: boolean(options.originalEditable, defaults.originalEditable),
    diffCodeLens: boolean(options.diffCodeLens, defaults.diffCodeLens),
    renderOverviewRuler: boolean(options.renderOverviewRuler, defaults.renderOverviewRuler),
    diffWordWrap: stringSet(options.diffWordWrap, defaults.diffWordWrap, ["off", "on", "inherit"]),
    diffAlgorithm: stringSet(options.diffAlgorithm, defaults.diffAlgorithm, ["legacy", "advanced"], { "smart": "legacy", "experimental": "advanced" }),
    accessibilityVerbose: boolean(options.accessibilityVerbose, defaults.accessibilityVerbose),
    experimental: {
      collapseUnchangedRegions: boolean((_a2 = options.experimental) === null || _a2 === void 0 ? void 0 : _a2.collapseUnchangedRegions, defaults.experimental.collapseUnchangedRegions),
      showMoves: boolean((_b2 = options.experimental) === null || _b2 === void 0 ? void 0 : _b2.showMoves, defaults.experimental.showMoves),
      showEmptyDecorations: boolean((_c2 = options.experimental) === null || _c2 === void 0 ? void 0 : _c2.showEmptyDecorations, defaults.experimental.showEmptyDecorations)
    },
    isInEmbeddedEditor: boolean(options.isInEmbeddedEditor, defaults.isInEmbeddedEditor),
    onlyShowAccessibleDiffViewer: boolean(options.onlyShowAccessibleDiffViewer, defaults.onlyShowAccessibleDiffViewer)
  };
}
var __decorate$2 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$2 = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter$2 = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
const accessibleDiffViewerInsertIcon = registerIcon("diff-review-insert", Codicon.add, localize("accessibleDiffViewerInsertIcon", "Icon for 'Insert' in accessible diff viewer."));
const accessibleDiffViewerRemoveIcon = registerIcon("diff-review-remove", Codicon.remove, localize("accessibleDiffViewerRemoveIcon", "Icon for 'Remove' in accessible diff viewer."));
const accessibleDiffViewerCloseIcon = registerIcon("diff-review-close", Codicon.close, localize("accessibleDiffViewerCloseIcon", "Icon for 'Close' in accessible diff viewer."));
let AccessibleDiffViewer = class AccessibleDiffViewer2 extends Disposable {
  constructor(_parentNode, _visible, _setVisible, _canClose, _width, _height, _diffs, _editors, _instantiationService) {
    super();
    this._parentNode = _parentNode;
    this._visible = _visible;
    this._setVisible = _setVisible;
    this._canClose = _canClose;
    this._width = _width;
    this._height = _height;
    this._diffs = _diffs;
    this._editors = _editors;
    this._instantiationService = _instantiationService;
    this.model = derivedWithStore("model", (reader, store) => {
      const visible = this._visible.read(reader);
      this._parentNode.style.visibility = visible ? "visible" : "hidden";
      if (!visible) {
        return null;
      }
      const model = store.add(this._instantiationService.createInstance(ViewModel2, this._diffs, this._editors, this._setVisible, this._canClose));
      const view = store.add(this._instantiationService.createInstance(View2, this._parentNode, model, this._width, this._height, this._editors));
      return {
        model,
        view
      };
    });
    this._register(keepAlive(this.model, true));
  }
  next() {
    transaction((tx) => {
      const isVisible = this._visible.get();
      this._setVisible(true, tx);
      if (isVisible) {
        this.model.get().model.nextGroup(tx);
      }
    });
  }
  prev() {
    transaction((tx) => {
      this._setVisible(true, tx);
      this.model.get().model.previousGroup(tx);
    });
  }
  close() {
    transaction((tx) => {
      this._setVisible(false, tx);
    });
  }
};
AccessibleDiffViewer = __decorate$2([
  __param$2(8, IInstantiationService)
], AccessibleDiffViewer);
let ViewModel2 = class ViewModel3 extends Disposable {
  constructor(_diffs, _editors, _setVisible, canClose, _audioCueService) {
    super();
    this._diffs = _diffs;
    this._editors = _editors;
    this._setVisible = _setVisible;
    this.canClose = canClose;
    this._audioCueService = _audioCueService;
    this._groups = observableValue("groups", []);
    this._currentGroupIdx = observableValue("currentGroupIdx", 0);
    this._currentElementIdx = observableValue("currentElementIdx", 0);
    this.groups = this._groups;
    this.currentGroup = this._currentGroupIdx.map((idx, r) => this._groups.read(r)[idx]);
    this.currentGroupIndex = this._currentGroupIdx;
    this.currentElement = this._currentElementIdx.map((idx, r) => {
      var _a2;
      return (_a2 = this.currentGroup.read(r)) === null || _a2 === void 0 ? void 0 : _a2.lines[idx];
    });
    this._register(autorun("update groups", (reader) => {
      const diffs = this._diffs.read(reader);
      if (!diffs) {
        this._groups.set([], void 0);
        return;
      }
      const groups = computeViewElementGroups(diffs, this._editors.original.getModel().getLineCount(), this._editors.modified.getModel().getLineCount());
      transaction((tx) => {
        const p2 = this._editors.modified.getPosition();
        if (p2) {
          const nextGroup = groups.findIndex((g) => (p2 === null || p2 === void 0 ? void 0 : p2.lineNumber) < g.range.modified.endLineNumberExclusive);
          if (nextGroup !== -1) {
            this._currentGroupIdx.set(nextGroup, tx);
          }
        }
        this._groups.set(groups, tx);
      });
    }));
    this._register(autorun("play audio-cue for diff", (reader) => {
      const currentViewItem = this.currentElement.read(reader);
      if ((currentViewItem === null || currentViewItem === void 0 ? void 0 : currentViewItem.type) === LineType.Deleted) {
        this._audioCueService.playAudioCue(AudioCue.diffLineDeleted);
      } else if ((currentViewItem === null || currentViewItem === void 0 ? void 0 : currentViewItem.type) === LineType.Added) {
        this._audioCueService.playAudioCue(AudioCue.diffLineInserted);
      }
    }));
    this._register(autorun("select lines in editor", (reader) => {
      var _a2;
      const currentViewItem = this.currentElement.read(reader);
      if (currentViewItem && currentViewItem.type !== LineType.Header) {
        const lineNumber = (_a2 = currentViewItem.modifiedLineNumber) !== null && _a2 !== void 0 ? _a2 : currentViewItem.diff.modifiedRange.startLineNumber;
        this._editors.modified.setSelection(Range$2.fromPositions(new Position$2(lineNumber, 1)));
      }
    }));
  }
  _goToGroupDelta(delta, tx) {
    const groups = this.groups.get();
    if (!groups || groups.length <= 1) {
      return;
    }
    subtransaction(tx, (tx2) => {
      this._currentGroupIdx.set((this._currentGroupIdx.get() + groups.length + delta) % groups.length, tx2);
      this._currentElementIdx.set(0, tx2);
    });
  }
  nextGroup(tx) {
    this._goToGroupDelta(1, tx);
  }
  previousGroup(tx) {
    this._goToGroupDelta(-1, tx);
  }
  _goToLineDelta(delta) {
    const group2 = this.currentGroup.get();
    if (!group2 || group2.lines.length <= 1) {
      return;
    }
    transaction((tx) => {
      this._currentElementIdx.set((this._currentElementIdx.get() + group2.lines.length + delta) % group2.lines.length, tx);
    });
  }
  goToNextLine() {
    this._goToLineDelta(1);
  }
  goToPreviousLine() {
    this._goToLineDelta(-1);
  }
  goToLine(line) {
    const group2 = this.currentGroup.get();
    if (!group2) {
      return;
    }
    const idx = group2.lines.indexOf(line);
    if (idx === -1) {
      return;
    }
    transaction((tx) => {
      this._currentElementIdx.set(idx, tx);
    });
  }
  revealCurrentElementInEditor() {
    this._setVisible(false, void 0);
    const curElem = this.currentElement.get();
    if (curElem) {
      if (curElem.type === LineType.Deleted) {
        this._editors.original.setSelection(Range$2.fromPositions(new Position$2(curElem.originalLineNumber, 1)));
        this._editors.original.revealLine(curElem.originalLineNumber);
        this._editors.original.focus();
      } else {
        if (curElem.type !== LineType.Header) {
          this._editors.modified.setSelection(Range$2.fromPositions(new Position$2(curElem.modifiedLineNumber, 1)));
          this._editors.modified.revealLine(curElem.modifiedLineNumber);
        }
        this._editors.modified.focus();
      }
    }
  }
  close() {
    this._setVisible(false, void 0);
    this._editors.modified.focus();
  }
};
ViewModel2 = __decorate$2([
  __param$2(4, IAudioCueService)
], ViewModel2);
const viewElementGroupLineMargin = 3;
function computeViewElementGroups(diffs, originalLineCount, modifiedLineCount) {
  const result2 = [];
  for (const g of group(diffs, (a, b) => b.modifiedRange.startLineNumber - a.modifiedRange.endLineNumberExclusive < 2 * viewElementGroupLineMargin)) {
    const viewElements = [];
    viewElements.push(new HeaderViewElement());
    const origFullRange = new LineRange2(Math.max(1, g[0].originalRange.startLineNumber - viewElementGroupLineMargin), Math.min(g[g.length - 1].originalRange.endLineNumberExclusive + viewElementGroupLineMargin, originalLineCount + 1));
    const modifiedFullRange = new LineRange2(Math.max(1, g[0].modifiedRange.startLineNumber - viewElementGroupLineMargin), Math.min(g[g.length - 1].modifiedRange.endLineNumberExclusive + viewElementGroupLineMargin, modifiedLineCount + 1));
    forEachAdjacentItems(g, (a, b) => {
      const origRange = new LineRange2(a ? a.originalRange.endLineNumberExclusive : origFullRange.startLineNumber, b ? b.originalRange.startLineNumber : origFullRange.endLineNumberExclusive);
      const modifiedRange2 = new LineRange2(a ? a.modifiedRange.endLineNumberExclusive : modifiedFullRange.startLineNumber, b ? b.modifiedRange.startLineNumber : modifiedFullRange.endLineNumberExclusive);
      origRange.forEach((origLineNumber) => {
        viewElements.push(new UnchangedLineViewElement(origLineNumber, modifiedRange2.startLineNumber + (origLineNumber - origRange.startLineNumber)));
      });
      if (b) {
        b.originalRange.forEach((origLineNumber) => {
          viewElements.push(new DeletedLineViewElement(b, origLineNumber));
        });
        b.modifiedRange.forEach((modifiedLineNumber) => {
          viewElements.push(new AddedLineViewElement(b, modifiedLineNumber));
        });
      }
    });
    const modifiedRange = g[0].modifiedRange.join(g[g.length - 1].modifiedRange);
    const originalRange = g[0].originalRange.join(g[g.length - 1].originalRange);
    result2.push(new ViewElementGroup(new SimpleLineRangeMapping(modifiedRange, originalRange), viewElements));
  }
  return result2;
}
var LineType;
(function(LineType2) {
  LineType2[LineType2["Header"] = 0] = "Header";
  LineType2[LineType2["Unchanged"] = 1] = "Unchanged";
  LineType2[LineType2["Deleted"] = 2] = "Deleted";
  LineType2[LineType2["Added"] = 3] = "Added";
})(LineType || (LineType = {}));
class ViewElementGroup {
  constructor(range2, lines) {
    this.range = range2;
    this.lines = lines;
  }
}
class HeaderViewElement {
  constructor() {
    this.type = LineType.Header;
  }
}
class DeletedLineViewElement {
  constructor(diff, originalLineNumber) {
    this.diff = diff;
    this.originalLineNumber = originalLineNumber;
    this.type = LineType.Deleted;
    this.modifiedLineNumber = void 0;
  }
}
class AddedLineViewElement {
  constructor(diff, modifiedLineNumber) {
    this.diff = diff;
    this.modifiedLineNumber = modifiedLineNumber;
    this.type = LineType.Added;
    this.originalLineNumber = void 0;
  }
}
class UnchangedLineViewElement {
  constructor(originalLineNumber, modifiedLineNumber) {
    this.originalLineNumber = originalLineNumber;
    this.modifiedLineNumber = modifiedLineNumber;
    this.type = LineType.Unchanged;
  }
}
let View2 = class View3 extends Disposable {
  constructor(_element, _model, _width, _height, _editors, _languageService) {
    super();
    this._element = _element;
    this._model = _model;
    this._width = _width;
    this._height = _height;
    this._editors = _editors;
    this._languageService = _languageService;
    this.domNode = this._element;
    this.domNode.className = "diff-review monaco-editor-background";
    const actionBarContainer = document.createElement("div");
    actionBarContainer.className = "diff-review-actions";
    this._actionBar = this._register(new ActionBar(actionBarContainer));
    this._register(autorun("update actions", (reader) => {
      this._actionBar.clear();
      if (this._model.canClose.read(reader)) {
        this._actionBar.push(new Action("diffreview.close", localize("label.close", "Close"), "close-diff-review " + ThemeIcon.asClassName(accessibleDiffViewerCloseIcon), true, () => __awaiter$2(this, void 0, void 0, function* () {
          return _model.close();
        })), { label: false, icon: true });
      }
    }));
    this._content = document.createElement("div");
    this._content.className = "diff-review-content";
    this._content.setAttribute("role", "code");
    this._scrollbar = this._register(new DomScrollableElement(this._content, {}));
    reset(this.domNode, this._scrollbar.getDomNode(), actionBarContainer);
    this._register(toDisposable(() => {
      reset(this.domNode);
    }));
    this._register(applyStyle(this.domNode, { width: this._width, height: this._height }));
    this._register(applyStyle(this._content, { width: this._width, height: this._height }));
    this._register(autorunWithStore2("render", (reader, store) => {
      this._model.currentGroup.read(reader);
      this._render(store);
    }));
    this._register(addStandardDisposableListener(this.domNode, "keydown", (e) => {
      if (e.equals(
        18
        /* KeyCode.DownArrow */
      ) || e.equals(
        2048 | 18
        /* KeyCode.DownArrow */
      ) || e.equals(
        512 | 18
        /* KeyCode.DownArrow */
      )) {
        e.preventDefault();
        this._model.goToNextLine();
      }
      if (e.equals(
        16
        /* KeyCode.UpArrow */
      ) || e.equals(
        2048 | 16
        /* KeyCode.UpArrow */
      ) || e.equals(
        512 | 16
        /* KeyCode.UpArrow */
      )) {
        e.preventDefault();
        this._model.goToPreviousLine();
      }
      if (e.equals(
        9
        /* KeyCode.Escape */
      ) || e.equals(
        2048 | 9
        /* KeyCode.Escape */
      ) || e.equals(
        512 | 9
        /* KeyCode.Escape */
      ) || e.equals(
        1024 | 9
        /* KeyCode.Escape */
      )) {
        e.preventDefault();
        this._model.close();
      }
      if (e.equals(
        10
        /* KeyCode.Space */
      ) || e.equals(
        3
        /* KeyCode.Enter */
      )) {
        e.preventDefault();
        this._model.revealCurrentElementInEditor();
      }
    }));
  }
  _render(store) {
    const originalOptions = this._editors.original.getOptions();
    const modifiedOptions = this._editors.modified.getOptions();
    const container2 = document.createElement("div");
    container2.className = "diff-review-table";
    container2.setAttribute("role", "list");
    container2.setAttribute("aria-label", localize("ariaLabel", "Accessible Diff Viewer. Use arrow up and down to navigate."));
    applyFontInfo(container2, modifiedOptions.get(
      49
      /* EditorOption.fontInfo */
    ));
    reset(this._content, container2);
    const originalModel = this._editors.original.getModel();
    const modifiedModel = this._editors.modified.getModel();
    if (!originalModel || !modifiedModel) {
      return;
    }
    const originalModelOpts = originalModel.getOptions();
    const modifiedModelOpts = modifiedModel.getOptions();
    const lineHeight = modifiedOptions.get(
      65
      /* EditorOption.lineHeight */
    );
    const group2 = this._model.currentGroup.get();
    for (const viewItem of (group2 === null || group2 === void 0 ? void 0 : group2.lines) || []) {
      if (!group2) {
        break;
      }
      let row;
      if (viewItem.type === LineType.Header) {
        const header = document.createElement("div");
        header.className = "diff-review-row";
        header.setAttribute("role", "listitem");
        const r = group2.range;
        const diffIndex = this._model.currentGroupIndex.get();
        const diffsLength = this._model.groups.get().length;
        const getAriaLines = (lines) => lines === 0 ? localize("no_lines_changed", "no lines changed") : lines === 1 ? localize("one_line_changed", "1 line changed") : localize("more_lines_changed", "{0} lines changed", lines);
        const originalChangedLinesCntAria = getAriaLines(r.original.length);
        const modifiedChangedLinesCntAria = getAriaLines(r.modified.length);
        header.setAttribute("aria-label", localize({
          key: "header",
          comment: [
            "This is the ARIA label for a git diff header.",
            "A git diff header looks like this: @@ -154,12 +159,39 @@.",
            "That encodes that at original line 154 (which is now line 159), 12 lines were removed/changed with 39 lines.",
            "Variables 0 and 1 refer to the diff index out of total number of diffs.",
            "Variables 2 and 4 will be numbers (a line number).",
            'Variables 3 and 5 will be "no lines changed", "1 line changed" or "X lines changed", localized separately.'
          ]
        }, "Difference {0} of {1}: original line {2}, {3}, modified line {4}, {5}", diffIndex + 1, diffsLength, r.original.startLineNumber, originalChangedLinesCntAria, r.modified.startLineNumber, modifiedChangedLinesCntAria));
        const cell = document.createElement("div");
        cell.className = "diff-review-cell diff-review-summary";
        cell.appendChild(document.createTextNode(`${diffIndex + 1}/${diffsLength}: @@ -${r.original.startLineNumber},${r.original.length} +${r.modified.startLineNumber},${r.modified.length} @@`));
        header.appendChild(cell);
        row = header;
      } else {
        row = this._createRow(viewItem, lineHeight, this._width.get(), originalOptions, originalModel, originalModelOpts, modifiedOptions, modifiedModel, modifiedModelOpts);
      }
      container2.appendChild(row);
      const isSelectedObs = derived("isSelected", (reader) => this._model.currentElement.read(reader) === viewItem);
      store.add(autorun("update tab index", (reader) => {
        const isSelected = isSelectedObs.read(reader);
        row.tabIndex = isSelected ? 0 : -1;
        if (isSelected) {
          row.focus();
        }
      }));
      store.add(addDisposableListener(row, "focus", () => {
        this._model.goToLine(viewItem);
      }));
    }
    this._scrollbar.scanDomNode();
  }
  _createRow(item, lineHeight, width, originalOptions, originalModel, originalModelOpts, modifiedOptions, modifiedModel, modifiedModelOpts) {
    const originalLayoutInfo = originalOptions.get(
      142
      /* EditorOption.layoutInfo */
    );
    const originalLineNumbersWidth = originalLayoutInfo.glyphMarginWidth + originalLayoutInfo.lineNumbersWidth;
    const modifiedLayoutInfo = modifiedOptions.get(
      142
      /* EditorOption.layoutInfo */
    );
    const modifiedLineNumbersWidth = 10 + modifiedLayoutInfo.glyphMarginWidth + modifiedLayoutInfo.lineNumbersWidth;
    let rowClassName = "diff-review-row";
    let lineNumbersExtraClassName = "";
    const spacerClassName = "diff-review-spacer";
    let spacerIcon = null;
    switch (item.type) {
      case LineType.Added:
        rowClassName = "diff-review-row line-insert";
        lineNumbersExtraClassName = " char-insert";
        spacerIcon = accessibleDiffViewerInsertIcon;
        break;
      case LineType.Deleted:
        rowClassName = "diff-review-row line-delete";
        lineNumbersExtraClassName = " char-delete";
        spacerIcon = accessibleDiffViewerRemoveIcon;
        break;
    }
    const row = document.createElement("div");
    row.style.minWidth = width + "px";
    row.className = rowClassName;
    row.setAttribute("role", "listitem");
    row.ariaLevel = "";
    const cell = document.createElement("div");
    cell.className = "diff-review-cell";
    cell.style.height = `${lineHeight}px`;
    row.appendChild(cell);
    const originalLineNumber = document.createElement("span");
    originalLineNumber.style.width = originalLineNumbersWidth + "px";
    originalLineNumber.style.minWidth = originalLineNumbersWidth + "px";
    originalLineNumber.className = "diff-review-line-number" + lineNumbersExtraClassName;
    if (item.originalLineNumber !== void 0) {
      originalLineNumber.appendChild(document.createTextNode(String(item.originalLineNumber)));
    } else {
      originalLineNumber.innerText = " ";
    }
    cell.appendChild(originalLineNumber);
    const modifiedLineNumber = document.createElement("span");
    modifiedLineNumber.style.width = modifiedLineNumbersWidth + "px";
    modifiedLineNumber.style.minWidth = modifiedLineNumbersWidth + "px";
    modifiedLineNumber.style.paddingRight = "10px";
    modifiedLineNumber.className = "diff-review-line-number" + lineNumbersExtraClassName;
    if (item.modifiedLineNumber !== void 0) {
      modifiedLineNumber.appendChild(document.createTextNode(String(item.modifiedLineNumber)));
    } else {
      modifiedLineNumber.innerText = " ";
    }
    cell.appendChild(modifiedLineNumber);
    const spacer = document.createElement("span");
    spacer.className = spacerClassName;
    if (spacerIcon) {
      const spacerCodicon = document.createElement("span");
      spacerCodicon.className = ThemeIcon.asClassName(spacerIcon);
      spacerCodicon.innerText = "  ";
      spacer.appendChild(spacerCodicon);
    } else {
      spacer.innerText = "  ";
    }
    cell.appendChild(spacer);
    let lineContent;
    if (item.modifiedLineNumber !== void 0) {
      let html2 = this._getLineHtml(modifiedModel, modifiedOptions, modifiedModelOpts.tabSize, item.modifiedLineNumber, this._languageService.languageIdCodec);
      if (DiffReview._ttPolicy) {
        html2 = DiffReview._ttPolicy.createHTML(html2);
      }
      cell.insertAdjacentHTML("beforeend", html2);
      lineContent = modifiedModel.getLineContent(item.modifiedLineNumber);
    } else {
      let html2 = this._getLineHtml(originalModel, originalOptions, originalModelOpts.tabSize, item.originalLineNumber, this._languageService.languageIdCodec);
      if (DiffReview._ttPolicy) {
        html2 = DiffReview._ttPolicy.createHTML(html2);
      }
      cell.insertAdjacentHTML("beforeend", html2);
      lineContent = originalModel.getLineContent(item.originalLineNumber);
    }
    if (lineContent.length === 0) {
      lineContent = localize("blankLine", "blank");
    }
    let ariaLabel = "";
    switch (item.type) {
      case LineType.Unchanged:
        if (item.originalLineNumber === item.modifiedLineNumber) {
          ariaLabel = localize({ key: "unchangedLine", comment: ["The placeholders are contents of the line and should not be translated."] }, "{0} unchanged line {1}", lineContent, item.originalLineNumber);
        } else {
          ariaLabel = localize("equalLine", "{0} original line {1} modified line {2}", lineContent, item.originalLineNumber, item.modifiedLineNumber);
        }
        break;
      case LineType.Added:
        ariaLabel = localize("insertLine", "+ {0} modified line {1}", lineContent, item.modifiedLineNumber);
        break;
      case LineType.Deleted:
        ariaLabel = localize("deleteLine", "- {0} original line {1}", lineContent, item.originalLineNumber);
        break;
    }
    row.setAttribute("aria-label", ariaLabel);
    return row;
  }
  _getLineHtml(model, options, tabSize, lineNumber, languageIdCodec) {
    const lineContent = model.getLineContent(lineNumber);
    const fontInfo = options.get(
      49
      /* EditorOption.fontInfo */
    );
    const lineTokens = LineTokens.createEmpty(lineContent, languageIdCodec);
    const isBasicASCII2 = ViewLineRenderingData.isBasicASCII(lineContent, model.mightContainNonBasicASCII());
    const containsRTL2 = ViewLineRenderingData.containsRTL(lineContent, isBasicASCII2, model.mightContainRTL());
    const r = renderViewLine2(new RenderLineInput(fontInfo.isMonospace && !options.get(
      32
      /* EditorOption.disableMonospaceOptimizations */
    ), fontInfo.canUseHalfwidthRightwardsArrow, lineContent, false, isBasicASCII2, containsRTL2, 0, lineTokens, [], tabSize, 0, fontInfo.spaceWidth, fontInfo.middotWidth, fontInfo.wsmiddotWidth, options.get(
      115
      /* EditorOption.stopRenderingLineAfter */
    ), options.get(
      97
      /* EditorOption.renderWhitespace */
    ), options.get(
      92
      /* EditorOption.renderControlCharacters */
    ), options.get(
      50
      /* EditorOption.fontLigatures */
    ) !== EditorFontLigatures.OFF, null));
    return r.html;
  }
};
View2 = __decorate$2([
  __param$2(5, ILanguageService)
], View2);
function forEachAdjacentItems(items, callback) {
  let last2;
  for (const item of items) {
    callback(last2, item);
    last2 = item;
  }
  callback(last2, void 0);
}
function* group(items, shouldBeGrouped) {
  let currentGroup;
  let last2;
  for (const item of items) {
    if (last2 !== void 0 && shouldBeGrouped(last2, item)) {
      currentGroup.push(item);
    } else {
      if (currentGroup) {
        yield currentGroup;
      }
      currentGroup = [item];
    }
    last2 = item;
  }
  if (currentGroup) {
    yield currentGroup;
  }
}
registerColor("diffEditor.move.border", { dark: "#8b8b8b9c", light: "#8b8b8b9c", hcDark: "#8b8b8b9c", hcLight: "#8b8b8b9c" }, localize("diffEditor.move.border", "The border color for text that got moved in the diff editor."));
var __decorate$1 = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param$1 = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let DiffEditorWidget22 = class DiffEditorWidget23 extends DelegatingEditor {
  constructor(_domElement, options, codeEditorWidgetOptions, _parentContextKeyService, _parentInstantiationService, codeEditorService, _audioCueService) {
    var _a2;
    super();
    this._domElement = _domElement;
    this._parentContextKeyService = _parentContextKeyService;
    this._parentInstantiationService = _parentInstantiationService;
    this._audioCueService = _audioCueService;
    this.elements = h("div.monaco-diff-editor.side-by-side", { style: { position: "relative", height: "100%" } }, [
      h("div.noModificationsOverlay@overlay", { style: { position: "absolute", height: "100%", visibility: "hidden" } }, [$$d("span", {}, "No Changes")]),
      h("div.editor.original@original", { style: { position: "absolute", height: "100%" } }),
      h("div.editor.modified@modified", { style: { position: "absolute", height: "100%" } }),
      h("div.accessibleDiffViewer@accessibleDiffViewer", { style: { position: "absolute", height: "100%" } })
    ]);
    this._diffModel = this._register(disposableObservableValue("diffModel", void 0));
    this.onDidChangeModel = Event$1.fromObservableLight(this._diffModel);
    this._contextKeyService = this._register(this._parentContextKeyService.createScoped(this._domElement));
    this._instantiationService = this._parentInstantiationService.createChild(new ServiceCollection([IContextKeyService, this._contextKeyService]));
    this._boundarySashes = observableValue("boundarySashes", void 0);
    this._accessibleDiffViewerShouldBeVisible = observableValue("accessibleDiffViewerShouldBeVisible", false);
    this._accessibleDiffViewerVisible = derived("accessibleDiffViewerVisible", (reader) => this._options.onlyShowAccessibleDiffViewer.read(reader) ? true : this._accessibleDiffViewerShouldBeVisible.read(reader));
    this._layoutInfo = derived("modifiedEditorLayoutInfo", (reader) => {
      var _a3;
      const width = this._rootSizeObserver.width.read(reader);
      const height = this._rootSizeObserver.height.read(reader);
      const sashLeft = (_a3 = this._sash.read(reader)) === null || _a3 === void 0 ? void 0 : _a3.sashLeft.read(reader);
      const originalWidth = sashLeft !== null && sashLeft !== void 0 ? sashLeft : Math.max(5, this._editors.original.getLayoutInfo().decorationsLeft);
      const modifiedWidth = width - originalWidth - (this._options.renderOverviewRuler.read(reader) ? OverviewRulerPart.ENTIRE_DIFF_OVERVIEW_WIDTH : 0);
      this.elements.original.style.width = originalWidth + "px";
      this.elements.original.style.left = "0px";
      this.elements.modified.style.width = modifiedWidth + "px";
      this.elements.modified.style.left = originalWidth + "px";
      this._editors.original.layout({ width: originalWidth, height });
      this._editors.modified.layout({ width: modifiedWidth, height });
      return {
        modifiedEditor: this._editors.modified.getLayoutInfo(),
        originalEditor: this._editors.original.getLayoutInfo()
      };
    });
    this._diffValue = this._diffModel.map((m, r) => m === null || m === void 0 ? void 0 : m.diff.read(r));
    this.onDidUpdateDiff = Event$1.fromObservableLight(this._diffValue);
    codeEditorService.willCreateDiffEditor();
    this._contextKeyService.createKey("isInDiffEditor", true);
    this._contextKeyService.createKey("diffEditorVersion", 2);
    this._options = new DiffEditorOptions(options);
    this._contextKeyService.createKey(EditorContextKeys.isEmbeddedDiffEditor.key, false);
    const isEmbeddedDiffEditorKey = EditorContextKeys.isEmbeddedDiffEditor.bindTo(this._contextKeyService);
    this._register(autorun("update isEmbeddedDiffEditorKey", (reader) => {
      isEmbeddedDiffEditorKey.set(this._options.isInEmbeddedEditor.read(reader));
    }));
    const accessibleDiffViewerVisibleContextKeyValue = EditorContextKeys.accessibleDiffViewerVisible.bindTo(this._contextKeyService);
    this._register(autorun("update accessibleDiffViewerVisible context key", (reader) => {
      accessibleDiffViewerVisibleContextKeyValue.set(this._accessibleDiffViewerVisible.read(reader));
    }));
    this._domElement.appendChild(this.elements.root);
    this._rootSizeObserver = this._register(new ObservableElementSizeObserver(this.elements.root, options.dimension));
    this._rootSizeObserver.setAutomaticLayout((_a2 = options.automaticLayout) !== null && _a2 !== void 0 ? _a2 : false);
    this._editors = this._register(this._instantiationService.createInstance(DiffEditorEditors, this.elements.original, this.elements.modified, this._options, codeEditorWidgetOptions, (i, c, o, o2) => this._createInnerEditor(i, c, o, o2)));
    this._sash = derivedWithStore("sash", (reader, store) => {
      const showSash = this._options.renderSideBySide.read(reader);
      this.elements.root.classList.toggle("side-by-side", showSash);
      if (!showSash) {
        return void 0;
      }
      const result2 = store.add(new DiffEditorSash(this._options, this.elements.root, {
        height: this._rootSizeObserver.height,
        width: this._rootSizeObserver.width.map((w, reader2) => w - (this._options.renderOverviewRuler.read(reader2) ? OverviewRulerPart.ENTIRE_DIFF_OVERVIEW_WIDTH : 0))
      }));
      store.add(autorun("setBoundarySashes", (reader2) => {
        const boundarySashes = this._boundarySashes.read(reader2);
        if (boundarySashes) {
          result2.setBoundarySashes(boundarySashes);
        }
      }));
      return result2;
    });
    this._register(keepAlive(this._sash, true));
    this._register(autorunWithStore2("UnchangedRangesFeature", (reader, store) => {
      this.unchangedRangesFeature = store.add(new (readHotReloadableExport(UnchangedRangesFeature, reader))(this._editors, this._diffModel, this._options));
    }));
    this._register(autorunWithStore2("DiffEditorDecorations", (reader, store) => {
      store.add(new (readHotReloadableExport(DiffEditorDecorations, reader))(this._editors, this._diffModel, this._options));
    }));
    this._register(autorunWithStore2("ViewZoneManager", (reader, store) => {
      store.add(this._instantiationService.createInstance(readHotReloadableExport(ViewZoneManager, reader), this._editors, this._diffModel, this._options, this, () => this.unchangedRangesFeature.isUpdatingViewZones));
    }));
    this._register(autorunWithStore2("OverviewRulerPart", (reader, store) => {
      store.add(this._instantiationService.createInstance(readHotReloadableExport(OverviewRulerPart, reader), this._editors, this.elements.root, this._diffModel, this._rootSizeObserver.width, this._rootSizeObserver.height, this._layoutInfo.map((i) => i.modifiedEditor), this._options));
    }));
    this._register(autorunWithStore2("_accessibleDiffViewer", (reader, store) => {
      this._accessibleDiffViewer = store.add(this._register(this._instantiationService.createInstance(readHotReloadableExport(AccessibleDiffViewer, reader), this.elements.accessibleDiffViewer, this._accessibleDiffViewerVisible, (visible, tx) => this._accessibleDiffViewerShouldBeVisible.set(visible, tx), this._options.onlyShowAccessibleDiffViewer.map((v) => !v), this._rootSizeObserver.width, this._rootSizeObserver.height, this._diffModel.map((m, r) => {
        var _a3;
        return (_a3 = m === null || m === void 0 ? void 0 : m.diff.read(r)) === null || _a3 === void 0 ? void 0 : _a3.mappings.map((m2) => m2.lineRangeMapping);
      }), this._editors)));
    }));
    const visibility = this._accessibleDiffViewerVisible.map((v) => v ? "hidden" : "visible");
    this._register(applyStyle(this.elements.modified, { visibility }));
    this._register(applyStyle(this.elements.original, { visibility }));
    this._createDiffEditorContributions();
    codeEditorService.addDiffEditor(this);
    this._register(keepAlive(this._layoutInfo, true));
    this._register(new MovedBlocksLinesPart(this.elements.root, this._diffModel, this._layoutInfo.map((i) => i.originalEditor), this._layoutInfo.map((i) => i.modifiedEditor), this._editors));
    this._register(applyStyle(this.elements.overlay, {
      width: this._layoutInfo.map((i, r) => i.originalEditor.width + (this._options.renderSideBySide.read(r) ? 0 : i.modifiedEditor.width)),
      visibility: derived("visibility", (reader) => {
        var _a3, _b2;
        return this._options.collapseUnchangedRegions.read(reader) && ((_b2 = (_a3 = this._diffModel.read(reader)) === null || _a3 === void 0 ? void 0 : _a3.diff.read(reader)) === null || _b2 === void 0 ? void 0 : _b2.mappings.length) === 0 ? "visible" : "hidden";
      })
    }));
    this._register(this._editors.original.onDidChangeCursorPosition((e) => {
      const m = this._diffModel.get();
      if (!m) {
        return;
      }
      const movedText = m.diff.get().movedTexts.find((m2) => m2.lineRangeMapping.original.contains(e.position.lineNumber));
      m.syncedMovedTexts.set(movedText, void 0);
    }));
    this._register(this._editors.modified.onDidChangeCursorPosition((e) => {
      const m = this._diffModel.get();
      if (!m) {
        return;
      }
      const movedText = m.diff.get().movedTexts.find((m2) => m2.lineRangeMapping.modified.contains(e.position.lineNumber));
      m.syncedMovedTexts.set(movedText, void 0);
    }));
    this._register(this._editors.modified.onMouseDown((event) => {
      var _a3, _b2;
      if (!event.event.rightButton && event.target.position && ((_a3 = event.target.element) === null || _a3 === void 0 ? void 0 : _a3.className.includes("arrow-revert-change"))) {
        const lineNumber = event.target.position.lineNumber;
        const viewZone = event.target;
        const model = this._diffModel.get();
        if (!model) {
          return;
        }
        const diffs = (_b2 = model.diff.get()) === null || _b2 === void 0 ? void 0 : _b2.mappings;
        if (!diffs) {
          return;
        }
        const diff = diffs.find((d) => (viewZone === null || viewZone === void 0 ? void 0 : viewZone.detail.afterLineNumber) === d.lineRangeMapping.modifiedRange.startLineNumber - 1 || d.lineRangeMapping.modifiedRange.startLineNumber === lineNumber);
        if (!diff) {
          return;
        }
        this.revert(diff.lineRangeMapping);
        event.event.stopPropagation();
      }
    }));
    this._register(Event$1.runAndSubscribe(this._editors.modified.onDidChangeCursorPosition, (e) => {
      var _a3, _b2;
      if ((e === null || e === void 0 ? void 0 : e.reason) === 3) {
        const diff = (_b2 = (_a3 = this._diffModel.get()) === null || _a3 === void 0 ? void 0 : _a3.diff.get()) === null || _b2 === void 0 ? void 0 : _b2.mappings.find((m) => m.lineRangeMapping.modifiedRange.contains(e.position.lineNumber));
        if (diff === null || diff === void 0 ? void 0 : diff.lineRangeMapping.modifiedRange.isEmpty) {
          this._audioCueService.playAudioCue(AudioCue.diffLineDeleted);
        } else if (diff === null || diff === void 0 ? void 0 : diff.lineRangeMapping.originalRange.isEmpty) {
          this._audioCueService.playAudioCue(AudioCue.diffLineInserted);
        } else if (diff) {
          this._audioCueService.playAudioCue(AudioCue.diffLineModified);
        }
      }
    }));
  }
  _createInnerEditor(instantiationService, container2, options, editorWidgetOptions) {
    const editor2 = instantiationService.createInstance(CodeEditorWidget, container2, options, editorWidgetOptions);
    return editor2;
  }
  _createDiffEditorContributions() {
    const contributions = EditorExtensionsRegistry.getDiffEditorContributions();
    for (const desc of contributions) {
      try {
        this._register(this._instantiationService.createInstance(desc.ctor, this));
      } catch (err) {
        onUnexpectedError(err);
      }
    }
  }
  get _targetEditor() {
    return this._editors.modified;
  }
  getEditorType() {
    return EditorType.IDiffEditor;
  }
  layout(dimension) {
    this._rootSizeObserver.observe(dimension);
  }
  hasTextFocus() {
    return this._editors.original.hasTextFocus() || this._editors.modified.hasTextFocus();
  }
  saveViewState() {
    var _a2;
    const originalViewState = this._editors.original.saveViewState();
    const modifiedViewState = this._editors.modified.saveViewState();
    return {
      original: originalViewState,
      modified: modifiedViewState,
      modelState: (_a2 = this._diffModel.get()) === null || _a2 === void 0 ? void 0 : _a2.serializeState()
    };
  }
  restoreViewState(s) {
    var _a2;
    if (s && s.original && s.modified) {
      const diffEditorState = s;
      this._editors.original.restoreViewState(diffEditorState.original);
      this._editors.modified.restoreViewState(diffEditorState.modified);
      if (diffEditorState.modelState) {
        (_a2 = this._diffModel.get()) === null || _a2 === void 0 ? void 0 : _a2.restoreSerializedState(diffEditorState.modelState);
      }
    }
  }
  createViewModel(model) {
    return new DiffEditorViewModel(
      model,
      this._options,
      // TODO@hediet make diffAlgorithm observable
      this._instantiationService.createInstance(WorkerBasedDocumentDiffProvider, { diffAlgorithm: this._options.diffAlgorithm.get() })
    );
  }
  getModel() {
    var _a2, _b2;
    return (_b2 = (_a2 = this._diffModel.get()) === null || _a2 === void 0 ? void 0 : _a2.model) !== null && _b2 !== void 0 ? _b2 : null;
  }
  setModel(model) {
    if (!model && this._diffModel.get()) {
      this._accessibleDiffViewer.close();
    }
    const vm = model ? "model" in model ? model : this.createViewModel(model) : void 0;
    this._editors.original.setModel(vm ? vm.model.original : null);
    this._editors.modified.setModel(vm ? vm.model.modified : null);
    transaction((tx) => {
      this._diffModel.set(vm, tx);
    });
  }
  /**
   * @param changedOptions Only has values for top-level options that have actually changed.
   */
  updateOptions(changedOptions) {
    this._options.updateOptions(changedOptions);
  }
  getContainerDomNode() {
    return this._domElement;
  }
  getOriginalEditor() {
    return this._editors.original;
  }
  getModifiedEditor() {
    return this._editors.modified;
  }
  /**
   * @deprecated Use `this.getDiffComputationResult().changes2` instead.
   */
  getLineChanges() {
    var _a2;
    const diffState = (_a2 = this._diffModel.get()) === null || _a2 === void 0 ? void 0 : _a2.diff.get();
    if (!diffState) {
      return null;
    }
    return toLineChanges(diffState);
  }
  revert(diff) {
    var _a2;
    const model = (_a2 = this._diffModel.get()) === null || _a2 === void 0 ? void 0 : _a2.model;
    if (!model) {
      return;
    }
    const changes = diff.innerChanges ? diff.innerChanges.map((c) => ({
      range: c.modifiedRange,
      text: model.original.getValueInRange(c.originalRange)
    })) : [
      {
        range: diff.modifiedRange.toExclusiveRange(),
        text: model.original.getValueInRange(diff.originalRange.toExclusiveRange())
      }
    ];
    this._editors.modified.executeEdits("diffEditor", changes);
  }
  accessibleDiffViewerNext() {
    this._accessibleDiffViewer.next();
  }
  accessibleDiffViewerPrev() {
    this._accessibleDiffViewer.prev();
  }
};
DiffEditorWidget22 = __decorate$1([
  __param$1(3, IContextKeyService),
  __param$1(4, IInstantiationService),
  __param$1(5, ICodeEditorService),
  __param$1(6, IAudioCueService)
], DiffEditorWidget22);
function toLineChanges(state) {
  return state.mappings.map((x) => {
    const m = x.lineRangeMapping;
    let originalStartLineNumber;
    let originalEndLineNumber;
    let modifiedStartLineNumber;
    let modifiedEndLineNumber;
    let innerChanges = m.innerChanges;
    if (m.originalRange.isEmpty) {
      originalStartLineNumber = m.originalRange.startLineNumber - 1;
      originalEndLineNumber = 0;
      innerChanges = void 0;
    } else {
      originalStartLineNumber = m.originalRange.startLineNumber;
      originalEndLineNumber = m.originalRange.endLineNumberExclusive - 1;
    }
    if (m.modifiedRange.isEmpty) {
      modifiedStartLineNumber = m.modifiedRange.startLineNumber - 1;
      modifiedEndLineNumber = 0;
      innerChanges = void 0;
    } else {
      modifiedStartLineNumber = m.modifiedRange.startLineNumber;
      modifiedEndLineNumber = m.modifiedRange.endLineNumberExclusive - 1;
    }
    return {
      originalStartLineNumber,
      originalEndLineNumber,
      modifiedStartLineNumber,
      modifiedEndLineNumber,
      charChanges: innerChanges === null || innerChanges === void 0 ? void 0 : innerChanges.map((m2) => ({
        originalStartLineNumber: m2.originalRange.startLineNumber,
        originalStartColumn: m2.originalRange.startColumn,
        originalEndLineNumber: m2.originalRange.endLineNumber,
        originalEndColumn: m2.originalRange.endColumn,
        modifiedStartLineNumber: m2.modifiedRange.startLineNumber,
        modifiedStartColumn: m2.modifiedRange.startColumn,
        modifiedEndLineNumber: m2.modifiedRange.endLineNumber,
        modifiedEndColumn: m2.modifiedRange.endColumn
      }))
    };
  });
}
var __decorate = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
let LAST_GENERATED_COMMAND_ID = 0;
let ariaDomNodeCreated = false;
function createAriaDomNode(parent) {
  if (!parent) {
    if (ariaDomNodeCreated) {
      return;
    }
    ariaDomNodeCreated = true;
  }
  setARIAContainer(parent || document.body);
}
let StandaloneCodeEditor = class StandaloneCodeEditor2 extends CodeEditorWidget {
  constructor(domElement, _options, instantiationService, codeEditorService, commandService, contextKeyService, keybindingService, themeService, notificationService, accessibilityService, languageConfigurationService, languageFeaturesService) {
    const options = Object.assign({}, _options);
    options.ariaLabel = options.ariaLabel || StandaloneCodeEditorNLS.editorViewAccessibleLabel;
    options.ariaLabel = options.ariaLabel + ";" + StandaloneCodeEditorNLS.accessibilityHelpMessage;
    super(domElement, options, {}, instantiationService, codeEditorService, commandService, contextKeyService, themeService, notificationService, accessibilityService, languageConfigurationService, languageFeaturesService);
    if (keybindingService instanceof StandaloneKeybindingService) {
      this._standaloneKeybindingService = keybindingService;
    } else {
      this._standaloneKeybindingService = null;
    }
    createAriaDomNode(options.ariaContainerElement);
  }
  addCommand(keybinding, handler, context) {
    if (!this._standaloneKeybindingService) {
      console.warn("Cannot add command because the editor is configured with an unrecognized KeybindingService");
      return null;
    }
    const commandId = "DYNAMIC_" + ++LAST_GENERATED_COMMAND_ID;
    const whenExpression = ContextKeyExpr.deserialize(context);
    this._standaloneKeybindingService.addDynamicKeybinding(commandId, keybinding, handler, whenExpression);
    return commandId;
  }
  createContextKey(key, defaultValue) {
    return this._contextKeyService.createKey(key, defaultValue);
  }
  addAction(_descriptor) {
    if (typeof _descriptor.id !== "string" || typeof _descriptor.label !== "string" || typeof _descriptor.run !== "function") {
      throw new Error("Invalid action descriptor, `id`, `label` and `run` are required properties!");
    }
    if (!this._standaloneKeybindingService) {
      console.warn("Cannot add keybinding because the editor is configured with an unrecognized KeybindingService");
      return Disposable.None;
    }
    const id3 = _descriptor.id;
    const label = _descriptor.label;
    const precondition = ContextKeyExpr.and(ContextKeyExpr.equals("editorId", this.getId()), ContextKeyExpr.deserialize(_descriptor.precondition));
    const keybindings = _descriptor.keybindings;
    const keybindingsWhen = ContextKeyExpr.and(precondition, ContextKeyExpr.deserialize(_descriptor.keybindingContext));
    const contextMenuGroupId = _descriptor.contextMenuGroupId || null;
    const contextMenuOrder = _descriptor.contextMenuOrder || 0;
    const run = (_accessor, ...args) => {
      return Promise.resolve(_descriptor.run(this, ...args));
    };
    const toDispose = new DisposableStore();
    const uniqueId = this.getId() + ":" + id3;
    toDispose.add(CommandsRegistry.registerCommand(uniqueId, run));
    if (contextMenuGroupId) {
      const menuItem = {
        command: {
          id: uniqueId,
          title: label
        },
        when: precondition,
        group: contextMenuGroupId,
        order: contextMenuOrder
      };
      toDispose.add(MenuRegistry.appendMenuItem(MenuId.EditorContext, menuItem));
    }
    if (Array.isArray(keybindings)) {
      for (const kb of keybindings) {
        toDispose.add(this._standaloneKeybindingService.addDynamicKeybinding(uniqueId, kb, run, keybindingsWhen));
      }
    }
    const internalAction = new InternalEditorAction(uniqueId, label, label, precondition, (...args) => Promise.resolve(_descriptor.run(this, ...args)), this._contextKeyService);
    this._actions.set(id3, internalAction);
    toDispose.add(toDisposable(() => {
      this._actions.delete(id3);
    }));
    return toDispose;
  }
  _triggerCommand(handlerId, payload) {
    if (this._codeEditorService instanceof StandaloneCodeEditorService) {
      try {
        this._codeEditorService.setActiveCodeEditor(this);
        super._triggerCommand(handlerId, payload);
      } finally {
        this._codeEditorService.setActiveCodeEditor(null);
      }
    } else {
      super._triggerCommand(handlerId, payload);
    }
  }
};
StandaloneCodeEditor = __decorate([
  __param(2, IInstantiationService),
  __param(3, ICodeEditorService),
  __param(4, ICommandService),
  __param(5, IContextKeyService),
  __param(6, IKeybindingService),
  __param(7, IThemeService),
  __param(8, INotificationService),
  __param(9, IAccessibilityService),
  __param(10, ILanguageConfigurationService),
  __param(11, ILanguageFeaturesService)
], StandaloneCodeEditor);
let StandaloneEditor = class StandaloneEditor2 extends StandaloneCodeEditor {
  constructor(domElement, _options, instantiationService, codeEditorService, commandService, contextKeyService, keybindingService, themeService, notificationService, configurationService, accessibilityService, modelService, languageService, languageConfigurationService, languageFeaturesService) {
    const options = Object.assign({}, _options);
    updateConfigurationService(configurationService, options, false);
    const themeDomRegistration = themeService.registerEditorContainer(domElement);
    if (typeof options.theme === "string") {
      themeService.setTheme(options.theme);
    }
    if (typeof options.autoDetectHighContrast !== "undefined") {
      themeService.setAutoDetectHighContrast(Boolean(options.autoDetectHighContrast));
    }
    const _model = options.model;
    delete options.model;
    super(domElement, options, instantiationService, codeEditorService, commandService, contextKeyService, keybindingService, themeService, notificationService, accessibilityService, languageConfigurationService, languageFeaturesService);
    this._configurationService = configurationService;
    this._standaloneThemeService = themeService;
    this._register(themeDomRegistration);
    let model;
    if (typeof _model === "undefined") {
      const languageId = languageService.getLanguageIdByMimeType(options.language) || options.language || PLAINTEXT_LANGUAGE_ID;
      model = createTextModel(modelService, languageService, options.value || "", languageId, void 0);
      this._ownsModel = true;
    } else {
      model = _model;
      this._ownsModel = false;
    }
    this._attachModel(model);
    if (model) {
      const e = {
        oldModelUrl: null,
        newModelUrl: model.uri
      };
      this._onDidChangeModel.fire(e);
    }
  }
  dispose() {
    super.dispose();
  }
  updateOptions(newOptions) {
    updateConfigurationService(this._configurationService, newOptions, false);
    if (typeof newOptions.theme === "string") {
      this._standaloneThemeService.setTheme(newOptions.theme);
    }
    if (typeof newOptions.autoDetectHighContrast !== "undefined") {
      this._standaloneThemeService.setAutoDetectHighContrast(Boolean(newOptions.autoDetectHighContrast));
    }
    super.updateOptions(newOptions);
  }
  _postDetachModelCleanup(detachedModel) {
    super._postDetachModelCleanup(detachedModel);
    if (detachedModel && this._ownsModel) {
      detachedModel.dispose();
      this._ownsModel = false;
    }
  }
};
StandaloneEditor = __decorate([
  __param(2, IInstantiationService),
  __param(3, ICodeEditorService),
  __param(4, ICommandService),
  __param(5, IContextKeyService),
  __param(6, IKeybindingService),
  __param(7, IStandaloneThemeService),
  __param(8, INotificationService),
  __param(9, IConfigurationService),
  __param(10, IAccessibilityService),
  __param(11, IModelService),
  __param(12, ILanguageService),
  __param(13, ILanguageConfigurationService),
  __param(14, ILanguageFeaturesService)
], StandaloneEditor);
let StandaloneDiffEditor = class StandaloneDiffEditor2 extends DiffEditorWidget {
  constructor(domElement, _options, instantiationService, contextKeyService, codeEditorService, themeService, notificationService, configurationService, contextMenuService, editorProgressService, clipboardService) {
    const options = Object.assign({}, _options);
    updateConfigurationService(configurationService, options, true);
    const themeDomRegistration = themeService.registerEditorContainer(domElement);
    if (typeof options.theme === "string") {
      themeService.setTheme(options.theme);
    }
    if (typeof options.autoDetectHighContrast !== "undefined") {
      themeService.setAutoDetectHighContrast(Boolean(options.autoDetectHighContrast));
    }
    super(domElement, options, {}, clipboardService, contextKeyService, instantiationService, codeEditorService, themeService, notificationService, contextMenuService, editorProgressService);
    this._configurationService = configurationService;
    this._standaloneThemeService = themeService;
    this._register(themeDomRegistration);
  }
  dispose() {
    super.dispose();
  }
  updateOptions(newOptions) {
    updateConfigurationService(this._configurationService, newOptions, true);
    if (typeof newOptions.theme === "string") {
      this._standaloneThemeService.setTheme(newOptions.theme);
    }
    if (typeof newOptions.autoDetectHighContrast !== "undefined") {
      this._standaloneThemeService.setAutoDetectHighContrast(Boolean(newOptions.autoDetectHighContrast));
    }
    super.updateOptions(newOptions);
  }
  _createInnerEditor(instantiationService, container2, options) {
    return instantiationService.createInstance(StandaloneCodeEditor, container2, options);
  }
  getOriginalEditor() {
    return super.getOriginalEditor();
  }
  getModifiedEditor() {
    return super.getModifiedEditor();
  }
  addCommand(keybinding, handler, context) {
    return this.getModifiedEditor().addCommand(keybinding, handler, context);
  }
  createContextKey(key, defaultValue) {
    return this.getModifiedEditor().createContextKey(key, defaultValue);
  }
  addAction(descriptor) {
    return this.getModifiedEditor().addAction(descriptor);
  }
};
StandaloneDiffEditor = __decorate([
  __param(2, IInstantiationService),
  __param(3, IContextKeyService),
  __param(4, ICodeEditorService),
  __param(5, IStandaloneThemeService),
  __param(6, INotificationService),
  __param(7, IConfigurationService),
  __param(8, IContextMenuService),
  __param(9, IEditorProgressService),
  __param(10, IClipboardService)
], StandaloneDiffEditor);
let StandaloneDiffEditor22 = class StandaloneDiffEditor23 extends DiffEditorWidget22 {
  constructor(domElement, _options, instantiationService, contextKeyService, codeEditorService, themeService, notificationService, configurationService, contextMenuService, editorProgressService, clipboardService, audioCueService) {
    const options = Object.assign({}, _options);
    updateConfigurationService(configurationService, options, true);
    const themeDomRegistration = themeService.registerEditorContainer(domElement);
    if (typeof options.theme === "string") {
      themeService.setTheme(options.theme);
    }
    if (typeof options.autoDetectHighContrast !== "undefined") {
      themeService.setAutoDetectHighContrast(Boolean(options.autoDetectHighContrast));
    }
    super(domElement, options, {}, contextKeyService, instantiationService, codeEditorService, audioCueService);
    this._configurationService = configurationService;
    this._standaloneThemeService = themeService;
    this._register(themeDomRegistration);
  }
  dispose() {
    super.dispose();
  }
  updateOptions(newOptions) {
    updateConfigurationService(this._configurationService, newOptions, true);
    if (typeof newOptions.theme === "string") {
      this._standaloneThemeService.setTheme(newOptions.theme);
    }
    if (typeof newOptions.autoDetectHighContrast !== "undefined") {
      this._standaloneThemeService.setAutoDetectHighContrast(Boolean(newOptions.autoDetectHighContrast));
    }
    super.updateOptions(newOptions);
  }
  _createInnerEditor(instantiationService, container2, options) {
    return instantiationService.createInstance(StandaloneCodeEditor, container2, options);
  }
  getOriginalEditor() {
    return super.getOriginalEditor();
  }
  getModifiedEditor() {
    return super.getModifiedEditor();
  }
  addCommand(keybinding, handler, context) {
    return this.getModifiedEditor().addCommand(keybinding, handler, context);
  }
  createContextKey(key, defaultValue) {
    return this.getModifiedEditor().createContextKey(key, defaultValue);
  }
  addAction(descriptor) {
    return this.getModifiedEditor().addAction(descriptor);
  }
};
StandaloneDiffEditor22 = __decorate([
  __param(2, IInstantiationService),
  __param(3, IContextKeyService),
  __param(4, ICodeEditorService),
  __param(5, IStandaloneThemeService),
  __param(6, INotificationService),
  __param(7, IConfigurationService),
  __param(8, IContextMenuService),
  __param(9, IEditorProgressService),
  __param(10, IClipboardService),
  __param(11, IAudioCueService)
], StandaloneDiffEditor22);
function createTextModel(modelService, languageService, value, languageId, uri) {
  value = value || "";
  if (!languageId) {
    const firstLF = value.indexOf("\n");
    let firstLine = value;
    if (firstLF !== -1) {
      firstLine = value.substring(0, firstLF);
    }
    return doCreateModel(modelService, value, languageService.createByFilepathOrFirstLine(uri || null, firstLine), uri);
  }
  return doCreateModel(modelService, value, languageService.createById(languageId), uri);
}
function doCreateModel(modelService, value, languageSelection, uri) {
  return modelService.createModel(value, languageSelection, uri);
}
var __awaiter$1 = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
function create(domElement, options, override) {
  const instantiationService = StandaloneServices.initialize(override || {});
  return instantiationService.createInstance(StandaloneEditor, domElement, options);
}
function onDidCreateEditor(listener) {
  const codeEditorService = StandaloneServices.get(ICodeEditorService);
  return codeEditorService.onCodeEditorAdd((editor2) => {
    listener(editor2);
  });
}
function onDidCreateDiffEditor(listener) {
  const codeEditorService = StandaloneServices.get(ICodeEditorService);
  return codeEditorService.onDiffEditorAdd((editor2) => {
    listener(editor2);
  });
}
function getEditors() {
  const codeEditorService = StandaloneServices.get(ICodeEditorService);
  return codeEditorService.listCodeEditors();
}
function getDiffEditors() {
  const codeEditorService = StandaloneServices.get(ICodeEditorService);
  return codeEditorService.listDiffEditors();
}
function createDiffEditor(domElement, options, override) {
  var _a2;
  const instantiationService = StandaloneServices.initialize(override || {});
  if ((_a2 = options === null || options === void 0 ? void 0 : options.experimental) === null || _a2 === void 0 ? void 0 : _a2.useVersion2) {
    return instantiationService.createInstance(StandaloneDiffEditor22, domElement, options);
  }
  return instantiationService.createInstance(StandaloneDiffEditor, domElement, options);
}
function createDiffNavigator(diffEditor2, opts) {
  const instantiationService = StandaloneServices.initialize({});
  return instantiationService.createInstance(DiffNavigator, diffEditor2, opts);
}
function addCommand(descriptor) {
  if (typeof descriptor.id !== "string" || typeof descriptor.run !== "function") {
    throw new Error("Invalid command descriptor, `id` and `run` are required properties!");
  }
  return CommandsRegistry.registerCommand(descriptor.id, descriptor.run);
}
function addEditorAction(descriptor) {
  if (typeof descriptor.id !== "string" || typeof descriptor.label !== "string" || typeof descriptor.run !== "function") {
    throw new Error("Invalid action descriptor, `id`, `label` and `run` are required properties!");
  }
  const precondition = ContextKeyExpr.deserialize(descriptor.precondition);
  const run = (accessor, ...args) => {
    return EditorCommand.runEditorCommand(accessor, args, precondition, (accessor2, editor2, args2) => Promise.resolve(descriptor.run(editor2, ...args2)));
  };
  const toDispose = new DisposableStore();
  toDispose.add(CommandsRegistry.registerCommand(descriptor.id, run));
  if (descriptor.contextMenuGroupId) {
    const menuItem = {
      command: {
        id: descriptor.id,
        title: descriptor.label
      },
      when: precondition,
      group: descriptor.contextMenuGroupId,
      order: descriptor.contextMenuOrder || 0
    };
    toDispose.add(MenuRegistry.appendMenuItem(MenuId.EditorContext, menuItem));
  }
  if (Array.isArray(descriptor.keybindings)) {
    const keybindingService = StandaloneServices.get(IKeybindingService);
    if (!(keybindingService instanceof StandaloneKeybindingService)) {
      console.warn("Cannot add keybinding because the editor is configured with an unrecognized KeybindingService");
    } else {
      const keybindingsWhen = ContextKeyExpr.and(precondition, ContextKeyExpr.deserialize(descriptor.keybindingContext));
      toDispose.add(keybindingService.addDynamicKeybindings(descriptor.keybindings.map((keybinding) => {
        return {
          keybinding,
          command: descriptor.id,
          when: keybindingsWhen
        };
      })));
    }
  }
  return toDispose;
}
function addKeybindingRule(rule2) {
  return addKeybindingRules([rule2]);
}
function addKeybindingRules(rules) {
  const keybindingService = StandaloneServices.get(IKeybindingService);
  if (!(keybindingService instanceof StandaloneKeybindingService)) {
    console.warn("Cannot add keybinding because the editor is configured with an unrecognized KeybindingService");
    return Disposable.None;
  }
  return keybindingService.addDynamicKeybindings(rules.map((rule2) => {
    return {
      keybinding: rule2.keybinding,
      command: rule2.command,
      commandArgs: rule2.commandArgs,
      when: ContextKeyExpr.deserialize(rule2.when)
    };
  }));
}
function createModel(value, language2, uri) {
  const languageService = StandaloneServices.get(ILanguageService);
  const languageId = languageService.getLanguageIdByMimeType(language2) || language2;
  return createTextModel(StandaloneServices.get(IModelService), languageService, value, languageId, uri);
}
function setModelLanguage(model, mimeTypeOrLanguageId) {
  const languageService = StandaloneServices.get(ILanguageService);
  const languageId = languageService.getLanguageIdByMimeType(mimeTypeOrLanguageId) || mimeTypeOrLanguageId || PLAINTEXT_LANGUAGE_ID;
  model.setLanguage(languageService.createById(languageId));
}
function setModelMarkers(model, owner, markers) {
  if (model) {
    const markerService = StandaloneServices.get(IMarkerService);
    markerService.changeOne(owner, model.uri, markers);
  }
}
function removeAllMarkers(owner) {
  const markerService = StandaloneServices.get(IMarkerService);
  markerService.changeAll(owner, []);
}
function getModelMarkers(filter2) {
  const markerService = StandaloneServices.get(IMarkerService);
  return markerService.read(filter2);
}
function onDidChangeMarkers(listener) {
  const markerService = StandaloneServices.get(IMarkerService);
  return markerService.onMarkerChanged(listener);
}
function getModel(uri) {
  const modelService = StandaloneServices.get(IModelService);
  return modelService.getModel(uri);
}
function getModels() {
  const modelService = StandaloneServices.get(IModelService);
  return modelService.getModels();
}
function onDidCreateModel(listener) {
  const modelService = StandaloneServices.get(IModelService);
  return modelService.onModelAdded(listener);
}
function onWillDisposeModel(listener) {
  const modelService = StandaloneServices.get(IModelService);
  return modelService.onModelRemoved(listener);
}
function onDidChangeModelLanguage(listener) {
  const modelService = StandaloneServices.get(IModelService);
  return modelService.onModelLanguageChanged((e) => {
    listener({
      model: e.model,
      oldLanguage: e.oldLanguageId
    });
  });
}
function createWebWorker(opts) {
  return createWebWorker$1(StandaloneServices.get(IModelService), StandaloneServices.get(ILanguageConfigurationService), opts);
}
function colorizeElement(domNode, options) {
  const languageService = StandaloneServices.get(ILanguageService);
  const themeService = StandaloneServices.get(IStandaloneThemeService);
  themeService.registerEditorContainer(domNode);
  return Colorizer.colorizeElement(themeService, languageService, domNode, options);
}
function colorize(text2, languageId, options) {
  const languageService = StandaloneServices.get(ILanguageService);
  const themeService = StandaloneServices.get(IStandaloneThemeService);
  themeService.registerEditorContainer(document.body);
  return Colorizer.colorize(languageService, text2, languageId, options);
}
function colorizeModelLine(model, lineNumber, tabSize = 4) {
  const themeService = StandaloneServices.get(IStandaloneThemeService);
  themeService.registerEditorContainer(document.body);
  return Colorizer.colorizeModelLine(model, lineNumber, tabSize);
}
function getSafeTokenizationSupport(language2) {
  const tokenizationSupport = TokenizationRegistry2.get(language2);
  if (tokenizationSupport) {
    return tokenizationSupport;
  }
  return {
    getInitialState: () => NullState,
    tokenize: (line, hasEOL, state) => nullTokenize(language2, state)
  };
}
function tokenize$2(text2, languageId) {
  TokenizationRegistry2.getOrCreate(languageId);
  const tokenizationSupport = getSafeTokenizationSupport(languageId);
  const lines = splitLines(text2);
  const result2 = [];
  let state = tokenizationSupport.getInitialState();
  for (let i = 0, len = lines.length; i < len; i++) {
    const line = lines[i];
    const tokenizationResult = tokenizationSupport.tokenize(line, true, state);
    result2[i] = tokenizationResult.tokens;
    state = tokenizationResult.endState;
  }
  return result2;
}
function defineTheme(themeName, themeData) {
  const standaloneThemeService = StandaloneServices.get(IStandaloneThemeService);
  standaloneThemeService.defineTheme(themeName, themeData);
}
function setTheme(themeName) {
  const standaloneThemeService = StandaloneServices.get(IStandaloneThemeService);
  standaloneThemeService.setTheme(themeName);
}
function remeasureFonts() {
  FontMeasurements.clearAllFontInfos();
}
function registerCommand(id3, handler) {
  return CommandsRegistry.registerCommand({ id: id3, handler });
}
function registerLinkOpener(opener) {
  const openerService = StandaloneServices.get(IOpenerService);
  return openerService.registerOpener({
    open(resource) {
      return __awaiter$1(this, void 0, void 0, function* () {
        if (typeof resource === "string") {
          resource = URI.parse(resource);
        }
        return opener.open(resource);
      });
    }
  });
}
function registerEditorOpener(opener) {
  const codeEditorService = StandaloneServices.get(ICodeEditorService);
  return codeEditorService.registerCodeEditorOpenHandler((input2, source, sideBySide) => __awaiter$1(this, void 0, void 0, function* () {
    var _a2;
    if (!source) {
      return null;
    }
    const selection = (_a2 = input2.options) === null || _a2 === void 0 ? void 0 : _a2.selection;
    let selectionOrPosition;
    if (selection && typeof selection.endLineNumber === "number" && typeof selection.endColumn === "number") {
      selectionOrPosition = selection;
    } else if (selection) {
      selectionOrPosition = { lineNumber: selection.startLineNumber, column: selection.startColumn };
    }
    if (yield opener.openCodeEditor(source, input2.resource, selectionOrPosition)) {
      return source;
    }
    return null;
  }));
}
function createMonacoEditorAPI() {
  return {
    // methods
    create,
    getEditors,
    getDiffEditors,
    onDidCreateEditor,
    onDidCreateDiffEditor,
    createDiffEditor,
    createDiffNavigator,
    addCommand,
    addEditorAction,
    addKeybindingRule,
    addKeybindingRules,
    createModel,
    setModelLanguage,
    setModelMarkers,
    getModelMarkers,
    removeAllMarkers,
    onDidChangeMarkers,
    getModels,
    getModel,
    onDidCreateModel,
    onWillDisposeModel,
    onDidChangeModelLanguage,
    createWebWorker,
    colorizeElement,
    colorize,
    colorizeModelLine,
    tokenize: tokenize$2,
    defineTheme,
    setTheme,
    remeasureFonts,
    registerCommand,
    registerLinkOpener,
    registerEditorOpener,
    // enums
    AccessibilitySupport,
    ContentWidgetPositionPreference,
    CursorChangeReason,
    DefaultEndOfLine,
    EditorAutoIndentStrategy,
    EditorOption,
    EndOfLinePreference,
    EndOfLineSequence,
    MinimapPosition,
    MouseTargetType,
    OverlayWidgetPositionPreference,
    OverviewRulerLane,
    GlyphMarginLane,
    RenderLineNumbersType,
    RenderMinimap,
    ScrollbarVisibility,
    ScrollType,
    TextEditorCursorBlinkingStyle,
    TextEditorCursorStyle,
    TrackedRangeStickiness,
    WrappingIndent,
    InjectedTextCursorStops,
    PositionAffinity,
    // classes
    ConfigurationChangedEvent,
    BareFontInfo,
    FontInfo,
    TextModelResolvedOptions,
    FindMatch,
    ApplyUpdateResult,
    LineRange: LineRange2,
    LineRangeMapping,
    RangeMapping,
    EditorZoom,
    MovedText,
    SimpleLineRangeMapping,
    // vars
    EditorType,
    EditorOptions
  };
}
function isArrayOf(elemType, obj) {
  if (!obj) {
    return false;
  }
  if (!Array.isArray(obj)) {
    return false;
  }
  for (const el of obj) {
    if (!elemType(el)) {
      return false;
    }
  }
  return true;
}
function bool(prop, defValue) {
  if (typeof prop === "boolean") {
    return prop;
  }
  return defValue;
}
function string$2(prop, defValue) {
  if (typeof prop === "string") {
    return prop;
  }
  return defValue;
}
function arrayToHash$1(array2) {
  const result2 = {};
  for (const e of array2) {
    result2[e] = true;
  }
  return result2;
}
function createKeywordMatcher(arr, caseInsensitive = false) {
  if (caseInsensitive) {
    arr = arr.map(function(x) {
      return x.toLowerCase();
    });
  }
  const hash2 = arrayToHash$1(arr);
  if (caseInsensitive) {
    return function(word2) {
      return hash2[word2.toLowerCase()] !== void 0 && hash2.hasOwnProperty(word2.toLowerCase());
    };
  } else {
    return function(word2) {
      return hash2[word2] !== void 0 && hash2.hasOwnProperty(word2);
    };
  }
}
function compileRegExp(lexer, str2) {
  str2 = str2.replace(/@@/g, ``);
  let n2 = 0;
  let hadExpansion;
  do {
    hadExpansion = false;
    str2 = str2.replace(/@(\w+)/g, function(s, attr) {
      hadExpansion = true;
      let sub = "";
      if (typeof lexer[attr] === "string") {
        sub = lexer[attr];
      } else if (lexer[attr] && lexer[attr] instanceof RegExp) {
        sub = lexer[attr].source;
      } else {
        if (lexer[attr] === void 0) {
          throw createError(lexer, "language definition does not contain attribute '" + attr + "', used at: " + str2);
        } else {
          throw createError(lexer, "attribute reference '" + attr + "' must be a string, used at: " + str2);
        }
      }
      return empty(sub) ? "" : "(?:" + sub + ")";
    });
    n2++;
  } while (hadExpansion && n2 < 5);
  str2 = str2.replace(/\x01/g, "@");
  const flags = (lexer.ignoreCase ? "i" : "") + (lexer.unicode ? "u" : "");
  return new RegExp(str2, flags);
}
function selectScrutinee(id3, matches, state, num) {
  if (num < 0) {
    return id3;
  }
  if (num < matches.length) {
    return matches[num];
  }
  if (num >= 100) {
    num = num - 100;
    const parts = state.split(".");
    parts.unshift(state);
    if (num < parts.length) {
      return parts[num];
    }
  }
  return null;
}
function createGuard(lexer, ruleName, tkey, val) {
  let scrut = -1;
  let oppat = tkey;
  let matches = tkey.match(/^\$(([sS]?)(\d\d?)|#)(.*)$/);
  if (matches) {
    if (matches[3]) {
      scrut = parseInt(matches[3]);
      if (matches[2]) {
        scrut = scrut + 100;
      }
    }
    oppat = matches[4];
  }
  let op = "~";
  let pat = oppat;
  if (!oppat || oppat.length === 0) {
    op = "!=";
    pat = "";
  } else if (/^\w*$/.test(pat)) {
    op = "==";
  } else {
    matches = oppat.match(/^(@|!@|~|!~|==|!=)(.*)$/);
    if (matches) {
      op = matches[1];
      pat = matches[2];
    }
  }
  let tester;
  if ((op === "~" || op === "!~") && /^(\w|\|)*$/.test(pat)) {
    const inWords = createKeywordMatcher(pat.split("|"), lexer.ignoreCase);
    tester = function(s) {
      return op === "~" ? inWords(s) : !inWords(s);
    };
  } else if (op === "@" || op === "!@") {
    const words = lexer[pat];
    if (!words) {
      throw createError(lexer, "the @ match target '" + pat + "' is not defined, in rule: " + ruleName);
    }
    if (!isArrayOf(function(elem) {
      return typeof elem === "string";
    }, words)) {
      throw createError(lexer, "the @ match target '" + pat + "' must be an array of strings, in rule: " + ruleName);
    }
    const inWords = createKeywordMatcher(words, lexer.ignoreCase);
    tester = function(s) {
      return op === "@" ? inWords(s) : !inWords(s);
    };
  } else if (op === "~" || op === "!~") {
    if (pat.indexOf("$") < 0) {
      const re = compileRegExp(lexer, "^" + pat + "$");
      tester = function(s) {
        return op === "~" ? re.test(s) : !re.test(s);
      };
    } else {
      tester = function(s, id3, matches2, state) {
        const re = compileRegExp(lexer, "^" + substituteMatches(lexer, pat, id3, matches2, state) + "$");
        return re.test(s);
      };
    }
  } else {
    if (pat.indexOf("$") < 0) {
      const patx = fixCase(lexer, pat);
      tester = function(s) {
        return op === "==" ? s === patx : s !== patx;
      };
    } else {
      const patx = fixCase(lexer, pat);
      tester = function(s, id3, matches2, state, eos) {
        const patexp = substituteMatches(lexer, patx, id3, matches2, state);
        return op === "==" ? s === patexp : s !== patexp;
      };
    }
  }
  if (scrut === -1) {
    return {
      name: tkey,
      value: val,
      test: function(id3, matches2, state, eos) {
        return tester(id3, id3, matches2, state, eos);
      }
    };
  } else {
    return {
      name: tkey,
      value: val,
      test: function(id3, matches2, state, eos) {
        const scrutinee = selectScrutinee(id3, matches2, state, scrut);
        return tester(!scrutinee ? "" : scrutinee, id3, matches2, state, eos);
      }
    };
  }
}
function compileAction(lexer, ruleName, action) {
  if (!action) {
    return { token: "" };
  } else if (typeof action === "string") {
    return action;
  } else if (action.token || action.token === "") {
    if (typeof action.token !== "string") {
      throw createError(lexer, "a 'token' attribute must be of type string, in rule: " + ruleName);
    } else {
      const newAction = { token: action.token };
      if (action.token.indexOf("$") >= 0) {
        newAction.tokenSubst = true;
      }
      if (typeof action.bracket === "string") {
        if (action.bracket === "@open") {
          newAction.bracket = 1;
        } else if (action.bracket === "@close") {
          newAction.bracket = -1;
        } else {
          throw createError(lexer, "a 'bracket' attribute must be either '@open' or '@close', in rule: " + ruleName);
        }
      }
      if (action.next) {
        if (typeof action.next !== "string") {
          throw createError(lexer, "the next state must be a string value in rule: " + ruleName);
        } else {
          let next = action.next;
          if (!/^(@pop|@push|@popall)$/.test(next)) {
            if (next[0] === "@") {
              next = next.substr(1);
            }
            if (next.indexOf("$") < 0) {
              if (!stateExists(lexer, substituteMatches(lexer, next, "", [], ""))) {
                throw createError(lexer, "the next state '" + action.next + "' is not defined in rule: " + ruleName);
              }
            }
          }
          newAction.next = next;
        }
      }
      if (typeof action.goBack === "number") {
        newAction.goBack = action.goBack;
      }
      if (typeof action.switchTo === "string") {
        newAction.switchTo = action.switchTo;
      }
      if (typeof action.log === "string") {
        newAction.log = action.log;
      }
      if (typeof action.nextEmbedded === "string") {
        newAction.nextEmbedded = action.nextEmbedded;
        lexer.usesEmbedded = true;
      }
      return newAction;
    }
  } else if (Array.isArray(action)) {
    const results = [];
    for (let i = 0, len = action.length; i < len; i++) {
      results[i] = compileAction(lexer, ruleName, action[i]);
    }
    return { group: results };
  } else if (action.cases) {
    const cases = [];
    for (const tkey in action.cases) {
      if (action.cases.hasOwnProperty(tkey)) {
        const val = compileAction(lexer, ruleName, action.cases[tkey]);
        if (tkey === "@default" || tkey === "@" || tkey === "") {
          cases.push({ test: void 0, value: val, name: tkey });
        } else if (tkey === "@eos") {
          cases.push({ test: function(id3, matches, state, eos) {
            return eos;
          }, value: val, name: tkey });
        } else {
          cases.push(createGuard(lexer, ruleName, tkey, val));
        }
      }
    }
    const def2 = lexer.defaultToken;
    return {
      test: function(id3, matches, state, eos) {
        for (const _case of cases) {
          const didmatch = !_case.test || _case.test(id3, matches, state, eos);
          if (didmatch) {
            return _case.value;
          }
        }
        return def2;
      }
    };
  } else {
    throw createError(lexer, "an action must be a string, an object with a 'token' or 'cases' attribute, or an array of actions; in rule: " + ruleName);
  }
}
let Rule$5 = class Rule {
  constructor(name) {
    this.regex = new RegExp("");
    this.action = { token: "" };
    this.matchOnlyAtLineStart = false;
    this.name = "";
    this.name = name;
  }
  setRegex(lexer, re) {
    let sregex;
    if (typeof re === "string") {
      sregex = re;
    } else if (re instanceof RegExp) {
      sregex = re.source;
    } else {
      throw createError(lexer, "rules must start with a match string or regular expression: " + this.name);
    }
    this.matchOnlyAtLineStart = sregex.length > 0 && sregex[0] === "^";
    this.name = this.name + ": " + sregex;
    this.regex = compileRegExp(lexer, "^(?:" + (this.matchOnlyAtLineStart ? sregex.substr(1) : sregex) + ")");
  }
  setAction(lexer, act) {
    this.action = compileAction(lexer, this.name, act);
  }
};
function compile(languageId, json) {
  if (!json || typeof json !== "object") {
    throw new Error("Monarch: expecting a language definition object");
  }
  const lexer = {};
  lexer.languageId = languageId;
  lexer.includeLF = bool(json.includeLF, false);
  lexer.noThrow = false;
  lexer.maxStack = 100;
  lexer.start = typeof json.start === "string" ? json.start : null;
  lexer.ignoreCase = bool(json.ignoreCase, false);
  lexer.unicode = bool(json.unicode, false);
  lexer.tokenPostfix = string$2(json.tokenPostfix, "." + lexer.languageId);
  lexer.defaultToken = string$2(json.defaultToken, "source");
  lexer.usesEmbedded = false;
  const lexerMin = json;
  lexerMin.languageId = languageId;
  lexerMin.includeLF = lexer.includeLF;
  lexerMin.ignoreCase = lexer.ignoreCase;
  lexerMin.unicode = lexer.unicode;
  lexerMin.noThrow = lexer.noThrow;
  lexerMin.usesEmbedded = lexer.usesEmbedded;
  lexerMin.stateNames = json.tokenizer;
  lexerMin.defaultToken = lexer.defaultToken;
  function addRules(state, newrules, rules) {
    for (const rule2 of rules) {
      let include = rule2.include;
      if (include) {
        if (typeof include !== "string") {
          throw createError(lexer, "an 'include' attribute must be a string at: " + state);
        }
        if (include[0] === "@") {
          include = include.substr(1);
        }
        if (!json.tokenizer[include]) {
          throw createError(lexer, "include target '" + include + "' is not defined at: " + state);
        }
        addRules(state + "." + include, newrules, json.tokenizer[include]);
      } else {
        const newrule = new Rule$5(state);
        if (Array.isArray(rule2) && rule2.length >= 1 && rule2.length <= 3) {
          newrule.setRegex(lexerMin, rule2[0]);
          if (rule2.length >= 3) {
            if (typeof rule2[1] === "string") {
              newrule.setAction(lexerMin, { token: rule2[1], next: rule2[2] });
            } else if (typeof rule2[1] === "object") {
              const rule1 = rule2[1];
              rule1.next = rule2[2];
              newrule.setAction(lexerMin, rule1);
            } else {
              throw createError(lexer, "a next state as the last element of a rule can only be given if the action is either an object or a string, at: " + state);
            }
          } else {
            newrule.setAction(lexerMin, rule2[1]);
          }
        } else {
          if (!rule2.regex) {
            throw createError(lexer, "a rule must either be an array, or an object with a 'regex' or 'include' field at: " + state);
          }
          if (rule2.name) {
            if (typeof rule2.name === "string") {
              newrule.name = rule2.name;
            }
          }
          if (rule2.matchOnlyAtStart) {
            newrule.matchOnlyAtLineStart = bool(rule2.matchOnlyAtLineStart, false);
          }
          newrule.setRegex(lexerMin, rule2.regex);
          newrule.setAction(lexerMin, rule2.action);
        }
        newrules.push(newrule);
      }
    }
  }
  if (!json.tokenizer || typeof json.tokenizer !== "object") {
    throw createError(lexer, "a language definition must define the 'tokenizer' attribute as an object");
  }
  lexer.tokenizer = [];
  for (const key in json.tokenizer) {
    if (json.tokenizer.hasOwnProperty(key)) {
      if (!lexer.start) {
        lexer.start = key;
      }
      const rules = json.tokenizer[key];
      lexer.tokenizer[key] = new Array();
      addRules("tokenizer." + key, lexer.tokenizer[key], rules);
    }
  }
  lexer.usesEmbedded = lexerMin.usesEmbedded;
  if (json.brackets) {
    if (!Array.isArray(json.brackets)) {
      throw createError(lexer, "the 'brackets' attribute must be defined as an array");
    }
  } else {
    json.brackets = [
      { open: "{", close: "}", token: "delimiter.curly" },
      { open: "[", close: "]", token: "delimiter.square" },
      { open: "(", close: ")", token: "delimiter.parenthesis" },
      { open: "<", close: ">", token: "delimiter.angle" }
    ];
  }
  const brackets = [];
  for (const el of json.brackets) {
    let desc = el;
    if (desc && Array.isArray(desc) && desc.length === 3) {
      desc = { token: desc[2], open: desc[0], close: desc[1] };
    }
    if (desc.open === desc.close) {
      throw createError(lexer, "open and close brackets in a 'brackets' attribute must be different: " + desc.open + "\n hint: use the 'bracket' attribute if matching on equal brackets is required.");
    }
    if (typeof desc.open === "string" && typeof desc.token === "string" && typeof desc.close === "string") {
      brackets.push({
        token: desc.token + lexer.tokenPostfix,
        open: fixCase(lexer, desc.open),
        close: fixCase(lexer, desc.close)
      });
    } else {
      throw createError(lexer, "every element in the 'brackets' array must be a '{open,close,token}' object or array");
    }
  }
  lexer.brackets = brackets;
  lexer.noThrow = true;
  return lexer;
}
var __awaiter = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve2) {
      resolve2(value);
    });
  }
  return new (P || (P = Promise))(function(resolve2, 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(result2) {
      result2.done ? resolve2(result2.value) : adopt(result2.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
function register(language2) {
  ModesRegistry.registerLanguage(language2);
}
function getLanguages() {
  let result2 = [];
  result2 = result2.concat(ModesRegistry.getLanguages());
  return result2;
}
function getEncodedLanguageId(languageId) {
  const languageService = StandaloneServices.get(ILanguageService);
  return languageService.languageIdCodec.encodeLanguageId(languageId);
}
function onLanguage(languageId, callback) {
  return StandaloneServices.withServices(() => {
    const languageService = StandaloneServices.get(ILanguageService);
    const disposable = languageService.onDidRequestRichLanguageFeatures((encounteredLanguageId) => {
      if (encounteredLanguageId === languageId) {
        disposable.dispose();
        callback();
      }
    });
    return disposable;
  });
}
function onLanguageEncountered(languageId, callback) {
  return StandaloneServices.withServices(() => {
    const languageService = StandaloneServices.get(ILanguageService);
    const disposable = languageService.onDidRequestBasicLanguageFeatures((encounteredLanguageId) => {
      if (encounteredLanguageId === languageId) {
        disposable.dispose();
        callback();
      }
    });
    return disposable;
  });
}
function setLanguageConfiguration(languageId, configuration) {
  const languageService = StandaloneServices.get(ILanguageService);
  if (!languageService.isRegisteredLanguageId(languageId)) {
    throw new Error(`Cannot set configuration for unknown language ${languageId}`);
  }
  const languageConfigurationService = StandaloneServices.get(ILanguageConfigurationService);
  return languageConfigurationService.register(languageId, configuration, 100);
}
class EncodedTokenizationSupportAdapter {
  constructor(languageId, actual) {
    this._languageId = languageId;
    this._actual = actual;
  }
  dispose() {
  }
  getInitialState() {
    return this._actual.getInitialState();
  }
  tokenize(line, hasEOL, state) {
    if (typeof this._actual.tokenize === "function") {
      return TokenizationSupportAdapter.adaptTokenize(this._languageId, this._actual, line, state);
    }
    throw new Error("Not supported!");
  }
  tokenizeEncoded(line, hasEOL, state) {
    const result2 = this._actual.tokenizeEncoded(line, state);
    return new EncodedTokenizationResult(result2.tokens, result2.endState);
  }
}
class TokenizationSupportAdapter {
  constructor(_languageId, _actual, _languageService, _standaloneThemeService) {
    this._languageId = _languageId;
    this._actual = _actual;
    this._languageService = _languageService;
    this._standaloneThemeService = _standaloneThemeService;
  }
  dispose() {
  }
  getInitialState() {
    return this._actual.getInitialState();
  }
  static _toClassicTokens(tokens, language2) {
    const result2 = [];
    let previousStartIndex = 0;
    for (let i = 0, len = tokens.length; i < len; i++) {
      const t = tokens[i];
      let startIndex = t.startIndex;
      if (i === 0) {
        startIndex = 0;
      } else if (startIndex < previousStartIndex) {
        startIndex = previousStartIndex;
      }
      result2[i] = new Token$3(startIndex, t.scopes, language2);
      previousStartIndex = startIndex;
    }
    return result2;
  }
  static adaptTokenize(language2, actual, line, state) {
    const actualResult = actual.tokenize(line, state);
    const tokens = TokenizationSupportAdapter._toClassicTokens(actualResult.tokens, language2);
    let endState;
    if (actualResult.endState.equals(state)) {
      endState = state;
    } else {
      endState = actualResult.endState;
    }
    return new TokenizationResult(tokens, endState);
  }
  tokenize(line, hasEOL, state) {
    return TokenizationSupportAdapter.adaptTokenize(this._languageId, this._actual, line, state);
  }
  _toBinaryTokens(languageIdCodec, tokens) {
    const languageId = languageIdCodec.encodeLanguageId(this._languageId);
    const tokenTheme = this._standaloneThemeService.getColorTheme().tokenTheme;
    const result2 = [];
    let resultLen = 0;
    let previousStartIndex = 0;
    for (let i = 0, len = tokens.length; i < len; i++) {
      const t = tokens[i];
      const metadata = tokenTheme.match(languageId, t.scopes) | 1024;
      if (resultLen > 0 && result2[resultLen - 1] === metadata) {
        continue;
      }
      let startIndex = t.startIndex;
      if (i === 0) {
        startIndex = 0;
      } else if (startIndex < previousStartIndex) {
        startIndex = previousStartIndex;
      }
      result2[resultLen++] = startIndex;
      result2[resultLen++] = metadata;
      previousStartIndex = startIndex;
    }
    const actualResult = new Uint32Array(resultLen);
    for (let i = 0; i < resultLen; i++) {
      actualResult[i] = result2[i];
    }
    return actualResult;
  }
  tokenizeEncoded(line, hasEOL, state) {
    const actualResult = this._actual.tokenize(line, state);
    const tokens = this._toBinaryTokens(this._languageService.languageIdCodec, actualResult.tokens);
    let endState;
    if (actualResult.endState.equals(state)) {
      endState = state;
    } else {
      endState = actualResult.endState;
    }
    return new EncodedTokenizationResult(tokens, endState);
  }
}
function isATokensProvider(provider) {
  return typeof provider.getInitialState === "function";
}
function isEncodedTokensProvider(provider) {
  return "tokenizeEncoded" in provider;
}
function isThenable(obj) {
  return obj && typeof obj.then === "function";
}
function setColorMap(colorMap) {
  const standaloneThemeService = StandaloneServices.get(IStandaloneThemeService);
  if (colorMap) {
    const result2 = [null];
    for (let i = 1, len = colorMap.length; i < len; i++) {
      result2[i] = Color.fromHex(colorMap[i]);
    }
    standaloneThemeService.setColorMapOverride(result2);
  } else {
    standaloneThemeService.setColorMapOverride(null);
  }
}
function createTokenizationSupportAdapter(languageId, provider) {
  if (isEncodedTokensProvider(provider)) {
    return new EncodedTokenizationSupportAdapter(languageId, provider);
  } else {
    return new TokenizationSupportAdapter(languageId, provider, StandaloneServices.get(ILanguageService), StandaloneServices.get(IStandaloneThemeService));
  }
}
function registerTokensProviderFactory(languageId, factory) {
  const adaptedFactory = new LazyTokenizationSupport(() => __awaiter(this, void 0, void 0, function* () {
    const result2 = yield Promise.resolve(factory.create());
    if (!result2) {
      return null;
    }
    if (isATokensProvider(result2)) {
      return createTokenizationSupportAdapter(languageId, result2);
    }
    return new MonarchTokenizer(StandaloneServices.get(ILanguageService), StandaloneServices.get(IStandaloneThemeService), languageId, compile(languageId, result2), StandaloneServices.get(IConfigurationService));
  }));
  return TokenizationRegistry2.registerFactory(languageId, adaptedFactory);
}
function setTokensProvider(languageId, provider) {
  const languageService = StandaloneServices.get(ILanguageService);
  if (!languageService.isRegisteredLanguageId(languageId)) {
    throw new Error(`Cannot set tokens provider for unknown language ${languageId}`);
  }
  if (isThenable(provider)) {
    return registerTokensProviderFactory(languageId, { create: () => provider });
  }
  return TokenizationRegistry2.register(languageId, createTokenizationSupportAdapter(languageId, provider));
}
function setMonarchTokensProvider(languageId, languageDef) {
  const create2 = (languageDef2) => {
    return new MonarchTokenizer(StandaloneServices.get(ILanguageService), StandaloneServices.get(IStandaloneThemeService), languageId, compile(languageId, languageDef2), StandaloneServices.get(IConfigurationService));
  };
  if (isThenable(languageDef)) {
    return registerTokensProviderFactory(languageId, { create: () => languageDef });
  }
  return TokenizationRegistry2.register(languageId, create2(languageDef));
}
function registerReferenceProvider(languageSelector, provider) {
  const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
  return languageFeaturesService.referenceProvider.register(languageSelector, provider);
}
function registerRenameProvider(languageSelector, provider) {
  const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
  return languageFeaturesService.renameProvider.register(languageSelector, provider);
}
function registerSignatureHelpProvider(languageSelector, provider) {
  const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
  return languageFeaturesService.signatureHelpProvider.register(languageSelector, provider);
}
function registerHoverProvider(languageSelector, provider) {
  const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
  return languageFeaturesService.hoverProvider.register(languageSelector, {
    provideHover: (model, position, token) => {
      const word2 = model.getWordAtPosition(position);
      return Promise.resolve(provider.provideHover(model, position, token)).then((value) => {
        if (!value) {
          return void 0;
        }
        if (!value.range && word2) {
          value.range = new Range$2(position.lineNumber, word2.startColumn, position.lineNumber, word2.endColumn);
        }
        if (!value.range) {
          value.range = new Range$2(position.lineNumber, position.column, position.lineNumber, position.column);
        }
        return value;
      });
    }
  });
}
function registerDocumentSymbolProvider(languageSelector, provider) {
  const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
  return languageFeaturesService.documentSymbolProvider.register(languageSelector, provider);
}
function registerDocumentHighlightProvider(languageSelector, provider) {
  const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
  return languageFeaturesService.documentHighlightProvider.register(languageSelector, provider);
}
function registerLinkedEditingRangeProvider(languageSelector, provider) {
  const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
  return languageFeaturesService.linkedEditingRangeProvider.register(languageSelector, provider);
}
function registerDefinitionProvider(languageSelector, provider) {
  const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
  return languageFeaturesService.definitionProvider.register(languageSelector, provider);
}
function registerImplementationProvider(languageSelector, provider) {
  const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
  return languageFeaturesService.implementationProvider.register(languageSelector, provider);
}
function registerTypeDefinitionProvider(languageSelector, provider) {
  const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
  return languageFeaturesService.typeDefinitionProvider.register(languageSelector, provider);
}
function registerCodeLensProvider(languageSelector, provider) {
  const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
  return languageFeaturesService.codeLensProvider.register(languageSelector, provider);
}
function registerCodeActionProvider(languageSelector, provider, metadata) {
  const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
  return languageFeaturesService.codeActionProvider.register(languageSelector, {
    providedCodeActionKinds: metadata === null || metadata === void 0 ? void 0 : metadata.providedCodeActionKinds,
    documentation: metadata === null || metadata === void 0 ? void 0 : metadata.documentation,
    provideCodeActions: (model, range2, context, token) => {
      const markerService = StandaloneServices.get(IMarkerService);
      const markers = markerService.read({ resource: model.uri }).filter((m) => {
        return Range$2.areIntersectingOrTouching(m, range2);
      });
      return provider.provideCodeActions(model, range2, { markers, only: context.only, trigger: context.trigger }, token);
    },
    resolveCodeAction: provider.resolveCodeAction
  });
}
function registerDocumentFormattingEditProvider(languageSelector, provider) {
  const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
  return languageFeaturesService.documentFormattingEditProvider.register(languageSelector, provider);
}
function registerDocumentRangeFormattingEditProvider(languageSelector, provider) {
  const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
  return languageFeaturesService.documentRangeFormattingEditProvider.register(languageSelector, provider);
}
function registerOnTypeFormattingEditProvider(languageSelector, provider) {
  const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
  return languageFeaturesService.onTypeFormattingEditProvider.register(languageSelector, provider);
}
function registerLinkProvider(languageSelector, provider) {
  const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
  return languageFeaturesService.linkProvider.register(languageSelector, provider);
}
function registerCompletionItemProvider(languageSelector, provider) {
  const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
  return languageFeaturesService.completionProvider.register(languageSelector, provider);
}
function registerColorProvider(languageSelector, provider) {
  const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
  return languageFeaturesService.colorProvider.register(languageSelector, provider);
}
function registerFoldingRangeProvider(languageSelector, provider) {
  const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
  return languageFeaturesService.foldingRangeProvider.register(languageSelector, provider);
}
function registerDeclarationProvider(languageSelector, provider) {
  const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
  return languageFeaturesService.declarationProvider.register(languageSelector, provider);
}
function registerSelectionRangeProvider(languageSelector, provider) {
  const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
  return languageFeaturesService.selectionRangeProvider.register(languageSelector, provider);
}
function registerDocumentSemanticTokensProvider(languageSelector, provider) {
  const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
  return languageFeaturesService.documentSemanticTokensProvider.register(languageSelector, provider);
}
function registerDocumentRangeSemanticTokensProvider(languageSelector, provider) {
  const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
  return languageFeaturesService.documentRangeSemanticTokensProvider.register(languageSelector, provider);
}
function registerInlineCompletionsProvider(languageSelector, provider) {
  const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
  return languageFeaturesService.inlineCompletionsProvider.register(languageSelector, provider);
}
function registerInlayHintsProvider(languageSelector, provider) {
  const languageFeaturesService = StandaloneServices.get(ILanguageFeaturesService);
  return languageFeaturesService.inlayHintsProvider.register(languageSelector, provider);
}
function createMonacoLanguagesAPI() {
  return {
    register,
    getLanguages,
    onLanguage,
    onLanguageEncountered,
    getEncodedLanguageId,
    // provider methods
    setLanguageConfiguration,
    setColorMap,
    registerTokensProviderFactory,
    setTokensProvider,
    setMonarchTokensProvider,
    registerReferenceProvider,
    registerRenameProvider,
    registerCompletionItemProvider,
    registerSignatureHelpProvider,
    registerHoverProvider,
    registerDocumentSymbolProvider,
    registerDocumentHighlightProvider,
    registerLinkedEditingRangeProvider,
    registerDefinitionProvider,
    registerImplementationProvider,
    registerTypeDefinitionProvider,
    registerCodeLensProvider,
    registerCodeActionProvider,
    registerDocumentFormattingEditProvider,
    registerDocumentRangeFormattingEditProvider,
    registerOnTypeFormattingEditProvider,
    registerLinkProvider,
    registerColorProvider,
    registerFoldingRangeProvider,
    registerDeclarationProvider,
    registerSelectionRangeProvider,
    registerDocumentSemanticTokensProvider,
    registerDocumentRangeSemanticTokensProvider,
    registerInlineCompletionsProvider,
    registerInlayHintsProvider,
    // enums
    DocumentHighlightKind,
    CompletionItemKind,
    CompletionItemTag,
    CompletionItemInsertTextRule,
    SymbolKind,
    SymbolTag,
    IndentAction,
    CompletionTriggerKind,
    SignatureHelpTriggerKind,
    InlayHintKind,
    InlineCompletionTriggerKind,
    CodeActionTriggerType,
    // classes
    FoldingRangeKind,
    SelectedSuggestionInfo
  };
}
EditorOptions.wrappingIndent.defaultValue = 0;
EditorOptions.glyphMargin.defaultValue = false;
EditorOptions.autoIndent.defaultValue = 3;
EditorOptions.overviewRulerLanes.defaultValue = 2;
FormattingConflicts.setFormatterSelector((formatter2, document2, mode) => Promise.resolve(formatter2[0]));
const api = createMonacoBaseAPI();
api.editor = createMonacoEditorAPI();
api.languages = createMonacoLanguagesAPI();
const CancellationTokenSource2 = api.CancellationTokenSource;
const Emitter2 = api.Emitter;
const KeyCode = api.KeyCode;
const KeyMod2 = api.KeyMod;
const Position$1 = api.Position;
const Range2 = api.Range;
const Selection2 = api.Selection;
const SelectionDirection = api.SelectionDirection;
const MarkerSeverity = api.MarkerSeverity;
const MarkerTag = api.MarkerTag;
const Uri2 = api.Uri;
const Token$1 = api.Token;
const editor = api.editor;
const languages = api.languages;
const monacoEnvironment = globalThis.MonacoEnvironment;
if ((monacoEnvironment === null || monacoEnvironment === void 0 ? void 0 : monacoEnvironment.globalAPI) || typeof define === "function" && define.amd) {
  globalThis.monaco = api;
}
if (typeof globalThis.require !== "undefined" && typeof globalThis.require.config === "function") {
  globalThis.require.config({
    ignoreDuplicateModules: [
      "vscode-languageserver-types",
      "vscode-languageserver-types/main",
      "vscode-languageserver-textdocument",
      "vscode-languageserver-textdocument/main",
      "vscode-nls",
      "vscode-nls/vscode-nls",
      "jsonc-parser",
      "jsonc-parser/main",
      "vscode-uri",
      "vscode-uri/index",
      "vs/basic-languages/typescript/typescript"
    ]
  });
}
const monaco = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  CancellationTokenSource: CancellationTokenSource2,
  Emitter: Emitter2,
  KeyCode,
  KeyMod: KeyMod2,
  MarkerSeverity,
  MarkerTag,
  Position: Position$1,
  Range: Range2,
  Selection: Selection2,
  SelectionDirection,
  Token: Token$1,
  Uri: Uri2,
  editor,
  languages
}, Symbol.toStringTag, { value: "Module" }));
const scriptRel = "modulepreload";
const assetsURL = function(dep) {
  return "/" + dep;
};
const seen$2 = {};
const __vitePreload = function preload(baseModule, deps, importerUrl) {
  if (!deps || deps.length === 0) {
    return baseModule();
  }
  const links2 = document.getElementsByTagName("link");
  return Promise.all(deps.map((dep) => {
    dep = assetsURL(dep);
    if (dep in seen$2)
      return;
    seen$2[dep] = true;
    const isCss = dep.endsWith(".css");
    const cssSelector = isCss ? '[rel="stylesheet"]' : "";
    const isBaseRelative = !!importerUrl;
    if (isBaseRelative) {
      for (let i = links2.length - 1; i >= 0; i--) {
        const link3 = links2[i];
        if (link3.href === dep && (!isCss || link3.rel === "stylesheet")) {
          return;
        }
      }
    } else if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) {
      return;
    }
    const link2 = document.createElement("link");
    link2.rel = isCss ? "stylesheet" : scriptRel;
    if (!isCss) {
      link2.as = "script";
      link2.crossOrigin = "";
    }
    link2.href = dep;
    document.head.appendChild(link2);
    if (isCss) {
      return new Promise((res, rej) => {
        link2.addEventListener("load", res);
        link2.addEventListener("error", () => rej(new Error(`Unable to preload CSS for ${dep}`)));
      });
    }
  })).then(() => baseModule()).catch((err) => {
    const e = new Event("vite:preloadError", { cancelable: true });
    e.payload = err;
    window.dispatchEvent(e);
    if (!e.defaultPrevented) {
      throw err;
    }
  });
};
const loadTheme = async (editor2) => {
  const themes = await __vitePreload(() => import("./index2-7d428fe1.js"), true ? [] : void 0);
  return themes.loadTheme(editor2);
};
const loadGrammars = async (monaco2, editor2) => {
  const grammars = await __vitePreload(() => import("./index3-1143d699.js"), true ? [] : void 0);
  return grammars.loadGrammars(monaco2, editor2);
};
var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
function getDefaultExportFromCjs(x) {
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
}
var sourcemapCodec_umd = { exports: {} };
(function(module2, exports2) {
  (function(global2, factory) {
    factory(exports2);
  })(commonjsGlobal, function(exports3) {
    const comma = ",".charCodeAt(0);
    const semicolon = ";".charCodeAt(0);
    const chars2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    const intToChar2 = new Uint8Array(64);
    const charToInt2 = new Uint8Array(128);
    for (let i = 0; i < chars2.length; i++) {
      const c = chars2.charCodeAt(i);
      intToChar2[i] = c;
      charToInt2[c] = i;
    }
    const td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? {
      decode(buf) {
        const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
        return out.toString();
      }
    } : {
      decode(buf) {
        let out = "";
        for (let i = 0; i < buf.length; i++) {
          out += String.fromCharCode(buf[i]);
        }
        return out;
      }
    };
    function decode(mappings) {
      const state = new Int32Array(5);
      const decoded = [];
      let index = 0;
      do {
        const semi = indexOf2(mappings, index);
        const line = [];
        let sorted = true;
        let lastCol = 0;
        state[0] = 0;
        for (let i = index; i < semi; i++) {
          let seg;
          i = decodeInteger(mappings, i, state, 0);
          const col = state[0];
          if (col < lastCol)
            sorted = false;
          lastCol = col;
          if (hasMoreVlq(mappings, i, semi)) {
            i = decodeInteger(mappings, i, state, 1);
            i = decodeInteger(mappings, i, state, 2);
            i = decodeInteger(mappings, i, state, 3);
            if (hasMoreVlq(mappings, i, semi)) {
              i = decodeInteger(mappings, i, state, 4);
              seg = [col, state[1], state[2], state[3], state[4]];
            } else {
              seg = [col, state[1], state[2], state[3]];
            }
          } else {
            seg = [col];
          }
          line.push(seg);
        }
        if (!sorted)
          sort(line);
        decoded.push(line);
        index = semi + 1;
      } while (index <= mappings.length);
      return decoded;
    }
    function indexOf2(mappings, index) {
      const idx = mappings.indexOf(";", index);
      return idx === -1 ? mappings.length : idx;
    }
    function decodeInteger(mappings, pos, state, j) {
      let value = 0;
      let shift2 = 0;
      let integer = 0;
      do {
        const c = mappings.charCodeAt(pos++);
        integer = charToInt2[c];
        value |= (integer & 31) << shift2;
        shift2 += 5;
      } while (integer & 32);
      const shouldNegate = value & 1;
      value >>>= 1;
      if (shouldNegate) {
        value = -2147483648 | -value;
      }
      state[j] += value;
      return pos;
    }
    function hasMoreVlq(mappings, i, length2) {
      if (i >= length2)
        return false;
      return mappings.charCodeAt(i) !== comma;
    }
    function sort(line) {
      line.sort(sortComparator);
    }
    function sortComparator(a, b) {
      return a[0] - b[0];
    }
    function encode(decoded) {
      const state = new Int32Array(5);
      const bufLength = 1024 * 16;
      const subLength = bufLength - 36;
      const buf = new Uint8Array(bufLength);
      const sub = buf.subarray(0, subLength);
      let pos = 0;
      let out = "";
      for (let i = 0; i < decoded.length; i++) {
        const line = decoded[i];
        if (i > 0) {
          if (pos === bufLength) {
            out += td.decode(buf);
            pos = 0;
          }
          buf[pos++] = semicolon;
        }
        if (line.length === 0)
          continue;
        state[0] = 0;
        for (let j = 0; j < line.length; j++) {
          const segment = line[j];
          if (pos > subLength) {
            out += td.decode(sub);
            buf.copyWithin(0, subLength, pos);
            pos -= subLength;
          }
          if (j > 0)
            buf[pos++] = comma;
          pos = encodeInteger(buf, pos, state, segment, 0);
          if (segment.length === 1)
            continue;
          pos = encodeInteger(buf, pos, state, segment, 1);
          pos = encodeInteger(buf, pos, state, segment, 2);
          pos = encodeInteger(buf, pos, state, segment, 3);
          if (segment.length === 4)
            continue;
          pos = encodeInteger(buf, pos, state, segment, 4);
        }
      }
      return out + td.decode(buf.subarray(0, pos));
    }
    function encodeInteger(buf, pos, state, segment, j) {
      const next = segment[j];
      let num = next - state[j];
      state[j] = next;
      num = num < 0 ? -num << 1 | 1 : num << 1;
      do {
        let clamped = num & 31;
        num >>>= 5;
        if (num > 0)
          clamped |= 32;
        buf[pos++] = intToChar2[clamped];
      } while (num > 0);
      return pos;
    }
    exports3.decode = decode;
    exports3.encode = encode;
    Object.defineProperty(exports3, "__esModule", { value: true });
  });
})(sourcemapCodec_umd, sourcemapCodec_umd.exports);
var sourcemapCodec_umdExports = sourcemapCodec_umd.exports;
class BitSet {
  constructor(arg) {
    this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  }
  add(n2) {
    this.bits[n2 >> 5] |= 1 << (n2 & 31);
  }
  has(n2) {
    return !!(this.bits[n2 >> 5] & 1 << (n2 & 31));
  }
}
class Chunk {
  constructor(start, end, content) {
    this.start = start;
    this.end = end;
    this.original = content;
    this.intro = "";
    this.outro = "";
    this.content = content;
    this.storeName = false;
    this.edited = false;
    {
      this.previous = null;
      this.next = null;
    }
  }
  appendLeft(content) {
    this.outro += content;
  }
  appendRight(content) {
    this.intro = this.intro + content;
  }
  clone() {
    const chunk = new Chunk(this.start, this.end, this.original);
    chunk.intro = this.intro;
    chunk.outro = this.outro;
    chunk.content = this.content;
    chunk.storeName = this.storeName;
    chunk.edited = this.edited;
    return chunk;
  }
  contains(index) {
    return this.start < index && index < this.end;
  }
  eachNext(fn) {
    let chunk = this;
    while (chunk) {
      fn(chunk);
      chunk = chunk.next;
    }
  }
  eachPrevious(fn) {
    let chunk = this;
    while (chunk) {
      fn(chunk);
      chunk = chunk.previous;
    }
  }
  edit(content, storeName, contentOnly) {
    this.content = content;
    if (!contentOnly) {
      this.intro = "";
      this.outro = "";
    }
    this.storeName = storeName;
    this.edited = true;
    return this;
  }
  prependLeft(content) {
    this.outro = content + this.outro;
  }
  prependRight(content) {
    this.intro = content + this.intro;
  }
  split(index) {
    const sliceIndex = index - this.start;
    const originalBefore = this.original.slice(0, sliceIndex);
    const originalAfter = this.original.slice(sliceIndex);
    this.original = originalBefore;
    const newChunk = new Chunk(index, this.end, originalAfter);
    newChunk.outro = this.outro;
    this.outro = "";
    this.end = index;
    if (this.edited) {
      newChunk.edit("", false);
      this.content = "";
    } else {
      this.content = originalBefore;
    }
    newChunk.next = this.next;
    if (newChunk.next)
      newChunk.next.previous = newChunk;
    newChunk.previous = this;
    this.next = newChunk;
    return newChunk;
  }
  toString() {
    return this.intro + this.content + this.outro;
  }
  trimEnd(rx) {
    this.outro = this.outro.replace(rx, "");
    if (this.outro.length)
      return true;
    const trimmed = this.content.replace(rx, "");
    if (trimmed.length) {
      if (trimmed !== this.content) {
        this.split(this.start + trimmed.length).edit("", void 0, true);
        if (this.edited) {
          this.edit(trimmed, this.storeName, true);
        }
      }
      return true;
    } else {
      this.edit("", void 0, true);
      this.intro = this.intro.replace(rx, "");
      if (this.intro.length)
        return true;
    }
  }
  trimStart(rx) {
    this.intro = this.intro.replace(rx, "");
    if (this.intro.length)
      return true;
    const trimmed = this.content.replace(rx, "");
    if (trimmed.length) {
      if (trimmed !== this.content) {
        const newChunk = this.split(this.end - trimmed.length);
        if (this.edited) {
          newChunk.edit(trimmed, this.storeName, true);
        }
        this.edit("", void 0, true);
      }
      return true;
    } else {
      this.edit("", void 0, true);
      this.outro = this.outro.replace(rx, "");
      if (this.outro.length)
        return true;
    }
  }
}
function getBtoa() {
  if (typeof window !== "undefined" && typeof window.btoa === "function") {
    return (str2) => window.btoa(unescape(encodeURIComponent(str2)));
  } else if (typeof Buffer === "function") {
    return (str2) => Buffer.from(str2, "utf-8").toString("base64");
  } else {
    return () => {
      throw new Error("Unsupported environment: `window.btoa` or `Buffer` should be supported.");
    };
  }
}
const btoa = /* @__PURE__ */ getBtoa();
class SourceMap {
  constructor(properties) {
    this.version = 3;
    this.file = properties.file;
    this.sources = properties.sources;
    this.sourcesContent = properties.sourcesContent;
    this.names = properties.names;
    this.mappings = sourcemapCodec_umdExports.encode(properties.mappings);
    if (typeof properties.x_google_ignoreList !== "undefined") {
      this.x_google_ignoreList = properties.x_google_ignoreList;
    }
  }
  toString() {
    return JSON.stringify(this);
  }
  toUrl() {
    return "data:application/json;charset=utf-8;base64," + btoa(this.toString());
  }
}
function guessIndent(code) {
  const lines = code.split("\n");
  const tabbed = lines.filter((line) => /^\t+/.test(line));
  const spaced = lines.filter((line) => /^ {2,}/.test(line));
  if (tabbed.length === 0 && spaced.length === 0) {
    return null;
  }
  if (tabbed.length >= spaced.length) {
    return "	";
  }
  const min = spaced.reduce((previous, current) => {
    const numSpaces = /^ +/.exec(current)[0].length;
    return Math.min(numSpaces, previous);
  }, Infinity);
  return new Array(min + 1).join(" ");
}
function getRelativePath(from2, to) {
  const fromParts = from2.split(/[/\\]/);
  const toParts = to.split(/[/\\]/);
  fromParts.pop();
  while (fromParts[0] === toParts[0]) {
    fromParts.shift();
    toParts.shift();
  }
  if (fromParts.length) {
    let i = fromParts.length;
    while (i--)
      fromParts[i] = "..";
  }
  return fromParts.concat(toParts).join("/");
}
const toString$2 = Object.prototype.toString;
function isObject$3(thing) {
  return toString$2.call(thing) === "[object Object]";
}
function getLocator(source) {
  const originalLines = source.split("\n");
  const lineOffsets = [];
  for (let i = 0, pos = 0; i < originalLines.length; i++) {
    lineOffsets.push(pos);
    pos += originalLines[i].length + 1;
  }
  return function locate(index) {
    let i = 0;
    let j = lineOffsets.length;
    while (i < j) {
      const m = i + j >> 1;
      if (index < lineOffsets[m]) {
        j = m;
      } else {
        i = m + 1;
      }
    }
    const line = i - 1;
    const column = index - lineOffsets[line];
    return { line, column };
  };
}
const wordRegex = /\w/;
class Mappings {
  constructor(hires) {
    this.hires = hires;
    this.generatedCodeLine = 0;
    this.generatedCodeColumn = 0;
    this.raw = [];
    this.rawSegments = this.raw[this.generatedCodeLine] = [];
    this.pending = null;
  }
  addEdit(sourceIndex, content, loc, nameIndex) {
    if (content.length) {
      const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
      if (nameIndex >= 0) {
        segment.push(nameIndex);
      }
      this.rawSegments.push(segment);
    } else if (this.pending) {
      this.rawSegments.push(this.pending);
    }
    this.advance(content);
    this.pending = null;
  }
  addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
    let originalCharIndex = chunk.start;
    let first2 = true;
    let charInHiresBoundary = false;
    while (originalCharIndex < chunk.end) {
      if (this.hires || first2 || sourcemapLocations.has(originalCharIndex)) {
        const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
        if (this.hires === "boundary") {
          if (wordRegex.test(original[originalCharIndex])) {
            if (!charInHiresBoundary) {
              this.rawSegments.push(segment);
              charInHiresBoundary = true;
            }
          } else {
            this.rawSegments.push(segment);
            charInHiresBoundary = false;
          }
        } else {
          this.rawSegments.push(segment);
        }
      }
      if (original[originalCharIndex] === "\n") {
        loc.line += 1;
        loc.column = 0;
        this.generatedCodeLine += 1;
        this.raw[this.generatedCodeLine] = this.rawSegments = [];
        this.generatedCodeColumn = 0;
        first2 = true;
      } else {
        loc.column += 1;
        this.generatedCodeColumn += 1;
        first2 = false;
      }
      originalCharIndex += 1;
    }
    this.pending = null;
  }
  advance(str2) {
    if (!str2)
      return;
    const lines = str2.split("\n");
    if (lines.length > 1) {
      for (let i = 0; i < lines.length - 1; i++) {
        this.generatedCodeLine++;
        this.raw[this.generatedCodeLine] = this.rawSegments = [];
      }
      this.generatedCodeColumn = 0;
    }
    this.generatedCodeColumn += lines[lines.length - 1].length;
  }
}
const n = "\n";
const warned = {
  insertLeft: false,
  insertRight: false,
  storeName: false
};
class MagicString {
  constructor(string3, options = {}) {
    const chunk = new Chunk(0, string3.length, string3);
    Object.defineProperties(this, {
      original: { writable: true, value: string3 },
      outro: { writable: true, value: "" },
      intro: { writable: true, value: "" },
      firstChunk: { writable: true, value: chunk },
      lastChunk: { writable: true, value: chunk },
      lastSearchedChunk: { writable: true, value: chunk },
      byStart: { writable: true, value: {} },
      byEnd: { writable: true, value: {} },
      filename: { writable: true, value: options.filename },
      indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
      sourcemapLocations: { writable: true, value: new BitSet() },
      storedNames: { writable: true, value: {} },
      indentStr: { writable: true, value: void 0 },
      ignoreList: { writable: true, value: options.ignoreList }
    });
    this.byStart[0] = chunk;
    this.byEnd[string3.length] = chunk;
  }
  addSourcemapLocation(char) {
    this.sourcemapLocations.add(char);
  }
  append(content) {
    if (typeof content !== "string")
      throw new TypeError("outro content must be a string");
    this.outro += content;
    return this;
  }
  appendLeft(index, content) {
    if (typeof content !== "string")
      throw new TypeError("inserted content must be a string");
    this._split(index);
    const chunk = this.byEnd[index];
    if (chunk) {
      chunk.appendLeft(content);
    } else {
      this.intro += content;
    }
    return this;
  }
  appendRight(index, content) {
    if (typeof content !== "string")
      throw new TypeError("inserted content must be a string");
    this._split(index);
    const chunk = this.byStart[index];
    if (chunk) {
      chunk.appendRight(content);
    } else {
      this.outro += content;
    }
    return this;
  }
  clone() {
    const cloned = new MagicString(this.original, { filename: this.filename });
    let originalChunk = this.firstChunk;
    let clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
    while (originalChunk) {
      cloned.byStart[clonedChunk.start] = clonedChunk;
      cloned.byEnd[clonedChunk.end] = clonedChunk;
      const nextOriginalChunk = originalChunk.next;
      const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
      if (nextClonedChunk) {
        clonedChunk.next = nextClonedChunk;
        nextClonedChunk.previous = clonedChunk;
        clonedChunk = nextClonedChunk;
      }
      originalChunk = nextOriginalChunk;
    }
    cloned.lastChunk = clonedChunk;
    if (this.indentExclusionRanges) {
      cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
    }
    cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
    cloned.intro = this.intro;
    cloned.outro = this.outro;
    return cloned;
  }
  generateDecodedMap(options) {
    options = options || {};
    const sourceIndex = 0;
    const names = Object.keys(this.storedNames);
    const mappings = new Mappings(options.hires);
    const locate = getLocator(this.original);
    if (this.intro) {
      mappings.advance(this.intro);
    }
    this.firstChunk.eachNext((chunk) => {
      const loc = locate(chunk.start);
      if (chunk.intro.length)
        mappings.advance(chunk.intro);
      if (chunk.edited) {
        mappings.addEdit(
          sourceIndex,
          chunk.content,
          loc,
          chunk.storeName ? names.indexOf(chunk.original) : -1
        );
      } else {
        mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
      }
      if (chunk.outro.length)
        mappings.advance(chunk.outro);
    });
    return {
      file: options.file ? options.file.split(/[/\\]/).pop() : void 0,
      sources: [
        options.source ? getRelativePath(options.file || "", options.source) : options.file || ""
      ],
      sourcesContent: options.includeContent ? [this.original] : void 0,
      names,
      mappings: mappings.raw,
      x_google_ignoreList: this.ignoreList ? [sourceIndex] : void 0
    };
  }
  generateMap(options) {
    return new SourceMap(this.generateDecodedMap(options));
  }
  _ensureindentStr() {
    if (this.indentStr === void 0) {
      this.indentStr = guessIndent(this.original);
    }
  }
  _getRawIndentString() {
    this._ensureindentStr();
    return this.indentStr;
  }
  getIndentString() {
    this._ensureindentStr();
    return this.indentStr === null ? "	" : this.indentStr;
  }
  indent(indentStr, options) {
    const pattern = /^[^\r\n]/gm;
    if (isObject$3(indentStr)) {
      options = indentStr;
      indentStr = void 0;
    }
    if (indentStr === void 0) {
      this._ensureindentStr();
      indentStr = this.indentStr || "	";
    }
    if (indentStr === "")
      return this;
    options = options || {};
    const isExcluded = {};
    if (options.exclude) {
      const exclusions = typeof options.exclude[0] === "number" ? [options.exclude] : options.exclude;
      exclusions.forEach((exclusion) => {
        for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
          isExcluded[i] = true;
        }
      });
    }
    let shouldIndentNextCharacter = options.indentStart !== false;
    const replacer2 = (match2) => {
      if (shouldIndentNextCharacter)
        return `${indentStr}${match2}`;
      shouldIndentNextCharacter = true;
      return match2;
    };
    this.intro = this.intro.replace(pattern, replacer2);
    let charIndex = 0;
    let chunk = this.firstChunk;
    while (chunk) {
      const end = chunk.end;
      if (chunk.edited) {
        if (!isExcluded[charIndex]) {
          chunk.content = chunk.content.replace(pattern, replacer2);
          if (chunk.content.length) {
            shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === "\n";
          }
        }
      } else {
        charIndex = chunk.start;
        while (charIndex < end) {
          if (!isExcluded[charIndex]) {
            const char = this.original[charIndex];
            if (char === "\n") {
              shouldIndentNextCharacter = true;
            } else if (char !== "\r" && shouldIndentNextCharacter) {
              shouldIndentNextCharacter = false;
              if (charIndex === chunk.start) {
                chunk.prependRight(indentStr);
              } else {
                this._splitChunk(chunk, charIndex);
                chunk = chunk.next;
                chunk.prependRight(indentStr);
              }
            }
          }
          charIndex += 1;
        }
      }
      charIndex = chunk.end;
      chunk = chunk.next;
    }
    this.outro = this.outro.replace(pattern, replacer2);
    return this;
  }
  insert() {
    throw new Error(
      "magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)"
    );
  }
  insertLeft(index, content) {
    if (!warned.insertLeft) {
      console.warn(
        "magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead"
      );
      warned.insertLeft = true;
    }
    return this.appendLeft(index, content);
  }
  insertRight(index, content) {
    if (!warned.insertRight) {
      console.warn(
        "magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead"
      );
      warned.insertRight = true;
    }
    return this.prependRight(index, content);
  }
  move(start, end, index) {
    if (index >= start && index <= end)
      throw new Error("Cannot move a selection inside itself");
    this._split(start);
    this._split(end);
    this._split(index);
    const first2 = this.byStart[start];
    const last2 = this.byEnd[end];
    const oldLeft = first2.previous;
    const oldRight = last2.next;
    const newRight = this.byStart[index];
    if (!newRight && last2 === this.lastChunk)
      return this;
    const newLeft = newRight ? newRight.previous : this.lastChunk;
    if (oldLeft)
      oldLeft.next = oldRight;
    if (oldRight)
      oldRight.previous = oldLeft;
    if (newLeft)
      newLeft.next = first2;
    if (newRight)
      newRight.previous = last2;
    if (!first2.previous)
      this.firstChunk = last2.next;
    if (!last2.next) {
      this.lastChunk = first2.previous;
      this.lastChunk.next = null;
    }
    first2.previous = newLeft;
    last2.next = newRight || null;
    if (!newLeft)
      this.firstChunk = first2;
    if (!newRight)
      this.lastChunk = last2;
    return this;
  }
  overwrite(start, end, content, options) {
    options = options || {};
    return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
  }
  update(start, end, content, options) {
    if (typeof content !== "string")
      throw new TypeError("replacement content must be a string");
    while (start < 0)
      start += this.original.length;
    while (end < 0)
      end += this.original.length;
    if (end > this.original.length)
      throw new Error("end is out of bounds");
    if (start === end)
      throw new Error(
        "Cannot overwrite a zero-length range – use appendLeft or prependRight instead"
      );
    this._split(start);
    this._split(end);
    if (options === true) {
      if (!warned.storeName) {
        console.warn(
          "The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string"
        );
        warned.storeName = true;
      }
      options = { storeName: true };
    }
    const storeName = options !== void 0 ? options.storeName : false;
    const overwrite = options !== void 0 ? options.overwrite : false;
    if (storeName) {
      const original = this.original.slice(start, end);
      Object.defineProperty(this.storedNames, original, {
        writable: true,
        value: true,
        enumerable: true
      });
    }
    const first2 = this.byStart[start];
    const last2 = this.byEnd[end];
    if (first2) {
      let chunk = first2;
      while (chunk !== last2) {
        if (chunk.next !== this.byStart[chunk.end]) {
          throw new Error("Cannot overwrite across a split point");
        }
        chunk = chunk.next;
        chunk.edit("", false);
      }
      first2.edit(content, storeName, !overwrite);
    } else {
      const newChunk = new Chunk(start, end, "").edit(content, storeName);
      last2.next = newChunk;
      newChunk.previous = last2;
    }
    return this;
  }
  prepend(content) {
    if (typeof content !== "string")
      throw new TypeError("outro content must be a string");
    this.intro = content + this.intro;
    return this;
  }
  prependLeft(index, content) {
    if (typeof content !== "string")
      throw new TypeError("inserted content must be a string");
    this._split(index);
    const chunk = this.byEnd[index];
    if (chunk) {
      chunk.prependLeft(content);
    } else {
      this.intro = content + this.intro;
    }
    return this;
  }
  prependRight(index, content) {
    if (typeof content !== "string")
      throw new TypeError("inserted content must be a string");
    this._split(index);
    const chunk = this.byStart[index];
    if (chunk) {
      chunk.prependRight(content);
    } else {
      this.outro = content + this.outro;
    }
    return this;
  }
  remove(start, end) {
    while (start < 0)
      start += this.original.length;
    while (end < 0)
      end += this.original.length;
    if (start === end)
      return this;
    if (start < 0 || end > this.original.length)
      throw new Error("Character is out of bounds");
    if (start > end)
      throw new Error("end must be greater than start");
    this._split(start);
    this._split(end);
    let chunk = this.byStart[start];
    while (chunk) {
      chunk.intro = "";
      chunk.outro = "";
      chunk.edit("");
      chunk = end > chunk.end ? this.byStart[chunk.end] : null;
    }
    return this;
  }
  lastChar() {
    if (this.outro.length)
      return this.outro[this.outro.length - 1];
    let chunk = this.lastChunk;
    do {
      if (chunk.outro.length)
        return chunk.outro[chunk.outro.length - 1];
      if (chunk.content.length)
        return chunk.content[chunk.content.length - 1];
      if (chunk.intro.length)
        return chunk.intro[chunk.intro.length - 1];
    } while (chunk = chunk.previous);
    if (this.intro.length)
      return this.intro[this.intro.length - 1];
    return "";
  }
  lastLine() {
    let lineIndex = this.outro.lastIndexOf(n);
    if (lineIndex !== -1)
      return this.outro.substr(lineIndex + 1);
    let lineStr = this.outro;
    let chunk = this.lastChunk;
    do {
      if (chunk.outro.length > 0) {
        lineIndex = chunk.outro.lastIndexOf(n);
        if (lineIndex !== -1)
          return chunk.outro.substr(lineIndex + 1) + lineStr;
        lineStr = chunk.outro + lineStr;
      }
      if (chunk.content.length > 0) {
        lineIndex = chunk.content.lastIndexOf(n);
        if (lineIndex !== -1)
          return chunk.content.substr(lineIndex + 1) + lineStr;
        lineStr = chunk.content + lineStr;
      }
      if (chunk.intro.length > 0) {
        lineIndex = chunk.intro.lastIndexOf(n);
        if (lineIndex !== -1)
          return chunk.intro.substr(lineIndex + 1) + lineStr;
        lineStr = chunk.intro + lineStr;
      }
    } while (chunk = chunk.previous);
    lineIndex = this.intro.lastIndexOf(n);
    if (lineIndex !== -1)
      return this.intro.substr(lineIndex + 1) + lineStr;
    return this.intro + lineStr;
  }
  slice(start = 0, end = this.original.length) {
    while (start < 0)
      start += this.original.length;
    while (end < 0)
      end += this.original.length;
    let result2 = "";
    let chunk = this.firstChunk;
    while (chunk && (chunk.start > start || chunk.end <= start)) {
      if (chunk.start < end && chunk.end >= end) {
        return result2;
      }
      chunk = chunk.next;
    }
    if (chunk && chunk.edited && chunk.start !== start)
      throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
    const startChunk = chunk;
    while (chunk) {
      if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
        result2 += chunk.intro;
      }
      const containsEnd = chunk.start < end && chunk.end >= end;
      if (containsEnd && chunk.edited && chunk.end !== end)
        throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
      const sliceStart = startChunk === chunk ? start - chunk.start : 0;
      const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
      result2 += chunk.content.slice(sliceStart, sliceEnd);
      if (chunk.outro && (!containsEnd || chunk.end === end)) {
        result2 += chunk.outro;
      }
      if (containsEnd) {
        break;
      }
      chunk = chunk.next;
    }
    return result2;
  }
  // TODO deprecate this? not really very useful
  snip(start, end) {
    const clone2 = this.clone();
    clone2.remove(0, start);
    clone2.remove(end, clone2.original.length);
    return clone2;
  }
  _split(index) {
    if (this.byStart[index] || this.byEnd[index])
      return;
    let chunk = this.lastSearchedChunk;
    const searchForward = index > chunk.end;
    while (chunk) {
      if (chunk.contains(index))
        return this._splitChunk(chunk, index);
      chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
    }
  }
  _splitChunk(chunk, index) {
    if (chunk.edited && chunk.content.length) {
      const loc = getLocator(this.original)(index);
      throw new Error(
        `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`
      );
    }
    const newChunk = chunk.split(index);
    this.byEnd[index] = chunk;
    this.byStart[index] = newChunk;
    this.byEnd[newChunk.end] = newChunk;
    if (chunk === this.lastChunk)
      this.lastChunk = newChunk;
    this.lastSearchedChunk = chunk;
    return true;
  }
  toString() {
    let str2 = this.intro;
    let chunk = this.firstChunk;
    while (chunk) {
      str2 += chunk.toString();
      chunk = chunk.next;
    }
    return str2 + this.outro;
  }
  isEmpty() {
    let chunk = this.firstChunk;
    do {
      if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim())
        return false;
    } while (chunk = chunk.next);
    return true;
  }
  length() {
    let chunk = this.firstChunk;
    let length2 = 0;
    do {
      length2 += chunk.intro.length + chunk.content.length + chunk.outro.length;
    } while (chunk = chunk.next);
    return length2;
  }
  trimLines() {
    return this.trim("[\\r\\n]");
  }
  trim(charType) {
    return this.trimStart(charType).trimEnd(charType);
  }
  trimEndAborted(charType) {
    const rx = new RegExp((charType || "\\s") + "+$");
    this.outro = this.outro.replace(rx, "");
    if (this.outro.length)
      return true;
    let chunk = this.lastChunk;
    do {
      const end = chunk.end;
      const aborted = chunk.trimEnd(rx);
      if (chunk.end !== end) {
        if (this.lastChunk === chunk) {
          this.lastChunk = chunk.next;
        }
        this.byEnd[chunk.end] = chunk;
        this.byStart[chunk.next.start] = chunk.next;
        this.byEnd[chunk.next.end] = chunk.next;
      }
      if (aborted)
        return true;
      chunk = chunk.previous;
    } while (chunk);
    return false;
  }
  trimEnd(charType) {
    this.trimEndAborted(charType);
    return this;
  }
  trimStartAborted(charType) {
    const rx = new RegExp("^" + (charType || "\\s") + "+");
    this.intro = this.intro.replace(rx, "");
    if (this.intro.length)
      return true;
    let chunk = this.firstChunk;
    do {
      const end = chunk.end;
      const aborted = chunk.trimStart(rx);
      if (chunk.end !== end) {
        if (chunk === this.lastChunk)
          this.lastChunk = chunk.next;
        this.byEnd[chunk.end] = chunk;
        this.byStart[chunk.next.start] = chunk.next;
        this.byEnd[chunk.next.end] = chunk.next;
      }
      if (aborted)
        return true;
      chunk = chunk.next;
    } while (chunk);
    return false;
  }
  trimStart(charType) {
    this.trimStartAborted(charType);
    return this;
  }
  hasChanged() {
    return this.original !== this.toString();
  }
  _replaceRegexp(searchValue, replacement) {
    function getReplacement(match2, str2) {
      if (typeof replacement === "string") {
        return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
          if (i === "$")
            return "$";
          if (i === "&")
            return match2[0];
          const num = +i;
          if (num < match2.length)
            return match2[+i];
          return `$${i}`;
        });
      } else {
        return replacement(...match2, match2.index, str2, match2.groups);
      }
    }
    function matchAll(re, str2) {
      let match2;
      const matches = [];
      while (match2 = re.exec(str2)) {
        matches.push(match2);
      }
      return matches;
    }
    if (searchValue.global) {
      const matches = matchAll(searchValue, this.original);
      matches.forEach((match2) => {
        if (match2.index != null)
          this.overwrite(
            match2.index,
            match2.index + match2[0].length,
            getReplacement(match2, this.original)
          );
      });
    } else {
      const match2 = this.original.match(searchValue);
      if (match2 && match2.index != null)
        this.overwrite(
          match2.index,
          match2.index + match2[0].length,
          getReplacement(match2, this.original)
        );
    }
    return this;
  }
  _replaceString(string3, replacement) {
    const { original } = this;
    const index = original.indexOf(string3);
    if (index !== -1) {
      this.overwrite(index, index + string3.length, replacement);
    }
    return this;
  }
  replace(searchValue, replacement) {
    if (typeof searchValue === "string") {
      return this._replaceString(searchValue, replacement);
    }
    return this._replaceRegexp(searchValue, replacement);
  }
  _replaceAllString(string3, replacement) {
    const { original } = this;
    const stringLength = string3.length;
    for (let index = original.indexOf(string3); index !== -1; index = original.indexOf(string3, index + stringLength)) {
      this.overwrite(index, index + stringLength, replacement);
    }
    return this;
  }
  replaceAll(searchValue, replacement) {
    if (typeof searchValue === "string") {
      return this._replaceAllString(searchValue, replacement);
    }
    if (!searchValue.global) {
      throw new TypeError(
        "MagicString.prototype.replaceAll called with a non-global RegExp argument"
      );
    }
    return this._replaceRegexp(searchValue, replacement);
  }
}
function countLines(source) {
  return (source.match(/\n/g) || []).length;
}
function lastLineLength(source) {
  return source.substring(source.lastIndexOf("\n")).length;
}
function createSourceLocation(source) {
  const endLine = countLines(source);
  const endColumn = lastLineLength(source);
  return {
    start: {
      offset: 0,
      line: 0,
      column: 0
    },
    end: {
      offset: source.length,
      line: endLine,
      column: endColumn
    },
    source
  };
}
function proxyBlock(source, block, handler = {}) {
  const { start: blockStart, end: blockEnd } = (block == null ? void 0 : block.loc) || createSourceLocation(source.toString());
  const content = source.toString().substring(blockStart.offset, blockEnd.offset);
  const snip = new MagicString(content);
  const proxified = {
    append: (content2) => {
      source.appendRight(blockEnd.offset, content2);
      return snip.append(content2);
    },
    appendLeft: (index, content2) => {
      source.appendLeft(blockStart.offset + index, content2);
      return snip.appendLeft(index, content2);
    },
    appendRight: (index, content2) => {
      source.appendRight(blockStart.offset + index, content2);
      return snip.appendRight(index, content2);
    },
    prepend: (content2) => {
      source.prependRight(blockStart.offset, content2);
      return snip.prepend(content2);
    },
    prependLeft: (index, content2) => {
      source.prependLeft(blockStart.offset + index, content2);
      return snip.prependLeft(index, content2);
    },
    prependRight: (index, content2) => {
      source.prependRight(blockStart.offset + index, content2);
      return snip.prependRight(index, content2);
    },
    overwrite: (start, end, replacement, options) => {
      source.overwrite(blockStart.offset + start, blockStart.offset + end, replacement, options);
      return snip.overwrite(start, end, replacement, options);
    },
    remove: (start, end) => {
      source.remove(blockStart.offset + start, blockStart.offset + end);
      return snip.remove(start, end);
    }
  };
  return new Proxy(
    block || {},
    {
      ...handler,
      get(target, key, receiver) {
        if (key === "source") {
          return source;
        }
        if (key in snip) {
          if (Object.hasOwn(proxified, key)) {
            return proxified[key];
          }
          return snip[key];
        }
        if (block && key in block && !handler.get) {
          return block[key];
        }
        if (handler.get) {
          return handler.get(target, key, receiver);
        }
      },
      set(target, key, value, receiver) {
        if (key in proxified) {
          proxified[key] = value;
          return true;
        }
        if (block && !handler.set) {
          block[key] = value;
          return true;
        }
        if (handler.set) {
          return handler.set(target, key, value, receiver);
        }
        return false;
      }
    }
  );
}
const magicSfcDefaultOptions = {
  parser: void 0,
  silent: false,
  parserOptions: void 0
};
class MagicSFC {
  constructor(source, userOptions, defaultOptions2 = magicSfcDefaultOptions) {
    __publicField(this, "source");
    __publicField(this, "ms");
    __publicField(this, "options");
    __publicField(this, "parsed");
    __publicField(this, "templates", []);
    __publicField(this, "scripts", []);
    __publicField(this, "styles", []);
    __publicField(this, "customs", []);
    var _a2, _b2;
    this.options = { ...defaultOptions2, ...userOptions };
    if (source instanceof MagicString) {
      this.source = source.toString();
      this.ms = source;
    } else {
      this.source = source;
      this.ms = new MagicString(this.source, { filename: (_a2 = this.options) == null ? void 0 : _a2.filename, indentExclusionRanges: (_b2 = this.options) == null ? void 0 : _b2.indentExclusionRanges });
    }
    this.parse();
  }
  parse() {
  }
  toString() {
    return this.ms.toString();
  }
  getSourcemap(sourceMapOptions) {
    var _a2;
    return this.ms.generateMap({ source: (_a2 = this.options) == null ? void 0 : _a2.filename, includeContent: true, hires: true, ...sourceMapOptions });
  }
  getTransformResult() {
    return { code: this.toString(), map: this.getSourcemap() };
  }
}
const magicVueSfcDefaultOptions = {
  parser: void 0,
  silent: false,
  parserOptions: void 0
};
class MagicVueSFC extends MagicSFC {
  constructor(source, userOptions, defaultOptions2 = magicVueSfcDefaultOptions) {
    super(source, userOptions, defaultOptions2);
  }
  parse() {
    var _a2, _b2, _c2, _d2, _e2, _f2, _g2;
    const {
      parser: parser2,
      silent = true,
      parserOptions: parserOptions2 = {}
    } = this.options;
    if (!parser2) {
      if (!silent) {
        throw new Error("You must provide a `parser` function (from vue/compiler-sfc) in options when using MagicVueSFC.");
      }
      return;
    }
    const parsedSfc = parser2(this.ms.toString(), parserOptions2);
    if (!parsedSfc) {
      return;
    }
    this.parsed = parsedSfc;
    if ((_a2 = parsedSfc.descriptor) == null ? void 0 : _a2.template) {
      this.templates = [proxyBlock(this.ms, parsedSfc.descriptor.template)];
    }
    const scripts = [];
    if ((_b2 = parsedSfc.descriptor) == null ? void 0 : _b2.script) {
      scripts.push(proxyBlock(this.ms, parsedSfc.descriptor.script));
    }
    if ((_c2 = parsedSfc.descriptor) == null ? void 0 : _c2.scriptSetup) {
      scripts.push(proxyBlock(this.ms, parsedSfc.descriptor.scriptSetup));
    }
    if (scripts.length) {
      this.scripts = scripts;
    }
    if ((_d2 = parsedSfc.descriptor) == null ? void 0 : _d2.styles) {
      this.styles = (_e2 = parsedSfc.descriptor) == null ? void 0 : _e2.styles.map((styleBlock) => proxyBlock(this.ms, styleBlock));
    }
    if ((_f2 = parsedSfc.descriptor) == null ? void 0 : _f2.customBlocks) {
      this.customs = (_g2 = parsedSfc.descriptor) == null ? void 0 : _g2.customBlocks.map((block) => proxyBlock(this.ms, block));
    }
  }
}
function makeMap(str2, expectsLowerCase) {
  const map2 = /* @__PURE__ */ Object.create(null);
  const list2 = str2.split(",");
  for (let i = 0; i < list2.length; i++) {
    map2[list2[i]] = true;
  }
  return expectsLowerCase ? (val) => !!map2[val.toLowerCase()] : (val) => !!map2[val];
}
const EMPTY_OBJ = Object.freeze({});
const NOOP = () => {
};
const NO = () => false;
const onRE = /^on[^a-z]/;
const isOn = (key) => onRE.test(key);
const extend = Object.assign;
const hasOwnProperty$3 = Object.prototype.hasOwnProperty;
const hasOwn = (val, key) => hasOwnProperty$3.call(val, key);
const isArray$3 = Array.isArray;
const isMap = (val) => toTypeString(val) === "[object Map]";
const isSet = (val) => toTypeString(val) === "[object Set]";
const isFunction$1 = (val) => typeof val === "function";
const isString$2 = (val) => typeof val === "string";
const isSymbol$1 = (val) => typeof val === "symbol";
const isObject$2 = (val) => val !== null && typeof val === "object";
const objectToString$1 = Object.prototype.toString;
const toTypeString = (value) => objectToString$1.call(value);
const isPlainObject = (val) => toTypeString(val) === "[object Object]";
const isReservedProp = /* @__PURE__ */ makeMap(
  // the leading comma is intentional so empty string "" is also included
  ",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"
);
const isBuiltInDirective = /* @__PURE__ */ makeMap(
  "bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo"
);
const cacheStringFunction = (fn) => {
  const cache2 = /* @__PURE__ */ Object.create(null);
  return (str2) => {
    const hit = cache2[str2];
    return hit || (cache2[str2] = fn(str2));
  };
};
const camelizeRE = /-(\w)/g;
const camelize = cacheStringFunction((str2) => {
  return str2.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : "");
});
const hyphenateRE = /\B([A-Z])/g;
const hyphenate = cacheStringFunction(
  (str2) => str2.replace(hyphenateRE, "-$1").toLowerCase()
);
const capitalize$1 = cacheStringFunction(
  (str2) => str2.charAt(0).toUpperCase() + str2.slice(1)
);
const toHandlerKey = cacheStringFunction(
  (str2) => str2 ? `on${capitalize$1(str2)}` : ``
);
const identRE = /^[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*$/;
function genPropsAccessExp(name) {
  return identRE.test(name) ? `__props.${name}` : `__props[${JSON.stringify(name)}]`;
}
const PatchFlagNames = {
  [1]: `TEXT`,
  [2]: `CLASS`,
  [4]: `STYLE`,
  [8]: `PROPS`,
  [16]: `FULL_PROPS`,
  [32]: `HYDRATE_EVENTS`,
  [64]: `STABLE_FRAGMENT`,
  [128]: `KEYED_FRAGMENT`,
  [256]: `UNKEYED_FRAGMENT`,
  [512]: `NEED_PATCH`,
  [1024]: `DYNAMIC_SLOTS`,
  [2048]: `DEV_ROOT_FRAGMENT`,
  [-1]: `HOISTED`,
  [-2]: `BAIL`
};
const slotFlagsText = {
  [1]: "STABLE",
  [2]: "DYNAMIC",
  [3]: "FORWARDED"
};
const GLOBALS_WHITE_LISTED = "Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console";
const isGloballyWhitelisted = /* @__PURE__ */ makeMap(GLOBALS_WHITE_LISTED);
const range = 2;
function generateCodeFrame(source, start = 0, end = source.length) {
  let lines = source.split(/(\r?\n)/);
  const newlineSequences = lines.filter((_, idx) => idx % 2 === 1);
  lines = lines.filter((_, idx) => idx % 2 === 0);
  let count = 0;
  const res = [];
  for (let i = 0; i < lines.length; i++) {
    count += lines[i].length + (newlineSequences[i] && newlineSequences[i].length || 0);
    if (count >= start) {
      for (let j = i - range; j <= i + range || end > count; j++) {
        if (j < 0 || j >= lines.length)
          continue;
        const line = j + 1;
        res.push(
          `${line}${" ".repeat(Math.max(3 - String(line).length, 0))}|  ${lines[j]}`
        );
        const lineLength = lines[j].length;
        const newLineSeqLength = newlineSequences[j] && newlineSequences[j].length || 0;
        if (j === i) {
          const pad2 = start - (count - (lineLength + newLineSeqLength));
          const length2 = Math.max(
            1,
            end > count ? lineLength - pad2 : end - start
          );
          res.push(`   |  ` + " ".repeat(pad2) + "^".repeat(length2));
        } else if (j > i) {
          if (end > count) {
            const length2 = Math.max(Math.min(end - count, lineLength), 1);
            res.push(`   |  ` + "^".repeat(length2));
          }
          count += lineLength + newLineSeqLength;
        }
      }
      break;
    }
  }
  return res.join("\n");
}
function normalizeStyle(value) {
  if (isArray$3(value)) {
    const res = {};
    for (let i = 0; i < value.length; i++) {
      const item = value[i];
      const normalized = isString$2(item) ? parseStringStyle(item) : normalizeStyle(item);
      if (normalized) {
        for (const key in normalized) {
          res[key] = normalized[key];
        }
      }
    }
    return res;
  } else if (isString$2(value)) {
    return value;
  } else if (isObject$2(value)) {
    return value;
  }
}
const listDelimiterRE = /;(?![^(]*\))/g;
const propertyDelimiterRE = /:([^]+)/;
const styleCommentRE = /\/\*[^]*?\*\//g;
function parseStringStyle(cssText) {
  const ret = {};
  cssText.replace(styleCommentRE, "").split(listDelimiterRE).forEach((item) => {
    if (item) {
      const tmp = item.split(propertyDelimiterRE);
      tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
    }
  });
  return ret;
}
function stringifyStyle(styles) {
  let ret = "";
  if (!styles || isString$2(styles)) {
    return ret;
  }
  for (const key in styles) {
    const value = styles[key];
    const normalizedKey = key.startsWith(`--`) ? key : hyphenate(key);
    if (isString$2(value) || typeof value === "number") {
      ret += `${normalizedKey}:${value};`;
    }
  }
  return ret;
}
function normalizeClass(value) {
  let res = "";
  if (isString$2(value)) {
    res = value;
  } else if (isArray$3(value)) {
    for (let i = 0; i < value.length; i++) {
      const normalized = normalizeClass(value[i]);
      if (normalized) {
        res += normalized + " ";
      }
    }
  } else if (isObject$2(value)) {
    for (const name in value) {
      if (value[name]) {
        res += name + " ";
      }
    }
  }
  return res.trim();
}
const HTML_TAGS = "html,body,base,head,link,meta,style,title,address,article,aside,footer,header,hgroup,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,summary,template,blockquote,iframe,tfoot";
const SVG_TAGS = "svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,feDistantLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,text,textPath,title,tspan,unknown,use,view";
const VOID_TAGS = "area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr";
const isHTMLTag = /* @__PURE__ */ makeMap(HTML_TAGS);
const isSVGTag = /* @__PURE__ */ makeMap(SVG_TAGS);
const isVoidTag = /* @__PURE__ */ makeMap(VOID_TAGS);
const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;
const isBooleanAttr = /* @__PURE__ */ makeMap(
  specialBooleanAttrs + `,async,autofocus,autoplay,controls,default,defer,disabled,hidden,inert,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected`
);
const isKnownHtmlAttr = /* @__PURE__ */ makeMap(
  `accept,accept-charset,accesskey,action,align,allow,alt,async,autocapitalize,autocomplete,autofocus,autoplay,background,bgcolor,border,buffered,capture,challenge,charset,checked,cite,class,code,codebase,color,cols,colspan,content,contenteditable,contextmenu,controls,coords,crossorigin,csp,data,datetime,decoding,default,defer,dir,dirname,disabled,download,draggable,dropzone,enctype,enterkeyhint,for,form,formaction,formenctype,formmethod,formnovalidate,formtarget,headers,height,hidden,high,href,hreflang,http-equiv,icon,id,importance,inert,integrity,ismap,itemprop,keytype,kind,label,lang,language,loading,list,loop,low,manifest,max,maxlength,minlength,media,min,multiple,muted,name,novalidate,open,optimum,pattern,ping,placeholder,poster,preload,radiogroup,readonly,referrerpolicy,rel,required,reversed,rows,rowspan,sandbox,scope,scoped,selected,shape,size,sizes,slot,span,spellcheck,src,srcdoc,srclang,srcset,start,step,style,summary,tabindex,target,title,translate,type,usemap,value,width,wrap`
);
const isKnownSvgAttr = /* @__PURE__ */ makeMap(
  `xmlns,accent-height,accumulate,additive,alignment-baseline,alphabetic,amplitude,arabic-form,ascent,attributeName,attributeType,azimuth,baseFrequency,baseline-shift,baseProfile,bbox,begin,bias,by,calcMode,cap-height,class,clip,clipPathUnits,clip-path,clip-rule,color,color-interpolation,color-interpolation-filters,color-profile,color-rendering,contentScriptType,contentStyleType,crossorigin,cursor,cx,cy,d,decelerate,descent,diffuseConstant,direction,display,divisor,dominant-baseline,dur,dx,dy,edgeMode,elevation,enable-background,end,exponent,fill,fill-opacity,fill-rule,filter,filterRes,filterUnits,flood-color,flood-opacity,font-family,font-size,font-size-adjust,font-stretch,font-style,font-variant,font-weight,format,from,fr,fx,fy,g1,g2,glyph-name,glyph-orientation-horizontal,glyph-orientation-vertical,glyphRef,gradientTransform,gradientUnits,hanging,height,href,hreflang,horiz-adv-x,horiz-origin-x,id,ideographic,image-rendering,in,in2,intercept,k,k1,k2,k3,k4,kernelMatrix,kernelUnitLength,kerning,keyPoints,keySplines,keyTimes,lang,lengthAdjust,letter-spacing,lighting-color,limitingConeAngle,local,marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mask,maskContentUnits,maskUnits,mathematical,max,media,method,min,mode,name,numOctaves,offset,opacity,operator,order,orient,orientation,origin,overflow,overline-position,overline-thickness,panose-1,paint-order,path,pathLength,patternContentUnits,patternTransform,patternUnits,ping,pointer-events,points,pointsAtX,pointsAtY,pointsAtZ,preserveAlpha,preserveAspectRatio,primitiveUnits,r,radius,referrerPolicy,refX,refY,rel,rendering-intent,repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,result,rotate,rx,ry,scale,seed,shape-rendering,slope,spacing,specularConstant,specularExponent,speed,spreadMethod,startOffset,stdDeviation,stemh,stemv,stitchTiles,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,string,stroke,stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,stroke-width,style,surfaceScale,systemLanguage,tabindex,tableValues,target,targetX,targetY,text-anchor,text-decoration,text-rendering,textLength,to,transform,transform-origin,type,u1,u2,underline-position,underline-thickness,unicode,unicode-bidi,unicode-range,units-per-em,v-alphabetic,v-hanging,v-ideographic,v-mathematical,values,vector-effect,version,vert-adv-y,vert-origin-x,vert-origin-y,viewBox,viewTarget,visibility,width,widths,word-spacing,writing-mode,x,x-height,x1,x2,xChannelSelector,xlink:actuate,xlink:arcrole,xlink:href,xlink:role,xlink:show,xlink:title,xlink:type,xml:base,xml:lang,xml:space,y,y1,y2,yChannelSelector,z,zoomAndPan`
);
const escapeRE = /["'&<>]/;
function escapeHtml(string3) {
  const str2 = "" + string3;
  const match2 = escapeRE.exec(str2);
  if (!match2) {
    return str2;
  }
  let html2 = "";
  let escaped;
  let index;
  let lastIndex2 = 0;
  for (index = match2.index; index < str2.length; index++) {
    switch (str2.charCodeAt(index)) {
      case 34:
        escaped = "&quot;";
        break;
      case 38:
        escaped = "&amp;";
        break;
      case 39:
        escaped = "&#39;";
        break;
      case 60:
        escaped = "&lt;";
        break;
      case 62:
        escaped = "&gt;";
        break;
      default:
        continue;
    }
    if (lastIndex2 !== index) {
      html2 += str2.slice(lastIndex2, index);
    }
    lastIndex2 = index + 1;
    html2 += escaped;
  }
  return lastIndex2 !== index ? html2 + str2.slice(lastIndex2, index) : html2;
}
const toDisplayString = (val) => {
  return isString$2(val) ? val : val == null ? "" : isArray$3(val) || isObject$2(val) && (val.toString === objectToString$1 || !isFunction$1(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$2(val) && !isArray$3(val) && !isPlainObject(val)) {
    return String(val);
  }
  return val;
};
function defaultOnError(error2) {
  throw error2;
}
function defaultOnWarn(msg) {
  console.warn(`[Vue warn] ${msg.message}`);
}
function createCompilerError(code, loc, messages, additionalMessage) {
  const msg = (messages || errorMessages)[code] + (additionalMessage || ``);
  const error2 = new SyntaxError(String(msg));
  error2.code = code;
  error2.loc = loc;
  return error2;
}
const errorMessages = {
  // parse errors
  [0]: "Illegal comment.",
  [1]: "CDATA section is allowed only in XML context.",
  [2]: "Duplicate attribute.",
  [3]: "End tag cannot have attributes.",
  [4]: "Illegal '/' in tags.",
  [5]: "Unexpected EOF in tag.",
  [6]: "Unexpected EOF in CDATA section.",
  [7]: "Unexpected EOF in comment.",
  [8]: "Unexpected EOF in script.",
  [9]: "Unexpected EOF in tag.",
  [10]: "Incorrectly closed comment.",
  [11]: "Incorrectly opened comment.",
  [12]: "Illegal tag name. Use '&lt;' to print '<'.",
  [13]: "Attribute value was expected.",
  [14]: "End tag name was expected.",
  [15]: "Whitespace was expected.",
  [16]: "Unexpected '<!--' in comment.",
  [17]: `Attribute name cannot contain U+0022 ("), U+0027 ('), and U+003C (<).`,
  [18]: "Unquoted attribute value cannot contain U+0022 (\"), U+0027 ('), U+003C (<), U+003D (=), and U+0060 (`).",
  [19]: "Attribute name cannot start with '='.",
  [21]: "'<?' is allowed only in XML context.",
  [20]: `Unexpected null character.`,
  [22]: "Illegal '/' in tags.",
  // Vue-specific parse errors
  [23]: "Invalid end tag.",
  [24]: "Element is missing end tag.",
  [25]: "Interpolation end sign was not found.",
  [27]: "End bracket for dynamic directive argument was not found. Note that dynamic directive argument cannot contain spaces.",
  [26]: "Legal directive name was expected.",
  // transform errors
  [28]: `v-if/v-else-if is missing expression.`,
  [29]: `v-if/else branches must use unique keys.`,
  [30]: `v-else/v-else-if has no adjacent v-if or v-else-if.`,
  [31]: `v-for is missing expression.`,
  [32]: `v-for has invalid expression.`,
  [33]: `<template v-for> key should be placed on the <template> tag.`,
  [34]: `v-bind is missing expression.`,
  [35]: `v-on is missing expression.`,
  [36]: `Unexpected custom directive on <slot> outlet.`,
  [37]: `Mixed v-slot usage on both the component and nested <template>. When there are multiple named slots, all slots should use <template> syntax to avoid scope ambiguity.`,
  [38]: `Duplicate slot names found. `,
  [39]: `Extraneous children found when component already has explicitly named default slot. These children will be ignored.`,
  [40]: `v-slot can only be used on components or <template> tags.`,
  [41]: `v-model is missing expression.`,
  [42]: `v-model value must be a valid JavaScript member expression.`,
  [43]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`,
  [44]: `v-model cannot be used on a prop, because local prop bindings are not writable.
Use a v-bind binding combined with a v-on listener that emits update:x event instead.`,
  [45]: `Error parsing JavaScript expression: `,
  [46]: `<KeepAlive> expects exactly one child component.`,
  // generic errors
  [47]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
  [48]: `ES module mode is not supported in this build of compiler.`,
  [49]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
  [50]: `"scopeId" option is only supported in module mode.`,
  // deprecations
  [51]: `@vnode-* hooks in templates are deprecated. Use the vue: prefix instead. For example, @vnode-mounted should be changed to @vue:mounted. @vnode-* hooks support will be removed in 3.4.`,
  [52]: `v-is="component-name" has been deprecated. Use is="vue:component-name" instead. v-is support will be removed in 3.4.`,
  // just to fulfill types
  [53]: ``
};
const FRAGMENT = Symbol(`Fragment`);
const TELEPORT = Symbol(`Teleport`);
const SUSPENSE = Symbol(`Suspense`);
const KEEP_ALIVE = Symbol(`KeepAlive`);
const BASE_TRANSITION = Symbol(`BaseTransition`);
const OPEN_BLOCK = Symbol(`openBlock`);
const CREATE_BLOCK = Symbol(`createBlock`);
const CREATE_ELEMENT_BLOCK = Symbol(`createElementBlock`);
const CREATE_VNODE = Symbol(`createVNode`);
const CREATE_ELEMENT_VNODE = Symbol(`createElementVNode`);
const CREATE_COMMENT = Symbol(`createCommentVNode`);
const CREATE_TEXT = Symbol(`createTextVNode`);
const CREATE_STATIC = Symbol(`createStaticVNode`);
const RESOLVE_COMPONENT = Symbol(`resolveComponent`);
const RESOLVE_DYNAMIC_COMPONENT = Symbol(
  `resolveDynamicComponent`
);
const RESOLVE_DIRECTIVE = Symbol(`resolveDirective`);
const RESOLVE_FILTER = Symbol(`resolveFilter`);
const WITH_DIRECTIVES = Symbol(`withDirectives`);
const RENDER_LIST = Symbol(`renderList`);
const RENDER_SLOT = Symbol(`renderSlot`);
const CREATE_SLOTS = Symbol(`createSlots`);
const TO_DISPLAY_STRING = Symbol(`toDisplayString`);
const MERGE_PROPS = Symbol(`mergeProps`);
const NORMALIZE_CLASS = Symbol(`normalizeClass`);
const NORMALIZE_STYLE = Symbol(`normalizeStyle`);
const NORMALIZE_PROPS = Symbol(`normalizeProps`);
const GUARD_REACTIVE_PROPS = Symbol(`guardReactiveProps`);
const TO_HANDLERS = Symbol(`toHandlers`);
const CAMELIZE = Symbol(`camelize`);
const CAPITALIZE = Symbol(`capitalize`);
const TO_HANDLER_KEY = Symbol(`toHandlerKey`);
const SET_BLOCK_TRACKING = Symbol(`setBlockTracking`);
const PUSH_SCOPE_ID = Symbol(`pushScopeId`);
const POP_SCOPE_ID = Symbol(`popScopeId`);
const WITH_CTX = Symbol(`withCtx`);
const UNREF = Symbol(`unref`);
const IS_REF = Symbol(`isRef`);
const WITH_MEMO = Symbol(`withMemo`);
const IS_MEMO_SAME = Symbol(`isMemoSame`);
const helperNameMap = {
  [FRAGMENT]: `Fragment`,
  [TELEPORT]: `Teleport`,
  [SUSPENSE]: `Suspense`,
  [KEEP_ALIVE]: `KeepAlive`,
  [BASE_TRANSITION]: `BaseTransition`,
  [OPEN_BLOCK]: `openBlock`,
  [CREATE_BLOCK]: `createBlock`,
  [CREATE_ELEMENT_BLOCK]: `createElementBlock`,
  [CREATE_VNODE]: `createVNode`,
  [CREATE_ELEMENT_VNODE]: `createElementVNode`,
  [CREATE_COMMENT]: `createCommentVNode`,
  [CREATE_TEXT]: `createTextVNode`,
  [CREATE_STATIC]: `createStaticVNode`,
  [RESOLVE_COMPONENT]: `resolveComponent`,
  [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
  [RESOLVE_DIRECTIVE]: `resolveDirective`,
  [RESOLVE_FILTER]: `resolveFilter`,
  [WITH_DIRECTIVES]: `withDirectives`,
  [RENDER_LIST]: `renderList`,
  [RENDER_SLOT]: `renderSlot`,
  [CREATE_SLOTS]: `createSlots`,
  [TO_DISPLAY_STRING]: `toDisplayString`,
  [MERGE_PROPS]: `mergeProps`,
  [NORMALIZE_CLASS]: `normalizeClass`,
  [NORMALIZE_STYLE]: `normalizeStyle`,
  [NORMALIZE_PROPS]: `normalizeProps`,
  [GUARD_REACTIVE_PROPS]: `guardReactiveProps`,
  [TO_HANDLERS]: `toHandlers`,
  [CAMELIZE]: `camelize`,
  [CAPITALIZE]: `capitalize`,
  [TO_HANDLER_KEY]: `toHandlerKey`,
  [SET_BLOCK_TRACKING]: `setBlockTracking`,
  [PUSH_SCOPE_ID]: `pushScopeId`,
  [POP_SCOPE_ID]: `popScopeId`,
  [WITH_CTX]: `withCtx`,
  [UNREF]: `unref`,
  [IS_REF]: `isRef`,
  [WITH_MEMO]: `withMemo`,
  [IS_MEMO_SAME]: `isMemoSame`
};
function registerRuntimeHelpers(helpers) {
  Object.getOwnPropertySymbols(helpers).forEach((s) => {
    helperNameMap[s] = helpers[s];
  });
}
const locStub = {
  source: "",
  start: { line: 1, column: 1, offset: 0 },
  end: { line: 1, column: 1, offset: 0 }
};
function createRoot(children, loc = locStub) {
  return {
    type: 0,
    children,
    helpers: /* @__PURE__ */ new Set(),
    components: [],
    directives: [],
    hoists: [],
    imports: [],
    cached: 0,
    temps: 0,
    codegenNode: void 0,
    loc
  };
}
function createVNodeCall(context, tag3, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, isComponent2 = false, loc = locStub) {
  if (context) {
    if (isBlock) {
      context.helper(OPEN_BLOCK);
      context.helper(getVNodeBlockHelper(context.inSSR, isComponent2));
    } else {
      context.helper(getVNodeHelper(context.inSSR, isComponent2));
    }
    if (directives) {
      context.helper(WITH_DIRECTIVES);
    }
  }
  return {
    type: 13,
    tag: tag3,
    props,
    children,
    patchFlag,
    dynamicProps,
    directives,
    isBlock,
    disableTracking,
    isComponent: isComponent2,
    loc
  };
}
function createArrayExpression(elements, loc = locStub) {
  return {
    type: 17,
    loc,
    elements
  };
}
function createObjectExpression(properties, loc = locStub) {
  return {
    type: 15,
    loc,
    properties
  };
}
function createObjectProperty(key, value) {
  return {
    type: 16,
    loc: locStub,
    key: isString$2(key) ? createSimpleExpression(key, true) : key,
    value
  };
}
function createSimpleExpression(content, isStatic = false, loc = locStub, constType = 0) {
  return {
    type: 4,
    loc,
    content,
    isStatic,
    constType: isStatic ? 3 : constType
  };
}
function createInterpolation(content, loc) {
  return {
    type: 5,
    loc,
    content: isString$2(content) ? createSimpleExpression(content, false, loc) : content
  };
}
function createCompoundExpression(children, loc = locStub) {
  return {
    type: 8,
    loc,
    children
  };
}
function createCallExpression(callee, args = [], loc = locStub) {
  return {
    type: 14,
    loc,
    callee,
    arguments: args
  };
}
function createFunctionExpression(params, returns = void 0, newline2 = false, isSlot = false, loc = locStub) {
  return {
    type: 18,
    params,
    returns,
    newline: newline2,
    isSlot,
    loc
  };
}
function createConditionalExpression(test, consequent, alternate, newline2 = true) {
  return {
    type: 19,
    test,
    consequent,
    alternate,
    newline: newline2,
    loc: locStub
  };
}
function createCacheExpression(index, value, isVNode2 = false) {
  return {
    type: 20,
    index,
    value,
    isVNode: isVNode2,
    loc: locStub
  };
}
function createBlockStatement(body) {
  return {
    type: 21,
    body,
    loc: locStub
  };
}
function createTemplateLiteral(elements) {
  return {
    type: 22,
    elements,
    loc: locStub
  };
}
function createIfStatement(test, consequent, alternate) {
  return {
    type: 23,
    test,
    consequent,
    alternate,
    loc: locStub
  };
}
function createAssignmentExpression(left, right) {
  return {
    type: 24,
    left,
    right,
    loc: locStub
  };
}
function createSequenceExpression(expressions) {
  return {
    type: 25,
    expressions,
    loc: locStub
  };
}
function createReturnStatement(returns) {
  return {
    type: 26,
    returns,
    loc: locStub
  };
}
function getVNodeHelper(ssr, isComponent2) {
  return ssr || isComponent2 ? CREATE_VNODE : CREATE_ELEMENT_VNODE;
}
function getVNodeBlockHelper(ssr, isComponent2) {
  return ssr || isComponent2 ? CREATE_BLOCK : CREATE_ELEMENT_BLOCK;
}
function convertToBlock(node2, { helper, removeHelper, inSSR }) {
  if (!node2.isBlock) {
    node2.isBlock = true;
    removeHelper(getVNodeHelper(inSSR, node2.isComponent));
    helper(OPEN_BLOCK);
    helper(getVNodeBlockHelper(inSSR, node2.isComponent));
  }
}
function getAugmentedNamespace(n2) {
  if (n2.__esModule)
    return n2;
  var f = n2.default;
  if (typeof f == "function") {
    var a = function a2() {
      if (this instanceof a2) {
        var args = [null];
        args.push.apply(args, arguments);
        var Ctor = Function.bind.apply(f, args);
        return new Ctor();
      }
      return f.apply(this, arguments);
    };
    a.prototype = f.prototype;
  } else
    a = {};
  Object.defineProperty(a, "__esModule", { value: true });
  Object.keys(n2).forEach(function(k) {
    var d = Object.getOwnPropertyDescriptor(n2, k);
    Object.defineProperty(a, k, d.get ? d : {
      enumerable: true,
      get: function() {
        return n2[k];
      }
    });
  });
  return a;
}
var lib$1 = {};
Object.defineProperty(lib$1, "__esModule", {
  value: true
});
const defaultOptions = {
  sourceType: "script",
  sourceFilename: void 0,
  startColumn: 0,
  startLine: 1,
  allowAwaitOutsideFunction: false,
  allowReturnOutsideFunction: false,
  allowNewTargetOutsideFunction: false,
  allowImportExportEverywhere: false,
  allowSuperOutsideMethod: false,
  allowUndeclaredExports: false,
  plugins: [],
  strictMode: null,
  ranges: false,
  tokens: false,
  createParenthesizedExpressions: false,
  errorRecovery: false,
  attachComment: true,
  annexB: true
};
function getOptions(opts) {
  if (opts && opts.annexB != null && opts.annexB !== false) {
    throw new Error("The `annexB` option can only be set to `false`.");
  }
  const options = {};
  for (const key of Object.keys(defaultOptions)) {
    options[key] = opts && opts[key] != null ? opts[key] : defaultOptions[key];
  }
  return options;
}
class TokContext {
  constructor(token, preserveSpace) {
    this.token = void 0;
    this.preserveSpace = void 0;
    this.token = token;
    this.preserveSpace = !!preserveSpace;
  }
}
const types$1 = {
  brace: new TokContext("{"),
  j_oTag: new TokContext("<tag"),
  j_cTag: new TokContext("</tag"),
  j_expr: new TokContext("<tag>...</tag>", true)
};
{
  types$1.template = new TokContext("`", true);
}
const beforeExpr = true;
const startsExpr = true;
const isLoop = true;
const isAssign = true;
const prefix = true;
const postfix = true;
class ExportedTokenType {
  constructor(label, conf = {}) {
    this.label = void 0;
    this.keyword = void 0;
    this.beforeExpr = void 0;
    this.startsExpr = void 0;
    this.rightAssociative = void 0;
    this.isLoop = void 0;
    this.isAssign = void 0;
    this.prefix = void 0;
    this.postfix = void 0;
    this.binop = void 0;
    this.label = label;
    this.keyword = conf.keyword;
    this.beforeExpr = !!conf.beforeExpr;
    this.startsExpr = !!conf.startsExpr;
    this.rightAssociative = !!conf.rightAssociative;
    this.isLoop = !!conf.isLoop;
    this.isAssign = !!conf.isAssign;
    this.prefix = !!conf.prefix;
    this.postfix = !!conf.postfix;
    this.binop = conf.binop != null ? conf.binop : null;
    {
      this.updateContext = null;
    }
  }
}
const keywords$1 = /* @__PURE__ */ new Map();
function createKeyword(name, options = {}) {
  options.keyword = name;
  const token = createToken(name, options);
  keywords$1.set(name, token);
  return token;
}
function createBinop(name, binop) {
  return createToken(name, {
    beforeExpr,
    binop
  });
}
let tokenTypeCounter = -1;
const tokenTypes$1 = [];
const tokenLabels = [];
const tokenBinops = [];
const tokenBeforeExprs = [];
const tokenStartsExprs = [];
const tokenPrefixes = [];
function createToken(name, options = {}) {
  var _options$binop, _options$beforeExpr, _options$startsExpr, _options$prefix;
  ++tokenTypeCounter;
  tokenLabels.push(name);
  tokenBinops.push((_options$binop = options.binop) != null ? _options$binop : -1);
  tokenBeforeExprs.push((_options$beforeExpr = options.beforeExpr) != null ? _options$beforeExpr : false);
  tokenStartsExprs.push((_options$startsExpr = options.startsExpr) != null ? _options$startsExpr : false);
  tokenPrefixes.push((_options$prefix = options.prefix) != null ? _options$prefix : false);
  tokenTypes$1.push(new ExportedTokenType(name, options));
  return tokenTypeCounter;
}
function createKeywordLike(name, options = {}) {
  var _options$binop2, _options$beforeExpr2, _options$startsExpr2, _options$prefix2;
  ++tokenTypeCounter;
  keywords$1.set(name, tokenTypeCounter);
  tokenLabels.push(name);
  tokenBinops.push((_options$binop2 = options.binop) != null ? _options$binop2 : -1);
  tokenBeforeExprs.push((_options$beforeExpr2 = options.beforeExpr) != null ? _options$beforeExpr2 : false);
  tokenStartsExprs.push((_options$startsExpr2 = options.startsExpr) != null ? _options$startsExpr2 : false);
  tokenPrefixes.push((_options$prefix2 = options.prefix) != null ? _options$prefix2 : false);
  tokenTypes$1.push(new ExportedTokenType("name", options));
  return tokenTypeCounter;
}
const tt = {
  bracketL: createToken("[", {
    beforeExpr,
    startsExpr
  }),
  bracketHashL: createToken("#[", {
    beforeExpr,
    startsExpr
  }),
  bracketBarL: createToken("[|", {
    beforeExpr,
    startsExpr
  }),
  bracketR: createToken("]"),
  bracketBarR: createToken("|]"),
  braceL: createToken("{", {
    beforeExpr,
    startsExpr
  }),
  braceBarL: createToken("{|", {
    beforeExpr,
    startsExpr
  }),
  braceHashL: createToken("#{", {
    beforeExpr,
    startsExpr
  }),
  braceR: createToken("}"),
  braceBarR: createToken("|}"),
  parenL: createToken("(", {
    beforeExpr,
    startsExpr
  }),
  parenR: createToken(")"),
  comma: createToken(",", {
    beforeExpr
  }),
  semi: createToken(";", {
    beforeExpr
  }),
  colon: createToken(":", {
    beforeExpr
  }),
  doubleColon: createToken("::", {
    beforeExpr
  }),
  dot: createToken("."),
  question: createToken("?", {
    beforeExpr
  }),
  questionDot: createToken("?."),
  arrow: createToken("=>", {
    beforeExpr
  }),
  template: createToken("template"),
  ellipsis: createToken("...", {
    beforeExpr
  }),
  backQuote: createToken("`", {
    startsExpr
  }),
  dollarBraceL: createToken("${", {
    beforeExpr,
    startsExpr
  }),
  templateTail: createToken("...`", {
    startsExpr
  }),
  templateNonTail: createToken("...${", {
    beforeExpr,
    startsExpr
  }),
  at: createToken("@"),
  hash: createToken("#", {
    startsExpr
  }),
  interpreterDirective: createToken("#!..."),
  eq: createToken("=", {
    beforeExpr,
    isAssign
  }),
  assign: createToken("_=", {
    beforeExpr,
    isAssign
  }),
  slashAssign: createToken("_=", {
    beforeExpr,
    isAssign
  }),
  xorAssign: createToken("_=", {
    beforeExpr,
    isAssign
  }),
  moduloAssign: createToken("_=", {
    beforeExpr,
    isAssign
  }),
  incDec: createToken("++/--", {
    prefix,
    postfix,
    startsExpr
  }),
  bang: createToken("!", {
    beforeExpr,
    prefix,
    startsExpr
  }),
  tilde: createToken("~", {
    beforeExpr,
    prefix,
    startsExpr
  }),
  doubleCaret: createToken("^^", {
    startsExpr
  }),
  doubleAt: createToken("@@", {
    startsExpr
  }),
  pipeline: createBinop("|>", 0),
  nullishCoalescing: createBinop("??", 1),
  logicalOR: createBinop("||", 1),
  logicalAND: createBinop("&&", 2),
  bitwiseOR: createBinop("|", 3),
  bitwiseXOR: createBinop("^", 4),
  bitwiseAND: createBinop("&", 5),
  equality: createBinop("==/!=/===/!==", 6),
  lt: createBinop("</>/<=/>=", 7),
  gt: createBinop("</>/<=/>=", 7),
  relational: createBinop("</>/<=/>=", 7),
  bitShift: createBinop("<</>>/>>>", 8),
  bitShiftL: createBinop("<</>>/>>>", 8),
  bitShiftR: createBinop("<</>>/>>>", 8),
  plusMin: createToken("+/-", {
    beforeExpr,
    binop: 9,
    prefix,
    startsExpr
  }),
  modulo: createToken("%", {
    binop: 10,
    startsExpr
  }),
  star: createToken("*", {
    binop: 10
  }),
  slash: createBinop("/", 10),
  exponent: createToken("**", {
    beforeExpr,
    binop: 11,
    rightAssociative: true
  }),
  _in: createKeyword("in", {
    beforeExpr,
    binop: 7
  }),
  _instanceof: createKeyword("instanceof", {
    beforeExpr,
    binop: 7
  }),
  _break: createKeyword("break"),
  _case: createKeyword("case", {
    beforeExpr
  }),
  _catch: createKeyword("catch"),
  _continue: createKeyword("continue"),
  _debugger: createKeyword("debugger"),
  _default: createKeyword("default", {
    beforeExpr
  }),
  _else: createKeyword("else", {
    beforeExpr
  }),
  _finally: createKeyword("finally"),
  _function: createKeyword("function", {
    startsExpr
  }),
  _if: createKeyword("if"),
  _return: createKeyword("return", {
    beforeExpr
  }),
  _switch: createKeyword("switch"),
  _throw: createKeyword("throw", {
    beforeExpr,
    prefix,
    startsExpr
  }),
  _try: createKeyword("try"),
  _var: createKeyword("var"),
  _const: createKeyword("const"),
  _with: createKeyword("with"),
  _new: createKeyword("new", {
    beforeExpr,
    startsExpr
  }),
  _this: createKeyword("this", {
    startsExpr
  }),
  _super: createKeyword("super", {
    startsExpr
  }),
  _class: createKeyword("class", {
    startsExpr
  }),
  _extends: createKeyword("extends", {
    beforeExpr
  }),
  _export: createKeyword("export"),
  _import: createKeyword("import", {
    startsExpr
  }),
  _null: createKeyword("null", {
    startsExpr
  }),
  _true: createKeyword("true", {
    startsExpr
  }),
  _false: createKeyword("false", {
    startsExpr
  }),
  _typeof: createKeyword("typeof", {
    beforeExpr,
    prefix,
    startsExpr
  }),
  _void: createKeyword("void", {
    beforeExpr,
    prefix,
    startsExpr
  }),
  _delete: createKeyword("delete", {
    beforeExpr,
    prefix,
    startsExpr
  }),
  _do: createKeyword("do", {
    isLoop,
    beforeExpr
  }),
  _for: createKeyword("for", {
    isLoop
  }),
  _while: createKeyword("while", {
    isLoop
  }),
  _as: createKeywordLike("as", {
    startsExpr
  }),
  _assert: createKeywordLike("assert", {
    startsExpr
  }),
  _async: createKeywordLike("async", {
    startsExpr
  }),
  _await: createKeywordLike("await", {
    startsExpr
  }),
  _from: createKeywordLike("from", {
    startsExpr
  }),
  _get: createKeywordLike("get", {
    startsExpr
  }),
  _let: createKeywordLike("let", {
    startsExpr
  }),
  _meta: createKeywordLike("meta", {
    startsExpr
  }),
  _of: createKeywordLike("of", {
    startsExpr
  }),
  _sent: createKeywordLike("sent", {
    startsExpr
  }),
  _set: createKeywordLike("set", {
    startsExpr
  }),
  _static: createKeywordLike("static", {
    startsExpr
  }),
  _using: createKeywordLike("using", {
    startsExpr
  }),
  _yield: createKeywordLike("yield", {
    startsExpr
  }),
  _asserts: createKeywordLike("asserts", {
    startsExpr
  }),
  _checks: createKeywordLike("checks", {
    startsExpr
  }),
  _exports: createKeywordLike("exports", {
    startsExpr
  }),
  _global: createKeywordLike("global", {
    startsExpr
  }),
  _implements: createKeywordLike("implements", {
    startsExpr
  }),
  _intrinsic: createKeywordLike("intrinsic", {
    startsExpr
  }),
  _infer: createKeywordLike("infer", {
    startsExpr
  }),
  _is: createKeywordLike("is", {
    startsExpr
  }),
  _mixins: createKeywordLike("mixins", {
    startsExpr
  }),
  _proto: createKeywordLike("proto", {
    startsExpr
  }),
  _require: createKeywordLike("require", {
    startsExpr
  }),
  _satisfies: createKeywordLike("satisfies", {
    startsExpr
  }),
  _keyof: createKeywordLike("keyof", {
    startsExpr
  }),
  _readonly: createKeywordLike("readonly", {
    startsExpr
  }),
  _unique: createKeywordLike("unique", {
    startsExpr
  }),
  _abstract: createKeywordLike("abstract", {
    startsExpr
  }),
  _declare: createKeywordLike("declare", {
    startsExpr
  }),
  _enum: createKeywordLike("enum", {
    startsExpr
  }),
  _module: createKeywordLike("module", {
    startsExpr
  }),
  _namespace: createKeywordLike("namespace", {
    startsExpr
  }),
  _interface: createKeywordLike("interface", {
    startsExpr
  }),
  _type: createKeywordLike("type", {
    startsExpr
  }),
  _opaque: createKeywordLike("opaque", {
    startsExpr
  }),
  name: createToken("name", {
    startsExpr
  }),
  string: createToken("string", {
    startsExpr
  }),
  num: createToken("num", {
    startsExpr
  }),
  bigint: createToken("bigint", {
    startsExpr
  }),
  decimal: createToken("decimal", {
    startsExpr
  }),
  regexp: createToken("regexp", {
    startsExpr
  }),
  privateName: createToken("#name", {
    startsExpr
  }),
  eof: createToken("eof"),
  jsxName: createToken("jsxName"),
  jsxText: createToken("jsxText", {
    beforeExpr: true
  }),
  jsxTagStart: createToken("jsxTagStart", {
    startsExpr: true
  }),
  jsxTagEnd: createToken("jsxTagEnd"),
  placeholder: createToken("%%", {
    startsExpr: true
  })
};
function tokenIsIdentifier(token) {
  return token >= 93 && token <= 130;
}
function tokenKeywordOrIdentifierIsKeyword(token) {
  return token <= 92;
}
function tokenIsKeywordOrIdentifier(token) {
  return token >= 58 && token <= 130;
}
function tokenIsLiteralPropertyName(token) {
  return token >= 58 && token <= 134;
}
function tokenComesBeforeExpression(token) {
  return tokenBeforeExprs[token];
}
function tokenCanStartExpression(token) {
  return tokenStartsExprs[token];
}
function tokenIsAssignment(token) {
  return token >= 29 && token <= 33;
}
function tokenIsFlowInterfaceOrTypeOrOpaque(token) {
  return token >= 127 && token <= 129;
}
function tokenIsLoop(token) {
  return token >= 90 && token <= 92;
}
function tokenIsKeyword(token) {
  return token >= 58 && token <= 92;
}
function tokenIsOperator(token) {
  return token >= 39 && token <= 59;
}
function tokenIsPostfix(token) {
  return token === 34;
}
function tokenIsPrefix(token) {
  return tokenPrefixes[token];
}
function tokenIsTSTypeOperator(token) {
  return token >= 119 && token <= 121;
}
function tokenIsTSDeclarationStart(token) {
  return token >= 122 && token <= 128;
}
function tokenLabelName(token) {
  return tokenLabels[token];
}
function tokenOperatorPrecedence(token) {
  return tokenBinops[token];
}
function tokenIsRightAssociative(token) {
  return token === 57;
}
function tokenIsTemplate(token) {
  return token >= 24 && token <= 25;
}
function getExportedToken(token) {
  return tokenTypes$1[token];
}
{
  tokenTypes$1[8].updateContext = (context) => {
    context.pop();
  };
  tokenTypes$1[5].updateContext = tokenTypes$1[7].updateContext = tokenTypes$1[23].updateContext = (context) => {
    context.push(types$1.brace);
  };
  tokenTypes$1[22].updateContext = (context) => {
    if (context[context.length - 1] === types$1.template) {
      context.pop();
    } else {
      context.push(types$1.template);
    }
  };
  tokenTypes$1[140].updateContext = (context) => {
    context.push(types$1.j_expr, types$1.j_oTag);
  };
}
function _objectWithoutPropertiesLoose(source, excluded) {
  if (source == null)
    return {};
  var target = {};
  var sourceKeys = Object.keys(source);
  var key, i;
  for (i = 0; i < sourceKeys.length; i++) {
    key = sourceKeys[i];
    if (excluded.indexOf(key) >= 0)
      continue;
    target[key] = source[key];
  }
  return target;
}
class Position2 {
  constructor(line, col, index) {
    this.line = void 0;
    this.column = void 0;
    this.index = void 0;
    this.line = line;
    this.column = col;
    this.index = index;
  }
}
class SourceLocation {
  constructor(start, end) {
    this.start = void 0;
    this.end = void 0;
    this.filename = void 0;
    this.identifierName = void 0;
    this.start = start;
    this.end = end;
  }
}
function createPositionWithColumnOffset(position, columnOffset) {
  const {
    line,
    column,
    index
  } = position;
  return new Position2(line, column + columnOffset, index + columnOffset);
}
var ParseErrorCode = {
  SyntaxError: "BABEL_PARSER_SYNTAX_ERROR",
  SourceTypeModuleError: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
};
const reflect = (keys, last2 = keys.length - 1) => ({
  get() {
    return keys.reduce((object2, key) => object2[key], this);
  },
  set(value) {
    keys.reduce((item, key, i) => i === last2 ? item[key] = value : item[key], this);
  }
});
const instantiate = (constructor, properties, descriptors) => Object.keys(descriptors).map((key) => [key, descriptors[key]]).filter(([, descriptor]) => !!descriptor).map(([key, descriptor]) => [key, typeof descriptor === "function" ? {
  value: descriptor,
  enumerable: false
} : typeof descriptor.reflect === "string" ? Object.assign({}, descriptor, reflect(descriptor.reflect.split("."))) : descriptor]).reduce((instance, [key, descriptor]) => Object.defineProperty(instance, key, Object.assign({
  configurable: true
}, descriptor)), Object.assign(new constructor(), properties));
var ModuleErrors = {
  ImportMetaOutsideModule: {
    message: `import.meta may appear only with 'sourceType: "module"'`,
    code: ParseErrorCode.SourceTypeModuleError
  },
  ImportOutsideModule: {
    message: `'import' and 'export' may appear only with 'sourceType: "module"'`,
    code: ParseErrorCode.SourceTypeModuleError
  }
};
const NodeDescriptions = {
  ArrayPattern: "array destructuring pattern",
  AssignmentExpression: "assignment expression",
  AssignmentPattern: "assignment expression",
  ArrowFunctionExpression: "arrow function expression",
  ConditionalExpression: "conditional expression",
  CatchClause: "catch clause",
  ForOfStatement: "for-of statement",
  ForInStatement: "for-in statement",
  ForStatement: "for-loop",
  FormalParameters: "function parameter list",
  Identifier: "identifier",
  ImportSpecifier: "import specifier",
  ImportDefaultSpecifier: "import default specifier",
  ImportNamespaceSpecifier: "import namespace specifier",
  ObjectPattern: "object destructuring pattern",
  ParenthesizedExpression: "parenthesized expression",
  RestElement: "rest element",
  UpdateExpression: {
    true: "prefix operation",
    false: "postfix operation"
  },
  VariableDeclarator: "variable declaration",
  YieldExpression: "yield expression"
};
const toNodeDescription = ({
  type,
  prefix: prefix2
}) => type === "UpdateExpression" ? NodeDescriptions.UpdateExpression[String(prefix2)] : NodeDescriptions[type];
var StandardErrors = {
  AccessorIsGenerator: ({
    kind
  }) => `A ${kind}ter cannot be a generator.`,
  ArgumentsInClass: "'arguments' is only allowed in functions and class methods.",
  AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block.",
  AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function.",
  AwaitBindingIdentifierInStaticBlock: "Can not use 'await' as identifier inside a static block.",
  AwaitExpressionFormalParameter: "'await' is not allowed in async function parameters.",
  AwaitInUsingBinding: "'await' is not allowed to be used as a name in 'using' declarations.",
  AwaitNotInAsyncContext: "'await' is only allowed within async functions and at the top levels of modules.",
  AwaitNotInAsyncFunction: "'await' is only allowed within async functions.",
  BadGetterArity: "A 'get' accessor must not have any formal parameters.",
  BadSetterArity: "A 'set' accessor must have exactly one formal parameter.",
  BadSetterRestParameter: "A 'set' accessor function argument must not be a rest parameter.",
  ConstructorClassField: "Classes may not have a field named 'constructor'.",
  ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'.",
  ConstructorIsAccessor: "Class constructor may not be an accessor.",
  ConstructorIsAsync: "Constructor can't be an async function.",
  ConstructorIsGenerator: "Constructor can't be a generator.",
  DeclarationMissingInitializer: ({
    kind
  }) => `Missing initializer in ${kind} declaration.`,
  DecoratorArgumentsOutsideParentheses: "Decorator arguments must be moved inside parentheses: use '@(decorator(args))' instead of '@(decorator)(args)'.",
  DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. Remove the 'decoratorsBeforeExport: true' option to use the 'export @decorator class {}' syntax.",
  DecoratorsBeforeAfterExport: "Decorators can be placed *either* before or after the 'export' keyword, but not in both locations at the same time.",
  DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",
  DecoratorExportClass: "Decorators must be placed *after* the 'export' keyword. Remove the 'decoratorsBeforeExport: false' option to use the '@decorator export class {}' syntax.",
  DecoratorSemicolon: "Decorators must not be followed by a semicolon.",
  DecoratorStaticBlock: "Decorators can't be used with a static block.",
  DeletePrivateField: "Deleting a private field is not allowed.",
  DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.",
  DuplicateConstructor: "Duplicate constructor in the same class.",
  DuplicateDefaultExport: "Only one default export allowed per module.",
  DuplicateExport: ({
    exportName
  }) => `\`${exportName}\` has already been exported. Exported identifiers must be unique.`,
  DuplicateProto: "Redefinition of __proto__ property.",
  DuplicateRegExpFlags: "Duplicate regular expression flag.",
  ElementAfterRest: "Rest element must be last element.",
  EscapedCharNotAnIdentifier: "Invalid Unicode escape.",
  ExportBindingIsString: ({
    localName,
    exportName
  }) => `A string literal cannot be used as an exported binding without \`from\`.
- Did you mean \`export { '${localName}' as '${exportName}' } from 'some-module'\`?`,
  ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'.",
  ForInOfLoopInitializer: ({
    type
  }) => `'${type === "ForInStatement" ? "for-in" : "for-of"}' loop variable declaration may not have an initializer.`,
  ForInUsing: "For-in loop may not start with 'using' declaration.",
  ForOfAsync: "The left-hand side of a for-of loop may not be 'async'.",
  ForOfLet: "The left-hand side of a for-of loop may not start with 'let'.",
  GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block.",
  IllegalBreakContinue: ({
    type
  }) => `Unsyntactic ${type === "BreakStatement" ? "break" : "continue"}.`,
  IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list.",
  IllegalReturn: "'return' outside of function.",
  ImportBindingIsString: ({
    importName
  }) => `A string literal cannot be used as an imported binding.
- Did you mean \`import { "${importName}" as foo }\`?`,
  ImportCallArgumentTrailingComma: "Trailing comma is disallowed inside import(...) arguments.",
  ImportCallArity: ({
    maxArgumentCount
  }) => `\`import()\` requires exactly ${maxArgumentCount === 1 ? "one argument" : "one or two arguments"}.`,
  ImportCallNotNewExpression: "Cannot use new with import(...).",
  ImportCallSpreadArgument: "`...` is not allowed in `import()`.",
  ImportJSONBindingNotDefault: "A JSON module can only be imported with `default`.",
  ImportReflectionHasAssertion: "`import module x` cannot have assertions.",
  ImportReflectionNotBinding: 'Only `import module x from "./module"` is valid.',
  IncompatibleRegExpUVFlags: "The 'u' and 'v' regular expression flags cannot be enabled at the same time.",
  InvalidBigIntLiteral: "Invalid BigIntLiteral.",
  InvalidCodePoint: "Code point out of bounds.",
  InvalidCoverInitializedName: "Invalid shorthand property initializer.",
  InvalidDecimal: "Invalid decimal.",
  InvalidDigit: ({
    radix
  }) => `Expected number in radix ${radix}.`,
  InvalidEscapeSequence: "Bad character escape sequence.",
  InvalidEscapeSequenceTemplate: "Invalid escape sequence in template.",
  InvalidEscapedReservedWord: ({
    reservedWord
  }) => `Escape sequence in keyword ${reservedWord}.`,
  InvalidIdentifier: ({
    identifierName
  }) => `Invalid identifier ${identifierName}.`,
  InvalidLhs: ({
    ancestor
  }) => `Invalid left-hand side in ${toNodeDescription(ancestor)}.`,
  InvalidLhsBinding: ({
    ancestor
  }) => `Binding invalid left-hand side in ${toNodeDescription(ancestor)}.`,
  InvalidNumber: "Invalid number.",
  InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'.",
  InvalidOrUnexpectedToken: ({
    unexpected
  }) => `Unexpected character '${unexpected}'.`,
  InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern.",
  InvalidPrivateFieldResolution: ({
    identifierName
  }) => `Private name #${identifierName} is not defined.`,
  InvalidPropertyBindingPattern: "Binding member expression.",
  InvalidRecordProperty: "Only properties and spread elements are allowed in record definitions.",
  InvalidRestAssignmentPattern: "Invalid rest operator's argument.",
  LabelRedeclaration: ({
    labelName
  }) => `Label '${labelName}' is already declared.`,
  LetInLexicalBinding: "'let' is not allowed to be used as a name in 'let' or 'const' declarations.",
  LineTerminatorBeforeArrow: "No line break is allowed before '=>'.",
  MalformedRegExpFlags: "Invalid regular expression flag.",
  MissingClassName: "A class name is required.",
  MissingEqInAssignment: "Only '=' operator can be used for specifying default value.",
  MissingSemicolon: "Missing semicolon.",
  MissingPlugin: ({
    missingPlugin
  }) => `This experimental syntax requires enabling the parser plugin: ${missingPlugin.map((name) => JSON.stringify(name)).join(", ")}.`,
  MissingOneOfPlugins: ({
    missingPlugin
  }) => `This experimental syntax requires enabling one of the following parser plugin(s): ${missingPlugin.map((name) => JSON.stringify(name)).join(", ")}.`,
  MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX.",
  MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators.",
  ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`.",
  ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values.",
  ModuleAttributesWithDuplicateKeys: ({
    key
  }) => `Duplicate key "${key}" is not allowed in module attributes.`,
  ModuleExportNameHasLoneSurrogate: ({
    surrogateCharCode
  }) => `An export name cannot include a lone surrogate, found '\\u${surrogateCharCode.toString(16)}'.`,
  ModuleExportUndefined: ({
    localName
  }) => `Export '${localName}' is not defined.`,
  MultipleDefaultsInSwitch: "Multiple default clauses.",
  NewlineAfterThrow: "Illegal newline after throw.",
  NoCatchOrFinally: "Missing catch or finally clause.",
  NumberIdentifier: "Identifier directly after number.",
  NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences.",
  ObsoleteAwaitStar: "'await*' has been removed from the async functions proposal. Use Promise.all() instead.",
  OptionalChainingNoNew: "Constructors in/after an Optional Chain are not allowed.",
  OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain.",
  OverrideOnConstructor: "'override' modifier cannot appear on a constructor declaration.",
  ParamDupe: "Argument name clash.",
  PatternHasAccessor: "Object pattern can't contain getter or setter.",
  PatternHasMethod: "Object pattern can't contain methods.",
  PrivateInExpectedIn: ({
    identifierName
  }) => `Private names are only allowed in property accesses (\`obj.#${identifierName}\`) or in \`in\` expressions (\`#${identifierName} in obj\`).`,
  PrivateNameRedeclaration: ({
    identifierName
  }) => `Duplicate private name #${identifierName}.`,
  RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",
  RecordNoProto: "'__proto__' is not allowed in Record expressions.",
  RestTrailingComma: "Unexpected trailing comma after rest element.",
  SloppyFunction: "In non-strict mode code, functions can only be declared at top level or inside a block.",
  SloppyFunctionAnnexB: "In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement.",
  StaticPrototype: "Classes may not have static property named prototype.",
  SuperNotAllowed: "`super()` is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?",
  SuperPrivateField: "Private fields can't be accessed on super.",
  TrailingDecorator: "Decorators must be attached to a class element.",
  TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'.",
  TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'.",
  UnexpectedArgumentPlaceholder: "Unexpected argument placeholder.",
  UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal.',
  UnexpectedDigitAfterHash: "Unexpected digit after hash token.",
  UnexpectedImportExport: "'import' and 'export' may only appear at the top level.",
  UnexpectedKeyword: ({
    keyword
  }) => `Unexpected keyword '${keyword}'.`,
  UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration.",
  UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context.",
  UnexpectedNewTarget: "`new.target` can only be used in functions or class properties.",
  UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits.",
  UnexpectedPrivateField: "Unexpected private name.",
  UnexpectedReservedWord: ({
    reservedWord
  }) => `Unexpected reserved word '${reservedWord}'.`,
  UnexpectedSuper: "'super' is only allowed in object methods and classes.",
  UnexpectedToken: ({
    expected,
    unexpected
  }) => `Unexpected token${unexpected ? ` '${unexpected}'.` : ""}${expected ? `, expected "${expected}"` : ""}`,
  UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",
  UnexpectedUsingDeclaration: "Using declaration cannot appear in the top level when source type is `script`.",
  UnsupportedBind: "Binding should be performed on object property.",
  UnsupportedDecoratorExport: "A decorated export must export a class declaration.",
  UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.",
  UnsupportedImport: "`import` can only be used in `import()` or `import.meta`.",
  UnsupportedMetaProperty: ({
    target,
    onlyValidPropertyName
  }) => `The only valid meta property for ${target} is ${target}.${onlyValidPropertyName}.`,
  UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters.",
  UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties.",
  UnsupportedSuper: "'super' can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop]).",
  UnterminatedComment: "Unterminated comment.",
  UnterminatedRegExp: "Unterminated regular expression.",
  UnterminatedString: "Unterminated string constant.",
  UnterminatedTemplate: "Unterminated template.",
  UsingDeclarationHasBindingPattern: "Using declaration cannot have destructuring patterns.",
  VarRedeclaration: ({
    identifierName
  }) => `Identifier '${identifierName}' has already been declared.`,
  YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator.",
  YieldInParameter: "Yield expression is not allowed in formal parameters.",
  ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0."
};
var StrictModeErrors = {
  StrictDelete: "Deleting local variable in strict mode.",
  StrictEvalArguments: ({
    referenceName
  }) => `Assigning to '${referenceName}' in strict mode.`,
  StrictEvalArgumentsBinding: ({
    bindingName
  }) => `Binding '${bindingName}' in strict mode.`,
  StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block.",
  StrictNumericEscape: "The only valid numeric escape in strict mode is '\\0'.",
  StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode.",
  StrictWith: "'with' in strict mode."
};
const UnparenthesizedPipeBodyDescriptions = /* @__PURE__ */ new Set(["ArrowFunctionExpression", "AssignmentExpression", "ConditionalExpression", "YieldExpression"]);
var PipelineOperatorErrors = {
  PipeBodyIsTighter: "Unexpected yield after pipeline body; any yield expression acting as Hack-style pipe body must be parenthesized due to its loose operator precedence.",
  PipeTopicRequiresHackPipes: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.',
  PipeTopicUnbound: "Topic reference is unbound; it must be inside a pipe body.",
  PipeTopicUnconfiguredToken: ({
    token
  }) => `Invalid topic token ${token}. In order to use ${token} as a topic reference, the pipelineOperator plugin must be configured with { "proposal": "hack", "topicToken": "${token}" }.`,
  PipeTopicUnused: "Hack-style pipe body does not contain a topic reference; Hack-style pipes must use topic at least once.",
  PipeUnparenthesizedBody: ({
    type
  }) => `Hack-style pipe body cannot be an unparenthesized ${toNodeDescription({
    type
  })}; please wrap it in parentheses.`,
  PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized.',
  PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression.",
  PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression.",
  PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference.",
  PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding.",
  PrimaryTopicRequiresSmartPipeline: 'Topic reference is used, but the pipelineOperator plugin was not passed a "proposal": "hack" or "smart" option.'
};
const _excluded$1 = ["toMessage"], _excluded2$1 = ["message"];
function toParseErrorConstructor(_ref2) {
  let {
    toMessage
  } = _ref2, properties = _objectWithoutPropertiesLoose(_ref2, _excluded$1);
  return function constructor({
    loc,
    details
  }) {
    return instantiate(SyntaxError, Object.assign({}, properties, {
      loc
    }), {
      clone(overrides = {}) {
        const loc2 = overrides.loc || {};
        return constructor({
          loc: new Position2("line" in loc2 ? loc2.line : this.loc.line, "column" in loc2 ? loc2.column : this.loc.column, "index" in loc2 ? loc2.index : this.loc.index),
          details: Object.assign({}, this.details, overrides.details)
        });
      },
      details: {
        value: details,
        enumerable: false
      },
      message: {
        get() {
          return `${toMessage(this.details)} (${this.loc.line}:${this.loc.column})`;
        },
        set(value) {
          Object.defineProperty(this, "message", {
            value
          });
        }
      },
      pos: {
        reflect: "loc.index",
        enumerable: true
      },
      missingPlugin: "missingPlugin" in details && {
        reflect: "details.missingPlugin",
        enumerable: true
      }
    });
  };
}
function ParseErrorEnum(argument, syntaxPlugin) {
  if (Array.isArray(argument)) {
    return (parseErrorTemplates) => ParseErrorEnum(parseErrorTemplates, argument[0]);
  }
  const ParseErrorConstructors = {};
  for (const reasonCode of Object.keys(argument)) {
    const template = argument[reasonCode];
    const _ref2 = typeof template === "string" ? {
      message: () => template
    } : typeof template === "function" ? {
      message: template
    } : template, {
      message
    } = _ref2, rest = _objectWithoutPropertiesLoose(_ref2, _excluded2$1);
    const toMessage = typeof message === "string" ? () => message : message;
    ParseErrorConstructors[reasonCode] = toParseErrorConstructor(Object.assign({
      code: ParseErrorCode.SyntaxError,
      reasonCode,
      toMessage
    }, syntaxPlugin ? {
      syntaxPlugin
    } : {}, rest));
  }
  return ParseErrorConstructors;
}
const Errors = Object.assign({}, ParseErrorEnum(ModuleErrors), ParseErrorEnum(StandardErrors), ParseErrorEnum(StrictModeErrors), ParseErrorEnum`pipelineOperator`(PipelineOperatorErrors));
const {
  defineProperty
} = Object;
const toUnenumerable = (object2, key) => defineProperty(object2, key, {
  enumerable: false,
  value: object2[key]
});
function toESTreeLocation(node2) {
  node2.loc.start && toUnenumerable(node2.loc.start, "index");
  node2.loc.end && toUnenumerable(node2.loc.end, "index");
  return node2;
}
var estree = (superClass) => class ESTreeParserMixin extends superClass {
  parse() {
    const file = toESTreeLocation(super.parse());
    if (this.options.tokens) {
      file.tokens = file.tokens.map(toESTreeLocation);
    }
    return file;
  }
  parseRegExpLiteral({
    pattern,
    flags
  }) {
    let regex = null;
    try {
      regex = new RegExp(pattern, flags);
    } catch (e) {
    }
    const node2 = this.estreeParseLiteral(regex);
    node2.regex = {
      pattern,
      flags
    };
    return node2;
  }
  parseBigIntLiteral(value) {
    let bigInt;
    try {
      bigInt = BigInt(value);
    } catch (_unused) {
      bigInt = null;
    }
    const node2 = this.estreeParseLiteral(bigInt);
    node2.bigint = String(node2.value || value);
    return node2;
  }
  parseDecimalLiteral(value) {
    const decimal = null;
    const node2 = this.estreeParseLiteral(decimal);
    node2.decimal = String(node2.value || value);
    return node2;
  }
  estreeParseLiteral(value) {
    return this.parseLiteral(value, "Literal");
  }
  parseStringLiteral(value) {
    return this.estreeParseLiteral(value);
  }
  parseNumericLiteral(value) {
    return this.estreeParseLiteral(value);
  }
  parseNullLiteral() {
    return this.estreeParseLiteral(null);
  }
  parseBooleanLiteral(value) {
    return this.estreeParseLiteral(value);
  }
  directiveToStmt(directive) {
    const expression = directive.value;
    delete directive.value;
    expression.type = "Literal";
    expression.raw = expression.extra.raw;
    expression.value = expression.extra.expressionValue;
    const stmt = directive;
    stmt.type = "ExpressionStatement";
    stmt.expression = expression;
    stmt.directive = expression.extra.rawValue;
    delete expression.extra;
    return stmt;
  }
  initFunction(node2, isAsync) {
    super.initFunction(node2, isAsync);
    node2.expression = false;
  }
  checkDeclaration(node2) {
    if (node2 != null && this.isObjectProperty(node2)) {
      this.checkDeclaration(node2.value);
    } else {
      super.checkDeclaration(node2);
    }
  }
  getObjectOrClassMethodParams(method) {
    return method.value.params;
  }
  isValidDirective(stmt) {
    var _stmt$expression$extr;
    return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && !((_stmt$expression$extr = stmt.expression.extra) != null && _stmt$expression$extr.parenthesized);
  }
  parseBlockBody(node2, allowDirectives, topLevel, end, afterBlockParse) {
    super.parseBlockBody(node2, allowDirectives, topLevel, end, afterBlockParse);
    const directiveStatements = node2.directives.map((d) => this.directiveToStmt(d));
    node2.body = directiveStatements.concat(node2.body);
    delete node2.directives;
  }
  pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
    this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true);
    if (method.typeParameters) {
      method.value.typeParameters = method.typeParameters;
      delete method.typeParameters;
    }
    classBody.body.push(method);
  }
  parsePrivateName() {
    const node2 = super.parsePrivateName();
    {
      if (!this.getPluginOption("estree", "classFeatures")) {
        return node2;
      }
    }
    return this.convertPrivateNameToPrivateIdentifier(node2);
  }
  convertPrivateNameToPrivateIdentifier(node2) {
    const name = super.getPrivateNameSV(node2);
    node2 = node2;
    delete node2.id;
    node2.name = name;
    node2.type = "PrivateIdentifier";
    return node2;
  }
  isPrivateName(node2) {
    {
      if (!this.getPluginOption("estree", "classFeatures")) {
        return super.isPrivateName(node2);
      }
    }
    return node2.type === "PrivateIdentifier";
  }
  getPrivateNameSV(node2) {
    {
      if (!this.getPluginOption("estree", "classFeatures")) {
        return super.getPrivateNameSV(node2);
      }
    }
    return node2.name;
  }
  parseLiteral(value, type) {
    const node2 = super.parseLiteral(value, type);
    node2.raw = node2.extra.raw;
    delete node2.extra;
    return node2;
  }
  parseFunctionBody(node2, allowExpression, isMethod = false) {
    super.parseFunctionBody(node2, allowExpression, isMethod);
    node2.expression = node2.body.type !== "BlockStatement";
  }
  parseMethod(node2, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
    let funcNode = this.startNode();
    funcNode.kind = node2.kind;
    funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
    funcNode.type = "FunctionExpression";
    delete funcNode.kind;
    node2.value = funcNode;
    if (type === "ClassPrivateMethod") {
      node2.computed = false;
    }
    return this.finishNode(node2, "MethodDefinition");
  }
  parseClassProperty(...args) {
    const propertyNode = super.parseClassProperty(...args);
    {
      if (!this.getPluginOption("estree", "classFeatures")) {
        return propertyNode;
      }
    }
    propertyNode.type = "PropertyDefinition";
    return propertyNode;
  }
  parseClassPrivateProperty(...args) {
    const propertyNode = super.parseClassPrivateProperty(...args);
    {
      if (!this.getPluginOption("estree", "classFeatures")) {
        return propertyNode;
      }
    }
    propertyNode.type = "PropertyDefinition";
    propertyNode.computed = false;
    return propertyNode;
  }
  parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
    const node2 = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor);
    if (node2) {
      node2.type = "Property";
      if (node2.kind === "method") {
        node2.kind = "init";
      }
      node2.shorthand = false;
    }
    return node2;
  }
  parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) {
    const node2 = super.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors);
    if (node2) {
      node2.kind = "init";
      node2.type = "Property";
    }
    return node2;
  }
  isValidLVal(type, isUnparenthesizedInAssign, binding2) {
    return type === "Property" ? "value" : super.isValidLVal(type, isUnparenthesizedInAssign, binding2);
  }
  isAssignable(node2, isBinding) {
    if (node2 != null && this.isObjectProperty(node2)) {
      return this.isAssignable(node2.value, isBinding);
    }
    return super.isAssignable(node2, isBinding);
  }
  toAssignable(node2, isLHS = false) {
    if (node2 != null && this.isObjectProperty(node2)) {
      const {
        key,
        value
      } = node2;
      if (this.isPrivateName(key)) {
        this.classScope.usePrivateName(this.getPrivateNameSV(key), key.loc.start);
      }
      this.toAssignable(value, isLHS);
    } else {
      super.toAssignable(node2, isLHS);
    }
  }
  toAssignableObjectExpressionProp(prop, isLast, isLHS) {
    if (prop.kind === "get" || prop.kind === "set") {
      this.raise(Errors.PatternHasAccessor, {
        at: prop.key
      });
    } else if (prop.method) {
      this.raise(Errors.PatternHasMethod, {
        at: prop.key
      });
    } else {
      super.toAssignableObjectExpressionProp(prop, isLast, isLHS);
    }
  }
  finishCallExpression(unfinished, optional) {
    const node2 = super.finishCallExpression(unfinished, optional);
    if (node2.callee.type === "Import") {
      node2.type = "ImportExpression";
      node2.source = node2.arguments[0];
      if (this.hasPlugin("importAssertions")) {
        var _node$arguments$;
        node2.attributes = (_node$arguments$ = node2.arguments[1]) != null ? _node$arguments$ : null;
      }
      delete node2.arguments;
      delete node2.callee;
    }
    return node2;
  }
  toReferencedArguments(node2) {
    if (node2.type === "ImportExpression") {
      return;
    }
    super.toReferencedArguments(node2);
  }
  parseExport(unfinished, decorators) {
    const exportStartLoc = this.state.lastTokStartLoc;
    const node2 = super.parseExport(unfinished, decorators);
    switch (node2.type) {
      case "ExportAllDeclaration":
        node2.exported = null;
        break;
      case "ExportNamedDeclaration":
        if (node2.specifiers.length === 1 && node2.specifiers[0].type === "ExportNamespaceSpecifier") {
          node2.type = "ExportAllDeclaration";
          node2.exported = node2.specifiers[0].exported;
          delete node2.specifiers;
        }
      case "ExportDefaultDeclaration":
        {
          var _declaration$decorato;
          const {
            declaration: declaration2
          } = node2;
          if ((declaration2 == null ? void 0 : declaration2.type) === "ClassDeclaration" && ((_declaration$decorato = declaration2.decorators) == null ? void 0 : _declaration$decorato.length) > 0 && declaration2.start === node2.start) {
            this.resetStartLocation(node2, exportStartLoc);
          }
        }
        break;
    }
    return node2;
  }
  parseSubscript(base2, startLoc, noCalls, state) {
    const node2 = super.parseSubscript(base2, startLoc, noCalls, state);
    if (state.optionalChainMember) {
      if (node2.type === "OptionalMemberExpression" || node2.type === "OptionalCallExpression") {
        node2.type = node2.type.substring(8);
      }
      if (state.stop) {
        const chain = this.startNodeAtNode(node2);
        chain.expression = node2;
        return this.finishNode(chain, "ChainExpression");
      }
    } else if (node2.type === "MemberExpression" || node2.type === "CallExpression") {
      node2.optional = false;
    }
    return node2;
  }
  hasPropertyAsPrivateName(node2) {
    if (node2.type === "ChainExpression") {
      node2 = node2.expression;
    }
    return super.hasPropertyAsPrivateName(node2);
  }
  isObjectProperty(node2) {
    return node2.type === "Property" && node2.kind === "init" && !node2.method;
  }
  isObjectMethod(node2) {
    return node2.method || node2.kind === "get" || node2.kind === "set";
  }
  finishNodeAt(node2, type, endLoc) {
    return toESTreeLocation(super.finishNodeAt(node2, type, endLoc));
  }
  resetStartLocation(node2, startLoc) {
    super.resetStartLocation(node2, startLoc);
    toESTreeLocation(node2);
  }
  resetEndLocation(node2, endLoc = this.state.lastTokEndLoc) {
    super.resetEndLocation(node2, endLoc);
    toESTreeLocation(node2);
  }
};
let nonASCIIidentifierStartChars = "ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࡰ-ࢇࢉ-ࢎࢠ-ࣉऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౝౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೝೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜑᜟ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭌᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꟊꟐꟑꟓꟕ-ꟙꟲ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ﬀ-ﬆﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼＡ-Ｚａ-ｚｦ-ﾾￂ-ￇￊ-ￏￒ-ￗￚ-ￜ";
let nonASCIIidentifierChars = "‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛࢘-࢟࣊-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄ఼ా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ೳഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-໎໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜕ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠏-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿ-ᫎᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏０-９＿";
const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 4026, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 757, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938, 6, 4191];
const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 81, 2, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 9, 5351, 0, 7, 14, 13835, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 983, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
function isInAstralSet(code, set2) {
  let pos = 65536;
  for (let i = 0, length2 = set2.length; i < length2; i += 2) {
    pos += set2[i];
    if (pos > code)
      return false;
    pos += set2[i + 1];
    if (pos >= code)
      return true;
  }
  return false;
}
function isIdentifierStart(code) {
  if (code < 65)
    return code === 36;
  if (code <= 90)
    return true;
  if (code < 97)
    return code === 95;
  if (code <= 122)
    return true;
  if (code <= 65535) {
    return code >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code));
  }
  return isInAstralSet(code, astralIdentifierStartCodes);
}
function isIdentifierChar(code) {
  if (code < 48)
    return code === 36;
  if (code < 58)
    return true;
  if (code < 65)
    return false;
  if (code <= 90)
    return true;
  if (code < 97)
    return code === 95;
  if (code <= 122)
    return true;
  if (code <= 65535) {
    return code >= 170 && nonASCIIidentifier.test(String.fromCharCode(code));
  }
  return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
}
const reservedWords = {
  keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"],
  strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
  strictBind: ["eval", "arguments"]
};
const keywords = new Set(reservedWords.keyword);
const reservedWordsStrictSet = new Set(reservedWords.strict);
const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
function isReservedWord(word2, inModule) {
  return inModule && word2 === "await" || word2 === "enum";
}
function isStrictReservedWord(word2, inModule) {
  return isReservedWord(word2, inModule) || reservedWordsStrictSet.has(word2);
}
function isStrictBindOnlyReservedWord(word2) {
  return reservedWordsStrictBindSet.has(word2);
}
function isStrictBindReservedWord(word2, inModule) {
  return isStrictReservedWord(word2, inModule) || isStrictBindOnlyReservedWord(word2);
}
function isKeyword(word2) {
  return keywords.has(word2);
}
function isIteratorStart(current, next, next2) {
  return current === 64 && next === 64 && isIdentifierStart(next2);
}
const reservedWordLikeSet = /* @__PURE__ */ new Set(["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete", "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield", "eval", "arguments", "enum", "await"]);
function canBeReservedWord(word2) {
  return reservedWordLikeSet.has(word2);
}
const SCOPE_OTHER = 0, SCOPE_PROGRAM = 1, SCOPE_FUNCTION = 2, SCOPE_ARROW = 4, SCOPE_SIMPLE_CATCH = 8, SCOPE_SUPER = 16, SCOPE_DIRECT_SUPER = 32, SCOPE_CLASS = 64, SCOPE_STATIC_BLOCK = 128, SCOPE_TS_MODULE = 256, SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION | SCOPE_STATIC_BLOCK | SCOPE_TS_MODULE;
const BIND_KIND_VALUE = 1, BIND_KIND_TYPE = 2, BIND_SCOPE_VAR = 4, BIND_SCOPE_LEXICAL = 8, BIND_SCOPE_FUNCTION = 16, BIND_FLAGS_NONE = 64, BIND_FLAGS_CLASS = 128, BIND_FLAGS_TS_ENUM = 256, BIND_FLAGS_TS_CONST_ENUM = 512, BIND_FLAGS_TS_EXPORT_ONLY = 1024, BIND_FLAGS_FLOW_DECLARE_FN = 2048, BIND_FLAGS_TS_IMPORT = 4096, BIND_FLAGS_NO_LET_IN_LEXICAL = 8192;
const BIND_CLASS = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_CLASS | BIND_FLAGS_NO_LET_IN_LEXICAL, BIND_LEXICAL = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | BIND_FLAGS_NO_LET_IN_LEXICAL, BIND_CATCH_PARAM = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | 0, BIND_VAR = BIND_KIND_VALUE | 0 | BIND_SCOPE_VAR | 0, BIND_FUNCTION = BIND_KIND_VALUE | 0 | BIND_SCOPE_FUNCTION | 0, BIND_TS_INTERFACE = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_CLASS, BIND_TS_TYPE = 0 | BIND_KIND_TYPE | 0 | 0, BIND_TS_ENUM = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_TS_ENUM | BIND_FLAGS_NO_LET_IN_LEXICAL, BIND_TS_AMBIENT = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY, BIND_NONE = 0 | 0 | 0 | BIND_FLAGS_NONE, BIND_OUTSIDE = BIND_KIND_VALUE | 0 | 0 | BIND_FLAGS_NONE, BIND_TS_CONST_ENUM = BIND_TS_ENUM | BIND_FLAGS_TS_CONST_ENUM, BIND_TS_NAMESPACE = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY, BIND_TS_TYPE_IMPORT = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_TS_IMPORT, BIND_FLOW_DECLARE_FN = BIND_FLAGS_FLOW_DECLARE_FN;
const CLASS_ELEMENT_FLAG_STATIC = 4, CLASS_ELEMENT_KIND_GETTER = 2, CLASS_ELEMENT_KIND_SETTER = 1, CLASS_ELEMENT_KIND_ACCESSOR = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_KIND_SETTER;
const CLASS_ELEMENT_STATIC_GETTER = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_FLAG_STATIC, CLASS_ELEMENT_STATIC_SETTER = CLASS_ELEMENT_KIND_SETTER | CLASS_ELEMENT_FLAG_STATIC, CLASS_ELEMENT_INSTANCE_GETTER = CLASS_ELEMENT_KIND_GETTER, CLASS_ELEMENT_INSTANCE_SETTER = CLASS_ELEMENT_KIND_SETTER, CLASS_ELEMENT_OTHER = 0;
class Scope {
  constructor(flags) {
    this.var = /* @__PURE__ */ new Set();
    this.lexical = /* @__PURE__ */ new Set();
    this.functions = /* @__PURE__ */ new Set();
    this.flags = flags;
  }
}
class ScopeHandler {
  constructor(parser2, inModule) {
    this.parser = void 0;
    this.scopeStack = [];
    this.inModule = void 0;
    this.undefinedExports = /* @__PURE__ */ new Map();
    this.parser = parser2;
    this.inModule = inModule;
  }
  get inTopLevel() {
    return (this.currentScope().flags & SCOPE_PROGRAM) > 0;
  }
  get inFunction() {
    return (this.currentVarScopeFlags() & SCOPE_FUNCTION) > 0;
  }
  get allowSuper() {
    return (this.currentThisScopeFlags() & SCOPE_SUPER) > 0;
  }
  get allowDirectSuper() {
    return (this.currentThisScopeFlags() & SCOPE_DIRECT_SUPER) > 0;
  }
  get inClass() {
    return (this.currentThisScopeFlags() & SCOPE_CLASS) > 0;
  }
  get inClassAndNotInNonArrowFunction() {
    const flags = this.currentThisScopeFlags();
    return (flags & SCOPE_CLASS) > 0 && (flags & SCOPE_FUNCTION) === 0;
  }
  get inStaticBlock() {
    for (let i = this.scopeStack.length - 1; ; i--) {
      const {
        flags
      } = this.scopeStack[i];
      if (flags & SCOPE_STATIC_BLOCK) {
        return true;
      }
      if (flags & (SCOPE_VAR | SCOPE_CLASS)) {
        return false;
      }
    }
  }
  get inNonArrowFunction() {
    return (this.currentThisScopeFlags() & SCOPE_FUNCTION) > 0;
  }
  get treatFunctionsAsVar() {
    return this.treatFunctionsAsVarInScope(this.currentScope());
  }
  createScope(flags) {
    return new Scope(flags);
  }
  enter(flags) {
    this.scopeStack.push(this.createScope(flags));
  }
  exit() {
    const scope = this.scopeStack.pop();
    return scope.flags;
  }
  treatFunctionsAsVarInScope(scope) {
    return !!(scope.flags & (SCOPE_FUNCTION | SCOPE_STATIC_BLOCK) || !this.parser.inModule && scope.flags & SCOPE_PROGRAM);
  }
  declareName(name, bindingType, loc) {
    let scope = this.currentScope();
    if (bindingType & BIND_SCOPE_LEXICAL || bindingType & BIND_SCOPE_FUNCTION) {
      this.checkRedeclarationInScope(scope, name, bindingType, loc);
      if (bindingType & BIND_SCOPE_FUNCTION) {
        scope.functions.add(name);
      } else {
        scope.lexical.add(name);
      }
      if (bindingType & BIND_SCOPE_LEXICAL) {
        this.maybeExportDefined(scope, name);
      }
    } else if (bindingType & BIND_SCOPE_VAR) {
      for (let i = this.scopeStack.length - 1; i >= 0; --i) {
        scope = this.scopeStack[i];
        this.checkRedeclarationInScope(scope, name, bindingType, loc);
        scope.var.add(name);
        this.maybeExportDefined(scope, name);
        if (scope.flags & SCOPE_VAR)
          break;
      }
    }
    if (this.parser.inModule && scope.flags & SCOPE_PROGRAM) {
      this.undefinedExports.delete(name);
    }
  }
  maybeExportDefined(scope, name) {
    if (this.parser.inModule && scope.flags & SCOPE_PROGRAM) {
      this.undefinedExports.delete(name);
    }
  }
  checkRedeclarationInScope(scope, name, bindingType, loc) {
    if (this.isRedeclaredInScope(scope, name, bindingType)) {
      this.parser.raise(Errors.VarRedeclaration, {
        at: loc,
        identifierName: name
      });
    }
  }
  isRedeclaredInScope(scope, name, bindingType) {
    if (!(bindingType & BIND_KIND_VALUE))
      return false;
    if (bindingType & BIND_SCOPE_LEXICAL) {
      return scope.lexical.has(name) || scope.functions.has(name) || scope.var.has(name);
    }
    if (bindingType & BIND_SCOPE_FUNCTION) {
      return scope.lexical.has(name) || !this.treatFunctionsAsVarInScope(scope) && scope.var.has(name);
    }
    return scope.lexical.has(name) && !(scope.flags & SCOPE_SIMPLE_CATCH && scope.lexical.values().next().value === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.has(name);
  }
  checkLocalExport(id3) {
    const {
      name
    } = id3;
    const topLevelScope = this.scopeStack[0];
    if (!topLevelScope.lexical.has(name) && !topLevelScope.var.has(name) && !topLevelScope.functions.has(name)) {
      this.undefinedExports.set(name, id3.loc.start);
    }
  }
  currentScope() {
    return this.scopeStack[this.scopeStack.length - 1];
  }
  currentVarScopeFlags() {
    for (let i = this.scopeStack.length - 1; ; i--) {
      const {
        flags
      } = this.scopeStack[i];
      if (flags & SCOPE_VAR) {
        return flags;
      }
    }
  }
  currentThisScopeFlags() {
    for (let i = this.scopeStack.length - 1; ; i--) {
      const {
        flags
      } = this.scopeStack[i];
      if (flags & (SCOPE_VAR | SCOPE_CLASS) && !(flags & SCOPE_ARROW)) {
        return flags;
      }
    }
  }
}
class FlowScope extends Scope {
  constructor(...args) {
    super(...args);
    this.declareFunctions = /* @__PURE__ */ new Set();
  }
}
class FlowScopeHandler extends ScopeHandler {
  createScope(flags) {
    return new FlowScope(flags);
  }
  declareName(name, bindingType, loc) {
    const scope = this.currentScope();
    if (bindingType & BIND_FLAGS_FLOW_DECLARE_FN) {
      this.checkRedeclarationInScope(scope, name, bindingType, loc);
      this.maybeExportDefined(scope, name);
      scope.declareFunctions.add(name);
      return;
    }
    super.declareName(name, bindingType, loc);
  }
  isRedeclaredInScope(scope, name, bindingType) {
    if (super.isRedeclaredInScope(scope, name, bindingType))
      return true;
    if (bindingType & BIND_FLAGS_FLOW_DECLARE_FN) {
      return !scope.declareFunctions.has(name) && (scope.lexical.has(name) || scope.functions.has(name));
    }
    return false;
  }
  checkLocalExport(id3) {
    if (!this.scopeStack[0].declareFunctions.has(id3.name)) {
      super.checkLocalExport(id3);
    }
  }
}
class BaseParser {
  constructor() {
    this.sawUnambiguousESM = false;
    this.ambiguousScriptDifferentAst = false;
  }
  hasPlugin(pluginConfig) {
    if (typeof pluginConfig === "string") {
      return this.plugins.has(pluginConfig);
    } else {
      const [pluginName, pluginOptions] = pluginConfig;
      if (!this.hasPlugin(pluginName)) {
        return false;
      }
      const actualOptions = this.plugins.get(pluginName);
      for (const key of Object.keys(pluginOptions)) {
        if ((actualOptions == null ? void 0 : actualOptions[key]) !== pluginOptions[key]) {
          return false;
        }
      }
      return true;
    }
  }
  getPluginOption(plugin2, name) {
    var _this$plugins$get;
    return (_this$plugins$get = this.plugins.get(plugin2)) == null ? void 0 : _this$plugins$get[name];
  }
}
function setTrailingComments(node2, comments) {
  if (node2.trailingComments === void 0) {
    node2.trailingComments = comments;
  } else {
    node2.trailingComments.unshift(...comments);
  }
}
function setLeadingComments(node2, comments) {
  if (node2.leadingComments === void 0) {
    node2.leadingComments = comments;
  } else {
    node2.leadingComments.unshift(...comments);
  }
}
function setInnerComments(node2, comments) {
  if (node2.innerComments === void 0) {
    node2.innerComments = comments;
  } else {
    node2.innerComments.unshift(...comments);
  }
}
function adjustInnerComments(node2, elements, commentWS) {
  let lastElement = null;
  let i = elements.length;
  while (lastElement === null && i > 0) {
    lastElement = elements[--i];
  }
  if (lastElement === null || lastElement.start > commentWS.start) {
    setInnerComments(node2, commentWS.comments);
  } else {
    setTrailingComments(lastElement, commentWS.comments);
  }
}
class CommentsParser extends BaseParser {
  addComment(comment3) {
    if (this.filename)
      comment3.loc.filename = this.filename;
    this.state.comments.push(comment3);
  }
  processComment(node2) {
    const {
      commentStack
    } = this.state;
    const commentStackLength = commentStack.length;
    if (commentStackLength === 0)
      return;
    let i = commentStackLength - 1;
    const lastCommentWS = commentStack[i];
    if (lastCommentWS.start === node2.end) {
      lastCommentWS.leadingNode = node2;
      i--;
    }
    const {
      start: nodeStart
    } = node2;
    for (; i >= 0; i--) {
      const commentWS = commentStack[i];
      const commentEnd = commentWS.end;
      if (commentEnd > nodeStart) {
        commentWS.containingNode = node2;
        this.finalizeComment(commentWS);
        commentStack.splice(i, 1);
      } else {
        if (commentEnd === nodeStart) {
          commentWS.trailingNode = node2;
        }
        break;
      }
    }
  }
  finalizeComment(commentWS) {
    const {
      comments
    } = commentWS;
    if (commentWS.leadingNode !== null || commentWS.trailingNode !== null) {
      if (commentWS.leadingNode !== null) {
        setTrailingComments(commentWS.leadingNode, comments);
      }
      if (commentWS.trailingNode !== null) {
        setLeadingComments(commentWS.trailingNode, comments);
      }
    } else {
      const {
        containingNode: node2,
        start: commentStart
      } = commentWS;
      if (this.input.charCodeAt(commentStart - 1) === 44) {
        switch (node2.type) {
          case "ObjectExpression":
          case "ObjectPattern":
          case "RecordExpression":
            adjustInnerComments(node2, node2.properties, commentWS);
            break;
          case "CallExpression":
          case "OptionalCallExpression":
            adjustInnerComments(node2, node2.arguments, commentWS);
            break;
          case "FunctionDeclaration":
          case "FunctionExpression":
          case "ArrowFunctionExpression":
          case "ObjectMethod":
          case "ClassMethod":
          case "ClassPrivateMethod":
            adjustInnerComments(node2, node2.params, commentWS);
            break;
          case "ArrayExpression":
          case "ArrayPattern":
          case "TupleExpression":
            adjustInnerComments(node2, node2.elements, commentWS);
            break;
          case "ExportNamedDeclaration":
          case "ImportDeclaration":
            adjustInnerComments(node2, node2.specifiers, commentWS);
            break;
          default: {
            setInnerComments(node2, comments);
          }
        }
      } else {
        setInnerComments(node2, comments);
      }
    }
  }
  finalizeRemainingComments() {
    const {
      commentStack
    } = this.state;
    for (let i = commentStack.length - 1; i >= 0; i--) {
      this.finalizeComment(commentStack[i]);
    }
    this.state.commentStack = [];
  }
  resetPreviousNodeTrailingComments(node2) {
    const {
      commentStack
    } = this.state;
    const {
      length: length2
    } = commentStack;
    if (length2 === 0)
      return;
    const commentWS = commentStack[length2 - 1];
    if (commentWS.leadingNode === node2) {
      commentWS.leadingNode = null;
    }
  }
  takeSurroundingComments(node2, start, end) {
    const {
      commentStack
    } = this.state;
    const commentStackLength = commentStack.length;
    if (commentStackLength === 0)
      return;
    let i = commentStackLength - 1;
    for (; i >= 0; i--) {
      const commentWS = commentStack[i];
      const commentEnd = commentWS.end;
      const commentStart = commentWS.start;
      if (commentStart === end) {
        commentWS.leadingNode = node2;
      } else if (commentEnd === start) {
        commentWS.trailingNode = node2;
      } else if (commentEnd < start) {
        break;
      }
    }
  }
}
const lineBreak = /\r\n?|[\n\u2028\u2029]/;
const lineBreakG = new RegExp(lineBreak.source, "g");
function isNewLine(code) {
  switch (code) {
    case 10:
    case 13:
    case 8232:
    case 8233:
      return true;
    default:
      return false;
  }
}
const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
const skipWhiteSpaceInLine = /(?:[^\S\n\r\u2028\u2029]|\/\/.*|\/\*.*?\*\/)*/y;
const skipWhiteSpaceToLineBreak = new RegExp("(?=(" + skipWhiteSpaceInLine.source + "))\\1" + /(?=[\n\r\u2028\u2029]|\/\*(?!.*?\*\/)|$)/.source, "y");
function isWhitespace(code) {
  switch (code) {
    case 9:
    case 11:
    case 12:
    case 32:
    case 160:
    case 5760:
    case 8192:
    case 8193:
    case 8194:
    case 8195:
    case 8196:
    case 8197:
    case 8198:
    case 8199:
    case 8200:
    case 8201:
    case 8202:
    case 8239:
    case 8287:
    case 12288:
    case 65279:
      return true;
    default:
      return false;
  }
}
class State {
  constructor() {
    this.strict = void 0;
    this.curLine = void 0;
    this.lineStart = void 0;
    this.startLoc = void 0;
    this.endLoc = void 0;
    this.errors = [];
    this.potentialArrowAt = -1;
    this.noArrowAt = [];
    this.noArrowParamsConversionAt = [];
    this.maybeInArrowParameters = false;
    this.inType = false;
    this.noAnonFunctionType = false;
    this.hasFlowComment = false;
    this.isAmbientContext = false;
    this.inAbstractClass = false;
    this.inDisallowConditionalTypesContext = false;
    this.topicContext = {
      maxNumOfResolvableTopics: 0,
      maxTopicIndex: null
    };
    this.soloAwait = false;
    this.inFSharpPipelineDirectBody = false;
    this.labels = [];
    this.comments = [];
    this.commentStack = [];
    this.pos = 0;
    this.type = 137;
    this.value = null;
    this.start = 0;
    this.end = 0;
    this.lastTokEndLoc = null;
    this.lastTokStartLoc = null;
    this.lastTokStart = 0;
    this.context = [types$1.brace];
    this.canStartJSXElement = true;
    this.containsEsc = false;
    this.firstInvalidTemplateEscapePos = null;
    this.strictErrors = /* @__PURE__ */ new Map();
    this.tokensLength = 0;
  }
  init({
    strictMode,
    sourceType,
    startLine,
    startColumn
  }) {
    this.strict = strictMode === false ? false : strictMode === true ? true : sourceType === "module";
    this.curLine = startLine;
    this.lineStart = -startColumn;
    this.startLoc = this.endLoc = new Position2(startLine, startColumn, 0);
  }
  curPosition() {
    return new Position2(this.curLine, this.pos - this.lineStart, this.pos);
  }
  clone(skipArrays) {
    const state = new State();
    const keys = Object.keys(this);
    for (let i = 0, length2 = keys.length; i < length2; i++) {
      const key = keys[i];
      let val = this[key];
      if (!skipArrays && Array.isArray(val)) {
        val = val.slice();
      }
      state[key] = val;
    }
    return state;
  }
}
var _isDigit = function isDigit(code) {
  return code >= 48 && code <= 57;
};
const forbiddenNumericSeparatorSiblings = {
  decBinOct: /* @__PURE__ */ new Set([46, 66, 69, 79, 95, 98, 101, 111]),
  hex: /* @__PURE__ */ new Set([46, 88, 95, 120])
};
const isAllowedNumericSeparatorSibling = {
  bin: (ch) => ch === 48 || ch === 49,
  oct: (ch) => ch >= 48 && ch <= 55,
  dec: (ch) => ch >= 48 && ch <= 57,
  hex: (ch) => ch >= 48 && ch <= 57 || ch >= 65 && ch <= 70 || ch >= 97 && ch <= 102
};
function readStringContents(type, input2, pos, lineStart, curLine, errors2) {
  const initialPos = pos;
  const initialLineStart = lineStart;
  const initialCurLine = curLine;
  let out = "";
  let firstInvalidLoc = null;
  let chunkStart = pos;
  const {
    length: length2
  } = input2;
  for (; ; ) {
    if (pos >= length2) {
      errors2.unterminated(initialPos, initialLineStart, initialCurLine);
      out += input2.slice(chunkStart, pos);
      break;
    }
    const ch = input2.charCodeAt(pos);
    if (isStringEnd(type, ch, input2, pos)) {
      out += input2.slice(chunkStart, pos);
      break;
    }
    if (ch === 92) {
      out += input2.slice(chunkStart, pos);
      const res = readEscapedChar(input2, pos, lineStart, curLine, type === "template", errors2);
      if (res.ch === null && !firstInvalidLoc) {
        firstInvalidLoc = {
          pos,
          lineStart,
          curLine
        };
      } else {
        out += res.ch;
      }
      ({
        pos,
        lineStart,
        curLine
      } = res);
      chunkStart = pos;
    } else if (ch === 8232 || ch === 8233) {
      ++pos;
      ++curLine;
      lineStart = pos;
    } else if (ch === 10 || ch === 13) {
      if (type === "template") {
        out += input2.slice(chunkStart, pos) + "\n";
        ++pos;
        if (ch === 13 && input2.charCodeAt(pos) === 10) {
          ++pos;
        }
        ++curLine;
        chunkStart = lineStart = pos;
      } else {
        errors2.unterminated(initialPos, initialLineStart, initialCurLine);
      }
    } else {
      ++pos;
    }
  }
  return {
    pos,
    str: out,
    firstInvalidLoc,
    lineStart,
    curLine,
    containsInvalid: !!firstInvalidLoc
  };
}
function isStringEnd(type, ch, input2, pos) {
  if (type === "template") {
    return ch === 96 || ch === 36 && input2.charCodeAt(pos + 1) === 123;
  }
  return ch === (type === "double" ? 34 : 39);
}
function readEscapedChar(input2, pos, lineStart, curLine, inTemplate, errors2) {
  const throwOnInvalid = !inTemplate;
  pos++;
  const res = (ch2) => ({
    pos,
    ch: ch2,
    lineStart,
    curLine
  });
  const ch = input2.charCodeAt(pos++);
  switch (ch) {
    case 110:
      return res("\n");
    case 114:
      return res("\r");
    case 120: {
      let code;
      ({
        code,
        pos
      } = readHexChar(input2, pos, lineStart, curLine, 2, false, throwOnInvalid, errors2));
      return res(code === null ? null : String.fromCharCode(code));
    }
    case 117: {
      let code;
      ({
        code,
        pos
      } = readCodePoint(input2, pos, lineStart, curLine, throwOnInvalid, errors2));
      return res(code === null ? null : String.fromCodePoint(code));
    }
    case 116:
      return res("	");
    case 98:
      return res("\b");
    case 118:
      return res("\v");
    case 102:
      return res("\f");
    case 13:
      if (input2.charCodeAt(pos) === 10) {
        ++pos;
      }
    case 10:
      lineStart = pos;
      ++curLine;
    case 8232:
    case 8233:
      return res("");
    case 56:
    case 57:
      if (inTemplate) {
        return res(null);
      } else {
        errors2.strictNumericEscape(pos - 1, lineStart, curLine);
      }
    default:
      if (ch >= 48 && ch <= 55) {
        const startPos = pos - 1;
        const match2 = input2.slice(startPos, pos + 2).match(/^[0-7]+/);
        let octalStr = match2[0];
        let octal = parseInt(octalStr, 8);
        if (octal > 255) {
          octalStr = octalStr.slice(0, -1);
          octal = parseInt(octalStr, 8);
        }
        pos += octalStr.length - 1;
        const next = input2.charCodeAt(pos);
        if (octalStr !== "0" || next === 56 || next === 57) {
          if (inTemplate) {
            return res(null);
          } else {
            errors2.strictNumericEscape(startPos, lineStart, curLine);
          }
        }
        return res(String.fromCharCode(octal));
      }
      return res(String.fromCharCode(ch));
  }
}
function readHexChar(input2, pos, lineStart, curLine, len, forceLen, throwOnInvalid, errors2) {
  const initialPos = pos;
  let n2;
  ({
    n: n2,
    pos
  } = readInt(input2, pos, lineStart, curLine, 16, len, forceLen, false, errors2, !throwOnInvalid));
  if (n2 === null) {
    if (throwOnInvalid) {
      errors2.invalidEscapeSequence(initialPos, lineStart, curLine);
    } else {
      pos = initialPos - 1;
    }
  }
  return {
    code: n2,
    pos
  };
}
function readInt(input2, pos, lineStart, curLine, radix, len, forceLen, allowNumSeparator, errors2, bailOnError) {
  const start = pos;
  const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct;
  const isAllowedSibling = radix === 16 ? isAllowedNumericSeparatorSibling.hex : radix === 10 ? isAllowedNumericSeparatorSibling.dec : radix === 8 ? isAllowedNumericSeparatorSibling.oct : isAllowedNumericSeparatorSibling.bin;
  let invalid = false;
  let total = 0;
  for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
    const code = input2.charCodeAt(pos);
    let val;
    if (code === 95 && allowNumSeparator !== "bail") {
      const prev = input2.charCodeAt(pos - 1);
      const next = input2.charCodeAt(pos + 1);
      if (!allowNumSeparator) {
        if (bailOnError)
          return {
            n: null,
            pos
          };
        errors2.numericSeparatorInEscapeSequence(pos, lineStart, curLine);
      } else if (Number.isNaN(next) || !isAllowedSibling(next) || forbiddenSiblings.has(prev) || forbiddenSiblings.has(next)) {
        if (bailOnError)
          return {
            n: null,
            pos
          };
        errors2.unexpectedNumericSeparator(pos, lineStart, curLine);
      }
      ++pos;
      continue;
    }
    if (code >= 97) {
      val = code - 97 + 10;
    } else if (code >= 65) {
      val = code - 65 + 10;
    } else if (_isDigit(code)) {
      val = code - 48;
    } else {
      val = Infinity;
    }
    if (val >= radix) {
      if (val <= 9 && bailOnError) {
        return {
          n: null,
          pos
        };
      } else if (val <= 9 && errors2.invalidDigit(pos, lineStart, curLine, radix)) {
        val = 0;
      } else if (forceLen) {
        val = 0;
        invalid = true;
      } else {
        break;
      }
    }
    ++pos;
    total = total * radix + val;
  }
  if (pos === start || len != null && pos - start !== len || invalid) {
    return {
      n: null,
      pos
    };
  }
  return {
    n: total,
    pos
  };
}
function readCodePoint(input2, pos, lineStart, curLine, throwOnInvalid, errors2) {
  const ch = input2.charCodeAt(pos);
  let code;
  if (ch === 123) {
    ++pos;
    ({
      code,
      pos
    } = readHexChar(input2, pos, lineStart, curLine, input2.indexOf("}", pos) - pos, true, throwOnInvalid, errors2));
    ++pos;
    if (code !== null && code > 1114111) {
      if (throwOnInvalid) {
        errors2.invalidCodePoint(pos, lineStart, curLine);
      } else {
        return {
          code: null,
          pos
        };
      }
    }
  } else {
    ({
      code,
      pos
    } = readHexChar(input2, pos, lineStart, curLine, 4, false, throwOnInvalid, errors2));
  }
  return {
    code,
    pos
  };
}
const _excluded = ["at"], _excluded2 = ["at"];
function buildPosition(pos, lineStart, curLine) {
  return new Position2(curLine, pos - lineStart, pos);
}
const VALID_REGEX_FLAGS = /* @__PURE__ */ new Set([103, 109, 115, 105, 121, 117, 100, 118]);
class Token3 {
  constructor(state) {
    this.type = state.type;
    this.value = state.value;
    this.start = state.start;
    this.end = state.end;
    this.loc = new SourceLocation(state.startLoc, state.endLoc);
  }
}
class Tokenizer extends CommentsParser {
  constructor(options, input2) {
    super();
    this.isLookahead = void 0;
    this.tokens = [];
    this.errorHandlers_readInt = {
      invalidDigit: (pos, lineStart, curLine, radix) => {
        if (!this.options.errorRecovery)
          return false;
        this.raise(Errors.InvalidDigit, {
          at: buildPosition(pos, lineStart, curLine),
          radix
        });
        return true;
      },
      numericSeparatorInEscapeSequence: this.errorBuilder(Errors.NumericSeparatorInEscapeSequence),
      unexpectedNumericSeparator: this.errorBuilder(Errors.UnexpectedNumericSeparator)
    };
    this.errorHandlers_readCodePoint = Object.assign({}, this.errorHandlers_readInt, {
      invalidEscapeSequence: this.errorBuilder(Errors.InvalidEscapeSequence),
      invalidCodePoint: this.errorBuilder(Errors.InvalidCodePoint)
    });
    this.errorHandlers_readStringContents_string = Object.assign({}, this.errorHandlers_readCodePoint, {
      strictNumericEscape: (pos, lineStart, curLine) => {
        this.recordStrictModeErrors(Errors.StrictNumericEscape, {
          at: buildPosition(pos, lineStart, curLine)
        });
      },
      unterminated: (pos, lineStart, curLine) => {
        throw this.raise(Errors.UnterminatedString, {
          at: buildPosition(pos - 1, lineStart, curLine)
        });
      }
    });
    this.errorHandlers_readStringContents_template = Object.assign({}, this.errorHandlers_readCodePoint, {
      strictNumericEscape: this.errorBuilder(Errors.StrictNumericEscape),
      unterminated: (pos, lineStart, curLine) => {
        throw this.raise(Errors.UnterminatedTemplate, {
          at: buildPosition(pos, lineStart, curLine)
        });
      }
    });
    this.state = new State();
    this.state.init(options);
    this.input = input2;
    this.length = input2.length;
    this.isLookahead = false;
  }
  pushToken(token) {
    this.tokens.length = this.state.tokensLength;
    this.tokens.push(token);
    ++this.state.tokensLength;
  }
  next() {
    this.checkKeywordEscapes();
    if (this.options.tokens) {
      this.pushToken(new Token3(this.state));
    }
    this.state.lastTokStart = this.state.start;
    this.state.lastTokEndLoc = this.state.endLoc;
    this.state.lastTokStartLoc = this.state.startLoc;
    this.nextToken();
  }
  eat(type) {
    if (this.match(type)) {
      this.next();
      return true;
    } else {
      return false;
    }
  }
  match(type) {
    return this.state.type === type;
  }
  createLookaheadState(state) {
    return {
      pos: state.pos,
      value: null,
      type: state.type,
      start: state.start,
      end: state.end,
      context: [this.curContext()],
      inType: state.inType,
      startLoc: state.startLoc,
      lastTokEndLoc: state.lastTokEndLoc,
      curLine: state.curLine,
      lineStart: state.lineStart,
      curPosition: state.curPosition
    };
  }
  lookahead() {
    const old = this.state;
    this.state = this.createLookaheadState(old);
    this.isLookahead = true;
    this.nextToken();
    this.isLookahead = false;
    const curr = this.state;
    this.state = old;
    return curr;
  }
  nextTokenStart() {
    return this.nextTokenStartSince(this.state.pos);
  }
  nextTokenStartSince(pos) {
    skipWhiteSpace.lastIndex = pos;
    return skipWhiteSpace.test(this.input) ? skipWhiteSpace.lastIndex : pos;
  }
  lookaheadCharCode() {
    return this.input.charCodeAt(this.nextTokenStart());
  }
  codePointAtPos(pos) {
    let cp = this.input.charCodeAt(pos);
    if ((cp & 64512) === 55296 && ++pos < this.input.length) {
      const trail = this.input.charCodeAt(pos);
      if ((trail & 64512) === 56320) {
        cp = 65536 + ((cp & 1023) << 10) + (trail & 1023);
      }
    }
    return cp;
  }
  setStrict(strict) {
    this.state.strict = strict;
    if (strict) {
      this.state.strictErrors.forEach(([toParseError, at2]) => this.raise(toParseError, {
        at: at2
      }));
      this.state.strictErrors.clear();
    }
  }
  curContext() {
    return this.state.context[this.state.context.length - 1];
  }
  nextToken() {
    this.skipSpace();
    this.state.start = this.state.pos;
    if (!this.isLookahead)
      this.state.startLoc = this.state.curPosition();
    if (this.state.pos >= this.length) {
      this.finishToken(137);
      return;
    }
    this.getTokenFromCode(this.codePointAtPos(this.state.pos));
  }
  skipBlockComment(commentEnd) {
    let startLoc;
    if (!this.isLookahead)
      startLoc = this.state.curPosition();
    const start = this.state.pos;
    const end = this.input.indexOf(commentEnd, start + 2);
    if (end === -1) {
      throw this.raise(Errors.UnterminatedComment, {
        at: this.state.curPosition()
      });
    }
    this.state.pos = end + commentEnd.length;
    lineBreakG.lastIndex = start + 2;
    while (lineBreakG.test(this.input) && lineBreakG.lastIndex <= end) {
      ++this.state.curLine;
      this.state.lineStart = lineBreakG.lastIndex;
    }
    if (this.isLookahead)
      return;
    const comment3 = {
      type: "CommentBlock",
      value: this.input.slice(start + 2, end),
      start,
      end: end + commentEnd.length,
      loc: new SourceLocation(startLoc, this.state.curPosition())
    };
    if (this.options.tokens)
      this.pushToken(comment3);
    return comment3;
  }
  skipLineComment(startSkip) {
    const start = this.state.pos;
    let startLoc;
    if (!this.isLookahead)
      startLoc = this.state.curPosition();
    let ch = this.input.charCodeAt(this.state.pos += startSkip);
    if (this.state.pos < this.length) {
      while (!isNewLine(ch) && ++this.state.pos < this.length) {
        ch = this.input.charCodeAt(this.state.pos);
      }
    }
    if (this.isLookahead)
      return;
    const end = this.state.pos;
    const value = this.input.slice(start + startSkip, end);
    const comment3 = {
      type: "CommentLine",
      value,
      start,
      end,
      loc: new SourceLocation(startLoc, this.state.curPosition())
    };
    if (this.options.tokens)
      this.pushToken(comment3);
    return comment3;
  }
  skipSpace() {
    const spaceStart = this.state.pos;
    const comments = [];
    loop:
      while (this.state.pos < this.length) {
        const ch = this.input.charCodeAt(this.state.pos);
        switch (ch) {
          case 32:
          case 160:
          case 9:
            ++this.state.pos;
            break;
          case 13:
            if (this.input.charCodeAt(this.state.pos + 1) === 10) {
              ++this.state.pos;
            }
          case 10:
          case 8232:
          case 8233:
            ++this.state.pos;
            ++this.state.curLine;
            this.state.lineStart = this.state.pos;
            break;
          case 47:
            switch (this.input.charCodeAt(this.state.pos + 1)) {
              case 42: {
                const comment3 = this.skipBlockComment("*/");
                if (comment3 !== void 0) {
                  this.addComment(comment3);
                  if (this.options.attachComment)
                    comments.push(comment3);
                }
                break;
              }
              case 47: {
                const comment3 = this.skipLineComment(2);
                if (comment3 !== void 0) {
                  this.addComment(comment3);
                  if (this.options.attachComment)
                    comments.push(comment3);
                }
                break;
              }
              default:
                break loop;
            }
            break;
          default:
            if (isWhitespace(ch)) {
              ++this.state.pos;
            } else if (ch === 45 && !this.inModule && this.options.annexB) {
              const pos = this.state.pos;
              if (this.input.charCodeAt(pos + 1) === 45 && this.input.charCodeAt(pos + 2) === 62 && (spaceStart === 0 || this.state.lineStart > spaceStart)) {
                const comment3 = this.skipLineComment(3);
                if (comment3 !== void 0) {
                  this.addComment(comment3);
                  if (this.options.attachComment)
                    comments.push(comment3);
                }
              } else {
                break loop;
              }
            } else if (ch === 60 && !this.inModule && this.options.annexB) {
              const pos = this.state.pos;
              if (this.input.charCodeAt(pos + 1) === 33 && this.input.charCodeAt(pos + 2) === 45 && this.input.charCodeAt(pos + 3) === 45) {
                const comment3 = this.skipLineComment(4);
                if (comment3 !== void 0) {
                  this.addComment(comment3);
                  if (this.options.attachComment)
                    comments.push(comment3);
                }
              } else {
                break loop;
              }
            } else {
              break loop;
            }
        }
      }
    if (comments.length > 0) {
      const end = this.state.pos;
      const commentWhitespace = {
        start: spaceStart,
        end,
        comments,
        leadingNode: null,
        trailingNode: null,
        containingNode: null
      };
      this.state.commentStack.push(commentWhitespace);
    }
  }
  finishToken(type, val) {
    this.state.end = this.state.pos;
    this.state.endLoc = this.state.curPosition();
    const prevType = this.state.type;
    this.state.type = type;
    this.state.value = val;
    if (!this.isLookahead) {
      this.updateContext(prevType);
    }
  }
  replaceToken(type) {
    this.state.type = type;
    this.updateContext();
  }
  readToken_numberSign() {
    if (this.state.pos === 0 && this.readToken_interpreter()) {
      return;
    }
    const nextPos = this.state.pos + 1;
    const next = this.codePointAtPos(nextPos);
    if (next >= 48 && next <= 57) {
      throw this.raise(Errors.UnexpectedDigitAfterHash, {
        at: this.state.curPosition()
      });
    }
    if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) {
      this.expectPlugin("recordAndTuple");
      if (this.getPluginOption("recordAndTuple", "syntaxType") === "bar") {
        throw this.raise(next === 123 ? Errors.RecordExpressionHashIncorrectStartSyntaxType : Errors.TupleExpressionHashIncorrectStartSyntaxType, {
          at: this.state.curPosition()
        });
      }
      this.state.pos += 2;
      if (next === 123) {
        this.finishToken(7);
      } else {
        this.finishToken(1);
      }
    } else if (isIdentifierStart(next)) {
      ++this.state.pos;
      this.finishToken(136, this.readWord1(next));
    } else if (next === 92) {
      ++this.state.pos;
      this.finishToken(136, this.readWord1());
    } else {
      this.finishOp(27, 1);
    }
  }
  readToken_dot() {
    const next = this.input.charCodeAt(this.state.pos + 1);
    if (next >= 48 && next <= 57) {
      this.readNumber(true);
      return;
    }
    if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) {
      this.state.pos += 3;
      this.finishToken(21);
    } else {
      ++this.state.pos;
      this.finishToken(16);
    }
  }
  readToken_slash() {
    const next = this.input.charCodeAt(this.state.pos + 1);
    if (next === 61) {
      this.finishOp(31, 2);
    } else {
      this.finishOp(56, 1);
    }
  }
  readToken_interpreter() {
    if (this.state.pos !== 0 || this.length < 2)
      return false;
    let ch = this.input.charCodeAt(this.state.pos + 1);
    if (ch !== 33)
      return false;
    const start = this.state.pos;
    this.state.pos += 1;
    while (!isNewLine(ch) && ++this.state.pos < this.length) {
      ch = this.input.charCodeAt(this.state.pos);
    }
    const value = this.input.slice(start + 2, this.state.pos);
    this.finishToken(28, value);
    return true;
  }
  readToken_mult_modulo(code) {
    let type = code === 42 ? 55 : 54;
    let width = 1;
    let next = this.input.charCodeAt(this.state.pos + 1);
    if (code === 42 && next === 42) {
      width++;
      next = this.input.charCodeAt(this.state.pos + 2);
      type = 57;
    }
    if (next === 61 && !this.state.inType) {
      width++;
      type = code === 37 ? 33 : 30;
    }
    this.finishOp(type, width);
  }
  readToken_pipe_amp(code) {
    const next = this.input.charCodeAt(this.state.pos + 1);
    if (next === code) {
      if (this.input.charCodeAt(this.state.pos + 2) === 61) {
        this.finishOp(30, 3);
      } else {
        this.finishOp(code === 124 ? 41 : 42, 2);
      }
      return;
    }
    if (code === 124) {
      if (next === 62) {
        this.finishOp(39, 2);
        return;
      }
      if (this.hasPlugin("recordAndTuple") && next === 125) {
        if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
          throw this.raise(Errors.RecordExpressionBarIncorrectEndSyntaxType, {
            at: this.state.curPosition()
          });
        }
        this.state.pos += 2;
        this.finishToken(9);
        return;
      }
      if (this.hasPlugin("recordAndTuple") && next === 93) {
        if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
          throw this.raise(Errors.TupleExpressionBarIncorrectEndSyntaxType, {
            at: this.state.curPosition()
          });
        }
        this.state.pos += 2;
        this.finishToken(4);
        return;
      }
    }
    if (next === 61) {
      this.finishOp(30, 2);
      return;
    }
    this.finishOp(code === 124 ? 43 : 45, 1);
  }
  readToken_caret() {
    const next = this.input.charCodeAt(this.state.pos + 1);
    if (next === 61 && !this.state.inType) {
      this.finishOp(32, 2);
    } else if (next === 94 && this.hasPlugin(["pipelineOperator", {
      proposal: "hack",
      topicToken: "^^"
    }])) {
      this.finishOp(37, 2);
      const lookaheadCh = this.input.codePointAt(this.state.pos);
      if (lookaheadCh === 94) {
        this.unexpected();
      }
    } else {
      this.finishOp(44, 1);
    }
  }
  readToken_atSign() {
    const next = this.input.charCodeAt(this.state.pos + 1);
    if (next === 64 && this.hasPlugin(["pipelineOperator", {
      proposal: "hack",
      topicToken: "@@"
    }])) {
      this.finishOp(38, 2);
    } else {
      this.finishOp(26, 1);
    }
  }
  readToken_plus_min(code) {
    const next = this.input.charCodeAt(this.state.pos + 1);
    if (next === code) {
      this.finishOp(34, 2);
      return;
    }
    if (next === 61) {
      this.finishOp(30, 2);
    } else {
      this.finishOp(53, 1);
    }
  }
  readToken_lt() {
    const {
      pos
    } = this.state;
    const next = this.input.charCodeAt(pos + 1);
    if (next === 60) {
      if (this.input.charCodeAt(pos + 2) === 61) {
        this.finishOp(30, 3);
        return;
      }
      this.finishOp(51, 2);
      return;
    }
    if (next === 61) {
      this.finishOp(49, 2);
      return;
    }
    this.finishOp(47, 1);
  }
  readToken_gt() {
    const {
      pos
    } = this.state;
    const next = this.input.charCodeAt(pos + 1);
    if (next === 62) {
      const size2 = this.input.charCodeAt(pos + 2) === 62 ? 3 : 2;
      if (this.input.charCodeAt(pos + size2) === 61) {
        this.finishOp(30, size2 + 1);
        return;
      }
      this.finishOp(52, size2);
      return;
    }
    if (next === 61) {
      this.finishOp(49, 2);
      return;
    }
    this.finishOp(48, 1);
  }
  readToken_eq_excl(code) {
    const next = this.input.charCodeAt(this.state.pos + 1);
    if (next === 61) {
      this.finishOp(46, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
      return;
    }
    if (code === 61 && next === 62) {
      this.state.pos += 2;
      this.finishToken(19);
      return;
    }
    this.finishOp(code === 61 ? 29 : 35, 1);
  }
  readToken_question() {
    const next = this.input.charCodeAt(this.state.pos + 1);
    const next2 = this.input.charCodeAt(this.state.pos + 2);
    if (next === 63) {
      if (next2 === 61) {
        this.finishOp(30, 3);
      } else {
        this.finishOp(40, 2);
      }
    } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) {
      this.state.pos += 2;
      this.finishToken(18);
    } else {
      ++this.state.pos;
      this.finishToken(17);
    }
  }
  getTokenFromCode(code) {
    switch (code) {
      case 46:
        this.readToken_dot();
        return;
      case 40:
        ++this.state.pos;
        this.finishToken(10);
        return;
      case 41:
        ++this.state.pos;
        this.finishToken(11);
        return;
      case 59:
        ++this.state.pos;
        this.finishToken(13);
        return;
      case 44:
        ++this.state.pos;
        this.finishToken(12);
        return;
      case 91:
        if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
          if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
            throw this.raise(Errors.TupleExpressionBarIncorrectStartSyntaxType, {
              at: this.state.curPosition()
            });
          }
          this.state.pos += 2;
          this.finishToken(2);
        } else {
          ++this.state.pos;
          this.finishToken(0);
        }
        return;
      case 93:
        ++this.state.pos;
        this.finishToken(3);
        return;
      case 123:
        if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
          if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
            throw this.raise(Errors.RecordExpressionBarIncorrectStartSyntaxType, {
              at: this.state.curPosition()
            });
          }
          this.state.pos += 2;
          this.finishToken(6);
        } else {
          ++this.state.pos;
          this.finishToken(5);
        }
        return;
      case 125:
        ++this.state.pos;
        this.finishToken(8);
        return;
      case 58:
        if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
          this.finishOp(15, 2);
        } else {
          ++this.state.pos;
          this.finishToken(14);
        }
        return;
      case 63:
        this.readToken_question();
        return;
      case 96:
        this.readTemplateToken();
        return;
      case 48: {
        const next = this.input.charCodeAt(this.state.pos + 1);
        if (next === 120 || next === 88) {
          this.readRadixNumber(16);
          return;
        }
        if (next === 111 || next === 79) {
          this.readRadixNumber(8);
          return;
        }
        if (next === 98 || next === 66) {
          this.readRadixNumber(2);
          return;
        }
      }
      case 49:
      case 50:
      case 51:
      case 52:
      case 53:
      case 54:
      case 55:
      case 56:
      case 57:
        this.readNumber(false);
        return;
      case 34:
      case 39:
        this.readString(code);
        return;
      case 47:
        this.readToken_slash();
        return;
      case 37:
      case 42:
        this.readToken_mult_modulo(code);
        return;
      case 124:
      case 38:
        this.readToken_pipe_amp(code);
        return;
      case 94:
        this.readToken_caret();
        return;
      case 43:
      case 45:
        this.readToken_plus_min(code);
        return;
      case 60:
        this.readToken_lt();
        return;
      case 62:
        this.readToken_gt();
        return;
      case 61:
      case 33:
        this.readToken_eq_excl(code);
        return;
      case 126:
        this.finishOp(36, 1);
        return;
      case 64:
        this.readToken_atSign();
        return;
      case 35:
        this.readToken_numberSign();
        return;
      case 92:
        this.readWord();
        return;
      default:
        if (isIdentifierStart(code)) {
          this.readWord(code);
          return;
        }
    }
    throw this.raise(Errors.InvalidOrUnexpectedToken, {
      at: this.state.curPosition(),
      unexpected: String.fromCodePoint(code)
    });
  }
  finishOp(type, size2) {
    const str2 = this.input.slice(this.state.pos, this.state.pos + size2);
    this.state.pos += size2;
    this.finishToken(type, str2);
  }
  readRegexp() {
    const startLoc = this.state.startLoc;
    const start = this.state.start + 1;
    let escaped, inClass;
    let {
      pos
    } = this.state;
    for (; ; ++pos) {
      if (pos >= this.length) {
        throw this.raise(Errors.UnterminatedRegExp, {
          at: createPositionWithColumnOffset(startLoc, 1)
        });
      }
      const ch = this.input.charCodeAt(pos);
      if (isNewLine(ch)) {
        throw this.raise(Errors.UnterminatedRegExp, {
          at: createPositionWithColumnOffset(startLoc, 1)
        });
      }
      if (escaped) {
        escaped = false;
      } else {
        if (ch === 91) {
          inClass = true;
        } else if (ch === 93 && inClass) {
          inClass = false;
        } else if (ch === 47 && !inClass) {
          break;
        }
        escaped = ch === 92;
      }
    }
    const content = this.input.slice(start, pos);
    ++pos;
    let mods = "";
    const nextPos = () => createPositionWithColumnOffset(startLoc, pos + 2 - start);
    while (pos < this.length) {
      const cp = this.codePointAtPos(pos);
      const char = String.fromCharCode(cp);
      if (VALID_REGEX_FLAGS.has(cp)) {
        if (cp === 118) {
          this.expectPlugin("regexpUnicodeSets", nextPos());
          if (mods.includes("u")) {
            this.raise(Errors.IncompatibleRegExpUVFlags, {
              at: nextPos()
            });
          }
        } else if (cp === 117) {
          if (mods.includes("v")) {
            this.raise(Errors.IncompatibleRegExpUVFlags, {
              at: nextPos()
            });
          }
        }
        if (mods.includes(char)) {
          this.raise(Errors.DuplicateRegExpFlags, {
            at: nextPos()
          });
        }
      } else if (isIdentifierChar(cp) || cp === 92) {
        this.raise(Errors.MalformedRegExpFlags, {
          at: nextPos()
        });
      } else {
        break;
      }
      ++pos;
      mods += char;
    }
    this.state.pos = pos;
    this.finishToken(135, {
      pattern: content,
      flags: mods
    });
  }
  readInt(radix, len, forceLen = false, allowNumSeparator = true) {
    const {
      n: n2,
      pos
    } = readInt(this.input, this.state.pos, this.state.lineStart, this.state.curLine, radix, len, forceLen, allowNumSeparator, this.errorHandlers_readInt, false);
    this.state.pos = pos;
    return n2;
  }
  readRadixNumber(radix) {
    const startLoc = this.state.curPosition();
    let isBigInt = false;
    this.state.pos += 2;
    const val = this.readInt(radix);
    if (val == null) {
      this.raise(Errors.InvalidDigit, {
        at: createPositionWithColumnOffset(startLoc, 2),
        radix
      });
    }
    const next = this.input.charCodeAt(this.state.pos);
    if (next === 110) {
      ++this.state.pos;
      isBigInt = true;
    } else if (next === 109) {
      throw this.raise(Errors.InvalidDecimal, {
        at: startLoc
      });
    }
    if (isIdentifierStart(this.codePointAtPos(this.state.pos))) {
      throw this.raise(Errors.NumberIdentifier, {
        at: this.state.curPosition()
      });
    }
    if (isBigInt) {
      const str2 = this.input.slice(startLoc.index, this.state.pos).replace(/[_n]/g, "");
      this.finishToken(133, str2);
      return;
    }
    this.finishToken(132, val);
  }
  readNumber(startsWithDot) {
    const start = this.state.pos;
    const startLoc = this.state.curPosition();
    let isFloat = false;
    let isBigInt = false;
    let isDecimal = false;
    let hasExponent = false;
    let isOctal = false;
    if (!startsWithDot && this.readInt(10) === null) {
      this.raise(Errors.InvalidNumber, {
        at: this.state.curPosition()
      });
    }
    const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48;
    if (hasLeadingZero) {
      const integer = this.input.slice(start, this.state.pos);
      this.recordStrictModeErrors(Errors.StrictOctalLiteral, {
        at: startLoc
      });
      if (!this.state.strict) {
        const underscorePos = integer.indexOf("_");
        if (underscorePos > 0) {
          this.raise(Errors.ZeroDigitNumericSeparator, {
            at: createPositionWithColumnOffset(startLoc, underscorePos)
          });
        }
      }
      isOctal = hasLeadingZero && !/[89]/.test(integer);
    }
    let next = this.input.charCodeAt(this.state.pos);
    if (next === 46 && !isOctal) {
      ++this.state.pos;
      this.readInt(10);
      isFloat = true;
      next = this.input.charCodeAt(this.state.pos);
    }
    if ((next === 69 || next === 101) && !isOctal) {
      next = this.input.charCodeAt(++this.state.pos);
      if (next === 43 || next === 45) {
        ++this.state.pos;
      }
      if (this.readInt(10) === null) {
        this.raise(Errors.InvalidOrMissingExponent, {
          at: startLoc
        });
      }
      isFloat = true;
      hasExponent = true;
      next = this.input.charCodeAt(this.state.pos);
    }
    if (next === 110) {
      if (isFloat || hasLeadingZero) {
        this.raise(Errors.InvalidBigIntLiteral, {
          at: startLoc
        });
      }
      ++this.state.pos;
      isBigInt = true;
    }
    if (next === 109) {
      this.expectPlugin("decimal", this.state.curPosition());
      if (hasExponent || hasLeadingZero) {
        this.raise(Errors.InvalidDecimal, {
          at: startLoc
        });
      }
      ++this.state.pos;
      isDecimal = true;
    }
    if (isIdentifierStart(this.codePointAtPos(this.state.pos))) {
      throw this.raise(Errors.NumberIdentifier, {
        at: this.state.curPosition()
      });
    }
    const str2 = this.input.slice(start, this.state.pos).replace(/[_mn]/g, "");
    if (isBigInt) {
      this.finishToken(133, str2);
      return;
    }
    if (isDecimal) {
      this.finishToken(134, str2);
      return;
    }
    const val = isOctal ? parseInt(str2, 8) : parseFloat(str2);
    this.finishToken(132, val);
  }
  readCodePoint(throwOnInvalid) {
    const {
      code,
      pos
    } = readCodePoint(this.input, this.state.pos, this.state.lineStart, this.state.curLine, throwOnInvalid, this.errorHandlers_readCodePoint);
    this.state.pos = pos;
    return code;
  }
  readString(quote) {
    const {
      str: str2,
      pos,
      curLine,
      lineStart
    } = readStringContents(quote === 34 ? "double" : "single", this.input, this.state.pos + 1, this.state.lineStart, this.state.curLine, this.errorHandlers_readStringContents_string);
    this.state.pos = pos + 1;
    this.state.lineStart = lineStart;
    this.state.curLine = curLine;
    this.finishToken(131, str2);
  }
  readTemplateContinuation() {
    if (!this.match(8)) {
      this.unexpected(null, 8);
    }
    this.state.pos--;
    this.readTemplateToken();
  }
  readTemplateToken() {
    const opening = this.input[this.state.pos];
    const {
      str: str2,
      firstInvalidLoc,
      pos,
      curLine,
      lineStart
    } = readStringContents("template", this.input, this.state.pos + 1, this.state.lineStart, this.state.curLine, this.errorHandlers_readStringContents_template);
    this.state.pos = pos + 1;
    this.state.lineStart = lineStart;
    this.state.curLine = curLine;
    if (firstInvalidLoc) {
      this.state.firstInvalidTemplateEscapePos = new Position2(firstInvalidLoc.curLine, firstInvalidLoc.pos - firstInvalidLoc.lineStart, firstInvalidLoc.pos);
    }
    if (this.input.codePointAt(pos) === 96) {
      this.finishToken(24, firstInvalidLoc ? null : opening + str2 + "`");
    } else {
      this.state.pos++;
      this.finishToken(25, firstInvalidLoc ? null : opening + str2 + "${");
    }
  }
  recordStrictModeErrors(toParseError, {
    at: at2
  }) {
    const index = at2.index;
    if (this.state.strict && !this.state.strictErrors.has(index)) {
      this.raise(toParseError, {
        at: at2
      });
    } else {
      this.state.strictErrors.set(index, [toParseError, at2]);
    }
  }
  readWord1(firstCode) {
    this.state.containsEsc = false;
    let word2 = "";
    const start = this.state.pos;
    let chunkStart = this.state.pos;
    if (firstCode !== void 0) {
      this.state.pos += firstCode <= 65535 ? 1 : 2;
    }
    while (this.state.pos < this.length) {
      const ch = this.codePointAtPos(this.state.pos);
      if (isIdentifierChar(ch)) {
        this.state.pos += ch <= 65535 ? 1 : 2;
      } else if (ch === 92) {
        this.state.containsEsc = true;
        word2 += this.input.slice(chunkStart, this.state.pos);
        const escStart = this.state.curPosition();
        const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar;
        if (this.input.charCodeAt(++this.state.pos) !== 117) {
          this.raise(Errors.MissingUnicodeEscape, {
            at: this.state.curPosition()
          });
          chunkStart = this.state.pos - 1;
          continue;
        }
        ++this.state.pos;
        const esc = this.readCodePoint(true);
        if (esc !== null) {
          if (!identifierCheck(esc)) {
            this.raise(Errors.EscapedCharNotAnIdentifier, {
              at: escStart
            });
          }
          word2 += String.fromCodePoint(esc);
        }
        chunkStart = this.state.pos;
      } else {
        break;
      }
    }
    return word2 + this.input.slice(chunkStart, this.state.pos);
  }
  readWord(firstCode) {
    const word2 = this.readWord1(firstCode);
    const type = keywords$1.get(word2);
    if (type !== void 0) {
      this.finishToken(type, tokenLabelName(type));
    } else {
      this.finishToken(130, word2);
    }
  }
  checkKeywordEscapes() {
    const {
      type
    } = this.state;
    if (tokenIsKeyword(type) && this.state.containsEsc) {
      this.raise(Errors.InvalidEscapedReservedWord, {
        at: this.state.startLoc,
        reservedWord: tokenLabelName(type)
      });
    }
  }
  raise(toParseError, raiseProperties) {
    const {
      at: at2
    } = raiseProperties, details = _objectWithoutPropertiesLoose(raiseProperties, _excluded);
    const loc = at2 instanceof Position2 ? at2 : at2.loc.start;
    const error2 = toParseError({
      loc,
      details
    });
    if (!this.options.errorRecovery)
      throw error2;
    if (!this.isLookahead)
      this.state.errors.push(error2);
    return error2;
  }
  raiseOverwrite(toParseError, raiseProperties) {
    const {
      at: at2
    } = raiseProperties, details = _objectWithoutPropertiesLoose(raiseProperties, _excluded2);
    const loc = at2 instanceof Position2 ? at2 : at2.loc.start;
    const pos = loc.index;
    const errors2 = this.state.errors;
    for (let i = errors2.length - 1; i >= 0; i--) {
      const error2 = errors2[i];
      if (error2.loc.index === pos) {
        return errors2[i] = toParseError({
          loc,
          details
        });
      }
      if (error2.loc.index < pos)
        break;
    }
    return this.raise(toParseError, raiseProperties);
  }
  updateContext(prevType) {
  }
  unexpected(loc, type) {
    throw this.raise(Errors.UnexpectedToken, {
      expected: type ? tokenLabelName(type) : null,
      at: loc != null ? loc : this.state.startLoc
    });
  }
  expectPlugin(pluginName, loc) {
    if (this.hasPlugin(pluginName)) {
      return true;
    }
    throw this.raise(Errors.MissingPlugin, {
      at: loc != null ? loc : this.state.startLoc,
      missingPlugin: [pluginName]
    });
  }
  expectOnePlugin(pluginNames) {
    if (!pluginNames.some((name) => this.hasPlugin(name))) {
      throw this.raise(Errors.MissingOneOfPlugins, {
        at: this.state.startLoc,
        missingPlugin: pluginNames
      });
    }
  }
  errorBuilder(error2) {
    return (pos, lineStart, curLine) => {
      this.raise(error2, {
        at: buildPosition(pos, lineStart, curLine)
      });
    };
  }
}
class ClassScope {
  constructor() {
    this.privateNames = /* @__PURE__ */ new Set();
    this.loneAccessors = /* @__PURE__ */ new Map();
    this.undefinedPrivateNames = /* @__PURE__ */ new Map();
  }
}
class ClassScopeHandler {
  constructor(parser2) {
    this.parser = void 0;
    this.stack = [];
    this.undefinedPrivateNames = /* @__PURE__ */ new Map();
    this.parser = parser2;
  }
  current() {
    return this.stack[this.stack.length - 1];
  }
  enter() {
    this.stack.push(new ClassScope());
  }
  exit() {
    const oldClassScope = this.stack.pop();
    const current = this.current();
    for (const [name, loc] of Array.from(oldClassScope.undefinedPrivateNames)) {
      if (current) {
        if (!current.undefinedPrivateNames.has(name)) {
          current.undefinedPrivateNames.set(name, loc);
        }
      } else {
        this.parser.raise(Errors.InvalidPrivateFieldResolution, {
          at: loc,
          identifierName: name
        });
      }
    }
  }
  declarePrivateName(name, elementType, loc) {
    const {
      privateNames,
      loneAccessors,
      undefinedPrivateNames
    } = this.current();
    let redefined = privateNames.has(name);
    if (elementType & CLASS_ELEMENT_KIND_ACCESSOR) {
      const accessor = redefined && loneAccessors.get(name);
      if (accessor) {
        const oldStatic = accessor & CLASS_ELEMENT_FLAG_STATIC;
        const newStatic = elementType & CLASS_ELEMENT_FLAG_STATIC;
        const oldKind = accessor & CLASS_ELEMENT_KIND_ACCESSOR;
        const newKind = elementType & CLASS_ELEMENT_KIND_ACCESSOR;
        redefined = oldKind === newKind || oldStatic !== newStatic;
        if (!redefined)
          loneAccessors.delete(name);
      } else if (!redefined) {
        loneAccessors.set(name, elementType);
      }
    }
    if (redefined) {
      this.parser.raise(Errors.PrivateNameRedeclaration, {
        at: loc,
        identifierName: name
      });
    }
    privateNames.add(name);
    undefinedPrivateNames.delete(name);
  }
  usePrivateName(name, loc) {
    let classScope;
    for (classScope of this.stack) {
      if (classScope.privateNames.has(name))
        return;
    }
    if (classScope) {
      classScope.undefinedPrivateNames.set(name, loc);
    } else {
      this.parser.raise(Errors.InvalidPrivateFieldResolution, {
        at: loc,
        identifierName: name
      });
    }
  }
}
const kExpression = 0, kMaybeArrowParameterDeclaration = 1, kMaybeAsyncArrowParameterDeclaration = 2, kParameterDeclaration = 3;
class ExpressionScope {
  constructor(type = kExpression) {
    this.type = void 0;
    this.type = type;
  }
  canBeArrowParameterDeclaration() {
    return this.type === kMaybeAsyncArrowParameterDeclaration || this.type === kMaybeArrowParameterDeclaration;
  }
  isCertainlyParameterDeclaration() {
    return this.type === kParameterDeclaration;
  }
}
class ArrowHeadParsingScope extends ExpressionScope {
  constructor(type) {
    super(type);
    this.declarationErrors = /* @__PURE__ */ new Map();
  }
  recordDeclarationError(ParsingErrorClass, {
    at: at2
  }) {
    const index = at2.index;
    this.declarationErrors.set(index, [ParsingErrorClass, at2]);
  }
  clearDeclarationError(index) {
    this.declarationErrors.delete(index);
  }
  iterateErrors(iterator2) {
    this.declarationErrors.forEach(iterator2);
  }
}
class ExpressionScopeHandler {
  constructor(parser2) {
    this.parser = void 0;
    this.stack = [new ExpressionScope()];
    this.parser = parser2;
  }
  enter(scope) {
    this.stack.push(scope);
  }
  exit() {
    this.stack.pop();
  }
  recordParameterInitializerError(toParseError, {
    at: node2
  }) {
    const origin = {
      at: node2.loc.start
    };
    const {
      stack
    } = this;
    let i = stack.length - 1;
    let scope = stack[i];
    while (!scope.isCertainlyParameterDeclaration()) {
      if (scope.canBeArrowParameterDeclaration()) {
        scope.recordDeclarationError(toParseError, origin);
      } else {
        return;
      }
      scope = stack[--i];
    }
    this.parser.raise(toParseError, origin);
  }
  recordArrowParameterBindingError(error2, {
    at: node2
  }) {
    const {
      stack
    } = this;
    const scope = stack[stack.length - 1];
    const origin = {
      at: node2.loc.start
    };
    if (scope.isCertainlyParameterDeclaration()) {
      this.parser.raise(error2, origin);
    } else if (scope.canBeArrowParameterDeclaration()) {
      scope.recordDeclarationError(error2, origin);
    } else {
      return;
    }
  }
  recordAsyncArrowParametersError({
    at: at2
  }) {
    const {
      stack
    } = this;
    let i = stack.length - 1;
    let scope = stack[i];
    while (scope.canBeArrowParameterDeclaration()) {
      if (scope.type === kMaybeAsyncArrowParameterDeclaration) {
        scope.recordDeclarationError(Errors.AwaitBindingIdentifier, {
          at: at2
        });
      }
      scope = stack[--i];
    }
  }
  validateAsPattern() {
    const {
      stack
    } = this;
    const currentScope = stack[stack.length - 1];
    if (!currentScope.canBeArrowParameterDeclaration())
      return;
    currentScope.iterateErrors(([toParseError, loc]) => {
      this.parser.raise(toParseError, {
        at: loc
      });
      let i = stack.length - 2;
      let scope = stack[i];
      while (scope.canBeArrowParameterDeclaration()) {
        scope.clearDeclarationError(loc.index);
        scope = stack[--i];
      }
    });
  }
}
function newParameterDeclarationScope() {
  return new ExpressionScope(kParameterDeclaration);
}
function newArrowHeadScope() {
  return new ArrowHeadParsingScope(kMaybeArrowParameterDeclaration);
}
function newAsyncArrowScope() {
  return new ArrowHeadParsingScope(kMaybeAsyncArrowParameterDeclaration);
}
function newExpressionScope() {
  return new ExpressionScope();
}
const PARAM = 0, PARAM_YIELD = 1, PARAM_AWAIT = 2, PARAM_RETURN = 4, PARAM_IN = 8;
class ProductionParameterHandler {
  constructor() {
    this.stacks = [];
  }
  enter(flags) {
    this.stacks.push(flags);
  }
  exit() {
    this.stacks.pop();
  }
  currentFlags() {
    return this.stacks[this.stacks.length - 1];
  }
  get hasAwait() {
    return (this.currentFlags() & PARAM_AWAIT) > 0;
  }
  get hasYield() {
    return (this.currentFlags() & PARAM_YIELD) > 0;
  }
  get hasReturn() {
    return (this.currentFlags() & PARAM_RETURN) > 0;
  }
  get hasIn() {
    return (this.currentFlags() & PARAM_IN) > 0;
  }
}
function functionFlags(isAsync, isGenerator) {
  return (isAsync ? PARAM_AWAIT : 0) | (isGenerator ? PARAM_YIELD : 0);
}
class UtilParser extends Tokenizer {
  addExtra(node2, key, value, enumerable = true) {
    if (!node2)
      return;
    const extra = node2.extra = node2.extra || {};
    if (enumerable) {
      extra[key] = value;
    } else {
      Object.defineProperty(extra, key, {
        enumerable,
        value
      });
    }
  }
  isContextual(token) {
    return this.state.type === token && !this.state.containsEsc;
  }
  isUnparsedContextual(nameStart, name) {
    const nameEnd = nameStart + name.length;
    if (this.input.slice(nameStart, nameEnd) === name) {
      const nextCh = this.input.charCodeAt(nameEnd);
      return !(isIdentifierChar(nextCh) || (nextCh & 64512) === 55296);
    }
    return false;
  }
  isLookaheadContextual(name) {
    const next = this.nextTokenStart();
    return this.isUnparsedContextual(next, name);
  }
  eatContextual(token) {
    if (this.isContextual(token)) {
      this.next();
      return true;
    }
    return false;
  }
  expectContextual(token, toParseError) {
    if (!this.eatContextual(token)) {
      if (toParseError != null) {
        throw this.raise(toParseError, {
          at: this.state.startLoc
        });
      }
      this.unexpected(null, token);
    }
  }
  canInsertSemicolon() {
    return this.match(137) || this.match(8) || this.hasPrecedingLineBreak();
  }
  hasPrecedingLineBreak() {
    return lineBreak.test(this.input.slice(this.state.lastTokEndLoc.index, this.state.start));
  }
  hasFollowingLineBreak() {
    skipWhiteSpaceToLineBreak.lastIndex = this.state.end;
    return skipWhiteSpaceToLineBreak.test(this.input);
  }
  isLineTerminator() {
    return this.eat(13) || this.canInsertSemicolon();
  }
  semicolon(allowAsi = true) {
    if (allowAsi ? this.isLineTerminator() : this.eat(13))
      return;
    this.raise(Errors.MissingSemicolon, {
      at: this.state.lastTokEndLoc
    });
  }
  expect(type, loc) {
    this.eat(type) || this.unexpected(loc, type);
  }
  tryParse(fn, oldState = this.state.clone()) {
    const abortSignal = {
      node: null
    };
    try {
      const node2 = fn((node3 = null) => {
        abortSignal.node = node3;
        throw abortSignal;
      });
      if (this.state.errors.length > oldState.errors.length) {
        const failState = this.state;
        this.state = oldState;
        this.state.tokensLength = failState.tokensLength;
        return {
          node: node2,
          error: failState.errors[oldState.errors.length],
          thrown: false,
          aborted: false,
          failState
        };
      }
      return {
        node: node2,
        error: null,
        thrown: false,
        aborted: false,
        failState: null
      };
    } catch (error2) {
      const failState = this.state;
      this.state = oldState;
      if (error2 instanceof SyntaxError) {
        return {
          node: null,
          error: error2,
          thrown: true,
          aborted: false,
          failState
        };
      }
      if (error2 === abortSignal) {
        return {
          node: abortSignal.node,
          error: null,
          thrown: false,
          aborted: true,
          failState
        };
      }
      throw error2;
    }
  }
  checkExpressionErrors(refExpressionErrors, andThrow) {
    if (!refExpressionErrors)
      return false;
    const {
      shorthandAssignLoc,
      doubleProtoLoc,
      privateKeyLoc,
      optionalParametersLoc
    } = refExpressionErrors;
    const hasErrors = !!shorthandAssignLoc || !!doubleProtoLoc || !!optionalParametersLoc || !!privateKeyLoc;
    if (!andThrow) {
      return hasErrors;
    }
    if (shorthandAssignLoc != null) {
      this.raise(Errors.InvalidCoverInitializedName, {
        at: shorthandAssignLoc
      });
    }
    if (doubleProtoLoc != null) {
      this.raise(Errors.DuplicateProto, {
        at: doubleProtoLoc
      });
    }
    if (privateKeyLoc != null) {
      this.raise(Errors.UnexpectedPrivateField, {
        at: privateKeyLoc
      });
    }
    if (optionalParametersLoc != null) {
      this.unexpected(optionalParametersLoc);
    }
  }
  isLiteralPropertyName() {
    return tokenIsLiteralPropertyName(this.state.type);
  }
  isPrivateName(node2) {
    return node2.type === "PrivateName";
  }
  getPrivateNameSV(node2) {
    return node2.id.name;
  }
  hasPropertyAsPrivateName(node2) {
    return (node2.type === "MemberExpression" || node2.type === "OptionalMemberExpression") && this.isPrivateName(node2.property);
  }
  isObjectProperty(node2) {
    return node2.type === "ObjectProperty";
  }
  isObjectMethod(node2) {
    return node2.type === "ObjectMethod";
  }
  initializeScopes(inModule = this.options.sourceType === "module") {
    const oldLabels = this.state.labels;
    this.state.labels = [];
    const oldExportedIdentifiers = this.exportedIdentifiers;
    this.exportedIdentifiers = /* @__PURE__ */ new Set();
    const oldInModule = this.inModule;
    this.inModule = inModule;
    const oldScope = this.scope;
    const ScopeHandler2 = this.getScopeHandler();
    this.scope = new ScopeHandler2(this, inModule);
    const oldProdParam = this.prodParam;
    this.prodParam = new ProductionParameterHandler();
    const oldClassScope = this.classScope;
    this.classScope = new ClassScopeHandler(this);
    const oldExpressionScope = this.expressionScope;
    this.expressionScope = new ExpressionScopeHandler(this);
    return () => {
      this.state.labels = oldLabels;
      this.exportedIdentifiers = oldExportedIdentifiers;
      this.inModule = oldInModule;
      this.scope = oldScope;
      this.prodParam = oldProdParam;
      this.classScope = oldClassScope;
      this.expressionScope = oldExpressionScope;
    };
  }
  enterInitialScopes() {
    let paramFlags = PARAM;
    if (this.inModule) {
      paramFlags |= PARAM_AWAIT;
    }
    this.scope.enter(SCOPE_PROGRAM);
    this.prodParam.enter(paramFlags);
  }
  checkDestructuringPrivate(refExpressionErrors) {
    const {
      privateKeyLoc
    } = refExpressionErrors;
    if (privateKeyLoc !== null) {
      this.expectPlugin("destructuringPrivate", privateKeyLoc);
    }
  }
}
class ExpressionErrors {
  constructor() {
    this.shorthandAssignLoc = null;
    this.doubleProtoLoc = null;
    this.privateKeyLoc = null;
    this.optionalParametersLoc = null;
  }
}
let Node$5 = class Node4 {
  constructor(parser2, pos, loc) {
    this.type = "";
    this.start = pos;
    this.end = 0;
    this.loc = new SourceLocation(loc);
    if (parser2 != null && parser2.options.ranges)
      this.range = [pos, 0];
    if (parser2 != null && parser2.filename)
      this.loc.filename = parser2.filename;
  }
};
const NodePrototype = Node$5.prototype;
{
  NodePrototype.__clone = function() {
    const newNode = new Node$5(void 0, this.start, this.loc.start);
    const keys = Object.keys(this);
    for (let i = 0, length2 = keys.length; i < length2; i++) {
      const key = keys[i];
      if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") {
        newNode[key] = this[key];
      }
    }
    return newNode;
  };
}
function clonePlaceholder(node2) {
  return cloneIdentifier(node2);
}
function cloneIdentifier(node2) {
  const {
    type,
    start,
    end,
    loc,
    range: range2,
    extra,
    name
  } = node2;
  const cloned = Object.create(NodePrototype);
  cloned.type = type;
  cloned.start = start;
  cloned.end = end;
  cloned.loc = loc;
  cloned.range = range2;
  cloned.extra = extra;
  cloned.name = name;
  if (type === "Placeholder") {
    cloned.expectedNode = node2.expectedNode;
  }
  return cloned;
}
function cloneStringLiteral(node2) {
  const {
    type,
    start,
    end,
    loc,
    range: range2,
    extra
  } = node2;
  if (type === "Placeholder") {
    return clonePlaceholder(node2);
  }
  const cloned = Object.create(NodePrototype);
  cloned.type = type;
  cloned.start = start;
  cloned.end = end;
  cloned.loc = loc;
  cloned.range = range2;
  if (node2.raw !== void 0) {
    cloned.raw = node2.raw;
  } else {
    cloned.extra = extra;
  }
  cloned.value = node2.value;
  return cloned;
}
class NodeUtils extends UtilParser {
  startNode() {
    return new Node$5(this, this.state.start, this.state.startLoc);
  }
  startNodeAt(loc) {
    return new Node$5(this, loc.index, loc);
  }
  startNodeAtNode(type) {
    return this.startNodeAt(type.loc.start);
  }
  finishNode(node2, type) {
    return this.finishNodeAt(node2, type, this.state.lastTokEndLoc);
  }
  finishNodeAt(node2, type, endLoc) {
    node2.type = type;
    node2.end = endLoc.index;
    node2.loc.end = endLoc;
    if (this.options.ranges)
      node2.range[1] = endLoc.index;
    if (this.options.attachComment)
      this.processComment(node2);
    return node2;
  }
  resetStartLocation(node2, startLoc) {
    node2.start = startLoc.index;
    node2.loc.start = startLoc;
    if (this.options.ranges)
      node2.range[0] = startLoc.index;
  }
  resetEndLocation(node2, endLoc = this.state.lastTokEndLoc) {
    node2.end = endLoc.index;
    node2.loc.end = endLoc;
    if (this.options.ranges)
      node2.range[1] = endLoc.index;
  }
  resetStartLocationFromNode(node2, locationNode) {
    this.resetStartLocation(node2, locationNode.loc.start);
  }
}
const reservedTypes = /* @__PURE__ */ new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]);
const FlowErrors = ParseErrorEnum`flow`({
  AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",
  AmbiguousDeclareModuleKind: "Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module.",
  AssignReservedType: ({
    reservedType
  }) => `Cannot overwrite reserved type ${reservedType}.`,
  DeclareClassElement: "The `declare` modifier can only appear on class fields.",
  DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.",
  DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement.",
  EnumBooleanMemberNotInitialized: ({
    memberName,
    enumName
  }) => `Boolean enum members need to be initialized. Use either \`${memberName} = true,\` or \`${memberName} = false,\` in enum \`${enumName}\`.`,
  EnumDuplicateMemberName: ({
    memberName,
    enumName
  }) => `Enum member names need to be unique, but the name \`${memberName}\` has already been used before in enum \`${enumName}\`.`,
  EnumInconsistentMemberValues: ({
    enumName
  }) => `Enum \`${enumName}\` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.`,
  EnumInvalidExplicitType: ({
    invalidEnumType,
    enumName
  }) => `Enum type \`${invalidEnumType}\` is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`,
  EnumInvalidExplicitTypeUnknownSupplied: ({
    enumName
  }) => `Supplied enum type is not valid. Use one of \`boolean\`, \`number\`, \`string\`, or \`symbol\` in enum \`${enumName}\`.`,
  EnumInvalidMemberInitializerPrimaryType: ({
    enumName,
    memberName,
    explicitType
  }) => `Enum \`${enumName}\` has type \`${explicitType}\`, so the initializer of \`${memberName}\` needs to be a ${explicitType} literal.`,
  EnumInvalidMemberInitializerSymbolType: ({
    enumName,
    memberName
  }) => `Symbol enum members cannot be initialized. Use \`${memberName},\` in enum \`${enumName}\`.`,
  EnumInvalidMemberInitializerUnknownType: ({
    enumName,
    memberName
  }) => `The enum member initializer for \`${memberName}\` needs to be a literal (either a boolean, number, or string) in enum \`${enumName}\`.`,
  EnumInvalidMemberName: ({
    enumName,
    memberName,
    suggestion
  }) => `Enum member names cannot start with lowercase 'a' through 'z'. Instead of using \`${memberName}\`, consider using \`${suggestion}\`, in enum \`${enumName}\`.`,
  EnumNumberMemberNotInitialized: ({
    enumName,
    memberName
  }) => `Number enum members need to be initialized, e.g. \`${memberName} = 1\` in enum \`${enumName}\`.`,
  EnumStringMemberInconsistentlyInitailized: ({
    enumName
  }) => `String enum members need to consistently either all use initializers, or use no initializers, in enum \`${enumName}\`.`,
  GetterMayNotHaveThisParam: "A getter cannot have a `this` parameter.",
  ImportReflectionHasImportType: "An `import module` declaration can not use `type` or `typeof` keyword.",
  ImportTypeShorthandOnlyInPureImport: "The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements.",
  InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type.",
  InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions.",
  InexactVariance: "Explicit inexact syntax cannot have variance.",
  InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`.",
  MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",
  NestedDeclareModule: "`declare module` cannot be used inside another `declare module`.",
  NestedFlowComment: "Cannot have a flow comment inside another flow comment.",
  PatternIsOptional: Object.assign({
    message: "A binding pattern parameter cannot be optional in an implementation signature."
  }, {
    reasonCode: "OptionalBindingPattern"
  }),
  SetterMayNotHaveThisParam: "A setter cannot have a `this` parameter.",
  SpreadVariance: "Spread properties cannot have variance.",
  ThisParamAnnotationRequired: "A type annotation is required for the `this` parameter.",
  ThisParamBannedInConstructor: "Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.",
  ThisParamMayNotBeOptional: "The `this` parameter cannot be optional.",
  ThisParamMustBeFirst: "The `this` parameter must be the first function parameter.",
  ThisParamNoDefault: "The `this` parameter may not have a default value.",
  TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",
  TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis.",
  UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object.",
  UnexpectedReservedType: ({
    reservedType
  }) => `Unexpected reserved type ${reservedType}.`,
  UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new.",
  UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.",
  UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions.",
  UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint".',
  UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration.",
  UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`.",
  UnsupportedDeclareExportKind: ({
    unsupportedExportKind,
    suggestion
  }) => `\`declare export ${unsupportedExportKind}\` is not supported. Use \`${suggestion}\` instead.`,
  UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module.",
  UnterminatedFlowComment: "Unterminated flow-comment."
});
function isEsModuleType(bodyElement) {
  return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration");
}
function hasTypeImportKind(node2) {
  return node2.importKind === "type" || node2.importKind === "typeof";
}
function isMaybeDefaultImport(type) {
  return tokenIsKeywordOrIdentifier(type) && type !== 97;
}
const exportSuggestions = {
  const: "declare export var",
  let: "declare export var",
  type: "export type",
  interface: "export interface"
};
function partition(list2, test) {
  const list1 = [];
  const list22 = [];
  for (let i = 0; i < list2.length; i++) {
    (test(list2[i], i, list2) ? list1 : list22).push(list2[i]);
  }
  return [list1, list22];
}
const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/;
var flow = (superClass) => class FlowParserMixin extends superClass {
  constructor(...args) {
    super(...args);
    this.flowPragma = void 0;
  }
  getScopeHandler() {
    return FlowScopeHandler;
  }
  shouldParseTypes() {
    return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
  }
  shouldParseEnums() {
    return !!this.getPluginOption("flow", "enums");
  }
  finishToken(type, val) {
    if (type !== 131 && type !== 13 && type !== 28) {
      if (this.flowPragma === void 0) {
        this.flowPragma = null;
      }
    }
    super.finishToken(type, val);
  }
  addComment(comment3) {
    if (this.flowPragma === void 0) {
      const matches = FLOW_PRAGMA_REGEX.exec(comment3.value);
      if (!matches)
        ;
      else if (matches[1] === "flow") {
        this.flowPragma = "flow";
      } else if (matches[1] === "noflow") {
        this.flowPragma = "noflow";
      } else {
        throw new Error("Unexpected flow pragma");
      }
    }
    super.addComment(comment3);
  }
  flowParseTypeInitialiser(tok) {
    const oldInType = this.state.inType;
    this.state.inType = true;
    this.expect(tok || 14);
    const type = this.flowParseType();
    this.state.inType = oldInType;
    return type;
  }
  flowParsePredicate() {
    const node2 = this.startNode();
    const moduloLoc = this.state.startLoc;
    this.next();
    this.expectContextual(108);
    if (this.state.lastTokStart > moduloLoc.index + 1) {
      this.raise(FlowErrors.UnexpectedSpaceBetweenModuloChecks, {
        at: moduloLoc
      });
    }
    if (this.eat(10)) {
      node2.value = super.parseExpression();
      this.expect(11);
      return this.finishNode(node2, "DeclaredPredicate");
    } else {
      return this.finishNode(node2, "InferredPredicate");
    }
  }
  flowParseTypeAndPredicateInitialiser() {
    const oldInType = this.state.inType;
    this.state.inType = true;
    this.expect(14);
    let type = null;
    let predicate = null;
    if (this.match(54)) {
      this.state.inType = oldInType;
      predicate = this.flowParsePredicate();
    } else {
      type = this.flowParseType();
      this.state.inType = oldInType;
      if (this.match(54)) {
        predicate = this.flowParsePredicate();
      }
    }
    return [type, predicate];
  }
  flowParseDeclareClass(node2) {
    this.next();
    this.flowParseInterfaceish(node2, true);
    return this.finishNode(node2, "DeclareClass");
  }
  flowParseDeclareFunction(node2) {
    this.next();
    const id3 = node2.id = this.parseIdentifier();
    const typeNode = this.startNode();
    const typeContainer = this.startNode();
    if (this.match(47)) {
      typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
    } else {
      typeNode.typeParameters = null;
    }
    this.expect(10);
    const tmp = this.flowParseFunctionTypeParams();
    typeNode.params = tmp.params;
    typeNode.rest = tmp.rest;
    typeNode.this = tmp._this;
    this.expect(11);
    [typeNode.returnType, node2.predicate] = this.flowParseTypeAndPredicateInitialiser();
    typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
    id3.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
    this.resetEndLocation(id3);
    this.semicolon();
    this.scope.declareName(node2.id.name, BIND_FLOW_DECLARE_FN, node2.id.loc.start);
    return this.finishNode(node2, "DeclareFunction");
  }
  flowParseDeclare(node2, insideModule) {
    if (this.match(80)) {
      return this.flowParseDeclareClass(node2);
    } else if (this.match(68)) {
      return this.flowParseDeclareFunction(node2);
    } else if (this.match(74)) {
      return this.flowParseDeclareVariable(node2);
    } else if (this.eatContextual(125)) {
      if (this.match(16)) {
        return this.flowParseDeclareModuleExports(node2);
      } else {
        if (insideModule) {
          this.raise(FlowErrors.NestedDeclareModule, {
            at: this.state.lastTokStartLoc
          });
        }
        return this.flowParseDeclareModule(node2);
      }
    } else if (this.isContextual(128)) {
      return this.flowParseDeclareTypeAlias(node2);
    } else if (this.isContextual(129)) {
      return this.flowParseDeclareOpaqueType(node2);
    } else if (this.isContextual(127)) {
      return this.flowParseDeclareInterface(node2);
    } else if (this.match(82)) {
      return this.flowParseDeclareExportDeclaration(node2, insideModule);
    } else {
      this.unexpected();
    }
  }
  flowParseDeclareVariable(node2) {
    this.next();
    node2.id = this.flowParseTypeAnnotatableIdentifier(true);
    this.scope.declareName(node2.id.name, BIND_VAR, node2.id.loc.start);
    this.semicolon();
    return this.finishNode(node2, "DeclareVariable");
  }
  flowParseDeclareModule(node2) {
    this.scope.enter(SCOPE_OTHER);
    if (this.match(131)) {
      node2.id = super.parseExprAtom();
    } else {
      node2.id = this.parseIdentifier();
    }
    const bodyNode = node2.body = this.startNode();
    const body = bodyNode.body = [];
    this.expect(5);
    while (!this.match(8)) {
      let bodyNode2 = this.startNode();
      if (this.match(83)) {
        this.next();
        if (!this.isContextual(128) && !this.match(87)) {
          this.raise(FlowErrors.InvalidNonTypeImportInDeclareModule, {
            at: this.state.lastTokStartLoc
          });
        }
        super.parseImport(bodyNode2);
      } else {
        this.expectContextual(123, FlowErrors.UnsupportedStatementInDeclareModule);
        bodyNode2 = this.flowParseDeclare(bodyNode2, true);
      }
      body.push(bodyNode2);
    }
    this.scope.exit();
    this.expect(8);
    this.finishNode(bodyNode, "BlockStatement");
    let kind = null;
    let hasModuleExport = false;
    body.forEach((bodyElement) => {
      if (isEsModuleType(bodyElement)) {
        if (kind === "CommonJS") {
          this.raise(FlowErrors.AmbiguousDeclareModuleKind, {
            at: bodyElement
          });
        }
        kind = "ES";
      } else if (bodyElement.type === "DeclareModuleExports") {
        if (hasModuleExport) {
          this.raise(FlowErrors.DuplicateDeclareModuleExports, {
            at: bodyElement
          });
        }
        if (kind === "ES") {
          this.raise(FlowErrors.AmbiguousDeclareModuleKind, {
            at: bodyElement
          });
        }
        kind = "CommonJS";
        hasModuleExport = true;
      }
    });
    node2.kind = kind || "CommonJS";
    return this.finishNode(node2, "DeclareModule");
  }
  flowParseDeclareExportDeclaration(node2, insideModule) {
    this.expect(82);
    if (this.eat(65)) {
      if (this.match(68) || this.match(80)) {
        node2.declaration = this.flowParseDeclare(this.startNode());
      } else {
        node2.declaration = this.flowParseType();
        this.semicolon();
      }
      node2.default = true;
      return this.finishNode(node2, "DeclareExportDeclaration");
    } else {
      if (this.match(75) || this.isLet() || (this.isContextual(128) || this.isContextual(127)) && !insideModule) {
        const label = this.state.value;
        throw this.raise(FlowErrors.UnsupportedDeclareExportKind, {
          at: this.state.startLoc,
          unsupportedExportKind: label,
          suggestion: exportSuggestions[label]
        });
      }
      if (this.match(74) || this.match(68) || this.match(80) || this.isContextual(129)) {
        node2.declaration = this.flowParseDeclare(this.startNode());
        node2.default = false;
        return this.finishNode(node2, "DeclareExportDeclaration");
      } else if (this.match(55) || this.match(5) || this.isContextual(127) || this.isContextual(128) || this.isContextual(129)) {
        node2 = this.parseExport(node2, null);
        if (node2.type === "ExportNamedDeclaration") {
          node2.type = "ExportDeclaration";
          node2.default = false;
          delete node2.exportKind;
        }
        node2.type = "Declare" + node2.type;
        return node2;
      }
    }
    this.unexpected();
  }
  flowParseDeclareModuleExports(node2) {
    this.next();
    this.expectContextual(109);
    node2.typeAnnotation = this.flowParseTypeAnnotation();
    this.semicolon();
    return this.finishNode(node2, "DeclareModuleExports");
  }
  flowParseDeclareTypeAlias(node2) {
    this.next();
    const finished = this.flowParseTypeAlias(node2);
    finished.type = "DeclareTypeAlias";
    return finished;
  }
  flowParseDeclareOpaqueType(node2) {
    this.next();
    const finished = this.flowParseOpaqueType(node2, true);
    finished.type = "DeclareOpaqueType";
    return finished;
  }
  flowParseDeclareInterface(node2) {
    this.next();
    this.flowParseInterfaceish(node2, false);
    return this.finishNode(node2, "DeclareInterface");
  }
  flowParseInterfaceish(node2, isClass) {
    node2.id = this.flowParseRestrictedIdentifier(!isClass, true);
    this.scope.declareName(node2.id.name, isClass ? BIND_FUNCTION : BIND_LEXICAL, node2.id.loc.start);
    if (this.match(47)) {
      node2.typeParameters = this.flowParseTypeParameterDeclaration();
    } else {
      node2.typeParameters = null;
    }
    node2.extends = [];
    node2.implements = [];
    node2.mixins = [];
    if (this.eat(81)) {
      do {
        node2.extends.push(this.flowParseInterfaceExtends());
      } while (!isClass && this.eat(12));
    }
    if (isClass) {
      if (this.eatContextual(115)) {
        do {
          node2.mixins.push(this.flowParseInterfaceExtends());
        } while (this.eat(12));
      }
      if (this.eatContextual(111)) {
        do {
          node2.implements.push(this.flowParseInterfaceExtends());
        } while (this.eat(12));
      }
    }
    node2.body = this.flowParseObjectType({
      allowStatic: isClass,
      allowExact: false,
      allowSpread: false,
      allowProto: isClass,
      allowInexact: false
    });
  }
  flowParseInterfaceExtends() {
    const node2 = this.startNode();
    node2.id = this.flowParseQualifiedTypeIdentifier();
    if (this.match(47)) {
      node2.typeParameters = this.flowParseTypeParameterInstantiation();
    } else {
      node2.typeParameters = null;
    }
    return this.finishNode(node2, "InterfaceExtends");
  }
  flowParseInterface(node2) {
    this.flowParseInterfaceish(node2, false);
    return this.finishNode(node2, "InterfaceDeclaration");
  }
  checkNotUnderscore(word2) {
    if (word2 === "_") {
      this.raise(FlowErrors.UnexpectedReservedUnderscore, {
        at: this.state.startLoc
      });
    }
  }
  checkReservedType(word2, startLoc, declaration2) {
    if (!reservedTypes.has(word2))
      return;
    this.raise(declaration2 ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, {
      at: startLoc,
      reservedType: word2
    });
  }
  flowParseRestrictedIdentifier(liberal, declaration2) {
    this.checkReservedType(this.state.value, this.state.startLoc, declaration2);
    return this.parseIdentifier(liberal);
  }
  flowParseTypeAlias(node2) {
    node2.id = this.flowParseRestrictedIdentifier(false, true);
    this.scope.declareName(node2.id.name, BIND_LEXICAL, node2.id.loc.start);
    if (this.match(47)) {
      node2.typeParameters = this.flowParseTypeParameterDeclaration();
    } else {
      node2.typeParameters = null;
    }
    node2.right = this.flowParseTypeInitialiser(29);
    this.semicolon();
    return this.finishNode(node2, "TypeAlias");
  }
  flowParseOpaqueType(node2, declare) {
    this.expectContextual(128);
    node2.id = this.flowParseRestrictedIdentifier(true, true);
    this.scope.declareName(node2.id.name, BIND_LEXICAL, node2.id.loc.start);
    if (this.match(47)) {
      node2.typeParameters = this.flowParseTypeParameterDeclaration();
    } else {
      node2.typeParameters = null;
    }
    node2.supertype = null;
    if (this.match(14)) {
      node2.supertype = this.flowParseTypeInitialiser(14);
    }
    node2.impltype = null;
    if (!declare) {
      node2.impltype = this.flowParseTypeInitialiser(29);
    }
    this.semicolon();
    return this.finishNode(node2, "OpaqueType");
  }
  flowParseTypeParameter(requireDefault = false) {
    const nodeStartLoc = this.state.startLoc;
    const node2 = this.startNode();
    const variance = this.flowParseVariance();
    const ident = this.flowParseTypeAnnotatableIdentifier();
    node2.name = ident.name;
    node2.variance = variance;
    node2.bound = ident.typeAnnotation;
    if (this.match(29)) {
      this.eat(29);
      node2.default = this.flowParseType();
    } else {
      if (requireDefault) {
        this.raise(FlowErrors.MissingTypeParamDefault, {
          at: nodeStartLoc
        });
      }
    }
    return this.finishNode(node2, "TypeParameter");
  }
  flowParseTypeParameterDeclaration() {
    const oldInType = this.state.inType;
    const node2 = this.startNode();
    node2.params = [];
    this.state.inType = true;
    if (this.match(47) || this.match(140)) {
      this.next();
    } else {
      this.unexpected();
    }
    let defaultRequired = false;
    do {
      const typeParameter = this.flowParseTypeParameter(defaultRequired);
      node2.params.push(typeParameter);
      if (typeParameter.default) {
        defaultRequired = true;
      }
      if (!this.match(48)) {
        this.expect(12);
      }
    } while (!this.match(48));
    this.expect(48);
    this.state.inType = oldInType;
    return this.finishNode(node2, "TypeParameterDeclaration");
  }
  flowParseTypeParameterInstantiation() {
    const node2 = this.startNode();
    const oldInType = this.state.inType;
    node2.params = [];
    this.state.inType = true;
    this.expect(47);
    const oldNoAnonFunctionType = this.state.noAnonFunctionType;
    this.state.noAnonFunctionType = false;
    while (!this.match(48)) {
      node2.params.push(this.flowParseType());
      if (!this.match(48)) {
        this.expect(12);
      }
    }
    this.state.noAnonFunctionType = oldNoAnonFunctionType;
    this.expect(48);
    this.state.inType = oldInType;
    return this.finishNode(node2, "TypeParameterInstantiation");
  }
  flowParseTypeParameterInstantiationCallOrNew() {
    const node2 = this.startNode();
    const oldInType = this.state.inType;
    node2.params = [];
    this.state.inType = true;
    this.expect(47);
    while (!this.match(48)) {
      node2.params.push(this.flowParseTypeOrImplicitInstantiation());
      if (!this.match(48)) {
        this.expect(12);
      }
    }
    this.expect(48);
    this.state.inType = oldInType;
    return this.finishNode(node2, "TypeParameterInstantiation");
  }
  flowParseInterfaceType() {
    const node2 = this.startNode();
    this.expectContextual(127);
    node2.extends = [];
    if (this.eat(81)) {
      do {
        node2.extends.push(this.flowParseInterfaceExtends());
      } while (this.eat(12));
    }
    node2.body = this.flowParseObjectType({
      allowStatic: false,
      allowExact: false,
      allowSpread: false,
      allowProto: false,
      allowInexact: false
    });
    return this.finishNode(node2, "InterfaceTypeAnnotation");
  }
  flowParseObjectPropertyKey() {
    return this.match(132) || this.match(131) ? super.parseExprAtom() : this.parseIdentifier(true);
  }
  flowParseObjectTypeIndexer(node2, isStatic, variance) {
    node2.static = isStatic;
    if (this.lookahead().type === 14) {
      node2.id = this.flowParseObjectPropertyKey();
      node2.key = this.flowParseTypeInitialiser();
    } else {
      node2.id = null;
      node2.key = this.flowParseType();
    }
    this.expect(3);
    node2.value = this.flowParseTypeInitialiser();
    node2.variance = variance;
    return this.finishNode(node2, "ObjectTypeIndexer");
  }
  flowParseObjectTypeInternalSlot(node2, isStatic) {
    node2.static = isStatic;
    node2.id = this.flowParseObjectPropertyKey();
    this.expect(3);
    this.expect(3);
    if (this.match(47) || this.match(10)) {
      node2.method = true;
      node2.optional = false;
      node2.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node2.loc.start));
    } else {
      node2.method = false;
      if (this.eat(17)) {
        node2.optional = true;
      }
      node2.value = this.flowParseTypeInitialiser();
    }
    return this.finishNode(node2, "ObjectTypeInternalSlot");
  }
  flowParseObjectTypeMethodish(node2) {
    node2.params = [];
    node2.rest = null;
    node2.typeParameters = null;
    node2.this = null;
    if (this.match(47)) {
      node2.typeParameters = this.flowParseTypeParameterDeclaration();
    }
    this.expect(10);
    if (this.match(78)) {
      node2.this = this.flowParseFunctionTypeParam(true);
      node2.this.name = null;
      if (!this.match(11)) {
        this.expect(12);
      }
    }
    while (!this.match(11) && !this.match(21)) {
      node2.params.push(this.flowParseFunctionTypeParam(false));
      if (!this.match(11)) {
        this.expect(12);
      }
    }
    if (this.eat(21)) {
      node2.rest = this.flowParseFunctionTypeParam(false);
    }
    this.expect(11);
    node2.returnType = this.flowParseTypeInitialiser();
    return this.finishNode(node2, "FunctionTypeAnnotation");
  }
  flowParseObjectTypeCallProperty(node2, isStatic) {
    const valueNode = this.startNode();
    node2.static = isStatic;
    node2.value = this.flowParseObjectTypeMethodish(valueNode);
    return this.finishNode(node2, "ObjectTypeCallProperty");
  }
  flowParseObjectType({
    allowStatic,
    allowExact,
    allowSpread,
    allowProto,
    allowInexact
  }) {
    const oldInType = this.state.inType;
    this.state.inType = true;
    const nodeStart = this.startNode();
    nodeStart.callProperties = [];
    nodeStart.properties = [];
    nodeStart.indexers = [];
    nodeStart.internalSlots = [];
    let endDelim;
    let exact;
    let inexact = false;
    if (allowExact && this.match(6)) {
      this.expect(6);
      endDelim = 9;
      exact = true;
    } else {
      this.expect(5);
      endDelim = 8;
      exact = false;
    }
    nodeStart.exact = exact;
    while (!this.match(endDelim)) {
      let isStatic = false;
      let protoStartLoc = null;
      let inexactStartLoc = null;
      const node2 = this.startNode();
      if (allowProto && this.isContextual(116)) {
        const lookahead = this.lookahead();
        if (lookahead.type !== 14 && lookahead.type !== 17) {
          this.next();
          protoStartLoc = this.state.startLoc;
          allowStatic = false;
        }
      }
      if (allowStatic && this.isContextual(104)) {
        const lookahead = this.lookahead();
        if (lookahead.type !== 14 && lookahead.type !== 17) {
          this.next();
          isStatic = true;
        }
      }
      const variance = this.flowParseVariance();
      if (this.eat(0)) {
        if (protoStartLoc != null) {
          this.unexpected(protoStartLoc);
        }
        if (this.eat(0)) {
          if (variance) {
            this.unexpected(variance.loc.start);
          }
          nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node2, isStatic));
        } else {
          nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node2, isStatic, variance));
        }
      } else if (this.match(10) || this.match(47)) {
        if (protoStartLoc != null) {
          this.unexpected(protoStartLoc);
        }
        if (variance) {
          this.unexpected(variance.loc.start);
        }
        nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node2, isStatic));
      } else {
        let kind = "init";
        if (this.isContextual(98) || this.isContextual(103)) {
          const lookahead = this.lookahead();
          if (tokenIsLiteralPropertyName(lookahead.type)) {
            kind = this.state.value;
            this.next();
          }
        }
        const propOrInexact = this.flowParseObjectTypeProperty(node2, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact);
        if (propOrInexact === null) {
          inexact = true;
          inexactStartLoc = this.state.lastTokStartLoc;
        } else {
          nodeStart.properties.push(propOrInexact);
        }
      }
      this.flowObjectTypeSemicolon();
      if (inexactStartLoc && !this.match(8) && !this.match(9)) {
        this.raise(FlowErrors.UnexpectedExplicitInexactInObject, {
          at: inexactStartLoc
        });
      }
    }
    this.expect(endDelim);
    if (allowSpread) {
      nodeStart.inexact = inexact;
    }
    const out = this.finishNode(nodeStart, "ObjectTypeAnnotation");
    this.state.inType = oldInType;
    return out;
  }
  flowParseObjectTypeProperty(node2, isStatic, protoStartLoc, variance, kind, allowSpread, allowInexact) {
    if (this.eat(21)) {
      const isInexactToken = this.match(12) || this.match(13) || this.match(8) || this.match(9);
      if (isInexactToken) {
        if (!allowSpread) {
          this.raise(FlowErrors.InexactInsideNonObject, {
            at: this.state.lastTokStartLoc
          });
        } else if (!allowInexact) {
          this.raise(FlowErrors.InexactInsideExact, {
            at: this.state.lastTokStartLoc
          });
        }
        if (variance) {
          this.raise(FlowErrors.InexactVariance, {
            at: variance
          });
        }
        return null;
      }
      if (!allowSpread) {
        this.raise(FlowErrors.UnexpectedSpreadType, {
          at: this.state.lastTokStartLoc
        });
      }
      if (protoStartLoc != null) {
        this.unexpected(protoStartLoc);
      }
      if (variance) {
        this.raise(FlowErrors.SpreadVariance, {
          at: variance
        });
      }
      node2.argument = this.flowParseType();
      return this.finishNode(node2, "ObjectTypeSpreadProperty");
    } else {
      node2.key = this.flowParseObjectPropertyKey();
      node2.static = isStatic;
      node2.proto = protoStartLoc != null;
      node2.kind = kind;
      let optional = false;
      if (this.match(47) || this.match(10)) {
        node2.method = true;
        if (protoStartLoc != null) {
          this.unexpected(protoStartLoc);
        }
        if (variance) {
          this.unexpected(variance.loc.start);
        }
        node2.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node2.loc.start));
        if (kind === "get" || kind === "set") {
          this.flowCheckGetterSetterParams(node2);
        }
        if (!allowSpread && node2.key.name === "constructor" && node2.value.this) {
          this.raise(FlowErrors.ThisParamBannedInConstructor, {
            at: node2.value.this
          });
        }
      } else {
        if (kind !== "init")
          this.unexpected();
        node2.method = false;
        if (this.eat(17)) {
          optional = true;
        }
        node2.value = this.flowParseTypeInitialiser();
        node2.variance = variance;
      }
      node2.optional = optional;
      return this.finishNode(node2, "ObjectTypeProperty");
    }
  }
  flowCheckGetterSetterParams(property) {
    const paramCount = property.kind === "get" ? 0 : 1;
    const length2 = property.value.params.length + (property.value.rest ? 1 : 0);
    if (property.value.this) {
      this.raise(property.kind === "get" ? FlowErrors.GetterMayNotHaveThisParam : FlowErrors.SetterMayNotHaveThisParam, {
        at: property.value.this
      });
    }
    if (length2 !== paramCount) {
      this.raise(property.kind === "get" ? Errors.BadGetterArity : Errors.BadSetterArity, {
        at: property
      });
    }
    if (property.kind === "set" && property.value.rest) {
      this.raise(Errors.BadSetterRestParameter, {
        at: property
      });
    }
  }
  flowObjectTypeSemicolon() {
    if (!this.eat(13) && !this.eat(12) && !this.match(8) && !this.match(9)) {
      this.unexpected();
    }
  }
  flowParseQualifiedTypeIdentifier(startLoc, id3) {
    var _startLoc;
    (_startLoc = startLoc) != null ? _startLoc : startLoc = this.state.startLoc;
    let node2 = id3 || this.flowParseRestrictedIdentifier(true);
    while (this.eat(16)) {
      const node22 = this.startNodeAt(startLoc);
      node22.qualification = node2;
      node22.id = this.flowParseRestrictedIdentifier(true);
      node2 = this.finishNode(node22, "QualifiedTypeIdentifier");
    }
    return node2;
  }
  flowParseGenericType(startLoc, id3) {
    const node2 = this.startNodeAt(startLoc);
    node2.typeParameters = null;
    node2.id = this.flowParseQualifiedTypeIdentifier(startLoc, id3);
    if (this.match(47)) {
      node2.typeParameters = this.flowParseTypeParameterInstantiation();
    }
    return this.finishNode(node2, "GenericTypeAnnotation");
  }
  flowParseTypeofType() {
    const node2 = this.startNode();
    this.expect(87);
    node2.argument = this.flowParsePrimaryType();
    return this.finishNode(node2, "TypeofTypeAnnotation");
  }
  flowParseTupleType() {
    const node2 = this.startNode();
    node2.types = [];
    this.expect(0);
    while (this.state.pos < this.length && !this.match(3)) {
      node2.types.push(this.flowParseType());
      if (this.match(3))
        break;
      this.expect(12);
    }
    this.expect(3);
    return this.finishNode(node2, "TupleTypeAnnotation");
  }
  flowParseFunctionTypeParam(first2) {
    let name = null;
    let optional = false;
    let typeAnnotation = null;
    const node2 = this.startNode();
    const lh = this.lookahead();
    const isThis = this.state.type === 78;
    if (lh.type === 14 || lh.type === 17) {
      if (isThis && !first2) {
        this.raise(FlowErrors.ThisParamMustBeFirst, {
          at: node2
        });
      }
      name = this.parseIdentifier(isThis);
      if (this.eat(17)) {
        optional = true;
        if (isThis) {
          this.raise(FlowErrors.ThisParamMayNotBeOptional, {
            at: node2
          });
        }
      }
      typeAnnotation = this.flowParseTypeInitialiser();
    } else {
      typeAnnotation = this.flowParseType();
    }
    node2.name = name;
    node2.optional = optional;
    node2.typeAnnotation = typeAnnotation;
    return this.finishNode(node2, "FunctionTypeParam");
  }
  reinterpretTypeAsFunctionTypeParam(type) {
    const node2 = this.startNodeAt(type.loc.start);
    node2.name = null;
    node2.optional = false;
    node2.typeAnnotation = type;
    return this.finishNode(node2, "FunctionTypeParam");
  }
  flowParseFunctionTypeParams(params = []) {
    let rest = null;
    let _this = null;
    if (this.match(78)) {
      _this = this.flowParseFunctionTypeParam(true);
      _this.name = null;
      if (!this.match(11)) {
        this.expect(12);
      }
    }
    while (!this.match(11) && !this.match(21)) {
      params.push(this.flowParseFunctionTypeParam(false));
      if (!this.match(11)) {
        this.expect(12);
      }
    }
    if (this.eat(21)) {
      rest = this.flowParseFunctionTypeParam(false);
    }
    return {
      params,
      rest,
      _this
    };
  }
  flowIdentToTypeAnnotation(startLoc, node2, id3) {
    switch (id3.name) {
      case "any":
        return this.finishNode(node2, "AnyTypeAnnotation");
      case "bool":
      case "boolean":
        return this.finishNode(node2, "BooleanTypeAnnotation");
      case "mixed":
        return this.finishNode(node2, "MixedTypeAnnotation");
      case "empty":
        return this.finishNode(node2, "EmptyTypeAnnotation");
      case "number":
        return this.finishNode(node2, "NumberTypeAnnotation");
      case "string":
        return this.finishNode(node2, "StringTypeAnnotation");
      case "symbol":
        return this.finishNode(node2, "SymbolTypeAnnotation");
      default:
        this.checkNotUnderscore(id3.name);
        return this.flowParseGenericType(startLoc, id3);
    }
  }
  flowParsePrimaryType() {
    const startLoc = this.state.startLoc;
    const node2 = this.startNode();
    let tmp;
    let type;
    let isGroupedType = false;
    const oldNoAnonFunctionType = this.state.noAnonFunctionType;
    switch (this.state.type) {
      case 5:
        return this.flowParseObjectType({
          allowStatic: false,
          allowExact: false,
          allowSpread: true,
          allowProto: false,
          allowInexact: true
        });
      case 6:
        return this.flowParseObjectType({
          allowStatic: false,
          allowExact: true,
          allowSpread: true,
          allowProto: false,
          allowInexact: false
        });
      case 0:
        this.state.noAnonFunctionType = false;
        type = this.flowParseTupleType();
        this.state.noAnonFunctionType = oldNoAnonFunctionType;
        return type;
      case 47:
        node2.typeParameters = this.flowParseTypeParameterDeclaration();
        this.expect(10);
        tmp = this.flowParseFunctionTypeParams();
        node2.params = tmp.params;
        node2.rest = tmp.rest;
        node2.this = tmp._this;
        this.expect(11);
        this.expect(19);
        node2.returnType = this.flowParseType();
        return this.finishNode(node2, "FunctionTypeAnnotation");
      case 10:
        this.next();
        if (!this.match(11) && !this.match(21)) {
          if (tokenIsIdentifier(this.state.type) || this.match(78)) {
            const token = this.lookahead().type;
            isGroupedType = token !== 17 && token !== 14;
          } else {
            isGroupedType = true;
          }
        }
        if (isGroupedType) {
          this.state.noAnonFunctionType = false;
          type = this.flowParseType();
          this.state.noAnonFunctionType = oldNoAnonFunctionType;
          if (this.state.noAnonFunctionType || !(this.match(12) || this.match(11) && this.lookahead().type === 19)) {
            this.expect(11);
            return type;
          } else {
            this.eat(12);
          }
        }
        if (type) {
          tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
        } else {
          tmp = this.flowParseFunctionTypeParams();
        }
        node2.params = tmp.params;
        node2.rest = tmp.rest;
        node2.this = tmp._this;
        this.expect(11);
        this.expect(19);
        node2.returnType = this.flowParseType();
        node2.typeParameters = null;
        return this.finishNode(node2, "FunctionTypeAnnotation");
      case 131:
        return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
      case 85:
      case 86:
        node2.value = this.match(85);
        this.next();
        return this.finishNode(node2, "BooleanLiteralTypeAnnotation");
      case 53:
        if (this.state.value === "-") {
          this.next();
          if (this.match(132)) {
            return this.parseLiteralAtNode(-this.state.value, "NumberLiteralTypeAnnotation", node2);
          }
          if (this.match(133)) {
            return this.parseLiteralAtNode(-this.state.value, "BigIntLiteralTypeAnnotation", node2);
          }
          throw this.raise(FlowErrors.UnexpectedSubtractionOperand, {
            at: this.state.startLoc
          });
        }
        this.unexpected();
        return;
      case 132:
        return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation");
      case 133:
        return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation");
      case 88:
        this.next();
        return this.finishNode(node2, "VoidTypeAnnotation");
      case 84:
        this.next();
        return this.finishNode(node2, "NullLiteralTypeAnnotation");
      case 78:
        this.next();
        return this.finishNode(node2, "ThisTypeAnnotation");
      case 55:
        this.next();
        return this.finishNode(node2, "ExistsTypeAnnotation");
      case 87:
        return this.flowParseTypeofType();
      default:
        if (tokenIsKeyword(this.state.type)) {
          const label = tokenLabelName(this.state.type);
          this.next();
          return super.createIdentifier(node2, label);
        } else if (tokenIsIdentifier(this.state.type)) {
          if (this.isContextual(127)) {
            return this.flowParseInterfaceType();
          }
          return this.flowIdentToTypeAnnotation(startLoc, node2, this.parseIdentifier());
        }
    }
    this.unexpected();
  }
  flowParsePostfixType() {
    const startLoc = this.state.startLoc;
    let type = this.flowParsePrimaryType();
    let seenOptionalIndexedAccess = false;
    while ((this.match(0) || this.match(18)) && !this.canInsertSemicolon()) {
      const node2 = this.startNodeAt(startLoc);
      const optional = this.eat(18);
      seenOptionalIndexedAccess = seenOptionalIndexedAccess || optional;
      this.expect(0);
      if (!optional && this.match(3)) {
        node2.elementType = type;
        this.next();
        type = this.finishNode(node2, "ArrayTypeAnnotation");
      } else {
        node2.objectType = type;
        node2.indexType = this.flowParseType();
        this.expect(3);
        if (seenOptionalIndexedAccess) {
          node2.optional = optional;
          type = this.finishNode(node2, "OptionalIndexedAccessType");
        } else {
          type = this.finishNode(node2, "IndexedAccessType");
        }
      }
    }
    return type;
  }
  flowParsePrefixType() {
    const node2 = this.startNode();
    if (this.eat(17)) {
      node2.typeAnnotation = this.flowParsePrefixType();
      return this.finishNode(node2, "NullableTypeAnnotation");
    } else {
      return this.flowParsePostfixType();
    }
  }
  flowParseAnonFunctionWithoutParens() {
    const param = this.flowParsePrefixType();
    if (!this.state.noAnonFunctionType && this.eat(19)) {
      const node2 = this.startNodeAt(param.loc.start);
      node2.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
      node2.rest = null;
      node2.this = null;
      node2.returnType = this.flowParseType();
      node2.typeParameters = null;
      return this.finishNode(node2, "FunctionTypeAnnotation");
    }
    return param;
  }
  flowParseIntersectionType() {
    const node2 = this.startNode();
    this.eat(45);
    const type = this.flowParseAnonFunctionWithoutParens();
    node2.types = [type];
    while (this.eat(45)) {
      node2.types.push(this.flowParseAnonFunctionWithoutParens());
    }
    return node2.types.length === 1 ? type : this.finishNode(node2, "IntersectionTypeAnnotation");
  }
  flowParseUnionType() {
    const node2 = this.startNode();
    this.eat(43);
    const type = this.flowParseIntersectionType();
    node2.types = [type];
    while (this.eat(43)) {
      node2.types.push(this.flowParseIntersectionType());
    }
    return node2.types.length === 1 ? type : this.finishNode(node2, "UnionTypeAnnotation");
  }
  flowParseType() {
    const oldInType = this.state.inType;
    this.state.inType = true;
    const type = this.flowParseUnionType();
    this.state.inType = oldInType;
    return type;
  }
  flowParseTypeOrImplicitInstantiation() {
    if (this.state.type === 130 && this.state.value === "_") {
      const startLoc = this.state.startLoc;
      const node2 = this.parseIdentifier();
      return this.flowParseGenericType(startLoc, node2);
    } else {
      return this.flowParseType();
    }
  }
  flowParseTypeAnnotation() {
    const node2 = this.startNode();
    node2.typeAnnotation = this.flowParseTypeInitialiser();
    return this.finishNode(node2, "TypeAnnotation");
  }
  flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) {
    const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier();
    if (this.match(14)) {
      ident.typeAnnotation = this.flowParseTypeAnnotation();
      this.resetEndLocation(ident);
    }
    return ident;
  }
  typeCastToParameter(node2) {
    node2.expression.typeAnnotation = node2.typeAnnotation;
    this.resetEndLocation(node2.expression, node2.typeAnnotation.loc.end);
    return node2.expression;
  }
  flowParseVariance() {
    let variance = null;
    if (this.match(53)) {
      variance = this.startNode();
      if (this.state.value === "+") {
        variance.kind = "plus";
      } else {
        variance.kind = "minus";
      }
      this.next();
      return this.finishNode(variance, "Variance");
    }
    return variance;
  }
  parseFunctionBody(node2, allowExpressionBody, isMethod = false) {
    if (allowExpressionBody) {
      this.forwardNoArrowParamsConversionAt(node2, () => super.parseFunctionBody(node2, true, isMethod));
      return;
    }
    super.parseFunctionBody(node2, false, isMethod);
  }
  parseFunctionBodyAndFinish(node2, type, isMethod = false) {
    if (this.match(14)) {
      const typeNode = this.startNode();
      [typeNode.typeAnnotation, node2.predicate] = this.flowParseTypeAndPredicateInitialiser();
      node2.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null;
    }
    return super.parseFunctionBodyAndFinish(node2, type, isMethod);
  }
  parseStatementLike(flags) {
    if (this.state.strict && this.isContextual(127)) {
      const lookahead = this.lookahead();
      if (tokenIsKeywordOrIdentifier(lookahead.type)) {
        const node2 = this.startNode();
        this.next();
        return this.flowParseInterface(node2);
      }
    } else if (this.shouldParseEnums() && this.isContextual(124)) {
      const node2 = this.startNode();
      this.next();
      return this.flowParseEnumDeclaration(node2);
    }
    const stmt = super.parseStatementLike(flags);
    if (this.flowPragma === void 0 && !this.isValidDirective(stmt)) {
      this.flowPragma = null;
    }
    return stmt;
  }
  parseExpressionStatement(node2, expr, decorators) {
    if (expr.type === "Identifier") {
      if (expr.name === "declare") {
        if (this.match(80) || tokenIsIdentifier(this.state.type) || this.match(68) || this.match(74) || this.match(82)) {
          return this.flowParseDeclare(node2);
        }
      } else if (tokenIsIdentifier(this.state.type)) {
        if (expr.name === "interface") {
          return this.flowParseInterface(node2);
        } else if (expr.name === "type") {
          return this.flowParseTypeAlias(node2);
        } else if (expr.name === "opaque") {
          return this.flowParseOpaqueType(node2, false);
        }
      }
    }
    return super.parseExpressionStatement(node2, expr, decorators);
  }
  shouldParseExportDeclaration() {
    const {
      type
    } = this.state;
    if (tokenIsFlowInterfaceOrTypeOrOpaque(type) || this.shouldParseEnums() && type === 124) {
      return !this.state.containsEsc;
    }
    return super.shouldParseExportDeclaration();
  }
  isExportDefaultSpecifier() {
    const {
      type
    } = this.state;
    if (tokenIsFlowInterfaceOrTypeOrOpaque(type) || this.shouldParseEnums() && type === 124) {
      return this.state.containsEsc;
    }
    return super.isExportDefaultSpecifier();
  }
  parseExportDefaultExpression() {
    if (this.shouldParseEnums() && this.isContextual(124)) {
      const node2 = this.startNode();
      this.next();
      return this.flowParseEnumDeclaration(node2);
    }
    return super.parseExportDefaultExpression();
  }
  parseConditional(expr, startLoc, refExpressionErrors) {
    if (!this.match(17))
      return expr;
    if (this.state.maybeInArrowParameters) {
      const nextCh = this.lookaheadCharCode();
      if (nextCh === 44 || nextCh === 61 || nextCh === 58 || nextCh === 41) {
        this.setOptionalParametersError(refExpressionErrors);
        return expr;
      }
    }
    this.expect(17);
    const state = this.state.clone();
    const originalNoArrowAt = this.state.noArrowAt;
    const node2 = this.startNodeAt(startLoc);
    let {
      consequent,
      failed
    } = this.tryParseConditionalConsequent();
    let [valid, invalid] = this.getArrowLikeExpressions(consequent);
    if (failed || invalid.length > 0) {
      const noArrowAt = [...originalNoArrowAt];
      if (invalid.length > 0) {
        this.state = state;
        this.state.noArrowAt = noArrowAt;
        for (let i = 0; i < invalid.length; i++) {
          noArrowAt.push(invalid[i].start);
        }
        ({
          consequent,
          failed
        } = this.tryParseConditionalConsequent());
        [valid, invalid] = this.getArrowLikeExpressions(consequent);
      }
      if (failed && valid.length > 1) {
        this.raise(FlowErrors.AmbiguousConditionalArrow, {
          at: state.startLoc
        });
      }
      if (failed && valid.length === 1) {
        this.state = state;
        noArrowAt.push(valid[0].start);
        this.state.noArrowAt = noArrowAt;
        ({
          consequent,
          failed
        } = this.tryParseConditionalConsequent());
      }
    }
    this.getArrowLikeExpressions(consequent, true);
    this.state.noArrowAt = originalNoArrowAt;
    this.expect(14);
    node2.test = expr;
    node2.consequent = consequent;
    node2.alternate = this.forwardNoArrowParamsConversionAt(node2, () => this.parseMaybeAssign(void 0, void 0));
    return this.finishNode(node2, "ConditionalExpression");
  }
  tryParseConditionalConsequent() {
    this.state.noArrowParamsConversionAt.push(this.state.start);
    const consequent = this.parseMaybeAssignAllowIn();
    const failed = !this.match(14);
    this.state.noArrowParamsConversionAt.pop();
    return {
      consequent,
      failed
    };
  }
  getArrowLikeExpressions(node2, disallowInvalid) {
    const stack = [node2];
    const arrows = [];
    while (stack.length !== 0) {
      const node3 = stack.pop();
      if (node3.type === "ArrowFunctionExpression") {
        if (node3.typeParameters || !node3.returnType) {
          this.finishArrowValidation(node3);
        } else {
          arrows.push(node3);
        }
        stack.push(node3.body);
      } else if (node3.type === "ConditionalExpression") {
        stack.push(node3.consequent);
        stack.push(node3.alternate);
      }
    }
    if (disallowInvalid) {
      arrows.forEach((node3) => this.finishArrowValidation(node3));
      return [arrows, []];
    }
    return partition(arrows, (node3) => node3.params.every((param) => this.isAssignable(param, true)));
  }
  finishArrowValidation(node2) {
    var _node$extra;
    this.toAssignableList(node2.params, (_node$extra = node2.extra) == null ? void 0 : _node$extra.trailingCommaLoc, false);
    this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
    super.checkParams(node2, false, true);
    this.scope.exit();
  }
  forwardNoArrowParamsConversionAt(node2, parse2) {
    let result2;
    if (this.state.noArrowParamsConversionAt.indexOf(node2.start) !== -1) {
      this.state.noArrowParamsConversionAt.push(this.state.start);
      result2 = parse2();
      this.state.noArrowParamsConversionAt.pop();
    } else {
      result2 = parse2();
    }
    return result2;
  }
  parseParenItem(node2, startLoc) {
    node2 = super.parseParenItem(node2, startLoc);
    if (this.eat(17)) {
      node2.optional = true;
      this.resetEndLocation(node2);
    }
    if (this.match(14)) {
      const typeCastNode = this.startNodeAt(startLoc);
      typeCastNode.expression = node2;
      typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();
      return this.finishNode(typeCastNode, "TypeCastExpression");
    }
    return node2;
  }
  assertModuleNodeAllowed(node2) {
    if (node2.type === "ImportDeclaration" && (node2.importKind === "type" || node2.importKind === "typeof") || node2.type === "ExportNamedDeclaration" && node2.exportKind === "type" || node2.type === "ExportAllDeclaration" && node2.exportKind === "type") {
      return;
    }
    super.assertModuleNodeAllowed(node2);
  }
  parseExport(node2, decorators) {
    const decl = super.parseExport(node2, decorators);
    if (decl.type === "ExportNamedDeclaration" || decl.type === "ExportAllDeclaration") {
      decl.exportKind = decl.exportKind || "value";
    }
    return decl;
  }
  parseExportDeclaration(node2) {
    if (this.isContextual(128)) {
      node2.exportKind = "type";
      const declarationNode = this.startNode();
      this.next();
      if (this.match(5)) {
        node2.specifiers = this.parseExportSpecifiers(true);
        super.parseExportFrom(node2);
        return null;
      } else {
        return this.flowParseTypeAlias(declarationNode);
      }
    } else if (this.isContextual(129)) {
      node2.exportKind = "type";
      const declarationNode = this.startNode();
      this.next();
      return this.flowParseOpaqueType(declarationNode, false);
    } else if (this.isContextual(127)) {
      node2.exportKind = "type";
      const declarationNode = this.startNode();
      this.next();
      return this.flowParseInterface(declarationNode);
    } else if (this.shouldParseEnums() && this.isContextual(124)) {
      node2.exportKind = "value";
      const declarationNode = this.startNode();
      this.next();
      return this.flowParseEnumDeclaration(declarationNode);
    } else {
      return super.parseExportDeclaration(node2);
    }
  }
  eatExportStar(node2) {
    if (super.eatExportStar(node2))
      return true;
    if (this.isContextual(128) && this.lookahead().type === 55) {
      node2.exportKind = "type";
      this.next();
      this.next();
      return true;
    }
    return false;
  }
  maybeParseExportNamespaceSpecifier(node2) {
    const {
      startLoc
    } = this.state;
    const hasNamespace = super.maybeParseExportNamespaceSpecifier(node2);
    if (hasNamespace && node2.exportKind === "type") {
      this.unexpected(startLoc);
    }
    return hasNamespace;
  }
  parseClassId(node2, isStatement, optionalId) {
    super.parseClassId(node2, isStatement, optionalId);
    if (this.match(47)) {
      node2.typeParameters = this.flowParseTypeParameterDeclaration();
    }
  }
  parseClassMember(classBody, member, state) {
    const {
      startLoc
    } = this.state;
    if (this.isContextual(123)) {
      if (super.parseClassMemberFromModifier(classBody, member)) {
        return;
      }
      member.declare = true;
    }
    super.parseClassMember(classBody, member, state);
    if (member.declare) {
      if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty" && member.type !== "PropertyDefinition") {
        this.raise(FlowErrors.DeclareClassElement, {
          at: startLoc
        });
      } else if (member.value) {
        this.raise(FlowErrors.DeclareClassFieldInitializer, {
          at: member.value
        });
      }
    }
  }
  isIterator(word2) {
    return word2 === "iterator" || word2 === "asyncIterator";
  }
  readIterator() {
    const word2 = super.readWord1();
    const fullWord = "@@" + word2;
    if (!this.isIterator(word2) || !this.state.inType) {
      this.raise(Errors.InvalidIdentifier, {
        at: this.state.curPosition(),
        identifierName: fullWord
      });
    }
    this.finishToken(130, fullWord);
  }
  getTokenFromCode(code) {
    const next = this.input.charCodeAt(this.state.pos + 1);
    if (code === 123 && next === 124) {
      this.finishOp(6, 2);
    } else if (this.state.inType && (code === 62 || code === 60)) {
      this.finishOp(code === 62 ? 48 : 47, 1);
    } else if (this.state.inType && code === 63) {
      if (next === 46) {
        this.finishOp(18, 2);
      } else {
        this.finishOp(17, 1);
      }
    } else if (isIteratorStart(code, next, this.input.charCodeAt(this.state.pos + 2))) {
      this.state.pos += 2;
      this.readIterator();
    } else {
      super.getTokenFromCode(code);
    }
  }
  isAssignable(node2, isBinding) {
    if (node2.type === "TypeCastExpression") {
      return this.isAssignable(node2.expression, isBinding);
    } else {
      return super.isAssignable(node2, isBinding);
    }
  }
  toAssignable(node2, isLHS = false) {
    if (!isLHS && node2.type === "AssignmentExpression" && node2.left.type === "TypeCastExpression") {
      node2.left = this.typeCastToParameter(node2.left);
    }
    super.toAssignable(node2, isLHS);
  }
  toAssignableList(exprList, trailingCommaLoc, isLHS) {
    for (let i = 0; i < exprList.length; i++) {
      const expr = exprList[i];
      if ((expr == null ? void 0 : expr.type) === "TypeCastExpression") {
        exprList[i] = this.typeCastToParameter(expr);
      }
    }
    super.toAssignableList(exprList, trailingCommaLoc, isLHS);
  }
  toReferencedList(exprList, isParenthesizedExpr) {
    for (let i = 0; i < exprList.length; i++) {
      var _expr$extra;
      const expr = exprList[i];
      if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) != null && _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) {
        this.raise(FlowErrors.TypeCastInPattern, {
          at: expr.typeAnnotation
        });
      }
    }
    return exprList;
  }
  parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
    const node2 = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors);
    if (canBePattern && !this.state.maybeInArrowParameters) {
      this.toReferencedList(node2.elements);
    }
    return node2;
  }
  isValidLVal(type, isParenthesized, binding2) {
    return type === "TypeCastExpression" || super.isValidLVal(type, isParenthesized, binding2);
  }
  parseClassProperty(node2) {
    if (this.match(14)) {
      node2.typeAnnotation = this.flowParseTypeAnnotation();
    }
    return super.parseClassProperty(node2);
  }
  parseClassPrivateProperty(node2) {
    if (this.match(14)) {
      node2.typeAnnotation = this.flowParseTypeAnnotation();
    }
    return super.parseClassPrivateProperty(node2);
  }
  isClassMethod() {
    return this.match(47) || super.isClassMethod();
  }
  isClassProperty() {
    return this.match(14) || super.isClassProperty();
  }
  isNonstaticConstructor(method) {
    return !this.match(14) && super.isNonstaticConstructor(method);
  }
  pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
    if (method.variance) {
      this.unexpected(method.variance.loc.start);
    }
    delete method.variance;
    if (this.match(47)) {
      method.typeParameters = this.flowParseTypeParameterDeclaration();
    }
    super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
    if (method.params && isConstructor) {
      const params = method.params;
      if (params.length > 0 && this.isThisParam(params[0])) {
        this.raise(FlowErrors.ThisParamBannedInConstructor, {
          at: method
        });
      }
    } else if (method.type === "MethodDefinition" && isConstructor && method.value.params) {
      const params = method.value.params;
      if (params.length > 0 && this.isThisParam(params[0])) {
        this.raise(FlowErrors.ThisParamBannedInConstructor, {
          at: method
        });
      }
    }
  }
  pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
    if (method.variance) {
      this.unexpected(method.variance.loc.start);
    }
    delete method.variance;
    if (this.match(47)) {
      method.typeParameters = this.flowParseTypeParameterDeclaration();
    }
    super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  }
  parseClassSuper(node2) {
    super.parseClassSuper(node2);
    if (node2.superClass && this.match(47)) {
      node2.superTypeParameters = this.flowParseTypeParameterInstantiation();
    }
    if (this.isContextual(111)) {
      this.next();
      const implemented = node2.implements = [];
      do {
        const node3 = this.startNode();
        node3.id = this.flowParseRestrictedIdentifier(true);
        if (this.match(47)) {
          node3.typeParameters = this.flowParseTypeParameterInstantiation();
        } else {
          node3.typeParameters = null;
        }
        implemented.push(this.finishNode(node3, "ClassImplements"));
      } while (this.eat(12));
    }
  }
  checkGetterSetterParams(method) {
    super.checkGetterSetterParams(method);
    const params = this.getObjectOrClassMethodParams(method);
    if (params.length > 0) {
      const param = params[0];
      if (this.isThisParam(param) && method.kind === "get") {
        this.raise(FlowErrors.GetterMayNotHaveThisParam, {
          at: param
        });
      } else if (this.isThisParam(param)) {
        this.raise(FlowErrors.SetterMayNotHaveThisParam, {
          at: param
        });
      }
    }
  }
  parsePropertyNamePrefixOperator(node2) {
    node2.variance = this.flowParseVariance();
  }
  parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
    if (prop.variance) {
      this.unexpected(prop.variance.loc.start);
    }
    delete prop.variance;
    let typeParameters;
    if (this.match(47) && !isAccessor) {
      typeParameters = this.flowParseTypeParameterDeclaration();
      if (!this.match(10))
        this.unexpected();
    }
    const result2 = super.parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
    if (typeParameters) {
      (result2.value || result2).typeParameters = typeParameters;
    }
    return result2;
  }
  parseAssignableListItemTypes(param) {
    if (this.eat(17)) {
      if (param.type !== "Identifier") {
        this.raise(FlowErrors.PatternIsOptional, {
          at: param
        });
      }
      if (this.isThisParam(param)) {
        this.raise(FlowErrors.ThisParamMayNotBeOptional, {
          at: param
        });
      }
      param.optional = true;
    }
    if (this.match(14)) {
      param.typeAnnotation = this.flowParseTypeAnnotation();
    } else if (this.isThisParam(param)) {
      this.raise(FlowErrors.ThisParamAnnotationRequired, {
        at: param
      });
    }
    if (this.match(29) && this.isThisParam(param)) {
      this.raise(FlowErrors.ThisParamNoDefault, {
        at: param
      });
    }
    this.resetEndLocation(param);
    return param;
  }
  parseMaybeDefault(startLoc, left) {
    const node2 = super.parseMaybeDefault(startLoc, left);
    if (node2.type === "AssignmentPattern" && node2.typeAnnotation && node2.right.start < node2.typeAnnotation.start) {
      this.raise(FlowErrors.TypeBeforeInitializer, {
        at: node2.typeAnnotation
      });
    }
    return node2;
  }
  shouldParseDefaultImport(node2) {
    if (!hasTypeImportKind(node2)) {
      return super.shouldParseDefaultImport(node2);
    }
    return isMaybeDefaultImport(this.state.type);
  }
  checkImportReflection(node2) {
    super.checkImportReflection(node2);
    if (node2.module && node2.importKind !== "value") {
      this.raise(FlowErrors.ImportReflectionHasImportType, {
        at: node2.specifiers[0].loc.start
      });
    }
  }
  parseImportSpecifierLocal(node2, specifier, type) {
    specifier.local = hasTypeImportKind(node2) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier();
    node2.specifiers.push(this.finishImportSpecifier(specifier, type));
  }
  maybeParseDefaultImportSpecifier(node2) {
    node2.importKind = "value";
    let kind = null;
    if (this.match(87)) {
      kind = "typeof";
    } else if (this.isContextual(128)) {
      kind = "type";
    }
    if (kind) {
      const lh = this.lookahead();
      const {
        type
      } = lh;
      if (kind === "type" && type === 55) {
        this.unexpected(null, lh.type);
      }
      if (isMaybeDefaultImport(type) || type === 5 || type === 55) {
        this.next();
        node2.importKind = kind;
      }
    }
    return super.maybeParseDefaultImportSpecifier(node2);
  }
  parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) {
    const firstIdent = specifier.imported;
    let specifierTypeKind = null;
    if (firstIdent.type === "Identifier") {
      if (firstIdent.name === "type") {
        specifierTypeKind = "type";
      } else if (firstIdent.name === "typeof") {
        specifierTypeKind = "typeof";
      }
    }
    let isBinding = false;
    if (this.isContextual(93) && !this.isLookaheadContextual("as")) {
      const as_ident = this.parseIdentifier(true);
      if (specifierTypeKind !== null && !tokenIsKeywordOrIdentifier(this.state.type)) {
        specifier.imported = as_ident;
        specifier.importKind = specifierTypeKind;
        specifier.local = cloneIdentifier(as_ident);
      } else {
        specifier.imported = firstIdent;
        specifier.importKind = null;
        specifier.local = this.parseIdentifier();
      }
    } else {
      if (specifierTypeKind !== null && tokenIsKeywordOrIdentifier(this.state.type)) {
        specifier.imported = this.parseIdentifier(true);
        specifier.importKind = specifierTypeKind;
      } else {
        if (importedIsString) {
          throw this.raise(Errors.ImportBindingIsString, {
            at: specifier,
            importName: firstIdent.value
          });
        }
        specifier.imported = firstIdent;
        specifier.importKind = null;
      }
      if (this.eatContextual(93)) {
        specifier.local = this.parseIdentifier();
      } else {
        isBinding = true;
        specifier.local = cloneIdentifier(specifier.imported);
      }
    }
    const specifierIsTypeImport = hasTypeImportKind(specifier);
    if (isInTypeOnlyImport && specifierIsTypeImport) {
      this.raise(FlowErrors.ImportTypeShorthandOnlyInPureImport, {
        at: specifier
      });
    }
    if (isInTypeOnlyImport || specifierIsTypeImport) {
      this.checkReservedType(specifier.local.name, specifier.local.loc.start, true);
    }
    if (isBinding && !isInTypeOnlyImport && !specifierIsTypeImport) {
      this.checkReservedWord(specifier.local.name, specifier.loc.start, true, true);
    }
    return this.finishImportSpecifier(specifier, "ImportSpecifier");
  }
  parseBindingAtom() {
    switch (this.state.type) {
      case 78:
        return this.parseIdentifier(true);
      default:
        return super.parseBindingAtom();
    }
  }
  parseFunctionParams(node2, isConstructor) {
    const kind = node2.kind;
    if (kind !== "get" && kind !== "set" && this.match(47)) {
      node2.typeParameters = this.flowParseTypeParameterDeclaration();
    }
    super.parseFunctionParams(node2, isConstructor);
  }
  parseVarId(decl, kind) {
    super.parseVarId(decl, kind);
    if (this.match(14)) {
      decl.id.typeAnnotation = this.flowParseTypeAnnotation();
      this.resetEndLocation(decl.id);
    }
  }
  parseAsyncArrowFromCallExpression(node2, call) {
    if (this.match(14)) {
      const oldNoAnonFunctionType = this.state.noAnonFunctionType;
      this.state.noAnonFunctionType = true;
      node2.returnType = this.flowParseTypeAnnotation();
      this.state.noAnonFunctionType = oldNoAnonFunctionType;
    }
    return super.parseAsyncArrowFromCallExpression(node2, call);
  }
  shouldParseAsyncArrow() {
    return this.match(14) || super.shouldParseAsyncArrow();
  }
  parseMaybeAssign(refExpressionErrors, afterLeftParse) {
    var _jsx;
    let state = null;
    let jsx2;
    if (this.hasPlugin("jsx") && (this.match(140) || this.match(47))) {
      state = this.state.clone();
      jsx2 = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
      if (!jsx2.error)
        return jsx2.node;
      const {
        context
      } = this.state;
      const currentContext = context[context.length - 1];
      if (currentContext === types$1.j_oTag || currentContext === types$1.j_expr) {
        context.pop();
      }
    }
    if ((_jsx = jsx2) != null && _jsx.error || this.match(47)) {
      var _jsx2, _jsx3;
      state = state || this.state.clone();
      let typeParameters;
      const arrow = this.tryParse((abort) => {
        var _arrowExpression$extr;
        typeParameters = this.flowParseTypeParameterDeclaration();
        const arrowExpression2 = this.forwardNoArrowParamsConversionAt(typeParameters, () => {
          const result2 = super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
          this.resetStartLocationFromNode(result2, typeParameters);
          return result2;
        });
        if ((_arrowExpression$extr = arrowExpression2.extra) != null && _arrowExpression$extr.parenthesized)
          abort();
        const expr = this.maybeUnwrapTypeCastExpression(arrowExpression2);
        if (expr.type !== "ArrowFunctionExpression")
          abort();
        expr.typeParameters = typeParameters;
        this.resetStartLocationFromNode(expr, typeParameters);
        return arrowExpression2;
      }, state);
      let arrowExpression = null;
      if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") {
        if (!arrow.error && !arrow.aborted) {
          if (arrow.node.async) {
            this.raise(FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction, {
              at: typeParameters
            });
          }
          return arrow.node;
        }
        arrowExpression = arrow.node;
      }
      if ((_jsx2 = jsx2) != null && _jsx2.node) {
        this.state = jsx2.failState;
        return jsx2.node;
      }
      if (arrowExpression) {
        this.state = arrow.failState;
        return arrowExpression;
      }
      if ((_jsx3 = jsx2) != null && _jsx3.thrown)
        throw jsx2.error;
      if (arrow.thrown)
        throw arrow.error;
      throw this.raise(FlowErrors.UnexpectedTokenAfterTypeParameter, {
        at: typeParameters
      });
    }
    return super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
  }
  parseArrow(node2) {
    if (this.match(14)) {
      const result2 = this.tryParse(() => {
        const oldNoAnonFunctionType = this.state.noAnonFunctionType;
        this.state.noAnonFunctionType = true;
        const typeNode = this.startNode();
        [typeNode.typeAnnotation, node2.predicate] = this.flowParseTypeAndPredicateInitialiser();
        this.state.noAnonFunctionType = oldNoAnonFunctionType;
        if (this.canInsertSemicolon())
          this.unexpected();
        if (!this.match(19))
          this.unexpected();
        return typeNode;
      });
      if (result2.thrown)
        return null;
      if (result2.error)
        this.state = result2.failState;
      node2.returnType = result2.node.typeAnnotation ? this.finishNode(result2.node, "TypeAnnotation") : null;
    }
    return super.parseArrow(node2);
  }
  shouldParseArrow(params) {
    return this.match(14) || super.shouldParseArrow(params);
  }
  setArrowFunctionParameters(node2, params) {
    if (this.state.noArrowParamsConversionAt.indexOf(node2.start) !== -1) {
      node2.params = params;
    } else {
      super.setArrowFunctionParameters(node2, params);
    }
  }
  checkParams(node2, allowDuplicates, isArrowFunction, strictModeChanged = true) {
    if (isArrowFunction && this.state.noArrowParamsConversionAt.indexOf(node2.start) !== -1) {
      return;
    }
    for (let i = 0; i < node2.params.length; i++) {
      if (this.isThisParam(node2.params[i]) && i > 0) {
        this.raise(FlowErrors.ThisParamMustBeFirst, {
          at: node2.params[i]
        });
      }
    }
    super.checkParams(node2, allowDuplicates, isArrowFunction, strictModeChanged);
  }
  parseParenAndDistinguishExpression(canBeArrow) {
    return super.parseParenAndDistinguishExpression(canBeArrow && this.state.noArrowAt.indexOf(this.state.start) === -1);
  }
  parseSubscripts(base2, startLoc, noCalls) {
    if (base2.type === "Identifier" && base2.name === "async" && this.state.noArrowAt.indexOf(startLoc.index) !== -1) {
      this.next();
      const node2 = this.startNodeAt(startLoc);
      node2.callee = base2;
      node2.arguments = super.parseCallExpressionArguments(11, false);
      base2 = this.finishNode(node2, "CallExpression");
    } else if (base2.type === "Identifier" && base2.name === "async" && this.match(47)) {
      const state = this.state.clone();
      const arrow = this.tryParse((abort) => this.parseAsyncArrowWithTypeParameters(startLoc) || abort(), state);
      if (!arrow.error && !arrow.aborted)
        return arrow.node;
      const result2 = this.tryParse(() => super.parseSubscripts(base2, startLoc, noCalls), state);
      if (result2.node && !result2.error)
        return result2.node;
      if (arrow.node) {
        this.state = arrow.failState;
        return arrow.node;
      }
      if (result2.node) {
        this.state = result2.failState;
        return result2.node;
      }
      throw arrow.error || result2.error;
    }
    return super.parseSubscripts(base2, startLoc, noCalls);
  }
  parseSubscript(base2, startLoc, noCalls, subscriptState) {
    if (this.match(18) && this.isLookaheadToken_lt()) {
      subscriptState.optionalChainMember = true;
      if (noCalls) {
        subscriptState.stop = true;
        return base2;
      }
      this.next();
      const node2 = this.startNodeAt(startLoc);
      node2.callee = base2;
      node2.typeArguments = this.flowParseTypeParameterInstantiation();
      this.expect(10);
      node2.arguments = this.parseCallExpressionArguments(11, false);
      node2.optional = true;
      return this.finishCallExpression(node2, true);
    } else if (!noCalls && this.shouldParseTypes() && this.match(47)) {
      const node2 = this.startNodeAt(startLoc);
      node2.callee = base2;
      const result2 = this.tryParse(() => {
        node2.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew();
        this.expect(10);
        node2.arguments = super.parseCallExpressionArguments(11, false);
        if (subscriptState.optionalChainMember) {
          node2.optional = false;
        }
        return this.finishCallExpression(node2, subscriptState.optionalChainMember);
      });
      if (result2.node) {
        if (result2.error)
          this.state = result2.failState;
        return result2.node;
      }
    }
    return super.parseSubscript(base2, startLoc, noCalls, subscriptState);
  }
  parseNewCallee(node2) {
    super.parseNewCallee(node2);
    let targs = null;
    if (this.shouldParseTypes() && this.match(47)) {
      targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node;
    }
    node2.typeArguments = targs;
  }
  parseAsyncArrowWithTypeParameters(startLoc) {
    const node2 = this.startNodeAt(startLoc);
    this.parseFunctionParams(node2, false);
    if (!this.parseArrow(node2))
      return;
    return super.parseArrowExpression(node2, void 0, true);
  }
  readToken_mult_modulo(code) {
    const next = this.input.charCodeAt(this.state.pos + 1);
    if (code === 42 && next === 47 && this.state.hasFlowComment) {
      this.state.hasFlowComment = false;
      this.state.pos += 2;
      this.nextToken();
      return;
    }
    super.readToken_mult_modulo(code);
  }
  readToken_pipe_amp(code) {
    const next = this.input.charCodeAt(this.state.pos + 1);
    if (code === 124 && next === 125) {
      this.finishOp(9, 2);
      return;
    }
    super.readToken_pipe_amp(code);
  }
  parseTopLevel(file, program) {
    const fileNode = super.parseTopLevel(file, program);
    if (this.state.hasFlowComment) {
      this.raise(FlowErrors.UnterminatedFlowComment, {
        at: this.state.curPosition()
      });
    }
    return fileNode;
  }
  skipBlockComment() {
    if (this.hasPlugin("flowComments") && this.skipFlowComment()) {
      if (this.state.hasFlowComment) {
        throw this.raise(FlowErrors.NestedFlowComment, {
          at: this.state.startLoc
        });
      }
      this.hasFlowCommentCompletion();
      const commentSkip = this.skipFlowComment();
      if (commentSkip) {
        this.state.pos += commentSkip;
        this.state.hasFlowComment = true;
      }
      return;
    }
    return super.skipBlockComment(this.state.hasFlowComment ? "*-/" : "*/");
  }
  skipFlowComment() {
    const {
      pos
    } = this.state;
    let shiftToFirstNonWhiteSpace = 2;
    while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) {
      shiftToFirstNonWhiteSpace++;
    }
    const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);
    const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);
    if (ch2 === 58 && ch3 === 58) {
      return shiftToFirstNonWhiteSpace + 2;
    }
    if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") {
      return shiftToFirstNonWhiteSpace + 12;
    }
    if (ch2 === 58 && ch3 !== 58) {
      return shiftToFirstNonWhiteSpace;
    }
    return false;
  }
  hasFlowCommentCompletion() {
    const end = this.input.indexOf("*/", this.state.pos);
    if (end === -1) {
      throw this.raise(Errors.UnterminatedComment, {
        at: this.state.curPosition()
      });
    }
  }
  flowEnumErrorBooleanMemberNotInitialized(loc, {
    enumName,
    memberName
  }) {
    this.raise(FlowErrors.EnumBooleanMemberNotInitialized, {
      at: loc,
      memberName,
      enumName
    });
  }
  flowEnumErrorInvalidMemberInitializer(loc, enumContext) {
    return this.raise(!enumContext.explicitType ? FlowErrors.EnumInvalidMemberInitializerUnknownType : enumContext.explicitType === "symbol" ? FlowErrors.EnumInvalidMemberInitializerSymbolType : FlowErrors.EnumInvalidMemberInitializerPrimaryType, Object.assign({
      at: loc
    }, enumContext));
  }
  flowEnumErrorNumberMemberNotInitialized(loc, {
    enumName,
    memberName
  }) {
    this.raise(FlowErrors.EnumNumberMemberNotInitialized, {
      at: loc,
      enumName,
      memberName
    });
  }
  flowEnumErrorStringMemberInconsistentlyInitailized(node2, {
    enumName
  }) {
    this.raise(FlowErrors.EnumStringMemberInconsistentlyInitailized, {
      at: node2,
      enumName
    });
  }
  flowEnumMemberInit() {
    const startLoc = this.state.startLoc;
    const endOfInit = () => this.match(12) || this.match(8);
    switch (this.state.type) {
      case 132: {
        const literal = this.parseNumericLiteral(this.state.value);
        if (endOfInit()) {
          return {
            type: "number",
            loc: literal.loc.start,
            value: literal
          };
        }
        return {
          type: "invalid",
          loc: startLoc
        };
      }
      case 131: {
        const literal = this.parseStringLiteral(this.state.value);
        if (endOfInit()) {
          return {
            type: "string",
            loc: literal.loc.start,
            value: literal
          };
        }
        return {
          type: "invalid",
          loc: startLoc
        };
      }
      case 85:
      case 86: {
        const literal = this.parseBooleanLiteral(this.match(85));
        if (endOfInit()) {
          return {
            type: "boolean",
            loc: literal.loc.start,
            value: literal
          };
        }
        return {
          type: "invalid",
          loc: startLoc
        };
      }
      default:
        return {
          type: "invalid",
          loc: startLoc
        };
    }
  }
  flowEnumMemberRaw() {
    const loc = this.state.startLoc;
    const id3 = this.parseIdentifier(true);
    const init2 = this.eat(29) ? this.flowEnumMemberInit() : {
      type: "none",
      loc
    };
    return {
      id: id3,
      init: init2
    };
  }
  flowEnumCheckExplicitTypeMismatch(loc, context, expectedType) {
    const {
      explicitType
    } = context;
    if (explicitType === null) {
      return;
    }
    if (explicitType !== expectedType) {
      this.flowEnumErrorInvalidMemberInitializer(loc, context);
    }
  }
  flowEnumMembers({
    enumName,
    explicitType
  }) {
    const seenNames = /* @__PURE__ */ new Set();
    const members = {
      booleanMembers: [],
      numberMembers: [],
      stringMembers: [],
      defaultedMembers: []
    };
    let hasUnknownMembers = false;
    while (!this.match(8)) {
      if (this.eat(21)) {
        hasUnknownMembers = true;
        break;
      }
      const memberNode = this.startNode();
      const {
        id: id3,
        init: init2
      } = this.flowEnumMemberRaw();
      const memberName = id3.name;
      if (memberName === "") {
        continue;
      }
      if (/^[a-z]/.test(memberName)) {
        this.raise(FlowErrors.EnumInvalidMemberName, {
          at: id3,
          memberName,
          suggestion: memberName[0].toUpperCase() + memberName.slice(1),
          enumName
        });
      }
      if (seenNames.has(memberName)) {
        this.raise(FlowErrors.EnumDuplicateMemberName, {
          at: id3,
          memberName,
          enumName
        });
      }
      seenNames.add(memberName);
      const context = {
        enumName,
        explicitType,
        memberName
      };
      memberNode.id = id3;
      switch (init2.type) {
        case "boolean": {
          this.flowEnumCheckExplicitTypeMismatch(init2.loc, context, "boolean");
          memberNode.init = init2.value;
          members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember"));
          break;
        }
        case "number": {
          this.flowEnumCheckExplicitTypeMismatch(init2.loc, context, "number");
          memberNode.init = init2.value;
          members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember"));
          break;
        }
        case "string": {
          this.flowEnumCheckExplicitTypeMismatch(init2.loc, context, "string");
          memberNode.init = init2.value;
          members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember"));
          break;
        }
        case "invalid": {
          throw this.flowEnumErrorInvalidMemberInitializer(init2.loc, context);
        }
        case "none": {
          switch (explicitType) {
            case "boolean":
              this.flowEnumErrorBooleanMemberNotInitialized(init2.loc, context);
              break;
            case "number":
              this.flowEnumErrorNumberMemberNotInitialized(init2.loc, context);
              break;
            default:
              members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember"));
          }
        }
      }
      if (!this.match(8)) {
        this.expect(12);
      }
    }
    return {
      members,
      hasUnknownMembers
    };
  }
  flowEnumStringMembers(initializedMembers, defaultedMembers, {
    enumName
  }) {
    if (initializedMembers.length === 0) {
      return defaultedMembers;
    } else if (defaultedMembers.length === 0) {
      return initializedMembers;
    } else if (defaultedMembers.length > initializedMembers.length) {
      for (const member of initializedMembers) {
        this.flowEnumErrorStringMemberInconsistentlyInitailized(member, {
          enumName
        });
      }
      return defaultedMembers;
    } else {
      for (const member of defaultedMembers) {
        this.flowEnumErrorStringMemberInconsistentlyInitailized(member, {
          enumName
        });
      }
      return initializedMembers;
    }
  }
  flowEnumParseExplicitType({
    enumName
  }) {
    if (!this.eatContextual(101))
      return null;
    if (!tokenIsIdentifier(this.state.type)) {
      throw this.raise(FlowErrors.EnumInvalidExplicitTypeUnknownSupplied, {
        at: this.state.startLoc,
        enumName
      });
    }
    const {
      value
    } = this.state;
    this.next();
    if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") {
      this.raise(FlowErrors.EnumInvalidExplicitType, {
        at: this.state.startLoc,
        enumName,
        invalidEnumType: value
      });
    }
    return value;
  }
  flowEnumBody(node2, id3) {
    const enumName = id3.name;
    const nameLoc = id3.loc.start;
    const explicitType = this.flowEnumParseExplicitType({
      enumName
    });
    this.expect(5);
    const {
      members,
      hasUnknownMembers
    } = this.flowEnumMembers({
      enumName,
      explicitType
    });
    node2.hasUnknownMembers = hasUnknownMembers;
    switch (explicitType) {
      case "boolean":
        node2.explicitType = true;
        node2.members = members.booleanMembers;
        this.expect(8);
        return this.finishNode(node2, "EnumBooleanBody");
      case "number":
        node2.explicitType = true;
        node2.members = members.numberMembers;
        this.expect(8);
        return this.finishNode(node2, "EnumNumberBody");
      case "string":
        node2.explicitType = true;
        node2.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
          enumName
        });
        this.expect(8);
        return this.finishNode(node2, "EnumStringBody");
      case "symbol":
        node2.members = members.defaultedMembers;
        this.expect(8);
        return this.finishNode(node2, "EnumSymbolBody");
      default: {
        const empty2 = () => {
          node2.members = [];
          this.expect(8);
          return this.finishNode(node2, "EnumStringBody");
        };
        node2.explicitType = false;
        const boolsLen = members.booleanMembers.length;
        const numsLen = members.numberMembers.length;
        const strsLen = members.stringMembers.length;
        const defaultedLen = members.defaultedMembers.length;
        if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {
          return empty2();
        } else if (!boolsLen && !numsLen) {
          node2.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
            enumName
          });
          this.expect(8);
          return this.finishNode(node2, "EnumStringBody");
        } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {
          for (const member of members.defaultedMembers) {
            this.flowEnumErrorBooleanMemberNotInitialized(member.loc.start, {
              enumName,
              memberName: member.id.name
            });
          }
          node2.members = members.booleanMembers;
          this.expect(8);
          return this.finishNode(node2, "EnumBooleanBody");
        } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {
          for (const member of members.defaultedMembers) {
            this.flowEnumErrorNumberMemberNotInitialized(member.loc.start, {
              enumName,
              memberName: member.id.name
            });
          }
          node2.members = members.numberMembers;
          this.expect(8);
          return this.finishNode(node2, "EnumNumberBody");
        } else {
          this.raise(FlowErrors.EnumInconsistentMemberValues, {
            at: nameLoc,
            enumName
          });
          return empty2();
        }
      }
    }
  }
  flowParseEnumDeclaration(node2) {
    const id3 = this.parseIdentifier();
    node2.id = id3;
    node2.body = this.flowEnumBody(this.startNode(), id3);
    return this.finishNode(node2, "EnumDeclaration");
  }
  isLookaheadToken_lt() {
    const next = this.nextTokenStart();
    if (this.input.charCodeAt(next) === 60) {
      const afterNext = this.input.charCodeAt(next + 1);
      return afterNext !== 60 && afterNext !== 61;
    }
    return false;
  }
  maybeUnwrapTypeCastExpression(node2) {
    return node2.type === "TypeCastExpression" ? node2.expression : node2;
  }
};
const entities = {
  __proto__: null,
  quot: '"',
  amp: "&",
  apos: "'",
  lt: "<",
  gt: ">",
  nbsp: " ",
  iexcl: "¡",
  cent: "¢",
  pound: "£",
  curren: "¤",
  yen: "¥",
  brvbar: "¦",
  sect: "§",
  uml: "¨",
  copy: "©",
  ordf: "ª",
  laquo: "«",
  not: "¬",
  shy: "­",
  reg: "®",
  macr: "¯",
  deg: "°",
  plusmn: "±",
  sup2: "²",
  sup3: "³",
  acute: "´",
  micro: "µ",
  para: "¶",
  middot: "·",
  cedil: "¸",
  sup1: "¹",
  ordm: "º",
  raquo: "»",
  frac14: "¼",
  frac12: "½",
  frac34: "¾",
  iquest: "¿",
  Agrave: "À",
  Aacute: "Á",
  Acirc: "Â",
  Atilde: "Ã",
  Auml: "Ä",
  Aring: "Å",
  AElig: "Æ",
  Ccedil: "Ç",
  Egrave: "È",
  Eacute: "É",
  Ecirc: "Ê",
  Euml: "Ë",
  Igrave: "Ì",
  Iacute: "Í",
  Icirc: "Î",
  Iuml: "Ï",
  ETH: "Ð",
  Ntilde: "Ñ",
  Ograve: "Ò",
  Oacute: "Ó",
  Ocirc: "Ô",
  Otilde: "Õ",
  Ouml: "Ö",
  times: "×",
  Oslash: "Ø",
  Ugrave: "Ù",
  Uacute: "Ú",
  Ucirc: "Û",
  Uuml: "Ü",
  Yacute: "Ý",
  THORN: "Þ",
  szlig: "ß",
  agrave: "à",
  aacute: "á",
  acirc: "â",
  atilde: "ã",
  auml: "ä",
  aring: "å",
  aelig: "æ",
  ccedil: "ç",
  egrave: "è",
  eacute: "é",
  ecirc: "ê",
  euml: "ë",
  igrave: "ì",
  iacute: "í",
  icirc: "î",
  iuml: "ï",
  eth: "ð",
  ntilde: "ñ",
  ograve: "ò",
  oacute: "ó",
  ocirc: "ô",
  otilde: "õ",
  ouml: "ö",
  divide: "÷",
  oslash: "ø",
  ugrave: "ù",
  uacute: "ú",
  ucirc: "û",
  uuml: "ü",
  yacute: "ý",
  thorn: "þ",
  yuml: "ÿ",
  OElig: "Œ",
  oelig: "œ",
  Scaron: "Š",
  scaron: "š",
  Yuml: "Ÿ",
  fnof: "ƒ",
  circ: "ˆ",
  tilde: "˜",
  Alpha: "Α",
  Beta: "Β",
  Gamma: "Γ",
  Delta: "Δ",
  Epsilon: "Ε",
  Zeta: "Ζ",
  Eta: "Η",
  Theta: "Θ",
  Iota: "Ι",
  Kappa: "Κ",
  Lambda: "Λ",
  Mu: "Μ",
  Nu: "Ν",
  Xi: "Ξ",
  Omicron: "Ο",
  Pi: "Π",
  Rho: "Ρ",
  Sigma: "Σ",
  Tau: "Τ",
  Upsilon: "Υ",
  Phi: "Φ",
  Chi: "Χ",
  Psi: "Ψ",
  Omega: "Ω",
  alpha: "α",
  beta: "β",
  gamma: "γ",
  delta: "δ",
  epsilon: "ε",
  zeta: "ζ",
  eta: "η",
  theta: "θ",
  iota: "ι",
  kappa: "κ",
  lambda: "λ",
  mu: "μ",
  nu: "ν",
  xi: "ξ",
  omicron: "ο",
  pi: "π",
  rho: "ρ",
  sigmaf: "ς",
  sigma: "σ",
  tau: "τ",
  upsilon: "υ",
  phi: "φ",
  chi: "χ",
  psi: "ψ",
  omega: "ω",
  thetasym: "ϑ",
  upsih: "ϒ",
  piv: "ϖ",
  ensp: " ",
  emsp: " ",
  thinsp: " ",
  zwnj: "‌",
  zwj: "‍",
  lrm: "‎",
  rlm: "‏",
  ndash: "–",
  mdash: "—",
  lsquo: "‘",
  rsquo: "’",
  sbquo: "‚",
  ldquo: "“",
  rdquo: "”",
  bdquo: "„",
  dagger: "†",
  Dagger: "‡",
  bull: "•",
  hellip: "…",
  permil: "‰",
  prime: "′",
  Prime: "″",
  lsaquo: "‹",
  rsaquo: "›",
  oline: "‾",
  frasl: "⁄",
  euro: "€",
  image: "ℑ",
  weierp: "℘",
  real: "ℜ",
  trade: "™",
  alefsym: "ℵ",
  larr: "←",
  uarr: "↑",
  rarr: "→",
  darr: "↓",
  harr: "↔",
  crarr: "↵",
  lArr: "⇐",
  uArr: "⇑",
  rArr: "⇒",
  dArr: "⇓",
  hArr: "⇔",
  forall: "∀",
  part: "∂",
  exist: "∃",
  empty: "∅",
  nabla: "∇",
  isin: "∈",
  notin: "∉",
  ni: "∋",
  prod: "∏",
  sum: "∑",
  minus: "−",
  lowast: "∗",
  radic: "√",
  prop: "∝",
  infin: "∞",
  ang: "∠",
  and: "∧",
  or: "∨",
  cap: "∩",
  cup: "∪",
  int: "∫",
  there4: "∴",
  sim: "∼",
  cong: "≅",
  asymp: "≈",
  ne: "≠",
  equiv: "≡",
  le: "≤",
  ge: "≥",
  sub: "⊂",
  sup: "⊃",
  nsub: "⊄",
  sube: "⊆",
  supe: "⊇",
  oplus: "⊕",
  otimes: "⊗",
  perp: "⊥",
  sdot: "⋅",
  lceil: "⌈",
  rceil: "⌉",
  lfloor: "⌊",
  rfloor: "⌋",
  lang: "〈",
  rang: "〉",
  loz: "◊",
  spades: "♠",
  clubs: "♣",
  hearts: "♥",
  diams: "♦"
};
const JsxErrors = ParseErrorEnum`jsx`({
  AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression.",
  MissingClosingTagElement: ({
    openingTagName
  }) => `Expected corresponding JSX closing tag for <${openingTagName}>.`,
  MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>.",
  UnexpectedSequenceExpression: "Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?",
  UnexpectedToken: ({
    unexpected,
    HTMLEntity
  }) => `Unexpected token \`${unexpected}\`. Did you mean \`${HTMLEntity}\` or \`{'${unexpected}'}\`?`,
  UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text.",
  UnterminatedJsxContent: "Unterminated JSX contents.",
  UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"
});
function isFragment(object2) {
  return object2 ? object2.type === "JSXOpeningFragment" || object2.type === "JSXClosingFragment" : false;
}
function getQualifiedJSXName(object2) {
  if (object2.type === "JSXIdentifier") {
    return object2.name;
  }
  if (object2.type === "JSXNamespacedName") {
    return object2.namespace.name + ":" + object2.name.name;
  }
  if (object2.type === "JSXMemberExpression") {
    return getQualifiedJSXName(object2.object) + "." + getQualifiedJSXName(object2.property);
  }
  throw new Error("Node had unexpected type: " + object2.type);
}
var jsx = (superClass) => class JSXParserMixin extends superClass {
  jsxReadToken() {
    let out = "";
    let chunkStart = this.state.pos;
    for (; ; ) {
      if (this.state.pos >= this.length) {
        throw this.raise(JsxErrors.UnterminatedJsxContent, {
          at: this.state.startLoc
        });
      }
      const ch = this.input.charCodeAt(this.state.pos);
      switch (ch) {
        case 60:
        case 123:
          if (this.state.pos === this.state.start) {
            if (ch === 60 && this.state.canStartJSXElement) {
              ++this.state.pos;
              this.finishToken(140);
            } else {
              super.getTokenFromCode(ch);
            }
            return;
          }
          out += this.input.slice(chunkStart, this.state.pos);
          this.finishToken(139, out);
          return;
        case 38:
          out += this.input.slice(chunkStart, this.state.pos);
          out += this.jsxReadEntity();
          chunkStart = this.state.pos;
          break;
        case 62:
        case 125:
        default:
          if (isNewLine(ch)) {
            out += this.input.slice(chunkStart, this.state.pos);
            out += this.jsxReadNewLine(true);
            chunkStart = this.state.pos;
          } else {
            ++this.state.pos;
          }
      }
    }
  }
  jsxReadNewLine(normalizeCRLF) {
    const ch = this.input.charCodeAt(this.state.pos);
    let out;
    ++this.state.pos;
    if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) {
      ++this.state.pos;
      out = normalizeCRLF ? "\n" : "\r\n";
    } else {
      out = String.fromCharCode(ch);
    }
    ++this.state.curLine;
    this.state.lineStart = this.state.pos;
    return out;
  }
  jsxReadString(quote) {
    let out = "";
    let chunkStart = ++this.state.pos;
    for (; ; ) {
      if (this.state.pos >= this.length) {
        throw this.raise(Errors.UnterminatedString, {
          at: this.state.startLoc
        });
      }
      const ch = this.input.charCodeAt(this.state.pos);
      if (ch === quote)
        break;
      if (ch === 38) {
        out += this.input.slice(chunkStart, this.state.pos);
        out += this.jsxReadEntity();
        chunkStart = this.state.pos;
      } else if (isNewLine(ch)) {
        out += this.input.slice(chunkStart, this.state.pos);
        out += this.jsxReadNewLine(false);
        chunkStart = this.state.pos;
      } else {
        ++this.state.pos;
      }
    }
    out += this.input.slice(chunkStart, this.state.pos++);
    this.finishToken(131, out);
  }
  jsxReadEntity() {
    const startPos = ++this.state.pos;
    if (this.codePointAtPos(this.state.pos) === 35) {
      ++this.state.pos;
      let radix = 10;
      if (this.codePointAtPos(this.state.pos) === 120) {
        radix = 16;
        ++this.state.pos;
      }
      const codePoint = this.readInt(radix, void 0, false, "bail");
      if (codePoint !== null && this.codePointAtPos(this.state.pos) === 59) {
        ++this.state.pos;
        return String.fromCodePoint(codePoint);
      }
    } else {
      let count = 0;
      let semi = false;
      while (count++ < 10 && this.state.pos < this.length && !(semi = this.codePointAtPos(this.state.pos) == 59)) {
        ++this.state.pos;
      }
      if (semi) {
        const desc = this.input.slice(startPos, this.state.pos);
        const entity = entities[desc];
        ++this.state.pos;
        if (entity) {
          return entity;
        }
      }
    }
    this.state.pos = startPos;
    return "&";
  }
  jsxReadWord() {
    let ch;
    const start = this.state.pos;
    do {
      ch = this.input.charCodeAt(++this.state.pos);
    } while (isIdentifierChar(ch) || ch === 45);
    this.finishToken(138, this.input.slice(start, this.state.pos));
  }
  jsxParseIdentifier() {
    const node2 = this.startNode();
    if (this.match(138)) {
      node2.name = this.state.value;
    } else if (tokenIsKeyword(this.state.type)) {
      node2.name = tokenLabelName(this.state.type);
    } else {
      this.unexpected();
    }
    this.next();
    return this.finishNode(node2, "JSXIdentifier");
  }
  jsxParseNamespacedName() {
    const startLoc = this.state.startLoc;
    const name = this.jsxParseIdentifier();
    if (!this.eat(14))
      return name;
    const node2 = this.startNodeAt(startLoc);
    node2.namespace = name;
    node2.name = this.jsxParseIdentifier();
    return this.finishNode(node2, "JSXNamespacedName");
  }
  jsxParseElementName() {
    const startLoc = this.state.startLoc;
    let node2 = this.jsxParseNamespacedName();
    if (node2.type === "JSXNamespacedName") {
      return node2;
    }
    while (this.eat(16)) {
      const newNode = this.startNodeAt(startLoc);
      newNode.object = node2;
      newNode.property = this.jsxParseIdentifier();
      node2 = this.finishNode(newNode, "JSXMemberExpression");
    }
    return node2;
  }
  jsxParseAttributeValue() {
    let node2;
    switch (this.state.type) {
      case 5:
        node2 = this.startNode();
        this.setContext(types$1.brace);
        this.next();
        node2 = this.jsxParseExpressionContainer(node2, types$1.j_oTag);
        if (node2.expression.type === "JSXEmptyExpression") {
          this.raise(JsxErrors.AttributeIsEmpty, {
            at: node2
          });
        }
        return node2;
      case 140:
      case 131:
        return this.parseExprAtom();
      default:
        throw this.raise(JsxErrors.UnsupportedJsxValue, {
          at: this.state.startLoc
        });
    }
  }
  jsxParseEmptyExpression() {
    const node2 = this.startNodeAt(this.state.lastTokEndLoc);
    return this.finishNodeAt(node2, "JSXEmptyExpression", this.state.startLoc);
  }
  jsxParseSpreadChild(node2) {
    this.next();
    node2.expression = this.parseExpression();
    this.setContext(types$1.j_expr);
    this.state.canStartJSXElement = true;
    this.expect(8);
    return this.finishNode(node2, "JSXSpreadChild");
  }
  jsxParseExpressionContainer(node2, previousContext) {
    if (this.match(8)) {
      node2.expression = this.jsxParseEmptyExpression();
    } else {
      const expression = this.parseExpression();
      node2.expression = expression;
    }
    this.setContext(previousContext);
    this.state.canStartJSXElement = true;
    this.expect(8);
    return this.finishNode(node2, "JSXExpressionContainer");
  }
  jsxParseAttribute() {
    const node2 = this.startNode();
    if (this.match(5)) {
      this.setContext(types$1.brace);
      this.next();
      this.expect(21);
      node2.argument = this.parseMaybeAssignAllowIn();
      this.setContext(types$1.j_oTag);
      this.state.canStartJSXElement = true;
      this.expect(8);
      return this.finishNode(node2, "JSXSpreadAttribute");
    }
    node2.name = this.jsxParseNamespacedName();
    node2.value = this.eat(29) ? this.jsxParseAttributeValue() : null;
    return this.finishNode(node2, "JSXAttribute");
  }
  jsxParseOpeningElementAt(startLoc) {
    const node2 = this.startNodeAt(startLoc);
    if (this.eat(141)) {
      return this.finishNode(node2, "JSXOpeningFragment");
    }
    node2.name = this.jsxParseElementName();
    return this.jsxParseOpeningElementAfterName(node2);
  }
  jsxParseOpeningElementAfterName(node2) {
    const attributes = [];
    while (!this.match(56) && !this.match(141)) {
      attributes.push(this.jsxParseAttribute());
    }
    node2.attributes = attributes;
    node2.selfClosing = this.eat(56);
    this.expect(141);
    return this.finishNode(node2, "JSXOpeningElement");
  }
  jsxParseClosingElementAt(startLoc) {
    const node2 = this.startNodeAt(startLoc);
    if (this.eat(141)) {
      return this.finishNode(node2, "JSXClosingFragment");
    }
    node2.name = this.jsxParseElementName();
    this.expect(141);
    return this.finishNode(node2, "JSXClosingElement");
  }
  jsxParseElementAt(startLoc) {
    const node2 = this.startNodeAt(startLoc);
    const children = [];
    const openingElement = this.jsxParseOpeningElementAt(startLoc);
    let closingElement = null;
    if (!openingElement.selfClosing) {
      contents:
        for (; ; ) {
          switch (this.state.type) {
            case 140:
              startLoc = this.state.startLoc;
              this.next();
              if (this.eat(56)) {
                closingElement = this.jsxParseClosingElementAt(startLoc);
                break contents;
              }
              children.push(this.jsxParseElementAt(startLoc));
              break;
            case 139:
              children.push(this.parseExprAtom());
              break;
            case 5: {
              const node3 = this.startNode();
              this.setContext(types$1.brace);
              this.next();
              if (this.match(21)) {
                children.push(this.jsxParseSpreadChild(node3));
              } else {
                children.push(this.jsxParseExpressionContainer(node3, types$1.j_expr));
              }
              break;
            }
            default:
              this.unexpected();
          }
        }
      if (isFragment(openingElement) && !isFragment(closingElement) && closingElement !== null) {
        this.raise(JsxErrors.MissingClosingTagFragment, {
          at: closingElement
        });
      } else if (!isFragment(openingElement) && isFragment(closingElement)) {
        this.raise(JsxErrors.MissingClosingTagElement, {
          at: closingElement,
          openingTagName: getQualifiedJSXName(openingElement.name)
        });
      } else if (!isFragment(openingElement) && !isFragment(closingElement)) {
        if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
          this.raise(JsxErrors.MissingClosingTagElement, {
            at: closingElement,
            openingTagName: getQualifiedJSXName(openingElement.name)
          });
        }
      }
    }
    if (isFragment(openingElement)) {
      node2.openingFragment = openingElement;
      node2.closingFragment = closingElement;
    } else {
      node2.openingElement = openingElement;
      node2.closingElement = closingElement;
    }
    node2.children = children;
    if (this.match(47)) {
      throw this.raise(JsxErrors.UnwrappedAdjacentJSXElements, {
        at: this.state.startLoc
      });
    }
    return isFragment(openingElement) ? this.finishNode(node2, "JSXFragment") : this.finishNode(node2, "JSXElement");
  }
  jsxParseElement() {
    const startLoc = this.state.startLoc;
    this.next();
    return this.jsxParseElementAt(startLoc);
  }
  setContext(newContext) {
    const {
      context
    } = this.state;
    context[context.length - 1] = newContext;
  }
  parseExprAtom(refExpressionErrors) {
    if (this.match(139)) {
      return this.parseLiteral(this.state.value, "JSXText");
    } else if (this.match(140)) {
      return this.jsxParseElement();
    } else if (this.match(47) && this.input.charCodeAt(this.state.pos) !== 33) {
      this.replaceToken(140);
      return this.jsxParseElement();
    } else {
      return super.parseExprAtom(refExpressionErrors);
    }
  }
  skipSpace() {
    const curContext = this.curContext();
    if (!curContext.preserveSpace)
      super.skipSpace();
  }
  getTokenFromCode(code) {
    const context = this.curContext();
    if (context === types$1.j_expr) {
      this.jsxReadToken();
      return;
    }
    if (context === types$1.j_oTag || context === types$1.j_cTag) {
      if (isIdentifierStart(code)) {
        this.jsxReadWord();
        return;
      }
      if (code === 62) {
        ++this.state.pos;
        this.finishToken(141);
        return;
      }
      if ((code === 34 || code === 39) && context === types$1.j_oTag) {
        this.jsxReadString(code);
        return;
      }
    }
    if (code === 60 && this.state.canStartJSXElement && this.input.charCodeAt(this.state.pos + 1) !== 33) {
      ++this.state.pos;
      this.finishToken(140);
      return;
    }
    super.getTokenFromCode(code);
  }
  updateContext(prevType) {
    const {
      context,
      type
    } = this.state;
    if (type === 56 && prevType === 140) {
      context.splice(-2, 2, types$1.j_cTag);
      this.state.canStartJSXElement = false;
    } else if (type === 140) {
      context.push(types$1.j_oTag);
    } else if (type === 141) {
      const out = context[context.length - 1];
      if (out === types$1.j_oTag && prevType === 56 || out === types$1.j_cTag) {
        context.pop();
        this.state.canStartJSXElement = context[context.length - 1] === types$1.j_expr;
      } else {
        this.setContext(types$1.j_expr);
        this.state.canStartJSXElement = true;
      }
    } else {
      this.state.canStartJSXElement = tokenComesBeforeExpression(type);
    }
  }
};
class TypeScriptScope extends Scope {
  constructor(...args) {
    super(...args);
    this.types = /* @__PURE__ */ new Set();
    this.enums = /* @__PURE__ */ new Set();
    this.constEnums = /* @__PURE__ */ new Set();
    this.classes = /* @__PURE__ */ new Set();
    this.exportOnlyBindings = /* @__PURE__ */ new Set();
  }
}
class TypeScriptScopeHandler extends ScopeHandler {
  constructor(...args) {
    super(...args);
    this.importsStack = [];
  }
  createScope(flags) {
    this.importsStack.push(/* @__PURE__ */ new Set());
    return new TypeScriptScope(flags);
  }
  enter(flags) {
    if (flags == SCOPE_TS_MODULE) {
      this.importsStack.push(/* @__PURE__ */ new Set());
    }
    super.enter(flags);
  }
  exit() {
    const flags = super.exit();
    if (flags == SCOPE_TS_MODULE) {
      this.importsStack.pop();
    }
    return flags;
  }
  hasImport(name, allowShadow) {
    const len = this.importsStack.length;
    if (this.importsStack[len - 1].has(name)) {
      return true;
    }
    if (!allowShadow && len > 1) {
      for (let i = 0; i < len - 1; i++) {
        if (this.importsStack[i].has(name))
          return true;
      }
    }
    return false;
  }
  declareName(name, bindingType, loc) {
    if (bindingType & BIND_FLAGS_TS_IMPORT) {
      if (this.hasImport(name, true)) {
        this.parser.raise(Errors.VarRedeclaration, {
          at: loc,
          identifierName: name
        });
      }
      this.importsStack[this.importsStack.length - 1].add(name);
      return;
    }
    const scope = this.currentScope();
    if (bindingType & BIND_FLAGS_TS_EXPORT_ONLY) {
      this.maybeExportDefined(scope, name);
      scope.exportOnlyBindings.add(name);
      return;
    }
    super.declareName(name, bindingType, loc);
    if (bindingType & BIND_KIND_TYPE) {
      if (!(bindingType & BIND_KIND_VALUE)) {
        this.checkRedeclarationInScope(scope, name, bindingType, loc);
        this.maybeExportDefined(scope, name);
      }
      scope.types.add(name);
    }
    if (bindingType & BIND_FLAGS_TS_ENUM)
      scope.enums.add(name);
    if (bindingType & BIND_FLAGS_TS_CONST_ENUM)
      scope.constEnums.add(name);
    if (bindingType & BIND_FLAGS_CLASS)
      scope.classes.add(name);
  }
  isRedeclaredInScope(scope, name, bindingType) {
    if (scope.enums.has(name)) {
      if (bindingType & BIND_FLAGS_TS_ENUM) {
        const isConst2 = !!(bindingType & BIND_FLAGS_TS_CONST_ENUM);
        const wasConst = scope.constEnums.has(name);
        return isConst2 !== wasConst;
      }
      return true;
    }
    if (bindingType & BIND_FLAGS_CLASS && scope.classes.has(name)) {
      if (scope.lexical.has(name)) {
        return !!(bindingType & BIND_KIND_VALUE);
      } else {
        return false;
      }
    }
    if (bindingType & BIND_KIND_TYPE && scope.types.has(name)) {
      return true;
    }
    return super.isRedeclaredInScope(scope, name, bindingType);
  }
  checkLocalExport(id3) {
    const {
      name
    } = id3;
    if (this.hasImport(name))
      return;
    const len = this.scopeStack.length;
    for (let i = len - 1; i >= 0; i--) {
      const scope = this.scopeStack[i];
      if (scope.types.has(name) || scope.exportOnlyBindings.has(name))
        return;
    }
    super.checkLocalExport(id3);
  }
}
const getOwn$1 = (object2, key) => Object.hasOwnProperty.call(object2, key) && object2[key];
const unwrapParenthesizedExpression = (node2) => {
  return node2.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node2.expression) : node2;
};
class LValParser extends NodeUtils {
  toAssignable(node2, isLHS = false) {
    var _node$extra, _node$extra3;
    let parenthesized = void 0;
    if (node2.type === "ParenthesizedExpression" || (_node$extra = node2.extra) != null && _node$extra.parenthesized) {
      parenthesized = unwrapParenthesizedExpression(node2);
      if (isLHS) {
        if (parenthesized.type === "Identifier") {
          this.expressionScope.recordArrowParameterBindingError(Errors.InvalidParenthesizedAssignment, {
            at: node2
          });
        } else if (parenthesized.type !== "MemberExpression") {
          this.raise(Errors.InvalidParenthesizedAssignment, {
            at: node2
          });
        }
      } else {
        this.raise(Errors.InvalidParenthesizedAssignment, {
          at: node2
        });
      }
    }
    switch (node2.type) {
      case "Identifier":
      case "ObjectPattern":
      case "ArrayPattern":
      case "AssignmentPattern":
      case "RestElement":
        break;
      case "ObjectExpression":
        node2.type = "ObjectPattern";
        for (let i = 0, length2 = node2.properties.length, last2 = length2 - 1; i < length2; i++) {
          var _node$extra2;
          const prop = node2.properties[i];
          const isLast = i === last2;
          this.toAssignableObjectExpressionProp(prop, isLast, isLHS);
          if (isLast && prop.type === "RestElement" && (_node$extra2 = node2.extra) != null && _node$extra2.trailingCommaLoc) {
            this.raise(Errors.RestTrailingComma, {
              at: node2.extra.trailingCommaLoc
            });
          }
        }
        break;
      case "ObjectProperty": {
        const {
          key,
          value
        } = node2;
        if (this.isPrivateName(key)) {
          this.classScope.usePrivateName(this.getPrivateNameSV(key), key.loc.start);
        }
        this.toAssignable(value, isLHS);
        break;
      }
      case "SpreadElement": {
        throw new Error("Internal @babel/parser error (this is a bug, please report it). SpreadElement should be converted by .toAssignable's caller.");
      }
      case "ArrayExpression":
        node2.type = "ArrayPattern";
        this.toAssignableList(node2.elements, (_node$extra3 = node2.extra) == null ? void 0 : _node$extra3.trailingCommaLoc, isLHS);
        break;
      case "AssignmentExpression":
        if (node2.operator !== "=") {
          this.raise(Errors.MissingEqInAssignment, {
            at: node2.left.loc.end
          });
        }
        node2.type = "AssignmentPattern";
        delete node2.operator;
        this.toAssignable(node2.left, isLHS);
        break;
      case "ParenthesizedExpression":
        this.toAssignable(parenthesized, isLHS);
        break;
    }
  }
  toAssignableObjectExpressionProp(prop, isLast, isLHS) {
    if (prop.type === "ObjectMethod") {
      this.raise(prop.kind === "get" || prop.kind === "set" ? Errors.PatternHasAccessor : Errors.PatternHasMethod, {
        at: prop.key
      });
    } else if (prop.type === "SpreadElement") {
      prop.type = "RestElement";
      const arg = prop.argument;
      this.checkToRestConversion(arg, false);
      this.toAssignable(arg, isLHS);
      if (!isLast) {
        this.raise(Errors.RestTrailingComma, {
          at: prop
        });
      }
    } else {
      this.toAssignable(prop, isLHS);
    }
  }
  toAssignableList(exprList, trailingCommaLoc, isLHS) {
    const end = exprList.length - 1;
    for (let i = 0; i <= end; i++) {
      const elt = exprList[i];
      if (!elt)
        continue;
      if (elt.type === "SpreadElement") {
        elt.type = "RestElement";
        const arg = elt.argument;
        this.checkToRestConversion(arg, true);
        this.toAssignable(arg, isLHS);
      } else {
        this.toAssignable(elt, isLHS);
      }
      if (elt.type === "RestElement") {
        if (i < end) {
          this.raise(Errors.RestTrailingComma, {
            at: elt
          });
        } else if (trailingCommaLoc) {
          this.raise(Errors.RestTrailingComma, {
            at: trailingCommaLoc
          });
        }
      }
    }
  }
  isAssignable(node2, isBinding) {
    switch (node2.type) {
      case "Identifier":
      case "ObjectPattern":
      case "ArrayPattern":
      case "AssignmentPattern":
      case "RestElement":
        return true;
      case "ObjectExpression": {
        const last2 = node2.properties.length - 1;
        return node2.properties.every((prop, i) => {
          return prop.type !== "ObjectMethod" && (i === last2 || prop.type !== "SpreadElement") && this.isAssignable(prop);
        });
      }
      case "ObjectProperty":
        return this.isAssignable(node2.value);
      case "SpreadElement":
        return this.isAssignable(node2.argument);
      case "ArrayExpression":
        return node2.elements.every((element) => element === null || this.isAssignable(element));
      case "AssignmentExpression":
        return node2.operator === "=";
      case "ParenthesizedExpression":
        return this.isAssignable(node2.expression);
      case "MemberExpression":
      case "OptionalMemberExpression":
        return !isBinding;
      default:
        return false;
    }
  }
  toReferencedList(exprList, isParenthesizedExpr) {
    return exprList;
  }
  toReferencedListDeep(exprList, isParenthesizedExpr) {
    this.toReferencedList(exprList, isParenthesizedExpr);
    for (const expr of exprList) {
      if ((expr == null ? void 0 : expr.type) === "ArrayExpression") {
        this.toReferencedListDeep(expr.elements);
      }
    }
  }
  parseSpread(refExpressionErrors) {
    const node2 = this.startNode();
    this.next();
    node2.argument = this.parseMaybeAssignAllowIn(refExpressionErrors, void 0);
    return this.finishNode(node2, "SpreadElement");
  }
  parseRestBinding() {
    const node2 = this.startNode();
    this.next();
    node2.argument = this.parseBindingAtom();
    return this.finishNode(node2, "RestElement");
  }
  parseBindingAtom() {
    switch (this.state.type) {
      case 0: {
        const node2 = this.startNode();
        this.next();
        node2.elements = this.parseBindingList(3, 93, 1);
        return this.finishNode(node2, "ArrayPattern");
      }
      case 5:
        return this.parseObjectLike(8, true);
    }
    return this.parseIdentifier();
  }
  parseBindingList(close, closeCharCode, flags) {
    const allowEmpty = flags & 1;
    const elts = [];
    let first2 = true;
    while (!this.eat(close)) {
      if (first2) {
        first2 = false;
      } else {
        this.expect(12);
      }
      if (allowEmpty && this.match(12)) {
        elts.push(null);
      } else if (this.eat(close)) {
        break;
      } else if (this.match(21)) {
        elts.push(this.parseAssignableListItemTypes(this.parseRestBinding(), flags));
        if (!this.checkCommaAfterRest(closeCharCode)) {
          this.expect(close);
          break;
        }
      } else {
        const decorators = [];
        if (this.match(26) && this.hasPlugin("decorators")) {
          this.raise(Errors.UnsupportedParameterDecorator, {
            at: this.state.startLoc
          });
        }
        while (this.match(26)) {
          decorators.push(this.parseDecorator());
        }
        elts.push(this.parseAssignableListItem(flags, decorators));
      }
    }
    return elts;
  }
  parseBindingRestProperty(prop) {
    this.next();
    prop.argument = this.parseIdentifier();
    this.checkCommaAfterRest(125);
    return this.finishNode(prop, "RestElement");
  }
  parseBindingProperty() {
    const prop = this.startNode();
    const {
      type,
      startLoc
    } = this.state;
    if (type === 21) {
      return this.parseBindingRestProperty(prop);
    } else if (type === 136) {
      this.expectPlugin("destructuringPrivate", startLoc);
      this.classScope.usePrivateName(this.state.value, startLoc);
      prop.key = this.parsePrivateName();
    } else {
      this.parsePropertyName(prop);
    }
    prop.method = false;
    return this.parseObjPropValue(prop, startLoc, false, false, true, false);
  }
  parseAssignableListItem(flags, decorators) {
    const left = this.parseMaybeDefault();
    this.parseAssignableListItemTypes(left, flags);
    const elt = this.parseMaybeDefault(left.loc.start, left);
    if (decorators.length) {
      left.decorators = decorators;
    }
    return elt;
  }
  parseAssignableListItemTypes(param, flags) {
    return param;
  }
  parseMaybeDefault(startLoc, left) {
    var _startLoc, _left;
    (_startLoc = startLoc) != null ? _startLoc : startLoc = this.state.startLoc;
    left = (_left = left) != null ? _left : this.parseBindingAtom();
    if (!this.eat(29))
      return left;
    const node2 = this.startNodeAt(startLoc);
    node2.left = left;
    node2.right = this.parseMaybeAssignAllowIn();
    return this.finishNode(node2, "AssignmentPattern");
  }
  isValidLVal(type, isUnparenthesizedInAssign, binding2) {
    return getOwn$1({
      AssignmentPattern: "left",
      RestElement: "argument",
      ObjectProperty: "value",
      ParenthesizedExpression: "expression",
      ArrayPattern: "elements",
      ObjectPattern: "properties"
    }, type);
  }
  checkLVal(expression, {
    in: ancestor,
    binding: binding2 = BIND_NONE,
    checkClashes = false,
    strictModeChanged = false,
    hasParenthesizedAncestor = false
  }) {
    var _expression$extra;
    const type = expression.type;
    if (this.isObjectMethod(expression))
      return;
    if (type === "MemberExpression") {
      if (binding2 !== BIND_NONE) {
        this.raise(Errors.InvalidPropertyBindingPattern, {
          at: expression
        });
      }
      return;
    }
    if (type === "Identifier") {
      this.checkIdentifier(expression, binding2, strictModeChanged);
      const {
        name
      } = expression;
      if (checkClashes) {
        if (checkClashes.has(name)) {
          this.raise(Errors.ParamDupe, {
            at: expression
          });
        } else {
          checkClashes.add(name);
        }
      }
      return;
    }
    const validity = this.isValidLVal(type, !(hasParenthesizedAncestor || (_expression$extra = expression.extra) != null && _expression$extra.parenthesized) && ancestor.type === "AssignmentExpression", binding2);
    if (validity === true)
      return;
    if (validity === false) {
      const ParseErrorClass = binding2 === BIND_NONE ? Errors.InvalidLhs : Errors.InvalidLhsBinding;
      this.raise(ParseErrorClass, {
        at: expression,
        ancestor
      });
      return;
    }
    const [key, isParenthesizedExpression] = Array.isArray(validity) ? validity : [validity, type === "ParenthesizedExpression"];
    const nextAncestor = type === "ArrayPattern" || type === "ObjectPattern" || type === "ParenthesizedExpression" ? {
      type
    } : ancestor;
    for (const child of [].concat(expression[key])) {
      if (child) {
        this.checkLVal(child, {
          in: nextAncestor,
          binding: binding2,
          checkClashes,
          strictModeChanged,
          hasParenthesizedAncestor: isParenthesizedExpression
        });
      }
    }
  }
  checkIdentifier(at2, bindingType, strictModeChanged = false) {
    if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(at2.name, this.inModule) : isStrictBindOnlyReservedWord(at2.name))) {
      if (bindingType === BIND_NONE) {
        this.raise(Errors.StrictEvalArguments, {
          at: at2,
          referenceName: at2.name
        });
      } else {
        this.raise(Errors.StrictEvalArgumentsBinding, {
          at: at2,
          bindingName: at2.name
        });
      }
    }
    if (bindingType & BIND_FLAGS_NO_LET_IN_LEXICAL && at2.name === "let") {
      this.raise(Errors.LetInLexicalBinding, {
        at: at2
      });
    }
    if (!(bindingType & BIND_NONE)) {
      this.declareNameFromIdentifier(at2, bindingType);
    }
  }
  declareNameFromIdentifier(identifier, binding2) {
    this.scope.declareName(identifier.name, binding2, identifier.loc.start);
  }
  checkToRestConversion(node2, allowPattern) {
    switch (node2.type) {
      case "ParenthesizedExpression":
        this.checkToRestConversion(node2.expression, allowPattern);
        break;
      case "Identifier":
      case "MemberExpression":
        break;
      case "ArrayExpression":
      case "ObjectExpression":
        if (allowPattern)
          break;
      default:
        this.raise(Errors.InvalidRestAssignmentPattern, {
          at: node2
        });
    }
  }
  checkCommaAfterRest(close) {
    if (!this.match(12)) {
      return false;
    }
    this.raise(this.lookaheadCharCode() === close ? Errors.RestTrailingComma : Errors.ElementAfterRest, {
      at: this.state.startLoc
    });
    return true;
  }
}
const getOwn = (object2, key) => Object.hasOwnProperty.call(object2, key) && object2[key];
function nonNull(x) {
  if (x == null) {
    throw new Error(`Unexpected ${x} value.`);
  }
  return x;
}
function assert$1(x) {
  if (!x) {
    throw new Error("Assert fail");
  }
}
const TSErrors = ParseErrorEnum`typescript`({
  AbstractMethodHasImplementation: ({
    methodName
  }) => `Method '${methodName}' cannot have an implementation because it is marked abstract.`,
  AbstractPropertyHasInitializer: ({
    propertyName
  }) => `Property '${propertyName}' cannot have an initializer because it is marked abstract.`,
  AccesorCannotDeclareThisParameter: "'get' and 'set' accessors cannot declare 'this' parameters.",
  AccesorCannotHaveTypeParameters: "An accessor cannot have type parameters.",
  AccessorCannotBeOptional: "An 'accessor' property cannot be declared optional.",
  ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier.",
  ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier.",
  ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference: "A 'const' initializer in an ambient context must be a string or numeric literal or literal enum reference.",
  ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.",
  DeclareAccessor: ({
    kind
  }) => `'declare' is not allowed in ${kind}ters.`,
  DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.",
  DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.",
  DuplicateAccessibilityModifier: ({
    modifier
  }) => `Accessibility modifier already seen.`,
  DuplicateModifier: ({
    modifier
  }) => `Duplicate modifier: '${modifier}'.`,
  EmptyHeritageClauseType: ({
    token
  }) => `'${token}' list cannot be empty.`,
  EmptyTypeArguments: "Type argument list cannot be empty.",
  EmptyTypeParameters: "Type parameter list cannot be empty.",
  ExpectedAmbientAfterExportDeclare: "'export declare' must be followed by an ambient declaration.",
  ImportAliasHasImportType: "An import alias can not use 'import type'.",
  ImportReflectionHasImportType: "An `import module` declaration can not use `type` modifier",
  IncompatibleModifiers: ({
    modifiers
  }) => `'${modifiers[0]}' modifier cannot be used with '${modifiers[1]}' modifier.`,
  IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier.",
  IndexSignatureHasAccessibility: ({
    modifier
  }) => `Index signatures cannot have an accessibility modifier ('${modifier}').`,
  IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier.",
  IndexSignatureHasOverride: "'override' modifier cannot appear on an index signature.",
  IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier.",
  InitializerNotAllowedInAmbientContext: "Initializers are not allowed in ambient contexts.",
  InvalidModifierOnTypeMember: ({
    modifier
  }) => `'${modifier}' modifier cannot appear on a type member.`,
  InvalidModifierOnTypeParameter: ({
    modifier
  }) => `'${modifier}' modifier cannot appear on a type parameter.`,
  InvalidModifierOnTypeParameterPositions: ({
    modifier
  }) => `'${modifier}' modifier can only appear on a type parameter of a class, interface or type alias.`,
  InvalidModifiersOrder: ({
    orderedModifiers
  }) => `'${orderedModifiers[0]}' modifier must precede '${orderedModifiers[1]}' modifier.`,
  InvalidPropertyAccessAfterInstantiationExpression: "Invalid property access after an instantiation expression. You can either wrap the instantiation expression in parentheses, or delete the type arguments.",
  InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.",
  MissingInterfaceName: "'interface' declarations must be followed by an identifier.",
  MixedLabeledAndUnlabeledElements: "Tuple members must all have names or all not have names.",
  NonAbstractClassHasAbstractMethod: "Abstract methods can only appear within an abstract class.",
  NonClassMethodPropertyHasAbstractModifer: "'abstract' modifier can only appear on a class, method, or property declaration.",
  OptionalTypeBeforeRequired: "A required element cannot follow an optional element.",
  OverrideNotInSubClass: "This member cannot have an 'override' modifier because its containing class does not extend another class.",
  PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.",
  PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.",
  PrivateElementHasAccessibility: ({
    modifier
  }) => `Private elements cannot have an accessibility modifier ('${modifier}').`,
  ReadonlyForMethodSignature: "'readonly' modifier can only appear on a property declaration or index signature.",
  ReservedArrowTypeParam: "This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma, as in `<T,>() => ...`.",
  ReservedTypeAssertion: "This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.",
  SetAccesorCannotHaveOptionalParameter: "A 'set' accessor cannot have an optional parameter.",
  SetAccesorCannotHaveRestParameter: "A 'set' accessor cannot have rest parameter.",
  SetAccesorCannotHaveReturnType: "A 'set' accessor cannot have a return type annotation.",
  SingleTypeParameterWithoutTrailingComma: ({
    typeParameterName
  }) => `Single type parameter ${typeParameterName} should have a trailing comma. Example usage: <${typeParameterName},>.`,
  StaticBlockCannotHaveModifier: "Static class blocks cannot have any modifier.",
  TupleOptionalAfterType: "A labeled tuple optional element must be declared using a question mark after the name and before the colon (`name?: type`), rather than after the type (`name: type?`).",
  TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`.",
  TypeImportCannotSpecifyDefaultAndNamed: "A type-only import can specify a default import or named bindings, but not both.",
  TypeModifierIsUsedInTypeExports: "The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.",
  TypeModifierIsUsedInTypeImports: "The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.",
  UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.",
  UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.",
  UnexpectedTypeAnnotation: "Did not expect a type annotation here.",
  UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.",
  UnsupportedImportTypeArgument: "Argument in a type import must be a string literal.",
  UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.",
  UnsupportedSignatureParameterKind: ({
    type
  }) => `Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got ${type}.`
});
function keywordTypeFromName(value) {
  switch (value) {
    case "any":
      return "TSAnyKeyword";
    case "boolean":
      return "TSBooleanKeyword";
    case "bigint":
      return "TSBigIntKeyword";
    case "never":
      return "TSNeverKeyword";
    case "number":
      return "TSNumberKeyword";
    case "object":
      return "TSObjectKeyword";
    case "string":
      return "TSStringKeyword";
    case "symbol":
      return "TSSymbolKeyword";
    case "undefined":
      return "TSUndefinedKeyword";
    case "unknown":
      return "TSUnknownKeyword";
    default:
      return void 0;
  }
}
function tsIsAccessModifier(modifier) {
  return modifier === "private" || modifier === "public" || modifier === "protected";
}
function tsIsVarianceAnnotations(modifier) {
  return modifier === "in" || modifier === "out";
}
var typescript = (superClass) => class TypeScriptParserMixin extends superClass {
  constructor(...args) {
    super(...args);
    this.tsParseInOutModifiers = this.tsParseModifiers.bind(this, {
      allowedModifiers: ["in", "out"],
      disallowedModifiers: ["const", "public", "private", "protected", "readonly", "declare", "abstract", "override"],
      errorTemplate: TSErrors.InvalidModifierOnTypeParameter
    });
    this.tsParseConstModifier = this.tsParseModifiers.bind(this, {
      allowedModifiers: ["const"],
      disallowedModifiers: ["in", "out"],
      errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions
    });
    this.tsParseInOutConstModifiers = this.tsParseModifiers.bind(this, {
      allowedModifiers: ["in", "out", "const"],
      disallowedModifiers: ["public", "private", "protected", "readonly", "declare", "abstract", "override"],
      errorTemplate: TSErrors.InvalidModifierOnTypeParameter
    });
  }
  getScopeHandler() {
    return TypeScriptScopeHandler;
  }
  tsIsIdentifier() {
    return tokenIsIdentifier(this.state.type);
  }
  tsTokenCanFollowModifier() {
    return (this.match(0) || this.match(5) || this.match(55) || this.match(21) || this.match(136) || this.isLiteralPropertyName()) && !this.hasPrecedingLineBreak();
  }
  tsNextTokenCanFollowModifier() {
    this.next();
    return this.tsTokenCanFollowModifier();
  }
  tsParseModifier(allowedModifiers, stopOnStartOfClassStaticBlock) {
    if (!tokenIsIdentifier(this.state.type) && this.state.type !== 58 && this.state.type !== 75) {
      return void 0;
    }
    const modifier = this.state.value;
    if (allowedModifiers.indexOf(modifier) !== -1) {
      if (stopOnStartOfClassStaticBlock && this.tsIsStartOfStaticBlocks()) {
        return void 0;
      }
      if (this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) {
        return modifier;
      }
    }
    return void 0;
  }
  tsParseModifiers({
    allowedModifiers,
    disallowedModifiers,
    stopOnStartOfClassStaticBlock,
    errorTemplate = TSErrors.InvalidModifierOnTypeMember
  }, modified) {
    const enforceOrder = (loc, modifier, before, after) => {
      if (modifier === before && modified[after]) {
        this.raise(TSErrors.InvalidModifiersOrder, {
          at: loc,
          orderedModifiers: [before, after]
        });
      }
    };
    const incompatible = (loc, modifier, mod1, mod2) => {
      if (modified[mod1] && modifier === mod2 || modified[mod2] && modifier === mod1) {
        this.raise(TSErrors.IncompatibleModifiers, {
          at: loc,
          modifiers: [mod1, mod2]
        });
      }
    };
    for (; ; ) {
      const {
        startLoc
      } = this.state;
      const modifier = this.tsParseModifier(allowedModifiers.concat(disallowedModifiers != null ? disallowedModifiers : []), stopOnStartOfClassStaticBlock);
      if (!modifier)
        break;
      if (tsIsAccessModifier(modifier)) {
        if (modified.accessibility) {
          this.raise(TSErrors.DuplicateAccessibilityModifier, {
            at: startLoc,
            modifier
          });
        } else {
          enforceOrder(startLoc, modifier, modifier, "override");
          enforceOrder(startLoc, modifier, modifier, "static");
          enforceOrder(startLoc, modifier, modifier, "readonly");
          modified.accessibility = modifier;
        }
      } else if (tsIsVarianceAnnotations(modifier)) {
        if (modified[modifier]) {
          this.raise(TSErrors.DuplicateModifier, {
            at: startLoc,
            modifier
          });
        }
        modified[modifier] = true;
        enforceOrder(startLoc, modifier, "in", "out");
      } else {
        if (Object.hasOwnProperty.call(modified, modifier)) {
          this.raise(TSErrors.DuplicateModifier, {
            at: startLoc,
            modifier
          });
        } else {
          enforceOrder(startLoc, modifier, "static", "readonly");
          enforceOrder(startLoc, modifier, "static", "override");
          enforceOrder(startLoc, modifier, "override", "readonly");
          enforceOrder(startLoc, modifier, "abstract", "override");
          incompatible(startLoc, modifier, "declare", "override");
          incompatible(startLoc, modifier, "static", "abstract");
        }
        modified[modifier] = true;
      }
      if (disallowedModifiers != null && disallowedModifiers.includes(modifier)) {
        this.raise(errorTemplate, {
          at: startLoc,
          modifier
        });
      }
    }
  }
  tsIsListTerminator(kind) {
    switch (kind) {
      case "EnumMembers":
      case "TypeMembers":
        return this.match(8);
      case "HeritageClauseElement":
        return this.match(5);
      case "TupleElementTypes":
        return this.match(3);
      case "TypeParametersOrArguments":
        return this.match(48);
    }
  }
  tsParseList(kind, parseElement2) {
    const result2 = [];
    while (!this.tsIsListTerminator(kind)) {
      result2.push(parseElement2());
    }
    return result2;
  }
  tsParseDelimitedList(kind, parseElement2, refTrailingCommaPos) {
    return nonNull(this.tsParseDelimitedListWorker(kind, parseElement2, true, refTrailingCommaPos));
  }
  tsParseDelimitedListWorker(kind, parseElement2, expectSuccess, refTrailingCommaPos) {
    const result2 = [];
    let trailingCommaPos = -1;
    for (; ; ) {
      if (this.tsIsListTerminator(kind)) {
        break;
      }
      trailingCommaPos = -1;
      const element = parseElement2();
      if (element == null) {
        return void 0;
      }
      result2.push(element);
      if (this.eat(12)) {
        trailingCommaPos = this.state.lastTokStart;
        continue;
      }
      if (this.tsIsListTerminator(kind)) {
        break;
      }
      if (expectSuccess) {
        this.expect(12);
      }
      return void 0;
    }
    if (refTrailingCommaPos) {
      refTrailingCommaPos.value = trailingCommaPos;
    }
    return result2;
  }
  tsParseBracketedList(kind, parseElement2, bracket, skipFirstToken, refTrailingCommaPos) {
    if (!skipFirstToken) {
      if (bracket) {
        this.expect(0);
      } else {
        this.expect(47);
      }
    }
    const result2 = this.tsParseDelimitedList(kind, parseElement2, refTrailingCommaPos);
    if (bracket) {
      this.expect(3);
    } else {
      this.expect(48);
    }
    return result2;
  }
  tsParseImportType() {
    const node2 = this.startNode();
    this.expect(83);
    this.expect(10);
    if (!this.match(131)) {
      this.raise(TSErrors.UnsupportedImportTypeArgument, {
        at: this.state.startLoc
      });
    }
    node2.argument = super.parseExprAtom();
    this.expect(11);
    if (this.eat(16)) {
      node2.qualifier = this.tsParseEntityName();
    }
    if (this.match(47)) {
      node2.typeParameters = this.tsParseTypeArguments();
    }
    return this.finishNode(node2, "TSImportType");
  }
  tsParseEntityName(allowReservedWords = true) {
    let entity = this.parseIdentifier(allowReservedWords);
    while (this.eat(16)) {
      const node2 = this.startNodeAtNode(entity);
      node2.left = entity;
      node2.right = this.parseIdentifier(allowReservedWords);
      entity = this.finishNode(node2, "TSQualifiedName");
    }
    return entity;
  }
  tsParseTypeReference() {
    const node2 = this.startNode();
    node2.typeName = this.tsParseEntityName();
    if (!this.hasPrecedingLineBreak() && this.match(47)) {
      node2.typeParameters = this.tsParseTypeArguments();
    }
    return this.finishNode(node2, "TSTypeReference");
  }
  tsParseThisTypePredicate(lhs) {
    this.next();
    const node2 = this.startNodeAtNode(lhs);
    node2.parameterName = lhs;
    node2.typeAnnotation = this.tsParseTypeAnnotation(false);
    node2.asserts = false;
    return this.finishNode(node2, "TSTypePredicate");
  }
  tsParseThisTypeNode() {
    const node2 = this.startNode();
    this.next();
    return this.finishNode(node2, "TSThisType");
  }
  tsParseTypeQuery() {
    const node2 = this.startNode();
    this.expect(87);
    if (this.match(83)) {
      node2.exprName = this.tsParseImportType();
    } else {
      node2.exprName = this.tsParseEntityName();
    }
    if (!this.hasPrecedingLineBreak() && this.match(47)) {
      node2.typeParameters = this.tsParseTypeArguments();
    }
    return this.finishNode(node2, "TSTypeQuery");
  }
  tsParseTypeParameter(parseModifiers) {
    const node2 = this.startNode();
    parseModifiers(node2);
    node2.name = this.tsParseTypeParameterName();
    node2.constraint = this.tsEatThenParseType(81);
    node2.default = this.tsEatThenParseType(29);
    return this.finishNode(node2, "TSTypeParameter");
  }
  tsTryParseTypeParameters(parseModifiers) {
    if (this.match(47)) {
      return this.tsParseTypeParameters(parseModifiers);
    }
  }
  tsParseTypeParameters(parseModifiers) {
    const node2 = this.startNode();
    if (this.match(47) || this.match(140)) {
      this.next();
    } else {
      this.unexpected();
    }
    const refTrailingCommaPos = {
      value: -1
    };
    node2.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this, parseModifiers), false, true, refTrailingCommaPos);
    if (node2.params.length === 0) {
      this.raise(TSErrors.EmptyTypeParameters, {
        at: node2
      });
    }
    if (refTrailingCommaPos.value !== -1) {
      this.addExtra(node2, "trailingComma", refTrailingCommaPos.value);
    }
    return this.finishNode(node2, "TSTypeParameterDeclaration");
  }
  tsFillSignature(returnToken, signature) {
    const returnTokenRequired = returnToken === 19;
    const paramsKey = "parameters";
    const returnTypeKey = "typeAnnotation";
    signature.typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
    this.expect(10);
    signature[paramsKey] = this.tsParseBindingListForSignature();
    if (returnTokenRequired) {
      signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
    } else if (this.match(returnToken)) {
      signature[returnTypeKey] = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
    }
  }
  tsParseBindingListForSignature() {
    return super.parseBindingList(11, 41, 2).map((pattern) => {
      if (pattern.type !== "Identifier" && pattern.type !== "RestElement" && pattern.type !== "ObjectPattern" && pattern.type !== "ArrayPattern") {
        this.raise(TSErrors.UnsupportedSignatureParameterKind, {
          at: pattern,
          type: pattern.type
        });
      }
      return pattern;
    });
  }
  tsParseTypeMemberSemicolon() {
    if (!this.eat(12) && !this.isLineTerminator()) {
      this.expect(13);
    }
  }
  tsParseSignatureMember(kind, node2) {
    this.tsFillSignature(14, node2);
    this.tsParseTypeMemberSemicolon();
    return this.finishNode(node2, kind);
  }
  tsIsUnambiguouslyIndexSignature() {
    this.next();
    if (tokenIsIdentifier(this.state.type)) {
      this.next();
      return this.match(14);
    }
    return false;
  }
  tsTryParseIndexSignature(node2) {
    if (!(this.match(0) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) {
      return void 0;
    }
    this.expect(0);
    const id3 = this.parseIdentifier();
    id3.typeAnnotation = this.tsParseTypeAnnotation();
    this.resetEndLocation(id3);
    this.expect(3);
    node2.parameters = [id3];
    const type = this.tsTryParseTypeAnnotation();
    if (type)
      node2.typeAnnotation = type;
    this.tsParseTypeMemberSemicolon();
    return this.finishNode(node2, "TSIndexSignature");
  }
  tsParsePropertyOrMethodSignature(node2, readonly2) {
    if (this.eat(17))
      node2.optional = true;
    const nodeAny = node2;
    if (this.match(10) || this.match(47)) {
      if (readonly2) {
        this.raise(TSErrors.ReadonlyForMethodSignature, {
          at: node2
        });
      }
      const method = nodeAny;
      if (method.kind && this.match(47)) {
        this.raise(TSErrors.AccesorCannotHaveTypeParameters, {
          at: this.state.curPosition()
        });
      }
      this.tsFillSignature(14, method);
      this.tsParseTypeMemberSemicolon();
      const paramsKey = "parameters";
      const returnTypeKey = "typeAnnotation";
      if (method.kind === "get") {
        if (method[paramsKey].length > 0) {
          this.raise(Errors.BadGetterArity, {
            at: this.state.curPosition()
          });
          if (this.isThisParam(method[paramsKey][0])) {
            this.raise(TSErrors.AccesorCannotDeclareThisParameter, {
              at: this.state.curPosition()
            });
          }
        }
      } else if (method.kind === "set") {
        if (method[paramsKey].length !== 1) {
          this.raise(Errors.BadSetterArity, {
            at: this.state.curPosition()
          });
        } else {
          const firstParameter = method[paramsKey][0];
          if (this.isThisParam(firstParameter)) {
            this.raise(TSErrors.AccesorCannotDeclareThisParameter, {
              at: this.state.curPosition()
            });
          }
          if (firstParameter.type === "Identifier" && firstParameter.optional) {
            this.raise(TSErrors.SetAccesorCannotHaveOptionalParameter, {
              at: this.state.curPosition()
            });
          }
          if (firstParameter.type === "RestElement") {
            this.raise(TSErrors.SetAccesorCannotHaveRestParameter, {
              at: this.state.curPosition()
            });
          }
        }
        if (method[returnTypeKey]) {
          this.raise(TSErrors.SetAccesorCannotHaveReturnType, {
            at: method[returnTypeKey]
          });
        }
      } else {
        method.kind = "method";
      }
      return this.finishNode(method, "TSMethodSignature");
    } else {
      const property = nodeAny;
      if (readonly2)
        property.readonly = true;
      const type = this.tsTryParseTypeAnnotation();
      if (type)
        property.typeAnnotation = type;
      this.tsParseTypeMemberSemicolon();
      return this.finishNode(property, "TSPropertySignature");
    }
  }
  tsParseTypeMember() {
    const node2 = this.startNode();
    if (this.match(10) || this.match(47)) {
      return this.tsParseSignatureMember("TSCallSignatureDeclaration", node2);
    }
    if (this.match(77)) {
      const id3 = this.startNode();
      this.next();
      if (this.match(10) || this.match(47)) {
        return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node2);
      } else {
        node2.key = this.createIdentifier(id3, "new");
        return this.tsParsePropertyOrMethodSignature(node2, false);
      }
    }
    this.tsParseModifiers({
      allowedModifiers: ["readonly"],
      disallowedModifiers: ["declare", "abstract", "private", "protected", "public", "static", "override"]
    }, node2);
    const idx = this.tsTryParseIndexSignature(node2);
    if (idx) {
      return idx;
    }
    super.parsePropertyName(node2);
    if (!node2.computed && node2.key.type === "Identifier" && (node2.key.name === "get" || node2.key.name === "set") && this.tsTokenCanFollowModifier()) {
      node2.kind = node2.key.name;
      super.parsePropertyName(node2);
    }
    return this.tsParsePropertyOrMethodSignature(node2, !!node2.readonly);
  }
  tsParseTypeLiteral() {
    const node2 = this.startNode();
    node2.members = this.tsParseObjectTypeMembers();
    return this.finishNode(node2, "TSTypeLiteral");
  }
  tsParseObjectTypeMembers() {
    this.expect(5);
    const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this));
    this.expect(8);
    return members;
  }
  tsIsStartOfMappedType() {
    this.next();
    if (this.eat(53)) {
      return this.isContextual(120);
    }
    if (this.isContextual(120)) {
      this.next();
    }
    if (!this.match(0)) {
      return false;
    }
    this.next();
    if (!this.tsIsIdentifier()) {
      return false;
    }
    this.next();
    return this.match(58);
  }
  tsParseMappedTypeParameter() {
    const node2 = this.startNode();
    node2.name = this.tsParseTypeParameterName();
    node2.constraint = this.tsExpectThenParseType(58);
    return this.finishNode(node2, "TSTypeParameter");
  }
  tsParseMappedType() {
    const node2 = this.startNode();
    this.expect(5);
    if (this.match(53)) {
      node2.readonly = this.state.value;
      this.next();
      this.expectContextual(120);
    } else if (this.eatContextual(120)) {
      node2.readonly = true;
    }
    this.expect(0);
    node2.typeParameter = this.tsParseMappedTypeParameter();
    node2.nameType = this.eatContextual(93) ? this.tsParseType() : null;
    this.expect(3);
    if (this.match(53)) {
      node2.optional = this.state.value;
      this.next();
      this.expect(17);
    } else if (this.eat(17)) {
      node2.optional = true;
    }
    node2.typeAnnotation = this.tsTryParseType();
    this.semicolon();
    this.expect(8);
    return this.finishNode(node2, "TSMappedType");
  }
  tsParseTupleType() {
    const node2 = this.startNode();
    node2.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false);
    let seenOptionalElement = false;
    let labeledElements = null;
    node2.elementTypes.forEach((elementNode) => {
      var _labeledElements;
      const {
        type
      } = elementNode;
      if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) {
        this.raise(TSErrors.OptionalTypeBeforeRequired, {
          at: elementNode
        });
      }
      seenOptionalElement || (seenOptionalElement = type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType");
      let checkType = type;
      if (type === "TSRestType") {
        elementNode = elementNode.typeAnnotation;
        checkType = elementNode.type;
      }
      const isLabeled = checkType === "TSNamedTupleMember";
      (_labeledElements = labeledElements) != null ? _labeledElements : labeledElements = isLabeled;
      if (labeledElements !== isLabeled) {
        this.raise(TSErrors.MixedLabeledAndUnlabeledElements, {
          at: elementNode
        });
      }
    });
    return this.finishNode(node2, "TSTupleType");
  }
  tsParseTupleElementType() {
    const {
      startLoc
    } = this.state;
    const rest = this.eat(21);
    let labeled;
    let label;
    let optional;
    let type;
    const isWord = tokenIsKeywordOrIdentifier(this.state.type);
    const chAfterWord = isWord ? this.lookaheadCharCode() : null;
    if (chAfterWord === 58) {
      labeled = true;
      optional = false;
      label = this.parseIdentifier(true);
      this.expect(14);
      type = this.tsParseType();
    } else if (chAfterWord === 63) {
      optional = true;
      const startLoc2 = this.state.startLoc;
      const wordName = this.state.value;
      const typeOrLabel = this.tsParseNonArrayType();
      if (this.lookaheadCharCode() === 58) {
        labeled = true;
        label = this.createIdentifier(this.startNodeAt(startLoc2), wordName);
        this.expect(17);
        this.expect(14);
        type = this.tsParseType();
      } else {
        labeled = false;
        type = typeOrLabel;
        this.expect(17);
      }
    } else {
      type = this.tsParseType();
      optional = this.eat(17);
      labeled = this.eat(14);
    }
    if (labeled) {
      let labeledNode;
      if (label) {
        labeledNode = this.startNodeAtNode(label);
        labeledNode.optional = optional;
        labeledNode.label = label;
        labeledNode.elementType = type;
        if (this.eat(17)) {
          labeledNode.optional = true;
          this.raise(TSErrors.TupleOptionalAfterType, {
            at: this.state.lastTokStartLoc
          });
        }
      } else {
        labeledNode = this.startNodeAtNode(type);
        labeledNode.optional = optional;
        this.raise(TSErrors.InvalidTupleMemberLabel, {
          at: type
        });
        labeledNode.label = type;
        labeledNode.elementType = this.tsParseType();
      }
      type = this.finishNode(labeledNode, "TSNamedTupleMember");
    } else if (optional) {
      const optionalTypeNode = this.startNodeAtNode(type);
      optionalTypeNode.typeAnnotation = type;
      type = this.finishNode(optionalTypeNode, "TSOptionalType");
    }
    if (rest) {
      const restNode = this.startNodeAt(startLoc);
      restNode.typeAnnotation = type;
      type = this.finishNode(restNode, "TSRestType");
    }
    return type;
  }
  tsParseParenthesizedType() {
    const node2 = this.startNode();
    this.expect(10);
    node2.typeAnnotation = this.tsParseType();
    this.expect(11);
    return this.finishNode(node2, "TSParenthesizedType");
  }
  tsParseFunctionOrConstructorType(type, abstract) {
    const node2 = this.startNode();
    if (type === "TSConstructorType") {
      node2.abstract = !!abstract;
      if (abstract)
        this.next();
      this.next();
    }
    this.tsInAllowConditionalTypesContext(() => this.tsFillSignature(19, node2));
    return this.finishNode(node2, type);
  }
  tsParseLiteralTypeNode() {
    const node2 = this.startNode();
    node2.literal = (() => {
      switch (this.state.type) {
        case 132:
        case 133:
        case 131:
        case 85:
        case 86:
          return super.parseExprAtom();
        default:
          this.unexpected();
      }
    })();
    return this.finishNode(node2, "TSLiteralType");
  }
  tsParseTemplateLiteralType() {
    const node2 = this.startNode();
    node2.literal = super.parseTemplate(false);
    return this.finishNode(node2, "TSLiteralType");
  }
  parseTemplateSubstitution() {
    if (this.state.inType)
      return this.tsParseType();
    return super.parseTemplateSubstitution();
  }
  tsParseThisTypeOrThisTypePredicate() {
    const thisKeyword = this.tsParseThisTypeNode();
    if (this.isContextual(114) && !this.hasPrecedingLineBreak()) {
      return this.tsParseThisTypePredicate(thisKeyword);
    } else {
      return thisKeyword;
    }
  }
  tsParseNonArrayType() {
    switch (this.state.type) {
      case 131:
      case 132:
      case 133:
      case 85:
      case 86:
        return this.tsParseLiteralTypeNode();
      case 53:
        if (this.state.value === "-") {
          const node2 = this.startNode();
          const nextToken = this.lookahead();
          if (nextToken.type !== 132 && nextToken.type !== 133) {
            this.unexpected();
          }
          node2.literal = this.parseMaybeUnary();
          return this.finishNode(node2, "TSLiteralType");
        }
        break;
      case 78:
        return this.tsParseThisTypeOrThisTypePredicate();
      case 87:
        return this.tsParseTypeQuery();
      case 83:
        return this.tsParseImportType();
      case 5:
        return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral();
      case 0:
        return this.tsParseTupleType();
      case 10:
        return this.tsParseParenthesizedType();
      case 25:
      case 24:
        return this.tsParseTemplateLiteralType();
      default: {
        const {
          type
        } = this.state;
        if (tokenIsIdentifier(type) || type === 88 || type === 84) {
          const nodeType = type === 88 ? "TSVoidKeyword" : type === 84 ? "TSNullKeyword" : keywordTypeFromName(this.state.value);
          if (nodeType !== void 0 && this.lookaheadCharCode() !== 46) {
            const node2 = this.startNode();
            this.next();
            return this.finishNode(node2, nodeType);
          }
          return this.tsParseTypeReference();
        }
      }
    }
    this.unexpected();
  }
  tsParseArrayTypeOrHigher() {
    let type = this.tsParseNonArrayType();
    while (!this.hasPrecedingLineBreak() && this.eat(0)) {
      if (this.match(3)) {
        const node2 = this.startNodeAtNode(type);
        node2.elementType = type;
        this.expect(3);
        type = this.finishNode(node2, "TSArrayType");
      } else {
        const node2 = this.startNodeAtNode(type);
        node2.objectType = type;
        node2.indexType = this.tsParseType();
        this.expect(3);
        type = this.finishNode(node2, "TSIndexedAccessType");
      }
    }
    return type;
  }
  tsParseTypeOperator() {
    const node2 = this.startNode();
    const operator = this.state.value;
    this.next();
    node2.operator = operator;
    node2.typeAnnotation = this.tsParseTypeOperatorOrHigher();
    if (operator === "readonly") {
      this.tsCheckTypeAnnotationForReadOnly(node2);
    }
    return this.finishNode(node2, "TSTypeOperator");
  }
  tsCheckTypeAnnotationForReadOnly(node2) {
    switch (node2.typeAnnotation.type) {
      case "TSTupleType":
      case "TSArrayType":
        return;
      default:
        this.raise(TSErrors.UnexpectedReadonly, {
          at: node2
        });
    }
  }
  tsParseInferType() {
    const node2 = this.startNode();
    this.expectContextual(113);
    const typeParameter = this.startNode();
    typeParameter.name = this.tsParseTypeParameterName();
    typeParameter.constraint = this.tsTryParse(() => this.tsParseConstraintForInferType());
    node2.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
    return this.finishNode(node2, "TSInferType");
  }
  tsParseConstraintForInferType() {
    if (this.eat(81)) {
      const constraint = this.tsInDisallowConditionalTypesContext(() => this.tsParseType());
      if (this.state.inDisallowConditionalTypesContext || !this.match(17)) {
        return constraint;
      }
    }
  }
  tsParseTypeOperatorOrHigher() {
    const isTypeOperator = tokenIsTSTypeOperator(this.state.type) && !this.state.containsEsc;
    return isTypeOperator ? this.tsParseTypeOperator() : this.isContextual(113) ? this.tsParseInferType() : this.tsInAllowConditionalTypesContext(() => this.tsParseArrayTypeOrHigher());
  }
  tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) {
    const node2 = this.startNode();
    const hasLeadingOperator = this.eat(operator);
    const types2 = [];
    do {
      types2.push(parseConstituentType());
    } while (this.eat(operator));
    if (types2.length === 1 && !hasLeadingOperator) {
      return types2[0];
    }
    node2.types = types2;
    return this.finishNode(node2, kind);
  }
  tsParseIntersectionTypeOrHigher() {
    return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), 45);
  }
  tsParseUnionTypeOrHigher() {
    return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), 43);
  }
  tsIsStartOfFunctionType() {
    if (this.match(47)) {
      return true;
    }
    return this.match(10) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this));
  }
  tsSkipParameterStart() {
    if (tokenIsIdentifier(this.state.type) || this.match(78)) {
      this.next();
      return true;
    }
    if (this.match(5)) {
      const {
        errors: errors2
      } = this.state;
      const previousErrorCount = errors2.length;
      try {
        this.parseObjectLike(8, true);
        return errors2.length === previousErrorCount;
      } catch (_unused) {
        return false;
      }
    }
    if (this.match(0)) {
      this.next();
      const {
        errors: errors2
      } = this.state;
      const previousErrorCount = errors2.length;
      try {
        super.parseBindingList(3, 93, 1);
        return errors2.length === previousErrorCount;
      } catch (_unused2) {
        return false;
      }
    }
    return false;
  }
  tsIsUnambiguouslyStartOfFunctionType() {
    this.next();
    if (this.match(11) || this.match(21)) {
      return true;
    }
    if (this.tsSkipParameterStart()) {
      if (this.match(14) || this.match(12) || this.match(17) || this.match(29)) {
        return true;
      }
      if (this.match(11)) {
        this.next();
        if (this.match(19)) {
          return true;
        }
      }
    }
    return false;
  }
  tsParseTypeOrTypePredicateAnnotation(returnToken) {
    return this.tsInType(() => {
      const t = this.startNode();
      this.expect(returnToken);
      const node2 = this.startNode();
      const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));
      if (asserts && this.match(78)) {
        let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate();
        if (thisTypePredicate.type === "TSThisType") {
          node2.parameterName = thisTypePredicate;
          node2.asserts = true;
          node2.typeAnnotation = null;
          thisTypePredicate = this.finishNode(node2, "TSTypePredicate");
        } else {
          this.resetStartLocationFromNode(thisTypePredicate, node2);
          thisTypePredicate.asserts = true;
        }
        t.typeAnnotation = thisTypePredicate;
        return this.finishNode(t, "TSTypeAnnotation");
      }
      const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));
      if (!typePredicateVariable) {
        if (!asserts) {
          return this.tsParseTypeAnnotation(false, t);
        }
        node2.parameterName = this.parseIdentifier();
        node2.asserts = asserts;
        node2.typeAnnotation = null;
        t.typeAnnotation = this.finishNode(node2, "TSTypePredicate");
        return this.finishNode(t, "TSTypeAnnotation");
      }
      const type = this.tsParseTypeAnnotation(false);
      node2.parameterName = typePredicateVariable;
      node2.typeAnnotation = type;
      node2.asserts = asserts;
      t.typeAnnotation = this.finishNode(node2, "TSTypePredicate");
      return this.finishNode(t, "TSTypeAnnotation");
    });
  }
  tsTryParseTypeOrTypePredicateAnnotation() {
    return this.match(14) ? this.tsParseTypeOrTypePredicateAnnotation(14) : void 0;
  }
  tsTryParseTypeAnnotation() {
    return this.match(14) ? this.tsParseTypeAnnotation() : void 0;
  }
  tsTryParseType() {
    return this.tsEatThenParseType(14);
  }
  tsParseTypePredicatePrefix() {
    const id3 = this.parseIdentifier();
    if (this.isContextual(114) && !this.hasPrecedingLineBreak()) {
      this.next();
      return id3;
    }
  }
  tsParseTypePredicateAsserts() {
    if (this.state.type !== 107) {
      return false;
    }
    const containsEsc = this.state.containsEsc;
    this.next();
    if (!tokenIsIdentifier(this.state.type) && !this.match(78)) {
      return false;
    }
    if (containsEsc) {
      this.raise(Errors.InvalidEscapedReservedWord, {
        at: this.state.lastTokStartLoc,
        reservedWord: "asserts"
      });
    }
    return true;
  }
  tsParseTypeAnnotation(eatColon = true, t = this.startNode()) {
    this.tsInType(() => {
      if (eatColon)
        this.expect(14);
      t.typeAnnotation = this.tsParseType();
    });
    return this.finishNode(t, "TSTypeAnnotation");
  }
  tsParseType() {
    assert$1(this.state.inType);
    const type = this.tsParseNonConditionalType();
    if (this.state.inDisallowConditionalTypesContext || this.hasPrecedingLineBreak() || !this.eat(81)) {
      return type;
    }
    const node2 = this.startNodeAtNode(type);
    node2.checkType = type;
    node2.extendsType = this.tsInDisallowConditionalTypesContext(() => this.tsParseNonConditionalType());
    this.expect(17);
    node2.trueType = this.tsInAllowConditionalTypesContext(() => this.tsParseType());
    this.expect(14);
    node2.falseType = this.tsInAllowConditionalTypesContext(() => this.tsParseType());
    return this.finishNode(node2, "TSConditionalType");
  }
  isAbstractConstructorSignature() {
    return this.isContextual(122) && this.lookahead().type === 77;
  }
  tsParseNonConditionalType() {
    if (this.tsIsStartOfFunctionType()) {
      return this.tsParseFunctionOrConstructorType("TSFunctionType");
    }
    if (this.match(77)) {
      return this.tsParseFunctionOrConstructorType("TSConstructorType");
    } else if (this.isAbstractConstructorSignature()) {
      return this.tsParseFunctionOrConstructorType("TSConstructorType", true);
    }
    return this.tsParseUnionTypeOrHigher();
  }
  tsParseTypeAssertion() {
    if (this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) {
      this.raise(TSErrors.ReservedTypeAssertion, {
        at: this.state.startLoc
      });
    }
    const node2 = this.startNode();
    node2.typeAnnotation = this.tsInType(() => {
      this.next();
      return this.match(75) ? this.tsParseTypeReference() : this.tsParseType();
    });
    this.expect(48);
    node2.expression = this.parseMaybeUnary();
    return this.finishNode(node2, "TSTypeAssertion");
  }
  tsParseHeritageClause(token) {
    const originalStartLoc = this.state.startLoc;
    const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", () => {
      const node2 = this.startNode();
      node2.expression = this.tsParseEntityName();
      if (this.match(47)) {
        node2.typeParameters = this.tsParseTypeArguments();
      }
      return this.finishNode(node2, "TSExpressionWithTypeArguments");
    });
    if (!delimitedList.length) {
      this.raise(TSErrors.EmptyHeritageClauseType, {
        at: originalStartLoc,
        token
      });
    }
    return delimitedList;
  }
  tsParseInterfaceDeclaration(node2, properties = {}) {
    if (this.hasFollowingLineBreak())
      return null;
    this.expectContextual(127);
    if (properties.declare)
      node2.declare = true;
    if (tokenIsIdentifier(this.state.type)) {
      node2.id = this.parseIdentifier();
      this.checkIdentifier(node2.id, BIND_TS_INTERFACE);
    } else {
      node2.id = null;
      this.raise(TSErrors.MissingInterfaceName, {
        at: this.state.startLoc
      });
    }
    node2.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers);
    if (this.eat(81)) {
      node2.extends = this.tsParseHeritageClause("extends");
    }
    const body = this.startNode();
    body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this));
    node2.body = this.finishNode(body, "TSInterfaceBody");
    return this.finishNode(node2, "TSInterfaceDeclaration");
  }
  tsParseTypeAliasDeclaration(node2) {
    node2.id = this.parseIdentifier();
    this.checkIdentifier(node2.id, BIND_TS_TYPE);
    node2.typeAnnotation = this.tsInType(() => {
      node2.typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutModifiers);
      this.expect(29);
      if (this.isContextual(112) && this.lookahead().type !== 16) {
        const node3 = this.startNode();
        this.next();
        return this.finishNode(node3, "TSIntrinsicKeyword");
      }
      return this.tsParseType();
    });
    this.semicolon();
    return this.finishNode(node2, "TSTypeAliasDeclaration");
  }
  tsInNoContext(cb) {
    const oldContext = this.state.context;
    this.state.context = [oldContext[0]];
    try {
      return cb();
    } finally {
      this.state.context = oldContext;
    }
  }
  tsInType(cb) {
    const oldInType = this.state.inType;
    this.state.inType = true;
    try {
      return cb();
    } finally {
      this.state.inType = oldInType;
    }
  }
  tsInDisallowConditionalTypesContext(cb) {
    const oldInDisallowConditionalTypesContext = this.state.inDisallowConditionalTypesContext;
    this.state.inDisallowConditionalTypesContext = true;
    try {
      return cb();
    } finally {
      this.state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext;
    }
  }
  tsInAllowConditionalTypesContext(cb) {
    const oldInDisallowConditionalTypesContext = this.state.inDisallowConditionalTypesContext;
    this.state.inDisallowConditionalTypesContext = false;
    try {
      return cb();
    } finally {
      this.state.inDisallowConditionalTypesContext = oldInDisallowConditionalTypesContext;
    }
  }
  tsEatThenParseType(token) {
    return !this.match(token) ? void 0 : this.tsNextThenParseType();
  }
  tsExpectThenParseType(token) {
    return this.tsDoThenParseType(() => this.expect(token));
  }
  tsNextThenParseType() {
    return this.tsDoThenParseType(() => this.next());
  }
  tsDoThenParseType(cb) {
    return this.tsInType(() => {
      cb();
      return this.tsParseType();
    });
  }
  tsParseEnumMember() {
    const node2 = this.startNode();
    node2.id = this.match(131) ? super.parseStringLiteral(this.state.value) : this.parseIdentifier(true);
    if (this.eat(29)) {
      node2.initializer = super.parseMaybeAssignAllowIn();
    }
    return this.finishNode(node2, "TSEnumMember");
  }
  tsParseEnumDeclaration(node2, properties = {}) {
    if (properties.const)
      node2.const = true;
    if (properties.declare)
      node2.declare = true;
    this.expectContextual(124);
    node2.id = this.parseIdentifier();
    this.checkIdentifier(node2.id, node2.const ? BIND_TS_CONST_ENUM : BIND_TS_ENUM);
    this.expect(5);
    node2.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
    this.expect(8);
    return this.finishNode(node2, "TSEnumDeclaration");
  }
  tsParseModuleBlock() {
    const node2 = this.startNode();
    this.scope.enter(SCOPE_OTHER);
    this.expect(5);
    super.parseBlockOrModuleBlockBody(node2.body = [], void 0, true, 8);
    this.scope.exit();
    return this.finishNode(node2, "TSModuleBlock");
  }
  tsParseModuleOrNamespaceDeclaration(node2, nested = false) {
    node2.id = this.parseIdentifier();
    if (!nested) {
      this.checkIdentifier(node2.id, BIND_TS_NAMESPACE);
    }
    if (this.eat(16)) {
      const inner = this.startNode();
      this.tsParseModuleOrNamespaceDeclaration(inner, true);
      node2.body = inner;
    } else {
      this.scope.enter(SCOPE_TS_MODULE);
      this.prodParam.enter(PARAM);
      node2.body = this.tsParseModuleBlock();
      this.prodParam.exit();
      this.scope.exit();
    }
    return this.finishNode(node2, "TSModuleDeclaration");
  }
  tsParseAmbientExternalModuleDeclaration(node2) {
    if (this.isContextual(110)) {
      node2.global = true;
      node2.id = this.parseIdentifier();
    } else if (this.match(131)) {
      node2.id = super.parseStringLiteral(this.state.value);
    } else {
      this.unexpected();
    }
    if (this.match(5)) {
      this.scope.enter(SCOPE_TS_MODULE);
      this.prodParam.enter(PARAM);
      node2.body = this.tsParseModuleBlock();
      this.prodParam.exit();
      this.scope.exit();
    } else {
      this.semicolon();
    }
    return this.finishNode(node2, "TSModuleDeclaration");
  }
  tsParseImportEqualsDeclaration(node2, isExport) {
    node2.isExport = isExport || false;
    node2.id = this.parseIdentifier();
    this.checkIdentifier(node2.id, BIND_FLAGS_TS_IMPORT);
    this.expect(29);
    const moduleReference = this.tsParseModuleReference();
    if (node2.importKind === "type" && moduleReference.type !== "TSExternalModuleReference") {
      this.raise(TSErrors.ImportAliasHasImportType, {
        at: moduleReference
      });
    }
    node2.moduleReference = moduleReference;
    this.semicolon();
    return this.finishNode(node2, "TSImportEqualsDeclaration");
  }
  tsIsExternalModuleReference() {
    return this.isContextual(117) && this.lookaheadCharCode() === 40;
  }
  tsParseModuleReference() {
    return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(false);
  }
  tsParseExternalModuleReference() {
    const node2 = this.startNode();
    this.expectContextual(117);
    this.expect(10);
    if (!this.match(131)) {
      this.unexpected();
    }
    node2.expression = super.parseExprAtom();
    this.expect(11);
    return this.finishNode(node2, "TSExternalModuleReference");
  }
  tsLookAhead(f) {
    const state = this.state.clone();
    const res = f();
    this.state = state;
    return res;
  }
  tsTryParseAndCatch(f) {
    const result2 = this.tryParse((abort) => f() || abort());
    if (result2.aborted || !result2.node)
      return void 0;
    if (result2.error)
      this.state = result2.failState;
    return result2.node;
  }
  tsTryParse(f) {
    const state = this.state.clone();
    const result2 = f();
    if (result2 !== void 0 && result2 !== false) {
      return result2;
    } else {
      this.state = state;
      return void 0;
    }
  }
  tsTryParseDeclare(nany) {
    if (this.isLineTerminator()) {
      return;
    }
    let starttype = this.state.type;
    let kind;
    if (this.isContextual(99)) {
      starttype = 74;
      kind = "let";
    }
    return this.tsInAmbientContext(() => {
      if (starttype === 68) {
        nany.declare = true;
        return super.parseFunctionStatement(nany, false, false);
      }
      if (starttype === 80) {
        nany.declare = true;
        return this.parseClass(nany, true, false);
      }
      if (starttype === 124) {
        return this.tsParseEnumDeclaration(nany, {
          declare: true
        });
      }
      if (starttype === 110) {
        return this.tsParseAmbientExternalModuleDeclaration(nany);
      }
      if (starttype === 75 || starttype === 74) {
        if (!this.match(75) || !this.isLookaheadContextual("enum")) {
          nany.declare = true;
          return this.parseVarStatement(nany, kind || this.state.value, true);
        }
        this.expect(75);
        return this.tsParseEnumDeclaration(nany, {
          const: true,
          declare: true
        });
      }
      if (starttype === 127) {
        const result2 = this.tsParseInterfaceDeclaration(nany, {
          declare: true
        });
        if (result2)
          return result2;
      }
      if (tokenIsIdentifier(starttype)) {
        return this.tsParseDeclaration(nany, this.state.value, true, null);
      }
    });
  }
  tsTryParseExportDeclaration() {
    return this.tsParseDeclaration(this.startNode(), this.state.value, true, null);
  }
  tsParseExpressionStatement(node2, expr, decorators) {
    switch (expr.name) {
      case "declare": {
        const declaration2 = this.tsTryParseDeclare(node2);
        if (declaration2) {
          declaration2.declare = true;
          return declaration2;
        }
        break;
      }
      case "global":
        if (this.match(5)) {
          this.scope.enter(SCOPE_TS_MODULE);
          this.prodParam.enter(PARAM);
          const mod = node2;
          mod.global = true;
          mod.id = expr;
          mod.body = this.tsParseModuleBlock();
          this.scope.exit();
          this.prodParam.exit();
          return this.finishNode(mod, "TSModuleDeclaration");
        }
        break;
      default:
        return this.tsParseDeclaration(node2, expr.name, false, decorators);
    }
  }
  tsParseDeclaration(node2, value, next, decorators) {
    switch (value) {
      case "abstract":
        if (this.tsCheckLineTerminator(next) && (this.match(80) || tokenIsIdentifier(this.state.type))) {
          return this.tsParseAbstractDeclaration(node2, decorators);
        }
        break;
      case "module":
        if (this.tsCheckLineTerminator(next)) {
          if (this.match(131)) {
            return this.tsParseAmbientExternalModuleDeclaration(node2);
          } else if (tokenIsIdentifier(this.state.type)) {
            return this.tsParseModuleOrNamespaceDeclaration(node2);
          }
        }
        break;
      case "namespace":
        if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) {
          return this.tsParseModuleOrNamespaceDeclaration(node2);
        }
        break;
      case "type":
        if (this.tsCheckLineTerminator(next) && tokenIsIdentifier(this.state.type)) {
          return this.tsParseTypeAliasDeclaration(node2);
        }
        break;
    }
  }
  tsCheckLineTerminator(next) {
    if (next) {
      if (this.hasFollowingLineBreak())
        return false;
      this.next();
      return true;
    }
    return !this.isLineTerminator();
  }
  tsTryParseGenericAsyncArrowFunction(startLoc) {
    if (!this.match(47)) {
      return void 0;
    }
    const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
    this.state.maybeInArrowParameters = true;
    const res = this.tsTryParseAndCatch(() => {
      const node2 = this.startNodeAt(startLoc);
      node2.typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier);
      super.parseFunctionParams(node2);
      node2.returnType = this.tsTryParseTypeOrTypePredicateAnnotation();
      this.expect(19);
      return node2;
    });
    this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
    if (!res) {
      return void 0;
    }
    return super.parseArrowExpression(res, null, true);
  }
  tsParseTypeArgumentsInExpression() {
    if (this.reScan_lt() !== 47) {
      return void 0;
    }
    return this.tsParseTypeArguments();
  }
  tsParseTypeArguments() {
    const node2 = this.startNode();
    node2.params = this.tsInType(() => this.tsInNoContext(() => {
      this.expect(47);
      return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this));
    }));
    if (node2.params.length === 0) {
      this.raise(TSErrors.EmptyTypeArguments, {
        at: node2
      });
    }
    this.expect(48);
    return this.finishNode(node2, "TSTypeParameterInstantiation");
  }
  tsIsDeclarationStart() {
    return tokenIsTSDeclarationStart(this.state.type);
  }
  isExportDefaultSpecifier() {
    if (this.tsIsDeclarationStart())
      return false;
    return super.isExportDefaultSpecifier();
  }
  parseAssignableListItem(flags, decorators) {
    const startLoc = this.state.startLoc;
    const modified = {};
    this.tsParseModifiers({
      allowedModifiers: ["public", "private", "protected", "override", "readonly"]
    }, modified);
    const accessibility = modified.accessibility;
    const override = modified.override;
    const readonly2 = modified.readonly;
    if (!(flags & 4) && (accessibility || readonly2 || override)) {
      this.raise(TSErrors.UnexpectedParameterModifier, {
        at: startLoc
      });
    }
    const left = this.parseMaybeDefault();
    this.parseAssignableListItemTypes(left, flags);
    const elt = this.parseMaybeDefault(left.loc.start, left);
    if (accessibility || readonly2 || override) {
      const pp = this.startNodeAt(startLoc);
      if (decorators.length) {
        pp.decorators = decorators;
      }
      if (accessibility)
        pp.accessibility = accessibility;
      if (readonly2)
        pp.readonly = readonly2;
      if (override)
        pp.override = override;
      if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") {
        this.raise(TSErrors.UnsupportedParameterPropertyKind, {
          at: pp
        });
      }
      pp.parameter = elt;
      return this.finishNode(pp, "TSParameterProperty");
    }
    if (decorators.length) {
      left.decorators = decorators;
    }
    return elt;
  }
  isSimpleParameter(node2) {
    return node2.type === "TSParameterProperty" && super.isSimpleParameter(node2.parameter) || super.isSimpleParameter(node2);
  }
  tsDisallowOptionalPattern(node2) {
    for (const param of node2.params) {
      if (param.type !== "Identifier" && param.optional && !this.state.isAmbientContext) {
        this.raise(TSErrors.PatternIsOptional, {
          at: param
        });
      }
    }
  }
  setArrowFunctionParameters(node2, params, trailingCommaLoc) {
    super.setArrowFunctionParameters(node2, params, trailingCommaLoc);
    this.tsDisallowOptionalPattern(node2);
  }
  parseFunctionBodyAndFinish(node2, type, isMethod = false) {
    if (this.match(14)) {
      node2.returnType = this.tsParseTypeOrTypePredicateAnnotation(14);
    }
    const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" || type === "ClassPrivateMethod" ? "TSDeclareMethod" : void 0;
    if (bodilessType && !this.match(5) && this.isLineTerminator()) {
      return this.finishNode(node2, bodilessType);
    }
    if (bodilessType === "TSDeclareFunction" && this.state.isAmbientContext) {
      this.raise(TSErrors.DeclareFunctionHasImplementation, {
        at: node2
      });
      if (node2.declare) {
        return super.parseFunctionBodyAndFinish(node2, bodilessType, isMethod);
      }
    }
    this.tsDisallowOptionalPattern(node2);
    return super.parseFunctionBodyAndFinish(node2, type, isMethod);
  }
  registerFunctionStatementId(node2) {
    if (!node2.body && node2.id) {
      this.checkIdentifier(node2.id, BIND_TS_AMBIENT);
    } else {
      super.registerFunctionStatementId(node2);
    }
  }
  tsCheckForInvalidTypeCasts(items) {
    items.forEach((node2) => {
      if ((node2 == null ? void 0 : node2.type) === "TSTypeCastExpression") {
        this.raise(TSErrors.UnexpectedTypeAnnotation, {
          at: node2.typeAnnotation
        });
      }
    });
  }
  toReferencedList(exprList, isInParens) {
    this.tsCheckForInvalidTypeCasts(exprList);
    return exprList;
  }
  parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
    const node2 = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors);
    if (node2.type === "ArrayExpression") {
      this.tsCheckForInvalidTypeCasts(node2.elements);
    }
    return node2;
  }
  parseSubscript(base2, startLoc, noCalls, state) {
    if (!this.hasPrecedingLineBreak() && this.match(35)) {
      this.state.canStartJSXElement = false;
      this.next();
      const nonNullExpression = this.startNodeAt(startLoc);
      nonNullExpression.expression = base2;
      return this.finishNode(nonNullExpression, "TSNonNullExpression");
    }
    let isOptionalCall = false;
    if (this.match(18) && this.lookaheadCharCode() === 60) {
      if (noCalls) {
        state.stop = true;
        return base2;
      }
      state.optionalChainMember = isOptionalCall = true;
      this.next();
    }
    if (this.match(47) || this.match(51)) {
      let missingParenErrorLoc;
      const result2 = this.tsTryParseAndCatch(() => {
        if (!noCalls && this.atPossibleAsyncArrow(base2)) {
          const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startLoc);
          if (asyncArrowFn) {
            return asyncArrowFn;
          }
        }
        const typeArguments = this.tsParseTypeArgumentsInExpression();
        if (!typeArguments)
          return;
        if (isOptionalCall && !this.match(10)) {
          missingParenErrorLoc = this.state.curPosition();
          return;
        }
        if (tokenIsTemplate(this.state.type)) {
          const result3 = super.parseTaggedTemplateExpression(base2, startLoc, state);
          result3.typeParameters = typeArguments;
          return result3;
        }
        if (!noCalls && this.eat(10)) {
          const node3 = this.startNodeAt(startLoc);
          node3.callee = base2;
          node3.arguments = this.parseCallExpressionArguments(11, false);
          this.tsCheckForInvalidTypeCasts(node3.arguments);
          node3.typeParameters = typeArguments;
          if (state.optionalChainMember) {
            node3.optional = isOptionalCall;
          }
          return this.finishCallExpression(node3, state.optionalChainMember);
        }
        const tokenType = this.state.type;
        if (tokenType === 48 || tokenType === 52 || tokenType !== 10 && tokenCanStartExpression(tokenType) && !this.hasPrecedingLineBreak()) {
          return;
        }
        const node2 = this.startNodeAt(startLoc);
        node2.expression = base2;
        node2.typeParameters = typeArguments;
        return this.finishNode(node2, "TSInstantiationExpression");
      });
      if (missingParenErrorLoc) {
        this.unexpected(missingParenErrorLoc, 10);
      }
      if (result2) {
        if (result2.type === "TSInstantiationExpression" && (this.match(16) || this.match(18) && this.lookaheadCharCode() !== 40)) {
          this.raise(TSErrors.InvalidPropertyAccessAfterInstantiationExpression, {
            at: this.state.startLoc
          });
        }
        return result2;
      }
    }
    return super.parseSubscript(base2, startLoc, noCalls, state);
  }
  parseNewCallee(node2) {
    var _callee$extra;
    super.parseNewCallee(node2);
    const {
      callee
    } = node2;
    if (callee.type === "TSInstantiationExpression" && !((_callee$extra = callee.extra) != null && _callee$extra.parenthesized)) {
      node2.typeParameters = callee.typeParameters;
      node2.callee = callee.expression;
    }
  }
  parseExprOp(left, leftStartLoc, minPrec) {
    let isSatisfies;
    if (tokenOperatorPrecedence(58) > minPrec && !this.hasPrecedingLineBreak() && (this.isContextual(93) || (isSatisfies = this.isContextual(118)))) {
      const node2 = this.startNodeAt(leftStartLoc);
      node2.expression = left;
      node2.typeAnnotation = this.tsInType(() => {
        this.next();
        if (this.match(75)) {
          if (isSatisfies) {
            this.raise(Errors.UnexpectedKeyword, {
              at: this.state.startLoc,
              keyword: "const"
            });
          }
          return this.tsParseTypeReference();
        }
        return this.tsParseType();
      });
      this.finishNode(node2, isSatisfies ? "TSSatisfiesExpression" : "TSAsExpression");
      this.reScan_lt_gt();
      return this.parseExprOp(node2, leftStartLoc, minPrec);
    }
    return super.parseExprOp(left, leftStartLoc, minPrec);
  }
  checkReservedWord(word2, startLoc, checkKeywords, isBinding) {
    if (!this.state.isAmbientContext) {
      super.checkReservedWord(word2, startLoc, checkKeywords, isBinding);
    }
  }
  checkImportReflection(node2) {
    super.checkImportReflection(node2);
    if (node2.module && node2.importKind !== "value") {
      this.raise(TSErrors.ImportReflectionHasImportType, {
        at: node2.specifiers[0].loc.start
      });
    }
  }
  checkDuplicateExports() {
  }
  parseImport(node2) {
    node2.importKind = "value";
    if (tokenIsIdentifier(this.state.type) || this.match(55) || this.match(5)) {
      let ahead = this.lookahead();
      if (this.isContextual(128) && ahead.type !== 12 && ahead.type !== 97 && ahead.type !== 29) {
        node2.importKind = "type";
        this.next();
        ahead = this.lookahead();
      }
      if (tokenIsIdentifier(this.state.type) && ahead.type === 29) {
        return this.tsParseImportEqualsDeclaration(node2);
      }
    }
    const importNode = super.parseImport(node2);
    if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") {
      this.raise(TSErrors.TypeImportCannotSpecifyDefaultAndNamed, {
        at: importNode
      });
    }
    return importNode;
  }
  parseExport(node2, decorators) {
    if (this.match(83)) {
      this.next();
      if (this.isContextual(128) && this.lookaheadCharCode() !== 61) {
        node2.importKind = "type";
        this.next();
      } else {
        node2.importKind = "value";
      }
      return this.tsParseImportEqualsDeclaration(node2, true);
    } else if (this.eat(29)) {
      const assign = node2;
      assign.expression = super.parseExpression();
      this.semicolon();
      return this.finishNode(assign, "TSExportAssignment");
    } else if (this.eatContextual(93)) {
      const decl = node2;
      this.expectContextual(126);
      decl.id = this.parseIdentifier();
      this.semicolon();
      return this.finishNode(decl, "TSNamespaceExportDeclaration");
    } else {
      node2.exportKind = "value";
      if (this.isContextual(128)) {
        const ch = this.lookaheadCharCode();
        if (ch === 123 || ch === 42) {
          this.next();
          node2.exportKind = "type";
        }
      }
      return super.parseExport(node2, decorators);
    }
  }
  isAbstractClass() {
    return this.isContextual(122) && this.lookahead().type === 80;
  }
  parseExportDefaultExpression() {
    if (this.isAbstractClass()) {
      const cls = this.startNode();
      this.next();
      cls.abstract = true;
      return this.parseClass(cls, true, true);
    }
    if (this.match(127)) {
      const result2 = this.tsParseInterfaceDeclaration(this.startNode());
      if (result2)
        return result2;
    }
    return super.parseExportDefaultExpression();
  }
  parseVarStatement(node2, kind, allowMissingInitializer = false) {
    const {
      isAmbientContext
    } = this.state;
    const declaration2 = super.parseVarStatement(node2, kind, allowMissingInitializer || isAmbientContext);
    if (!isAmbientContext)
      return declaration2;
    for (const {
      id: id3,
      init: init2
    } of declaration2.declarations) {
      if (!init2)
        continue;
      if (kind !== "const" || !!id3.typeAnnotation) {
        this.raise(TSErrors.InitializerNotAllowedInAmbientContext, {
          at: init2
        });
      } else if (!isValidAmbientConstInitializer(init2, this.hasPlugin("estree"))) {
        this.raise(TSErrors.ConstInitiailizerMustBeStringOrNumericLiteralOrLiteralEnumReference, {
          at: init2
        });
      }
    }
    return declaration2;
  }
  parseStatementContent(flags, decorators) {
    if (this.match(75) && this.isLookaheadContextual("enum")) {
      const node2 = this.startNode();
      this.expect(75);
      return this.tsParseEnumDeclaration(node2, {
        const: true
      });
    }
    if (this.isContextual(124)) {
      return this.tsParseEnumDeclaration(this.startNode());
    }
    if (this.isContextual(127)) {
      const result2 = this.tsParseInterfaceDeclaration(this.startNode());
      if (result2)
        return result2;
    }
    return super.parseStatementContent(flags, decorators);
  }
  parseAccessModifier() {
    return this.tsParseModifier(["public", "protected", "private"]);
  }
  tsHasSomeModifiers(member, modifiers) {
    return modifiers.some((modifier) => {
      if (tsIsAccessModifier(modifier)) {
        return member.accessibility === modifier;
      }
      return !!member[modifier];
    });
  }
  tsIsStartOfStaticBlocks() {
    return this.isContextual(104) && this.lookaheadCharCode() === 123;
  }
  parseClassMember(classBody, member, state) {
    const modifiers = ["declare", "private", "public", "protected", "override", "abstract", "readonly", "static"];
    this.tsParseModifiers({
      allowedModifiers: modifiers,
      disallowedModifiers: ["in", "out"],
      stopOnStartOfClassStaticBlock: true,
      errorTemplate: TSErrors.InvalidModifierOnTypeParameterPositions
    }, member);
    const callParseClassMemberWithIsStatic = () => {
      if (this.tsIsStartOfStaticBlocks()) {
        this.next();
        this.next();
        if (this.tsHasSomeModifiers(member, modifiers)) {
          this.raise(TSErrors.StaticBlockCannotHaveModifier, {
            at: this.state.curPosition()
          });
        }
        super.parseClassStaticBlock(classBody, member);
      } else {
        this.parseClassMemberWithIsStatic(classBody, member, state, !!member.static);
      }
    };
    if (member.declare) {
      this.tsInAmbientContext(callParseClassMemberWithIsStatic);
    } else {
      callParseClassMemberWithIsStatic();
    }
  }
  parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
    const idx = this.tsTryParseIndexSignature(member);
    if (idx) {
      classBody.body.push(idx);
      if (member.abstract) {
        this.raise(TSErrors.IndexSignatureHasAbstract, {
          at: member
        });
      }
      if (member.accessibility) {
        this.raise(TSErrors.IndexSignatureHasAccessibility, {
          at: member,
          modifier: member.accessibility
        });
      }
      if (member.declare) {
        this.raise(TSErrors.IndexSignatureHasDeclare, {
          at: member
        });
      }
      if (member.override) {
        this.raise(TSErrors.IndexSignatureHasOverride, {
          at: member
        });
      }
      return;
    }
    if (!this.state.inAbstractClass && member.abstract) {
      this.raise(TSErrors.NonAbstractClassHasAbstractMethod, {
        at: member
      });
    }
    if (member.override) {
      if (!state.hadSuperClass) {
        this.raise(TSErrors.OverrideNotInSubClass, {
          at: member
        });
      }
    }
    super.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  }
  parsePostMemberNameModifiers(methodOrProp) {
    const optional = this.eat(17);
    if (optional)
      methodOrProp.optional = true;
    if (methodOrProp.readonly && this.match(10)) {
      this.raise(TSErrors.ClassMethodHasReadonly, {
        at: methodOrProp
      });
    }
    if (methodOrProp.declare && this.match(10)) {
      this.raise(TSErrors.ClassMethodHasDeclare, {
        at: methodOrProp
      });
    }
  }
  parseExpressionStatement(node2, expr, decorators) {
    const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node2, expr, decorators) : void 0;
    return decl || super.parseExpressionStatement(node2, expr, decorators);
  }
  shouldParseExportDeclaration() {
    if (this.tsIsDeclarationStart())
      return true;
    return super.shouldParseExportDeclaration();
  }
  parseConditional(expr, startLoc, refExpressionErrors) {
    if (!this.state.maybeInArrowParameters || !this.match(17)) {
      return super.parseConditional(expr, startLoc, refExpressionErrors);
    }
    const result2 = this.tryParse(() => super.parseConditional(expr, startLoc));
    if (!result2.node) {
      if (result2.error) {
        super.setOptionalParametersError(refExpressionErrors, result2.error);
      }
      return expr;
    }
    if (result2.error)
      this.state = result2.failState;
    return result2.node;
  }
  parseParenItem(node2, startLoc) {
    node2 = super.parseParenItem(node2, startLoc);
    if (this.eat(17)) {
      node2.optional = true;
      this.resetEndLocation(node2);
    }
    if (this.match(14)) {
      const typeCastNode = this.startNodeAt(startLoc);
      typeCastNode.expression = node2;
      typeCastNode.typeAnnotation = this.tsParseTypeAnnotation();
      return this.finishNode(typeCastNode, "TSTypeCastExpression");
    }
    return node2;
  }
  parseExportDeclaration(node2) {
    if (!this.state.isAmbientContext && this.isContextual(123)) {
      return this.tsInAmbientContext(() => this.parseExportDeclaration(node2));
    }
    const startLoc = this.state.startLoc;
    const isDeclare = this.eatContextual(123);
    if (isDeclare && (this.isContextual(123) || !this.shouldParseExportDeclaration())) {
      throw this.raise(TSErrors.ExpectedAmbientAfterExportDeclare, {
        at: this.state.startLoc
      });
    }
    const isIdentifier2 = tokenIsIdentifier(this.state.type);
    const declaration2 = isIdentifier2 && this.tsTryParseExportDeclaration() || super.parseExportDeclaration(node2);
    if (!declaration2)
      return null;
    if (declaration2.type === "TSInterfaceDeclaration" || declaration2.type === "TSTypeAliasDeclaration" || isDeclare) {
      node2.exportKind = "type";
    }
    if (isDeclare) {
      this.resetStartLocation(declaration2, startLoc);
      declaration2.declare = true;
    }
    return declaration2;
  }
  parseClassId(node2, isStatement, optionalId, bindingType) {
    if ((!isStatement || optionalId) && this.isContextual(111)) {
      return;
    }
    super.parseClassId(node2, isStatement, optionalId, node2.declare ? BIND_TS_AMBIENT : BIND_CLASS);
    const typeParameters = this.tsTryParseTypeParameters(this.tsParseInOutConstModifiers);
    if (typeParameters)
      node2.typeParameters = typeParameters;
  }
  parseClassPropertyAnnotation(node2) {
    if (!node2.optional) {
      if (this.eat(35)) {
        node2.definite = true;
      } else if (this.eat(17)) {
        node2.optional = true;
      }
    }
    const type = this.tsTryParseTypeAnnotation();
    if (type)
      node2.typeAnnotation = type;
  }
  parseClassProperty(node2) {
    this.parseClassPropertyAnnotation(node2);
    if (this.state.isAmbientContext && !(node2.readonly && !node2.typeAnnotation) && this.match(29)) {
      this.raise(TSErrors.DeclareClassFieldHasInitializer, {
        at: this.state.startLoc
      });
    }
    if (node2.abstract && this.match(29)) {
      const {
        key
      } = node2;
      this.raise(TSErrors.AbstractPropertyHasInitializer, {
        at: this.state.startLoc,
        propertyName: key.type === "Identifier" && !node2.computed ? key.name : `[${this.input.slice(key.start, key.end)}]`
      });
    }
    return super.parseClassProperty(node2);
  }
  parseClassPrivateProperty(node2) {
    if (node2.abstract) {
      this.raise(TSErrors.PrivateElementHasAbstract, {
        at: node2
      });
    }
    if (node2.accessibility) {
      this.raise(TSErrors.PrivateElementHasAccessibility, {
        at: node2,
        modifier: node2.accessibility
      });
    }
    this.parseClassPropertyAnnotation(node2);
    return super.parseClassPrivateProperty(node2);
  }
  parseClassAccessorProperty(node2) {
    this.parseClassPropertyAnnotation(node2);
    if (node2.optional) {
      this.raise(TSErrors.AccessorCannotBeOptional, {
        at: node2
      });
    }
    return super.parseClassAccessorProperty(node2);
  }
  pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
    const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
    if (typeParameters && isConstructor) {
      this.raise(TSErrors.ConstructorHasTypeParameters, {
        at: typeParameters
      });
    }
    const {
      declare = false,
      kind
    } = method;
    if (declare && (kind === "get" || kind === "set")) {
      this.raise(TSErrors.DeclareAccessor, {
        at: method,
        kind
      });
    }
    if (typeParameters)
      method.typeParameters = typeParameters;
    super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  }
  pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
    const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
    if (typeParameters)
      method.typeParameters = typeParameters;
    super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  }
  declareClassPrivateMethodInScope(node2, kind) {
    if (node2.type === "TSDeclareMethod")
      return;
    if (node2.type === "MethodDefinition" && !node2.value.body)
      return;
    super.declareClassPrivateMethodInScope(node2, kind);
  }
  parseClassSuper(node2) {
    super.parseClassSuper(node2);
    if (node2.superClass && (this.match(47) || this.match(51))) {
      node2.superTypeParameters = this.tsParseTypeArgumentsInExpression();
    }
    if (this.eatContextual(111)) {
      node2.implements = this.tsParseHeritageClause("implements");
    }
  }
  parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
    const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
    if (typeParameters)
      prop.typeParameters = typeParameters;
    return super.parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  }
  parseFunctionParams(node2, isConstructor) {
    const typeParameters = this.tsTryParseTypeParameters(this.tsParseConstModifier);
    if (typeParameters)
      node2.typeParameters = typeParameters;
    super.parseFunctionParams(node2, isConstructor);
  }
  parseVarId(decl, kind) {
    super.parseVarId(decl, kind);
    if (decl.id.type === "Identifier" && !this.hasPrecedingLineBreak() && this.eat(35)) {
      decl.definite = true;
    }
    const type = this.tsTryParseTypeAnnotation();
    if (type) {
      decl.id.typeAnnotation = type;
      this.resetEndLocation(decl.id);
    }
  }
  parseAsyncArrowFromCallExpression(node2, call) {
    if (this.match(14)) {
      node2.returnType = this.tsParseTypeAnnotation();
    }
    return super.parseAsyncArrowFromCallExpression(node2, call);
  }
  parseMaybeAssign(refExpressionErrors, afterLeftParse) {
    var _jsx, _jsx2, _typeCast, _jsx3, _typeCast2, _jsx4, _typeCast3;
    let state;
    let jsx2;
    let typeCast;
    if (this.hasPlugin("jsx") && (this.match(140) || this.match(47))) {
      state = this.state.clone();
      jsx2 = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
      if (!jsx2.error)
        return jsx2.node;
      const {
        context
      } = this.state;
      const currentContext = context[context.length - 1];
      if (currentContext === types$1.j_oTag || currentContext === types$1.j_expr) {
        context.pop();
      }
    }
    if (!((_jsx = jsx2) != null && _jsx.error) && !this.match(47)) {
      return super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
    }
    if (!state || state === this.state)
      state = this.state.clone();
    let typeParameters;
    const arrow = this.tryParse((abort) => {
      var _expr$extra, _typeParameters;
      typeParameters = this.tsParseTypeParameters(this.tsParseConstModifier);
      const expr = super.parseMaybeAssign(refExpressionErrors, afterLeftParse);
      if (expr.type !== "ArrowFunctionExpression" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) {
        abort();
      }
      if (((_typeParameters = typeParameters) == null ? void 0 : _typeParameters.params.length) !== 0) {
        this.resetStartLocationFromNode(expr, typeParameters);
      }
      expr.typeParameters = typeParameters;
      return expr;
    }, state);
    if (!arrow.error && !arrow.aborted) {
      if (typeParameters)
        this.reportReservedArrowTypeParam(typeParameters);
      return arrow.node;
    }
    if (!jsx2) {
      assert$1(!this.hasPlugin("jsx"));
      typeCast = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse), state);
      if (!typeCast.error)
        return typeCast.node;
    }
    if ((_jsx2 = jsx2) != null && _jsx2.node) {
      this.state = jsx2.failState;
      return jsx2.node;
    }
    if (arrow.node) {
      this.state = arrow.failState;
      if (typeParameters)
        this.reportReservedArrowTypeParam(typeParameters);
      return arrow.node;
    }
    if ((_typeCast = typeCast) != null && _typeCast.node) {
      this.state = typeCast.failState;
      return typeCast.node;
    }
    if ((_jsx3 = jsx2) != null && _jsx3.thrown)
      throw jsx2.error;
    if (arrow.thrown)
      throw arrow.error;
    if ((_typeCast2 = typeCast) != null && _typeCast2.thrown)
      throw typeCast.error;
    throw ((_jsx4 = jsx2) == null ? void 0 : _jsx4.error) || arrow.error || ((_typeCast3 = typeCast) == null ? void 0 : _typeCast3.error);
  }
  reportReservedArrowTypeParam(node2) {
    var _node$extra;
    if (node2.params.length === 1 && !node2.params[0].constraint && !((_node$extra = node2.extra) != null && _node$extra.trailingComma) && this.getPluginOption("typescript", "disallowAmbiguousJSXLike")) {
      this.raise(TSErrors.ReservedArrowTypeParam, {
        at: node2
      });
    }
  }
  parseMaybeUnary(refExpressionErrors, sawUnary) {
    if (!this.hasPlugin("jsx") && this.match(47)) {
      return this.tsParseTypeAssertion();
    } else {
      return super.parseMaybeUnary(refExpressionErrors, sawUnary);
    }
  }
  parseArrow(node2) {
    if (this.match(14)) {
      const result2 = this.tryParse((abort) => {
        const returnType = this.tsParseTypeOrTypePredicateAnnotation(14);
        if (this.canInsertSemicolon() || !this.match(19))
          abort();
        return returnType;
      });
      if (result2.aborted)
        return;
      if (!result2.thrown) {
        if (result2.error)
          this.state = result2.failState;
        node2.returnType = result2.node;
      }
    }
    return super.parseArrow(node2);
  }
  parseAssignableListItemTypes(param, flags) {
    if (!(flags & 2))
      return param;
    if (this.eat(17)) {
      param.optional = true;
    }
    const type = this.tsTryParseTypeAnnotation();
    if (type)
      param.typeAnnotation = type;
    this.resetEndLocation(param);
    return param;
  }
  isAssignable(node2, isBinding) {
    switch (node2.type) {
      case "TSTypeCastExpression":
        return this.isAssignable(node2.expression, isBinding);
      case "TSParameterProperty":
        return true;
      default:
        return super.isAssignable(node2, isBinding);
    }
  }
  toAssignable(node2, isLHS = false) {
    switch (node2.type) {
      case "ParenthesizedExpression":
        this.toAssignableParenthesizedExpression(node2, isLHS);
        break;
      case "TSAsExpression":
      case "TSSatisfiesExpression":
      case "TSNonNullExpression":
      case "TSTypeAssertion":
        if (isLHS) {
          this.expressionScope.recordArrowParameterBindingError(TSErrors.UnexpectedTypeCastInParameter, {
            at: node2
          });
        } else {
          this.raise(TSErrors.UnexpectedTypeCastInParameter, {
            at: node2
          });
        }
        this.toAssignable(node2.expression, isLHS);
        break;
      case "AssignmentExpression":
        if (!isLHS && node2.left.type === "TSTypeCastExpression") {
          node2.left = this.typeCastToParameter(node2.left);
        }
      default:
        super.toAssignable(node2, isLHS);
    }
  }
  toAssignableParenthesizedExpression(node2, isLHS) {
    switch (node2.expression.type) {
      case "TSAsExpression":
      case "TSSatisfiesExpression":
      case "TSNonNullExpression":
      case "TSTypeAssertion":
      case "ParenthesizedExpression":
        this.toAssignable(node2.expression, isLHS);
        break;
      default:
        super.toAssignable(node2, isLHS);
    }
  }
  checkToRestConversion(node2, allowPattern) {
    switch (node2.type) {
      case "TSAsExpression":
      case "TSSatisfiesExpression":
      case "TSTypeAssertion":
      case "TSNonNullExpression":
        this.checkToRestConversion(node2.expression, false);
        break;
      default:
        super.checkToRestConversion(node2, allowPattern);
    }
  }
  isValidLVal(type, isUnparenthesizedInAssign, binding2) {
    return getOwn({
      TSTypeCastExpression: true,
      TSParameterProperty: "parameter",
      TSNonNullExpression: "expression",
      TSAsExpression: (binding2 !== BIND_NONE || !isUnparenthesizedInAssign) && ["expression", true],
      TSSatisfiesExpression: (binding2 !== BIND_NONE || !isUnparenthesizedInAssign) && ["expression", true],
      TSTypeAssertion: (binding2 !== BIND_NONE || !isUnparenthesizedInAssign) && ["expression", true]
    }, type) || super.isValidLVal(type, isUnparenthesizedInAssign, binding2);
  }
  parseBindingAtom() {
    switch (this.state.type) {
      case 78:
        return this.parseIdentifier(true);
      default:
        return super.parseBindingAtom();
    }
  }
  parseMaybeDecoratorArguments(expr) {
    if (this.match(47) || this.match(51)) {
      const typeArguments = this.tsParseTypeArgumentsInExpression();
      if (this.match(10)) {
        const call = super.parseMaybeDecoratorArguments(expr);
        call.typeParameters = typeArguments;
        return call;
      }
      this.unexpected(null, 10);
    }
    return super.parseMaybeDecoratorArguments(expr);
  }
  checkCommaAfterRest(close) {
    if (this.state.isAmbientContext && this.match(12) && this.lookaheadCharCode() === close) {
      this.next();
      return false;
    } else {
      return super.checkCommaAfterRest(close);
    }
  }
  isClassMethod() {
    return this.match(47) || super.isClassMethod();
  }
  isClassProperty() {
    return this.match(35) || this.match(14) || super.isClassProperty();
  }
  parseMaybeDefault(startLoc, left) {
    const node2 = super.parseMaybeDefault(startLoc, left);
    if (node2.type === "AssignmentPattern" && node2.typeAnnotation && node2.right.start < node2.typeAnnotation.start) {
      this.raise(TSErrors.TypeAnnotationAfterAssign, {
        at: node2.typeAnnotation
      });
    }
    return node2;
  }
  getTokenFromCode(code) {
    if (this.state.inType) {
      if (code === 62) {
        this.finishOp(48, 1);
        return;
      }
      if (code === 60) {
        this.finishOp(47, 1);
        return;
      }
    }
    super.getTokenFromCode(code);
  }
  reScan_lt_gt() {
    const {
      type
    } = this.state;
    if (type === 47) {
      this.state.pos -= 1;
      this.readToken_lt();
    } else if (type === 48) {
      this.state.pos -= 1;
      this.readToken_gt();
    }
  }
  reScan_lt() {
    const {
      type
    } = this.state;
    if (type === 51) {
      this.state.pos -= 2;
      this.finishOp(47, 1);
      return 47;
    }
    return type;
  }
  toAssignableList(exprList, trailingCommaLoc, isLHS) {
    for (let i = 0; i < exprList.length; i++) {
      const expr = exprList[i];
      if ((expr == null ? void 0 : expr.type) === "TSTypeCastExpression") {
        exprList[i] = this.typeCastToParameter(expr);
      }
    }
    super.toAssignableList(exprList, trailingCommaLoc, isLHS);
  }
  typeCastToParameter(node2) {
    node2.expression.typeAnnotation = node2.typeAnnotation;
    this.resetEndLocation(node2.expression, node2.typeAnnotation.loc.end);
    return node2.expression;
  }
  shouldParseArrow(params) {
    if (this.match(14)) {
      return params.every((expr) => this.isAssignable(expr, true));
    }
    return super.shouldParseArrow(params);
  }
  shouldParseAsyncArrow() {
    return this.match(14) || super.shouldParseAsyncArrow();
  }
  canHaveLeadingDecorator() {
    return super.canHaveLeadingDecorator() || this.isAbstractClass();
  }
  jsxParseOpeningElementAfterName(node2) {
    if (this.match(47) || this.match(51)) {
      const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArgumentsInExpression());
      if (typeArguments)
        node2.typeParameters = typeArguments;
    }
    return super.jsxParseOpeningElementAfterName(node2);
  }
  getGetterSetterExpectedParamCount(method) {
    const baseCount = super.getGetterSetterExpectedParamCount(method);
    const params = this.getObjectOrClassMethodParams(method);
    const firstParam = params[0];
    const hasContextParam = firstParam && this.isThisParam(firstParam);
    return hasContextParam ? baseCount + 1 : baseCount;
  }
  parseCatchClauseParam() {
    const param = super.parseCatchClauseParam();
    const type = this.tsTryParseTypeAnnotation();
    if (type) {
      param.typeAnnotation = type;
      this.resetEndLocation(param);
    }
    return param;
  }
  tsInAmbientContext(cb) {
    const oldIsAmbientContext = this.state.isAmbientContext;
    this.state.isAmbientContext = true;
    try {
      return cb();
    } finally {
      this.state.isAmbientContext = oldIsAmbientContext;
    }
  }
  parseClass(node2, isStatement, optionalId) {
    const oldInAbstractClass = this.state.inAbstractClass;
    this.state.inAbstractClass = !!node2.abstract;
    try {
      return super.parseClass(node2, isStatement, optionalId);
    } finally {
      this.state.inAbstractClass = oldInAbstractClass;
    }
  }
  tsParseAbstractDeclaration(node2, decorators) {
    if (this.match(80)) {
      node2.abstract = true;
      return this.maybeTakeDecorators(decorators, this.parseClass(node2, true, false));
    } else if (this.isContextual(127)) {
      if (!this.hasFollowingLineBreak()) {
        node2.abstract = true;
        this.raise(TSErrors.NonClassMethodPropertyHasAbstractModifer, {
          at: node2
        });
        return this.tsParseInterfaceDeclaration(node2);
      }
    } else {
      this.unexpected(null, 80);
    }
  }
  parseMethod(node2, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope) {
    const method = super.parseMethod(node2, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
    if (method.abstract) {
      const hasBody = this.hasPlugin("estree") ? !!method.value.body : !!method.body;
      if (hasBody) {
        const {
          key
        } = method;
        this.raise(TSErrors.AbstractMethodHasImplementation, {
          at: method,
          methodName: key.type === "Identifier" && !method.computed ? key.name : `[${this.input.slice(key.start, key.end)}]`
        });
      }
    }
    return method;
  }
  tsParseTypeParameterName() {
    const typeName = this.parseIdentifier();
    return typeName.name;
  }
  shouldParseAsAmbientContext() {
    return !!this.getPluginOption("typescript", "dts");
  }
  parse() {
    if (this.shouldParseAsAmbientContext()) {
      this.state.isAmbientContext = true;
    }
    return super.parse();
  }
  getExpression() {
    if (this.shouldParseAsAmbientContext()) {
      this.state.isAmbientContext = true;
    }
    return super.getExpression();
  }
  parseExportSpecifier(node2, isString2, isInTypeExport, isMaybeTypeOnly) {
    if (!isString2 && isMaybeTypeOnly) {
      this.parseTypeOnlyImportExportSpecifier(node2, false, isInTypeExport);
      return this.finishNode(node2, "ExportSpecifier");
    }
    node2.exportKind = "value";
    return super.parseExportSpecifier(node2, isString2, isInTypeExport, isMaybeTypeOnly);
  }
  parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) {
    if (!importedIsString && isMaybeTypeOnly) {
      this.parseTypeOnlyImportExportSpecifier(specifier, true, isInTypeOnlyImport);
      return this.finishNode(specifier, "ImportSpecifier");
    }
    specifier.importKind = "value";
    return super.parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, isInTypeOnlyImport ? BIND_TS_TYPE_IMPORT : BIND_FLAGS_TS_IMPORT);
  }
  parseTypeOnlyImportExportSpecifier(node2, isImport, isInTypeOnlyImportExport) {
    const leftOfAsKey = isImport ? "imported" : "local";
    const rightOfAsKey = isImport ? "local" : "exported";
    let leftOfAs = node2[leftOfAsKey];
    let rightOfAs;
    let hasTypeSpecifier = false;
    let canParseAsKeyword = true;
    const loc = leftOfAs.loc.start;
    if (this.isContextual(93)) {
      const firstAs = this.parseIdentifier();
      if (this.isContextual(93)) {
        const secondAs = this.parseIdentifier();
        if (tokenIsKeywordOrIdentifier(this.state.type)) {
          hasTypeSpecifier = true;
          leftOfAs = firstAs;
          rightOfAs = isImport ? this.parseIdentifier() : this.parseModuleExportName();
          canParseAsKeyword = false;
        } else {
          rightOfAs = secondAs;
          canParseAsKeyword = false;
        }
      } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
        canParseAsKeyword = false;
        rightOfAs = isImport ? this.parseIdentifier() : this.parseModuleExportName();
      } else {
        hasTypeSpecifier = true;
        leftOfAs = firstAs;
      }
    } else if (tokenIsKeywordOrIdentifier(this.state.type)) {
      hasTypeSpecifier = true;
      if (isImport) {
        leftOfAs = this.parseIdentifier(true);
        if (!this.isContextual(93)) {
          this.checkReservedWord(leftOfAs.name, leftOfAs.loc.start, true, true);
        }
      } else {
        leftOfAs = this.parseModuleExportName();
      }
    }
    if (hasTypeSpecifier && isInTypeOnlyImportExport) {
      this.raise(isImport ? TSErrors.TypeModifierIsUsedInTypeImports : TSErrors.TypeModifierIsUsedInTypeExports, {
        at: loc
      });
    }
    node2[leftOfAsKey] = leftOfAs;
    node2[rightOfAsKey] = rightOfAs;
    const kindKey = isImport ? "importKind" : "exportKind";
    node2[kindKey] = hasTypeSpecifier ? "type" : "value";
    if (canParseAsKeyword && this.eatContextual(93)) {
      node2[rightOfAsKey] = isImport ? this.parseIdentifier() : this.parseModuleExportName();
    }
    if (!node2[rightOfAsKey]) {
      node2[rightOfAsKey] = cloneIdentifier(node2[leftOfAsKey]);
    }
    if (isImport) {
      this.checkIdentifier(node2[rightOfAsKey], hasTypeSpecifier ? BIND_TS_TYPE_IMPORT : BIND_FLAGS_TS_IMPORT);
    }
  }
};
function isPossiblyLiteralEnum(expression) {
  if (expression.type !== "MemberExpression")
    return false;
  const {
    computed: computed2,
    property
  } = expression;
  if (computed2 && property.type !== "StringLiteral" && (property.type !== "TemplateLiteral" || property.expressions.length > 0)) {
    return false;
  }
  return isUncomputedMemberExpressionChain(expression.object);
}
function isValidAmbientConstInitializer(expression, estree2) {
  var _expression$extra;
  const {
    type
  } = expression;
  if ((_expression$extra = expression.extra) != null && _expression$extra.parenthesized) {
    return false;
  }
  if (estree2) {
    if (type === "Literal") {
      const {
        value
      } = expression;
      if (typeof value === "string" || typeof value === "boolean") {
        return true;
      }
    }
  } else {
    if (type === "StringLiteral" || type === "BooleanLiteral") {
      return true;
    }
  }
  if (isNumber$1(expression, estree2) || isNegativeNumber(expression, estree2)) {
    return true;
  }
  if (type === "TemplateLiteral" && expression.expressions.length === 0) {
    return true;
  }
  if (isPossiblyLiteralEnum(expression)) {
    return true;
  }
  return false;
}
function isNumber$1(expression, estree2) {
  if (estree2) {
    return expression.type === "Literal" && (typeof expression.value === "number" || "bigint" in expression);
  } else {
    return expression.type === "NumericLiteral" || expression.type === "BigIntLiteral";
  }
}
function isNegativeNumber(expression, estree2) {
  if (expression.type === "UnaryExpression") {
    const {
      operator,
      argument
    } = expression;
    if (operator === "-" && isNumber$1(argument, estree2)) {
      return true;
    }
  }
  return false;
}
function isUncomputedMemberExpressionChain(expression) {
  if (expression.type === "Identifier")
    return true;
  if (expression.type !== "MemberExpression")
    return false;
  if (expression.computed)
    return false;
  return isUncomputedMemberExpressionChain(expression.object);
}
const PlaceholderErrors = ParseErrorEnum`placeholders`({
  ClassNameIsRequired: "A class name is required.",
  UnexpectedSpace: "Unexpected space in placeholder."
});
var placeholders = (superClass) => class PlaceholdersParserMixin extends superClass {
  parsePlaceholder(expectedNode) {
    if (this.match(142)) {
      const node2 = this.startNode();
      this.next();
      this.assertNoSpace();
      node2.name = super.parseIdentifier(true);
      this.assertNoSpace();
      this.expect(142);
      return this.finishPlaceholder(node2, expectedNode);
    }
  }
  finishPlaceholder(node2, expectedNode) {
    const isFinished = !!(node2.expectedNode && node2.type === "Placeholder");
    node2.expectedNode = expectedNode;
    return isFinished ? node2 : this.finishNode(node2, "Placeholder");
  }
  getTokenFromCode(code) {
    if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) {
      this.finishOp(142, 2);
    } else {
      super.getTokenFromCode(code);
    }
  }
  parseExprAtom(refExpressionErrors) {
    return this.parsePlaceholder("Expression") || super.parseExprAtom(refExpressionErrors);
  }
  parseIdentifier(liberal) {
    return this.parsePlaceholder("Identifier") || super.parseIdentifier(liberal);
  }
  checkReservedWord(word2, startLoc, checkKeywords, isBinding) {
    if (word2 !== void 0) {
      super.checkReservedWord(word2, startLoc, checkKeywords, isBinding);
    }
  }
  parseBindingAtom() {
    return this.parsePlaceholder("Pattern") || super.parseBindingAtom();
  }
  isValidLVal(type, isParenthesized, binding2) {
    return type === "Placeholder" || super.isValidLVal(type, isParenthesized, binding2);
  }
  toAssignable(node2, isLHS) {
    if (node2 && node2.type === "Placeholder" && node2.expectedNode === "Expression") {
      node2.expectedNode = "Pattern";
    } else {
      super.toAssignable(node2, isLHS);
    }
  }
  chStartsBindingIdentifier(ch, pos) {
    if (super.chStartsBindingIdentifier(ch, pos)) {
      return true;
    }
    const nextToken = this.lookahead();
    if (nextToken.type === 142) {
      return true;
    }
    return false;
  }
  verifyBreakContinue(node2, isBreak) {
    if (node2.label && node2.label.type === "Placeholder")
      return;
    super.verifyBreakContinue(node2, isBreak);
  }
  parseExpressionStatement(node2, expr) {
    if (expr.type !== "Placeholder" || expr.extra && expr.extra.parenthesized) {
      return super.parseExpressionStatement(node2, expr);
    }
    if (this.match(14)) {
      const stmt = node2;
      stmt.label = this.finishPlaceholder(expr, "Identifier");
      this.next();
      stmt.body = super.parseStatementOrSloppyAnnexBFunctionDeclaration();
      return this.finishNode(stmt, "LabeledStatement");
    }
    this.semicolon();
    node2.name = expr.name;
    return this.finishPlaceholder(node2, "Statement");
  }
  parseBlock(allowDirectives, createNewLexicalScope, afterBlockParse) {
    return this.parsePlaceholder("BlockStatement") || super.parseBlock(allowDirectives, createNewLexicalScope, afterBlockParse);
  }
  parseFunctionId(requireId) {
    return this.parsePlaceholder("Identifier") || super.parseFunctionId(requireId);
  }
  parseClass(node2, isStatement, optionalId) {
    const type = isStatement ? "ClassDeclaration" : "ClassExpression";
    this.next();
    const oldStrict = this.state.strict;
    const placeholder = this.parsePlaceholder("Identifier");
    if (placeholder) {
      if (this.match(81) || this.match(142) || this.match(5)) {
        node2.id = placeholder;
      } else if (optionalId || !isStatement) {
        node2.id = null;
        node2.body = this.finishPlaceholder(placeholder, "ClassBody");
        return this.finishNode(node2, type);
      } else {
        throw this.raise(PlaceholderErrors.ClassNameIsRequired, {
          at: this.state.startLoc
        });
      }
    } else {
      this.parseClassId(node2, isStatement, optionalId);
    }
    super.parseClassSuper(node2);
    node2.body = this.parsePlaceholder("ClassBody") || super.parseClassBody(!!node2.superClass, oldStrict);
    return this.finishNode(node2, type);
  }
  parseExport(node2, decorators) {
    const placeholder = this.parsePlaceholder("Identifier");
    if (!placeholder)
      return super.parseExport(node2, decorators);
    if (!this.isContextual(97) && !this.match(12)) {
      node2.specifiers = [];
      node2.source = null;
      node2.declaration = this.finishPlaceholder(placeholder, "Declaration");
      return this.finishNode(node2, "ExportNamedDeclaration");
    }
    this.expectPlugin("exportDefaultFrom");
    const specifier = this.startNode();
    specifier.exported = placeholder;
    node2.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
    return super.parseExport(node2, decorators);
  }
  isExportDefaultSpecifier() {
    if (this.match(65)) {
      const next = this.nextTokenStart();
      if (this.isUnparsedContextual(next, "from")) {
        if (this.input.startsWith(tokenLabelName(142), this.nextTokenStartSince(next + 4))) {
          return true;
        }
      }
    }
    return super.isExportDefaultSpecifier();
  }
  maybeParseExportDefaultSpecifier(node2) {
    if (node2.specifiers && node2.specifiers.length > 0) {
      return true;
    }
    return super.maybeParseExportDefaultSpecifier(node2);
  }
  checkExport(node2) {
    const {
      specifiers
    } = node2;
    if (specifiers != null && specifiers.length) {
      node2.specifiers = specifiers.filter((node3) => node3.exported.type === "Placeholder");
    }
    super.checkExport(node2);
    node2.specifiers = specifiers;
  }
  parseImport(node2) {
    const placeholder = this.parsePlaceholder("Identifier");
    if (!placeholder)
      return super.parseImport(node2);
    node2.specifiers = [];
    if (!this.isContextual(97) && !this.match(12)) {
      node2.source = this.finishPlaceholder(placeholder, "StringLiteral");
      this.semicolon();
      return this.finishNode(node2, "ImportDeclaration");
    }
    const specifier = this.startNodeAtNode(placeholder);
    specifier.local = placeholder;
    node2.specifiers.push(this.finishNode(specifier, "ImportDefaultSpecifier"));
    if (this.eat(12)) {
      const hasStarImport = this.maybeParseStarImportSpecifier(node2);
      if (!hasStarImport)
        this.parseNamedImportSpecifiers(node2);
    }
    this.expectContextual(97);
    node2.source = this.parseImportSource();
    this.semicolon();
    return this.finishNode(node2, "ImportDeclaration");
  }
  parseImportSource() {
    return this.parsePlaceholder("StringLiteral") || super.parseImportSource();
  }
  assertNoSpace() {
    if (this.state.start > this.state.lastTokEndLoc.index) {
      this.raise(PlaceholderErrors.UnexpectedSpace, {
        at: this.state.lastTokEndLoc
      });
    }
  }
};
var v8intrinsic = (superClass) => class V8IntrinsicMixin extends superClass {
  parseV8Intrinsic() {
    if (this.match(54)) {
      const v8IntrinsicStartLoc = this.state.startLoc;
      const node2 = this.startNode();
      this.next();
      if (tokenIsIdentifier(this.state.type)) {
        const name = this.parseIdentifierName();
        const identifier = this.createIdentifier(node2, name);
        identifier.type = "V8IntrinsicIdentifier";
        if (this.match(10)) {
          return identifier;
        }
      }
      this.unexpected(v8IntrinsicStartLoc);
    }
  }
  parseExprAtom(refExpressionErrors) {
    return this.parseV8Intrinsic() || super.parseExprAtom(refExpressionErrors);
  }
};
function hasPlugin(plugins, expectedConfig) {
  const [expectedName, expectedOptions] = typeof expectedConfig === "string" ? [expectedConfig, {}] : expectedConfig;
  const expectedKeys = Object.keys(expectedOptions);
  const expectedOptionsIsEmpty = expectedKeys.length === 0;
  return plugins.some((p2) => {
    if (typeof p2 === "string") {
      return expectedOptionsIsEmpty && p2 === expectedName;
    } else {
      const [pluginName, pluginOptions] = p2;
      if (pluginName !== expectedName) {
        return false;
      }
      for (const key of expectedKeys) {
        if (pluginOptions[key] !== expectedOptions[key]) {
          return false;
        }
      }
      return true;
    }
  });
}
function getPluginOption(plugins, name, option) {
  const plugin2 = plugins.find((plugin3) => {
    if (Array.isArray(plugin3)) {
      return plugin3[0] === name;
    } else {
      return plugin3 === name;
    }
  });
  if (plugin2 && Array.isArray(plugin2) && plugin2.length > 1) {
    return plugin2[1][option];
  }
  return null;
}
const PIPELINE_PROPOSALS = ["minimal", "fsharp", "hack", "smart"];
const TOPIC_TOKENS = ["^^", "@@", "^", "%", "#"];
const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"];
function validatePlugins(plugins) {
  if (hasPlugin(plugins, "decorators")) {
    if (hasPlugin(plugins, "decorators-legacy")) {
      throw new Error("Cannot use the decorators and decorators-legacy plugin together");
    }
    const decoratorsBeforeExport = getPluginOption(plugins, "decorators", "decoratorsBeforeExport");
    if (decoratorsBeforeExport != null && typeof decoratorsBeforeExport !== "boolean") {
      throw new Error("'decoratorsBeforeExport' must be a boolean, if specified.");
    }
    const allowCallParenthesized = getPluginOption(plugins, "decorators", "allowCallParenthesized");
    if (allowCallParenthesized != null && typeof allowCallParenthesized !== "boolean") {
      throw new Error("'allowCallParenthesized' must be a boolean.");
    }
  }
  if (hasPlugin(plugins, "flow") && hasPlugin(plugins, "typescript")) {
    throw new Error("Cannot combine flow and typescript plugins.");
  }
  if (hasPlugin(plugins, "placeholders") && hasPlugin(plugins, "v8intrinsic")) {
    throw new Error("Cannot combine placeholders and v8intrinsic plugins.");
  }
  if (hasPlugin(plugins, "pipelineOperator")) {
    const proposal = getPluginOption(plugins, "pipelineOperator", "proposal");
    if (!PIPELINE_PROPOSALS.includes(proposal)) {
      const proposalList = PIPELINE_PROPOSALS.map((p2) => `"${p2}"`).join(", ");
      throw new Error(`"pipelineOperator" requires "proposal" option whose value must be one of: ${proposalList}.`);
    }
    const tupleSyntaxIsHash = hasPlugin(plugins, ["recordAndTuple", {
      syntaxType: "hash"
    }]);
    if (proposal === "hack") {
      if (hasPlugin(plugins, "placeholders")) {
        throw new Error("Cannot combine placeholders plugin and Hack-style pipes.");
      }
      if (hasPlugin(plugins, "v8intrinsic")) {
        throw new Error("Cannot combine v8intrinsic plugin and Hack-style pipes.");
      }
      const topicToken = getPluginOption(plugins, "pipelineOperator", "topicToken");
      if (!TOPIC_TOKENS.includes(topicToken)) {
        const tokenList = TOPIC_TOKENS.map((t) => `"${t}"`).join(", ");
        throw new Error(`"pipelineOperator" in "proposal": "hack" mode also requires a "topicToken" option whose value must be one of: ${tokenList}.`);
      }
      if (topicToken === "#" && tupleSyntaxIsHash) {
        throw new Error('Plugin conflict between `["pipelineOperator", { proposal: "hack", topicToken: "#" }]` and `["recordAndtuple", { syntaxType: "hash"}]`.');
      }
    } else if (proposal === "smart" && tupleSyntaxIsHash) {
      throw new Error('Plugin conflict between `["pipelineOperator", { proposal: "smart" }]` and `["recordAndtuple", { syntaxType: "hash"}]`.');
    }
  }
  if (hasPlugin(plugins, "moduleAttributes")) {
    {
      if (hasPlugin(plugins, "importAssertions")) {
        throw new Error("Cannot combine importAssertions and moduleAttributes plugins.");
      }
      const moduleAttributesVersionPluginOption = getPluginOption(plugins, "moduleAttributes", "version");
      if (moduleAttributesVersionPluginOption !== "may-2020") {
        throw new Error("The 'moduleAttributes' plugin requires a 'version' option, representing the last proposal update. Currently, the only supported value is 'may-2020'.");
      }
    }
  }
  if (hasPlugin(plugins, "recordAndTuple") && getPluginOption(plugins, "recordAndTuple", "syntaxType") != null && !RECORD_AND_TUPLE_SYNTAX_TYPES.includes(getPluginOption(plugins, "recordAndTuple", "syntaxType"))) {
    throw new Error("The 'syntaxType' option of the 'recordAndTuple' plugin must be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map((p2) => `'${p2}'`).join(", "));
  }
  if (hasPlugin(plugins, "asyncDoExpressions") && !hasPlugin(plugins, "doExpressions")) {
    const error2 = new Error("'asyncDoExpressions' requires 'doExpressions', please add 'doExpressions' to parser plugins.");
    error2.missingPlugins = "doExpressions";
    throw error2;
  }
}
const mixinPlugins = {
  estree,
  jsx,
  flow,
  typescript,
  v8intrinsic,
  placeholders
};
const mixinPluginNames = Object.keys(mixinPlugins);
class ExpressionParser extends LValParser {
  checkProto(prop, isRecord, protoRef, refExpressionErrors) {
    if (prop.type === "SpreadElement" || this.isObjectMethod(prop) || prop.computed || prop.shorthand) {
      return;
    }
    const key = prop.key;
    const name = key.type === "Identifier" ? key.name : key.value;
    if (name === "__proto__") {
      if (isRecord) {
        this.raise(Errors.RecordNoProto, {
          at: key
        });
        return;
      }
      if (protoRef.used) {
        if (refExpressionErrors) {
          if (refExpressionErrors.doubleProtoLoc === null) {
            refExpressionErrors.doubleProtoLoc = key.loc.start;
          }
        } else {
          this.raise(Errors.DuplicateProto, {
            at: key
          });
        }
      }
      protoRef.used = true;
    }
  }
  shouldExitDescending(expr, potentialArrowAt) {
    return expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt;
  }
  getExpression() {
    this.enterInitialScopes();
    this.nextToken();
    const expr = this.parseExpression();
    if (!this.match(137)) {
      this.unexpected();
    }
    this.finalizeRemainingComments();
    expr.comments = this.state.comments;
    expr.errors = this.state.errors;
    if (this.options.tokens) {
      expr.tokens = this.tokens;
    }
    return expr;
  }
  parseExpression(disallowIn, refExpressionErrors) {
    if (disallowIn) {
      return this.disallowInAnd(() => this.parseExpressionBase(refExpressionErrors));
    }
    return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  }
  parseExpressionBase(refExpressionErrors) {
    const startLoc = this.state.startLoc;
    const expr = this.parseMaybeAssign(refExpressionErrors);
    if (this.match(12)) {
      const node2 = this.startNodeAt(startLoc);
      node2.expressions = [expr];
      while (this.eat(12)) {
        node2.expressions.push(this.parseMaybeAssign(refExpressionErrors));
      }
      this.toReferencedList(node2.expressions);
      return this.finishNode(node2, "SequenceExpression");
    }
    return expr;
  }
  parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse) {
    return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse));
  }
  parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse) {
    return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse));
  }
  setOptionalParametersError(refExpressionErrors, resultError) {
    var _resultError$loc;
    refExpressionErrors.optionalParametersLoc = (_resultError$loc = resultError == null ? void 0 : resultError.loc) != null ? _resultError$loc : this.state.startLoc;
  }
  parseMaybeAssign(refExpressionErrors, afterLeftParse) {
    const startLoc = this.state.startLoc;
    if (this.isContextual(106)) {
      if (this.prodParam.hasYield) {
        let left2 = this.parseYield();
        if (afterLeftParse) {
          left2 = afterLeftParse.call(this, left2, startLoc);
        }
        return left2;
      }
    }
    let ownExpressionErrors;
    if (refExpressionErrors) {
      ownExpressionErrors = false;
    } else {
      refExpressionErrors = new ExpressionErrors();
      ownExpressionErrors = true;
    }
    const {
      type
    } = this.state;
    if (type === 10 || tokenIsIdentifier(type)) {
      this.state.potentialArrowAt = this.state.start;
    }
    let left = this.parseMaybeConditional(refExpressionErrors);
    if (afterLeftParse) {
      left = afterLeftParse.call(this, left, startLoc);
    }
    if (tokenIsAssignment(this.state.type)) {
      const node2 = this.startNodeAt(startLoc);
      const operator = this.state.value;
      node2.operator = operator;
      if (this.match(29)) {
        this.toAssignable(left, true);
        node2.left = left;
        const startIndex = startLoc.index;
        if (refExpressionErrors.doubleProtoLoc != null && refExpressionErrors.doubleProtoLoc.index >= startIndex) {
          refExpressionErrors.doubleProtoLoc = null;
        }
        if (refExpressionErrors.shorthandAssignLoc != null && refExpressionErrors.shorthandAssignLoc.index >= startIndex) {
          refExpressionErrors.shorthandAssignLoc = null;
        }
        if (refExpressionErrors.privateKeyLoc != null && refExpressionErrors.privateKeyLoc.index >= startIndex) {
          this.checkDestructuringPrivate(refExpressionErrors);
          refExpressionErrors.privateKeyLoc = null;
        }
      } else {
        node2.left = left;
      }
      this.next();
      node2.right = this.parseMaybeAssign();
      this.checkLVal(left, {
        in: this.finishNode(node2, "AssignmentExpression")
      });
      return node2;
    } else if (ownExpressionErrors) {
      this.checkExpressionErrors(refExpressionErrors, true);
    }
    return left;
  }
  parseMaybeConditional(refExpressionErrors) {
    const startLoc = this.state.startLoc;
    const potentialArrowAt = this.state.potentialArrowAt;
    const expr = this.parseExprOps(refExpressionErrors);
    if (this.shouldExitDescending(expr, potentialArrowAt)) {
      return expr;
    }
    return this.parseConditional(expr, startLoc, refExpressionErrors);
  }
  parseConditional(expr, startLoc, refExpressionErrors) {
    if (this.eat(17)) {
      const node2 = this.startNodeAt(startLoc);
      node2.test = expr;
      node2.consequent = this.parseMaybeAssignAllowIn();
      this.expect(14);
      node2.alternate = this.parseMaybeAssign();
      return this.finishNode(node2, "ConditionalExpression");
    }
    return expr;
  }
  parseMaybeUnaryOrPrivate(refExpressionErrors) {
    return this.match(136) ? this.parsePrivateName() : this.parseMaybeUnary(refExpressionErrors);
  }
  parseExprOps(refExpressionErrors) {
    const startLoc = this.state.startLoc;
    const potentialArrowAt = this.state.potentialArrowAt;
    const expr = this.parseMaybeUnaryOrPrivate(refExpressionErrors);
    if (this.shouldExitDescending(expr, potentialArrowAt)) {
      return expr;
    }
    return this.parseExprOp(expr, startLoc, -1);
  }
  parseExprOp(left, leftStartLoc, minPrec) {
    if (this.isPrivateName(left)) {
      const value = this.getPrivateNameSV(left);
      if (minPrec >= tokenOperatorPrecedence(58) || !this.prodParam.hasIn || !this.match(58)) {
        this.raise(Errors.PrivateInExpectedIn, {
          at: left,
          identifierName: value
        });
      }
      this.classScope.usePrivateName(value, left.loc.start);
    }
    const op = this.state.type;
    if (tokenIsOperator(op) && (this.prodParam.hasIn || !this.match(58))) {
      let prec = tokenOperatorPrecedence(op);
      if (prec > minPrec) {
        if (op === 39) {
          this.expectPlugin("pipelineOperator");
          if (this.state.inFSharpPipelineDirectBody) {
            return left;
          }
          this.checkPipelineAtInfixOperator(left, leftStartLoc);
        }
        const node2 = this.startNodeAt(leftStartLoc);
        node2.left = left;
        node2.operator = this.state.value;
        const logical = op === 41 || op === 42;
        const coalesce2 = op === 40;
        if (coalesce2) {
          prec = tokenOperatorPrecedence(42);
        }
        this.next();
        if (op === 39 && this.hasPlugin(["pipelineOperator", {
          proposal: "minimal"
        }])) {
          if (this.state.type === 96 && this.prodParam.hasAwait) {
            throw this.raise(Errors.UnexpectedAwaitAfterPipelineBody, {
              at: this.state.startLoc
            });
          }
        }
        node2.right = this.parseExprOpRightExpr(op, prec);
        const finishedNode = this.finishNode(node2, logical || coalesce2 ? "LogicalExpression" : "BinaryExpression");
        const nextOp = this.state.type;
        if (coalesce2 && (nextOp === 41 || nextOp === 42) || logical && nextOp === 40) {
          throw this.raise(Errors.MixingCoalesceWithLogical, {
            at: this.state.startLoc
          });
        }
        return this.parseExprOp(finishedNode, leftStartLoc, minPrec);
      }
    }
    return left;
  }
  parseExprOpRightExpr(op, prec) {
    const startLoc = this.state.startLoc;
    switch (op) {
      case 39:
        switch (this.getPluginOption("pipelineOperator", "proposal")) {
          case "hack":
            return this.withTopicBindingContext(() => {
              return this.parseHackPipeBody();
            });
          case "smart":
            return this.withTopicBindingContext(() => {
              if (this.prodParam.hasYield && this.isContextual(106)) {
                throw this.raise(Errors.PipeBodyIsTighter, {
                  at: this.state.startLoc
                });
              }
              return this.parseSmartPipelineBodyInStyle(this.parseExprOpBaseRightExpr(op, prec), startLoc);
            });
          case "fsharp":
            return this.withSoloAwaitPermittingContext(() => {
              return this.parseFSharpPipelineBody(prec);
            });
        }
      default:
        return this.parseExprOpBaseRightExpr(op, prec);
    }
  }
  parseExprOpBaseRightExpr(op, prec) {
    const startLoc = this.state.startLoc;
    return this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startLoc, tokenIsRightAssociative(op) ? prec - 1 : prec);
  }
  parseHackPipeBody() {
    var _body$extra;
    const {
      startLoc
    } = this.state;
    const body = this.parseMaybeAssign();
    const requiredParentheses = UnparenthesizedPipeBodyDescriptions.has(body.type);
    if (requiredParentheses && !((_body$extra = body.extra) != null && _body$extra.parenthesized)) {
      this.raise(Errors.PipeUnparenthesizedBody, {
        at: startLoc,
        type: body.type
      });
    }
    if (!this.topicReferenceWasUsedInCurrentContext()) {
      this.raise(Errors.PipeTopicUnused, {
        at: startLoc
      });
    }
    return body;
  }
  checkExponentialAfterUnary(node2) {
    if (this.match(57)) {
      this.raise(Errors.UnexpectedTokenUnaryExponentiation, {
        at: node2.argument
      });
    }
  }
  parseMaybeUnary(refExpressionErrors, sawUnary) {
    const startLoc = this.state.startLoc;
    const isAwait = this.isContextual(96);
    if (isAwait && this.isAwaitAllowed()) {
      this.next();
      const expr2 = this.parseAwait(startLoc);
      if (!sawUnary)
        this.checkExponentialAfterUnary(expr2);
      return expr2;
    }
    const update = this.match(34);
    const node2 = this.startNode();
    if (tokenIsPrefix(this.state.type)) {
      node2.operator = this.state.value;
      node2.prefix = true;
      if (this.match(72)) {
        this.expectPlugin("throwExpressions");
      }
      const isDelete = this.match(89);
      this.next();
      node2.argument = this.parseMaybeUnary(null, true);
      this.checkExpressionErrors(refExpressionErrors, true);
      if (this.state.strict && isDelete) {
        const arg = node2.argument;
        if (arg.type === "Identifier") {
          this.raise(Errors.StrictDelete, {
            at: node2
          });
        } else if (this.hasPropertyAsPrivateName(arg)) {
          this.raise(Errors.DeletePrivateField, {
            at: node2
          });
        }
      }
      if (!update) {
        if (!sawUnary) {
          this.checkExponentialAfterUnary(node2);
        }
        return this.finishNode(node2, "UnaryExpression");
      }
    }
    const expr = this.parseUpdate(node2, update, refExpressionErrors);
    if (isAwait) {
      const {
        type
      } = this.state;
      const startsExpr2 = this.hasPlugin("v8intrinsic") ? tokenCanStartExpression(type) : tokenCanStartExpression(type) && !this.match(54);
      if (startsExpr2 && !this.isAmbiguousAwait()) {
        this.raiseOverwrite(Errors.AwaitNotInAsyncContext, {
          at: startLoc
        });
        return this.parseAwait(startLoc);
      }
    }
    return expr;
  }
  parseUpdate(node2, update, refExpressionErrors) {
    if (update) {
      const updateExpressionNode = node2;
      this.checkLVal(updateExpressionNode.argument, {
        in: this.finishNode(updateExpressionNode, "UpdateExpression")
      });
      return node2;
    }
    const startLoc = this.state.startLoc;
    let expr = this.parseExprSubscripts(refExpressionErrors);
    if (this.checkExpressionErrors(refExpressionErrors, false))
      return expr;
    while (tokenIsPostfix(this.state.type) && !this.canInsertSemicolon()) {
      const node3 = this.startNodeAt(startLoc);
      node3.operator = this.state.value;
      node3.prefix = false;
      node3.argument = expr;
      this.next();
      this.checkLVal(expr, {
        in: expr = this.finishNode(node3, "UpdateExpression")
      });
    }
    return expr;
  }
  parseExprSubscripts(refExpressionErrors) {
    const startLoc = this.state.startLoc;
    const potentialArrowAt = this.state.potentialArrowAt;
    const expr = this.parseExprAtom(refExpressionErrors);
    if (this.shouldExitDescending(expr, potentialArrowAt)) {
      return expr;
    }
    return this.parseSubscripts(expr, startLoc);
  }
  parseSubscripts(base2, startLoc, noCalls) {
    const state = {
      optionalChainMember: false,
      maybeAsyncArrow: this.atPossibleAsyncArrow(base2),
      stop: false
    };
    do {
      base2 = this.parseSubscript(base2, startLoc, noCalls, state);
      state.maybeAsyncArrow = false;
    } while (!state.stop);
    return base2;
  }
  parseSubscript(base2, startLoc, noCalls, state) {
    const {
      type
    } = this.state;
    if (!noCalls && type === 15) {
      return this.parseBind(base2, startLoc, noCalls, state);
    } else if (tokenIsTemplate(type)) {
      return this.parseTaggedTemplateExpression(base2, startLoc, state);
    }
    let optional = false;
    if (type === 18) {
      if (noCalls) {
        this.raise(Errors.OptionalChainingNoNew, {
          at: this.state.startLoc
        });
        if (this.lookaheadCharCode() === 40) {
          state.stop = true;
          return base2;
        }
      }
      state.optionalChainMember = optional = true;
      this.next();
    }
    if (!noCalls && this.match(10)) {
      return this.parseCoverCallAndAsyncArrowHead(base2, startLoc, state, optional);
    } else {
      const computed2 = this.eat(0);
      if (computed2 || optional || this.eat(16)) {
        return this.parseMember(base2, startLoc, state, computed2, optional);
      } else {
        state.stop = true;
        return base2;
      }
    }
  }
  parseMember(base2, startLoc, state, computed2, optional) {
    const node2 = this.startNodeAt(startLoc);
    node2.object = base2;
    node2.computed = computed2;
    if (computed2) {
      node2.property = this.parseExpression();
      this.expect(3);
    } else if (this.match(136)) {
      if (base2.type === "Super") {
        this.raise(Errors.SuperPrivateField, {
          at: startLoc
        });
      }
      this.classScope.usePrivateName(this.state.value, this.state.startLoc);
      node2.property = this.parsePrivateName();
    } else {
      node2.property = this.parseIdentifier(true);
    }
    if (state.optionalChainMember) {
      node2.optional = optional;
      return this.finishNode(node2, "OptionalMemberExpression");
    } else {
      return this.finishNode(node2, "MemberExpression");
    }
  }
  parseBind(base2, startLoc, noCalls, state) {
    const node2 = this.startNodeAt(startLoc);
    node2.object = base2;
    this.next();
    node2.callee = this.parseNoCallExpr();
    state.stop = true;
    return this.parseSubscripts(this.finishNode(node2, "BindExpression"), startLoc, noCalls);
  }
  parseCoverCallAndAsyncArrowHead(base2, startLoc, state, optional) {
    const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
    let refExpressionErrors = null;
    this.state.maybeInArrowParameters = true;
    this.next();
    const node2 = this.startNodeAt(startLoc);
    node2.callee = base2;
    const {
      maybeAsyncArrow,
      optionalChainMember
    } = state;
    if (maybeAsyncArrow) {
      this.expressionScope.enter(newAsyncArrowScope());
      refExpressionErrors = new ExpressionErrors();
    }
    if (optionalChainMember) {
      node2.optional = optional;
    }
    if (optional) {
      node2.arguments = this.parseCallExpressionArguments(11);
    } else {
      node2.arguments = this.parseCallExpressionArguments(11, base2.type === "Import", base2.type !== "Super", node2, refExpressionErrors);
    }
    let finishedNode = this.finishCallExpression(node2, optionalChainMember);
    if (maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) {
      state.stop = true;
      this.checkDestructuringPrivate(refExpressionErrors);
      this.expressionScope.validateAsPattern();
      this.expressionScope.exit();
      finishedNode = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startLoc), finishedNode);
    } else {
      if (maybeAsyncArrow) {
        this.checkExpressionErrors(refExpressionErrors, true);
        this.expressionScope.exit();
      }
      this.toReferencedArguments(finishedNode);
    }
    this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
    return finishedNode;
  }
  toReferencedArguments(node2, isParenthesizedExpr) {
    this.toReferencedListDeep(node2.arguments, isParenthesizedExpr);
  }
  parseTaggedTemplateExpression(base2, startLoc, state) {
    const node2 = this.startNodeAt(startLoc);
    node2.tag = base2;
    node2.quasi = this.parseTemplate(true);
    if (state.optionalChainMember) {
      this.raise(Errors.OptionalChainingNoTemplate, {
        at: startLoc
      });
    }
    return this.finishNode(node2, "TaggedTemplateExpression");
  }
  atPossibleAsyncArrow(base2) {
    return base2.type === "Identifier" && base2.name === "async" && this.state.lastTokEndLoc.index === base2.end && !this.canInsertSemicolon() && base2.end - base2.start === 5 && base2.start === this.state.potentialArrowAt;
  }
  finishCallExpression(node2, optional) {
    if (node2.callee.type === "Import") {
      if (node2.arguments.length === 2) {
        {
          if (!this.hasPlugin("moduleAttributes")) {
            this.expectPlugin("importAssertions");
          }
        }
      }
      if (node2.arguments.length === 0 || node2.arguments.length > 2) {
        this.raise(Errors.ImportCallArity, {
          at: node2,
          maxArgumentCount: this.hasPlugin("importAssertions") || this.hasPlugin("moduleAttributes") ? 2 : 1
        });
      } else {
        for (const arg of node2.arguments) {
          if (arg.type === "SpreadElement") {
            this.raise(Errors.ImportCallSpreadArgument, {
              at: arg
            });
          }
        }
      }
    }
    return this.finishNode(node2, optional ? "OptionalCallExpression" : "CallExpression");
  }
  parseCallExpressionArguments(close, dynamicImport, allowPlaceholder, nodeForExtra, refExpressionErrors) {
    const elts = [];
    let first2 = true;
    const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
    this.state.inFSharpPipelineDirectBody = false;
    while (!this.eat(close)) {
      if (first2) {
        first2 = false;
      } else {
        this.expect(12);
        if (this.match(close)) {
          if (dynamicImport && !this.hasPlugin("importAssertions") && !this.hasPlugin("moduleAttributes")) {
            this.raise(Errors.ImportCallArgumentTrailingComma, {
              at: this.state.lastTokStartLoc
            });
          }
          if (nodeForExtra) {
            this.addTrailingCommaExtraToNode(nodeForExtra);
          }
          this.next();
          break;
        }
      }
      elts.push(this.parseExprListItem(false, refExpressionErrors, allowPlaceholder));
    }
    this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
    return elts;
  }
  shouldParseAsyncArrow() {
    return this.match(19) && !this.canInsertSemicolon();
  }
  parseAsyncArrowFromCallExpression(node2, call) {
    var _call$extra;
    this.resetPreviousNodeTrailingComments(call);
    this.expect(19);
    this.parseArrowExpression(node2, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingCommaLoc);
    if (call.innerComments) {
      setInnerComments(node2, call.innerComments);
    }
    if (call.callee.trailingComments) {
      setInnerComments(node2, call.callee.trailingComments);
    }
    return node2;
  }
  parseNoCallExpr() {
    const startLoc = this.state.startLoc;
    return this.parseSubscripts(this.parseExprAtom(), startLoc, true);
  }
  parseExprAtom(refExpressionErrors) {
    let node2;
    let decorators = null;
    const {
      type
    } = this.state;
    switch (type) {
      case 79:
        return this.parseSuper();
      case 83:
        node2 = this.startNode();
        this.next();
        if (this.match(16)) {
          return this.parseImportMetaProperty(node2);
        }
        if (!this.match(10)) {
          this.raise(Errors.UnsupportedImport, {
            at: this.state.lastTokStartLoc
          });
        }
        return this.finishNode(node2, "Import");
      case 78:
        node2 = this.startNode();
        this.next();
        return this.finishNode(node2, "ThisExpression");
      case 90: {
        return this.parseDo(this.startNode(), false);
      }
      case 56:
      case 31: {
        this.readRegexp();
        return this.parseRegExpLiteral(this.state.value);
      }
      case 132:
        return this.parseNumericLiteral(this.state.value);
      case 133:
        return this.parseBigIntLiteral(this.state.value);
      case 134:
        return this.parseDecimalLiteral(this.state.value);
      case 131:
        return this.parseStringLiteral(this.state.value);
      case 84:
        return this.parseNullLiteral();
      case 85:
        return this.parseBooleanLiteral(true);
      case 86:
        return this.parseBooleanLiteral(false);
      case 10: {
        const canBeArrow = this.state.potentialArrowAt === this.state.start;
        return this.parseParenAndDistinguishExpression(canBeArrow);
      }
      case 2:
      case 1: {
        return this.parseArrayLike(this.state.type === 2 ? 4 : 3, false, true);
      }
      case 0: {
        return this.parseArrayLike(3, true, false, refExpressionErrors);
      }
      case 6:
      case 7: {
        return this.parseObjectLike(this.state.type === 6 ? 9 : 8, false, true);
      }
      case 5: {
        return this.parseObjectLike(8, false, false, refExpressionErrors);
      }
      case 68:
        return this.parseFunctionOrFunctionSent();
      case 26:
        decorators = this.parseDecorators();
      case 80:
        return this.parseClass(this.maybeTakeDecorators(decorators, this.startNode()), false);
      case 77:
        return this.parseNewOrNewTarget();
      case 25:
      case 24:
        return this.parseTemplate(false);
      case 15: {
        node2 = this.startNode();
        this.next();
        node2.object = null;
        const callee = node2.callee = this.parseNoCallExpr();
        if (callee.type === "MemberExpression") {
          return this.finishNode(node2, "BindExpression");
        } else {
          throw this.raise(Errors.UnsupportedBind, {
            at: callee
          });
        }
      }
      case 136: {
        this.raise(Errors.PrivateInExpectedIn, {
          at: this.state.startLoc,
          identifierName: this.state.value
        });
        return this.parsePrivateName();
      }
      case 33: {
        return this.parseTopicReferenceThenEqualsSign(54, "%");
      }
      case 32: {
        return this.parseTopicReferenceThenEqualsSign(44, "^");
      }
      case 37:
      case 38: {
        return this.parseTopicReference("hack");
      }
      case 44:
      case 54:
      case 27: {
        const pipeProposal = this.getPluginOption("pipelineOperator", "proposal");
        if (pipeProposal) {
          return this.parseTopicReference(pipeProposal);
        }
        this.unexpected();
        break;
      }
      case 47: {
        const lookaheadCh = this.input.codePointAt(this.nextTokenStart());
        if (isIdentifierStart(lookaheadCh) || lookaheadCh === 62) {
          this.expectOnePlugin(["jsx", "flow", "typescript"]);
        } else {
          this.unexpected();
        }
        break;
      }
      default:
        if (tokenIsIdentifier(type)) {
          if (this.isContextual(125) && this.lookaheadCharCode() === 123 && !this.hasFollowingLineBreak()) {
            return this.parseModuleExpression();
          }
          const canBeArrow = this.state.potentialArrowAt === this.state.start;
          const containsEsc = this.state.containsEsc;
          const id3 = this.parseIdentifier();
          if (!containsEsc && id3.name === "async" && !this.canInsertSemicolon()) {
            const {
              type: type2
            } = this.state;
            if (type2 === 68) {
              this.resetPreviousNodeTrailingComments(id3);
              this.next();
              return this.parseAsyncFunctionExpression(this.startNodeAtNode(id3));
            } else if (tokenIsIdentifier(type2)) {
              if (this.lookaheadCharCode() === 61) {
                return this.parseAsyncArrowUnaryFunction(this.startNodeAtNode(id3));
              } else {
                return id3;
              }
            } else if (type2 === 90) {
              this.resetPreviousNodeTrailingComments(id3);
              return this.parseDo(this.startNodeAtNode(id3), true);
            }
          }
          if (canBeArrow && this.match(19) && !this.canInsertSemicolon()) {
            this.next();
            return this.parseArrowExpression(this.startNodeAtNode(id3), [id3], false);
          }
          return id3;
        } else {
          this.unexpected();
        }
    }
  }
  parseTopicReferenceThenEqualsSign(topicTokenType, topicTokenValue) {
    const pipeProposal = this.getPluginOption("pipelineOperator", "proposal");
    if (pipeProposal) {
      this.state.type = topicTokenType;
      this.state.value = topicTokenValue;
      this.state.pos--;
      this.state.end--;
      this.state.endLoc = createPositionWithColumnOffset(this.state.endLoc, -1);
      return this.parseTopicReference(pipeProposal);
    } else {
      this.unexpected();
    }
  }
  parseTopicReference(pipeProposal) {
    const node2 = this.startNode();
    const startLoc = this.state.startLoc;
    const tokenType = this.state.type;
    this.next();
    return this.finishTopicReference(node2, startLoc, pipeProposal, tokenType);
  }
  finishTopicReference(node2, startLoc, pipeProposal, tokenType) {
    if (this.testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType)) {
      const nodeType = pipeProposal === "smart" ? "PipelinePrimaryTopicReference" : "TopicReference";
      if (!this.topicReferenceIsAllowedInCurrentContext()) {
        this.raise(pipeProposal === "smart" ? Errors.PrimaryTopicNotAllowed : Errors.PipeTopicUnbound, {
          at: startLoc
        });
      }
      this.registerTopicReference();
      return this.finishNode(node2, nodeType);
    } else {
      throw this.raise(Errors.PipeTopicUnconfiguredToken, {
        at: startLoc,
        token: tokenLabelName(tokenType)
      });
    }
  }
  testTopicReferenceConfiguration(pipeProposal, startLoc, tokenType) {
    switch (pipeProposal) {
      case "hack": {
        return this.hasPlugin(["pipelineOperator", {
          topicToken: tokenLabelName(tokenType)
        }]);
      }
      case "smart":
        return tokenType === 27;
      default:
        throw this.raise(Errors.PipeTopicRequiresHackPipes, {
          at: startLoc
        });
    }
  }
  parseAsyncArrowUnaryFunction(node2) {
    this.prodParam.enter(functionFlags(true, this.prodParam.hasYield));
    const params = [this.parseIdentifier()];
    this.prodParam.exit();
    if (this.hasPrecedingLineBreak()) {
      this.raise(Errors.LineTerminatorBeforeArrow, {
        at: this.state.curPosition()
      });
    }
    this.expect(19);
    return this.parseArrowExpression(node2, params, true);
  }
  parseDo(node2, isAsync) {
    this.expectPlugin("doExpressions");
    if (isAsync) {
      this.expectPlugin("asyncDoExpressions");
    }
    node2.async = isAsync;
    this.next();
    const oldLabels = this.state.labels;
    this.state.labels = [];
    if (isAsync) {
      this.prodParam.enter(PARAM_AWAIT);
      node2.body = this.parseBlock();
      this.prodParam.exit();
    } else {
      node2.body = this.parseBlock();
    }
    this.state.labels = oldLabels;
    return this.finishNode(node2, "DoExpression");
  }
  parseSuper() {
    const node2 = this.startNode();
    this.next();
    if (this.match(10) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) {
      this.raise(Errors.SuperNotAllowed, {
        at: node2
      });
    } else if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) {
      this.raise(Errors.UnexpectedSuper, {
        at: node2
      });
    }
    if (!this.match(10) && !this.match(0) && !this.match(16)) {
      this.raise(Errors.UnsupportedSuper, {
        at: node2
      });
    }
    return this.finishNode(node2, "Super");
  }
  parsePrivateName() {
    const node2 = this.startNode();
    const id3 = this.startNodeAt(createPositionWithColumnOffset(this.state.startLoc, 1));
    const name = this.state.value;
    this.next();
    node2.id = this.createIdentifier(id3, name);
    return this.finishNode(node2, "PrivateName");
  }
  parseFunctionOrFunctionSent() {
    const node2 = this.startNode();
    this.next();
    if (this.prodParam.hasYield && this.match(16)) {
      const meta = this.createIdentifier(this.startNodeAtNode(node2), "function");
      this.next();
      if (this.match(102)) {
        this.expectPlugin("functionSent");
      } else if (!this.hasPlugin("functionSent")) {
        this.unexpected();
      }
      return this.parseMetaProperty(node2, meta, "sent");
    }
    return this.parseFunction(node2);
  }
  parseMetaProperty(node2, meta, propertyName) {
    node2.meta = meta;
    const containsEsc = this.state.containsEsc;
    node2.property = this.parseIdentifier(true);
    if (node2.property.name !== propertyName || containsEsc) {
      this.raise(Errors.UnsupportedMetaProperty, {
        at: node2.property,
        target: meta.name,
        onlyValidPropertyName: propertyName
      });
    }
    return this.finishNode(node2, "MetaProperty");
  }
  parseImportMetaProperty(node2) {
    const id3 = this.createIdentifier(this.startNodeAtNode(node2), "import");
    this.next();
    if (this.isContextual(100)) {
      if (!this.inModule) {
        this.raise(Errors.ImportMetaOutsideModule, {
          at: id3
        });
      }
      this.sawUnambiguousESM = true;
    }
    return this.parseMetaProperty(node2, id3, "meta");
  }
  parseLiteralAtNode(value, type, node2) {
    this.addExtra(node2, "rawValue", value);
    this.addExtra(node2, "raw", this.input.slice(node2.start, this.state.end));
    node2.value = value;
    this.next();
    return this.finishNode(node2, type);
  }
  parseLiteral(value, type) {
    const node2 = this.startNode();
    return this.parseLiteralAtNode(value, type, node2);
  }
  parseStringLiteral(value) {
    return this.parseLiteral(value, "StringLiteral");
  }
  parseNumericLiteral(value) {
    return this.parseLiteral(value, "NumericLiteral");
  }
  parseBigIntLiteral(value) {
    return this.parseLiteral(value, "BigIntLiteral");
  }
  parseDecimalLiteral(value) {
    return this.parseLiteral(value, "DecimalLiteral");
  }
  parseRegExpLiteral(value) {
    const node2 = this.parseLiteral(value.value, "RegExpLiteral");
    node2.pattern = value.pattern;
    node2.flags = value.flags;
    return node2;
  }
  parseBooleanLiteral(value) {
    const node2 = this.startNode();
    node2.value = value;
    this.next();
    return this.finishNode(node2, "BooleanLiteral");
  }
  parseNullLiteral() {
    const node2 = this.startNode();
    this.next();
    return this.finishNode(node2, "NullLiteral");
  }
  parseParenAndDistinguishExpression(canBeArrow) {
    const startLoc = this.state.startLoc;
    let val;
    this.next();
    this.expressionScope.enter(newArrowHeadScope());
    const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
    const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
    this.state.maybeInArrowParameters = true;
    this.state.inFSharpPipelineDirectBody = false;
    const innerStartLoc = this.state.startLoc;
    const exprList = [];
    const refExpressionErrors = new ExpressionErrors();
    let first2 = true;
    let spreadStartLoc;
    let optionalCommaStartLoc;
    while (!this.match(11)) {
      if (first2) {
        first2 = false;
      } else {
        this.expect(12, refExpressionErrors.optionalParametersLoc === null ? null : refExpressionErrors.optionalParametersLoc);
        if (this.match(11)) {
          optionalCommaStartLoc = this.state.startLoc;
          break;
        }
      }
      if (this.match(21)) {
        const spreadNodeStartLoc = this.state.startLoc;
        spreadStartLoc = this.state.startLoc;
        exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartLoc));
        if (!this.checkCommaAfterRest(41)) {
          break;
        }
      } else {
        exprList.push(this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem));
      }
    }
    const innerEndLoc = this.state.lastTokEndLoc;
    this.expect(11);
    this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
    this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
    let arrowNode = this.startNodeAt(startLoc);
    if (canBeArrow && this.shouldParseArrow(exprList) && (arrowNode = this.parseArrow(arrowNode))) {
      this.checkDestructuringPrivate(refExpressionErrors);
      this.expressionScope.validateAsPattern();
      this.expressionScope.exit();
      this.parseArrowExpression(arrowNode, exprList, false);
      return arrowNode;
    }
    this.expressionScope.exit();
    if (!exprList.length) {
      this.unexpected(this.state.lastTokStartLoc);
    }
    if (optionalCommaStartLoc)
      this.unexpected(optionalCommaStartLoc);
    if (spreadStartLoc)
      this.unexpected(spreadStartLoc);
    this.checkExpressionErrors(refExpressionErrors, true);
    this.toReferencedListDeep(exprList, true);
    if (exprList.length > 1) {
      val = this.startNodeAt(innerStartLoc);
      val.expressions = exprList;
      this.finishNode(val, "SequenceExpression");
      this.resetEndLocation(val, innerEndLoc);
    } else {
      val = exprList[0];
    }
    return this.wrapParenthesis(startLoc, val);
  }
  wrapParenthesis(startLoc, expression) {
    if (!this.options.createParenthesizedExpressions) {
      this.addExtra(expression, "parenthesized", true);
      this.addExtra(expression, "parenStart", startLoc.index);
      this.takeSurroundingComments(expression, startLoc.index, this.state.lastTokEndLoc.index);
      return expression;
    }
    const parenExpression = this.startNodeAt(startLoc);
    parenExpression.expression = expression;
    return this.finishNode(parenExpression, "ParenthesizedExpression");
  }
  shouldParseArrow(params) {
    return !this.canInsertSemicolon();
  }
  parseArrow(node2) {
    if (this.eat(19)) {
      return node2;
    }
  }
  parseParenItem(node2, startLoc) {
    return node2;
  }
  parseNewOrNewTarget() {
    const node2 = this.startNode();
    this.next();
    if (this.match(16)) {
      const meta = this.createIdentifier(this.startNodeAtNode(node2), "new");
      this.next();
      const metaProp = this.parseMetaProperty(node2, meta, "target");
      if (!this.scope.inNonArrowFunction && !this.scope.inClass && !this.options.allowNewTargetOutsideFunction) {
        this.raise(Errors.UnexpectedNewTarget, {
          at: metaProp
        });
      }
      return metaProp;
    }
    return this.parseNew(node2);
  }
  parseNew(node2) {
    this.parseNewCallee(node2);
    if (this.eat(10)) {
      const args = this.parseExprList(11);
      this.toReferencedList(args);
      node2.arguments = args;
    } else {
      node2.arguments = [];
    }
    return this.finishNode(node2, "NewExpression");
  }
  parseNewCallee(node2) {
    node2.callee = this.parseNoCallExpr();
    if (node2.callee.type === "Import") {
      this.raise(Errors.ImportCallNotNewExpression, {
        at: node2.callee
      });
    }
  }
  parseTemplateElement(isTagged) {
    const {
      start,
      startLoc,
      end,
      value
    } = this.state;
    const elemStart = start + 1;
    const elem = this.startNodeAt(createPositionWithColumnOffset(startLoc, 1));
    if (value === null) {
      if (!isTagged) {
        this.raise(Errors.InvalidEscapeSequenceTemplate, {
          at: createPositionWithColumnOffset(this.state.firstInvalidTemplateEscapePos, 1)
        });
      }
    }
    const isTail = this.match(24);
    const endOffset = isTail ? -1 : -2;
    const elemEnd = end + endOffset;
    elem.value = {
      raw: this.input.slice(elemStart, elemEnd).replace(/\r\n?/g, "\n"),
      cooked: value === null ? null : value.slice(1, endOffset)
    };
    elem.tail = isTail;
    this.next();
    const finishedNode = this.finishNode(elem, "TemplateElement");
    this.resetEndLocation(finishedNode, createPositionWithColumnOffset(this.state.lastTokEndLoc, endOffset));
    return finishedNode;
  }
  parseTemplate(isTagged) {
    const node2 = this.startNode();
    node2.expressions = [];
    let curElt = this.parseTemplateElement(isTagged);
    node2.quasis = [curElt];
    while (!curElt.tail) {
      node2.expressions.push(this.parseTemplateSubstitution());
      this.readTemplateContinuation();
      node2.quasis.push(curElt = this.parseTemplateElement(isTagged));
    }
    return this.finishNode(node2, "TemplateLiteral");
  }
  parseTemplateSubstitution() {
    return this.parseExpression();
  }
  parseObjectLike(close, isPattern, isRecord, refExpressionErrors) {
    if (isRecord) {
      this.expectPlugin("recordAndTuple");
    }
    const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
    this.state.inFSharpPipelineDirectBody = false;
    const propHash = /* @__PURE__ */ Object.create(null);
    let first2 = true;
    const node2 = this.startNode();
    node2.properties = [];
    this.next();
    while (!this.match(close)) {
      if (first2) {
        first2 = false;
      } else {
        this.expect(12);
        if (this.match(close)) {
          this.addTrailingCommaExtraToNode(node2);
          break;
        }
      }
      let prop;
      if (isPattern) {
        prop = this.parseBindingProperty();
      } else {
        prop = this.parsePropertyDefinition(refExpressionErrors);
        this.checkProto(prop, isRecord, propHash, refExpressionErrors);
      }
      if (isRecord && !this.isObjectProperty(prop) && prop.type !== "SpreadElement") {
        this.raise(Errors.InvalidRecordProperty, {
          at: prop
        });
      }
      if (prop.shorthand) {
        this.addExtra(prop, "shorthand", true);
      }
      node2.properties.push(prop);
    }
    this.next();
    this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
    let type = "ObjectExpression";
    if (isPattern) {
      type = "ObjectPattern";
    } else if (isRecord) {
      type = "RecordExpression";
    }
    return this.finishNode(node2, type);
  }
  addTrailingCommaExtraToNode(node2) {
    this.addExtra(node2, "trailingComma", this.state.lastTokStart);
    this.addExtra(node2, "trailingCommaLoc", this.state.lastTokStartLoc, false);
  }
  maybeAsyncOrAccessorProp(prop) {
    return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(0) || this.match(55));
  }
  parsePropertyDefinition(refExpressionErrors) {
    let decorators = [];
    if (this.match(26)) {
      if (this.hasPlugin("decorators")) {
        this.raise(Errors.UnsupportedPropertyDecorator, {
          at: this.state.startLoc
        });
      }
      while (this.match(26)) {
        decorators.push(this.parseDecorator());
      }
    }
    const prop = this.startNode();
    let isAsync = false;
    let isAccessor = false;
    let startLoc;
    if (this.match(21)) {
      if (decorators.length)
        this.unexpected();
      return this.parseSpread();
    }
    if (decorators.length) {
      prop.decorators = decorators;
      decorators = [];
    }
    prop.method = false;
    if (refExpressionErrors) {
      startLoc = this.state.startLoc;
    }
    let isGenerator = this.eat(55);
    this.parsePropertyNamePrefixOperator(prop);
    const containsEsc = this.state.containsEsc;
    const key = this.parsePropertyName(prop, refExpressionErrors);
    if (!isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) {
      const keyName = key.name;
      if (keyName === "async" && !this.hasPrecedingLineBreak()) {
        isAsync = true;
        this.resetPreviousNodeTrailingComments(key);
        isGenerator = this.eat(55);
        this.parsePropertyName(prop);
      }
      if (keyName === "get" || keyName === "set") {
        isAccessor = true;
        this.resetPreviousNodeTrailingComments(key);
        prop.kind = keyName;
        if (this.match(55)) {
          isGenerator = true;
          this.raise(Errors.AccessorIsGenerator, {
            at: this.state.curPosition(),
            kind: keyName
          });
          this.next();
        }
        this.parsePropertyName(prop);
      }
    }
    return this.parseObjPropValue(prop, startLoc, isGenerator, isAsync, false, isAccessor, refExpressionErrors);
  }
  getGetterSetterExpectedParamCount(method) {
    return method.kind === "get" ? 0 : 1;
  }
  getObjectOrClassMethodParams(method) {
    return method.params;
  }
  checkGetterSetterParams(method) {
    var _params;
    const paramCount = this.getGetterSetterExpectedParamCount(method);
    const params = this.getObjectOrClassMethodParams(method);
    if (params.length !== paramCount) {
      this.raise(method.kind === "get" ? Errors.BadGetterArity : Errors.BadSetterArity, {
        at: method
      });
    }
    if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") {
      this.raise(Errors.BadSetterRestParameter, {
        at: method
      });
    }
  }
  parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
    if (isAccessor) {
      const finishedProp = this.parseMethod(prop, isGenerator, false, false, false, "ObjectMethod");
      this.checkGetterSetterParams(finishedProp);
      return finishedProp;
    }
    if (isAsync || isGenerator || this.match(10)) {
      if (isPattern)
        this.unexpected();
      prop.kind = "method";
      prop.method = true;
      return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod");
    }
  }
  parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors) {
    prop.shorthand = false;
    if (this.eat(14)) {
      prop.value = isPattern ? this.parseMaybeDefault(this.state.startLoc) : this.parseMaybeAssignAllowIn(refExpressionErrors);
      return this.finishNode(prop, "ObjectProperty");
    }
    if (!prop.computed && prop.key.type === "Identifier") {
      this.checkReservedWord(prop.key.name, prop.key.loc.start, true, false);
      if (isPattern) {
        prop.value = this.parseMaybeDefault(startLoc, cloneIdentifier(prop.key));
      } else if (this.match(29)) {
        const shorthandAssignLoc = this.state.startLoc;
        if (refExpressionErrors != null) {
          if (refExpressionErrors.shorthandAssignLoc === null) {
            refExpressionErrors.shorthandAssignLoc = shorthandAssignLoc;
          }
        } else {
          this.raise(Errors.InvalidCoverInitializedName, {
            at: shorthandAssignLoc
          });
        }
        prop.value = this.parseMaybeDefault(startLoc, cloneIdentifier(prop.key));
      } else {
        prop.value = cloneIdentifier(prop.key);
      }
      prop.shorthand = true;
      return this.finishNode(prop, "ObjectProperty");
    }
  }
  parseObjPropValue(prop, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
    const node2 = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) || this.parseObjectProperty(prop, startLoc, isPattern, refExpressionErrors);
    if (!node2)
      this.unexpected();
    return node2;
  }
  parsePropertyName(prop, refExpressionErrors) {
    if (this.eat(0)) {
      prop.computed = true;
      prop.key = this.parseMaybeAssignAllowIn();
      this.expect(3);
    } else {
      const {
        type,
        value
      } = this.state;
      let key;
      if (tokenIsKeywordOrIdentifier(type)) {
        key = this.parseIdentifier(true);
      } else {
        switch (type) {
          case 132:
            key = this.parseNumericLiteral(value);
            break;
          case 131:
            key = this.parseStringLiteral(value);
            break;
          case 133:
            key = this.parseBigIntLiteral(value);
            break;
          case 134:
            key = this.parseDecimalLiteral(value);
            break;
          case 136: {
            const privateKeyLoc = this.state.startLoc;
            if (refExpressionErrors != null) {
              if (refExpressionErrors.privateKeyLoc === null) {
                refExpressionErrors.privateKeyLoc = privateKeyLoc;
              }
            } else {
              this.raise(Errors.UnexpectedPrivateField, {
                at: privateKeyLoc
              });
            }
            key = this.parsePrivateName();
            break;
          }
          default:
            this.unexpected();
        }
      }
      prop.key = key;
      if (type !== 136) {
        prop.computed = false;
      }
    }
    return prop.key;
  }
  initFunction(node2, isAsync) {
    node2.id = null;
    node2.generator = false;
    node2.async = isAsync;
  }
  parseMethod(node2, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
    this.initFunction(node2, isAsync);
    node2.generator = isGenerator;
    this.scope.enter(SCOPE_FUNCTION | SCOPE_SUPER | (inClassScope ? SCOPE_CLASS : 0) | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
    this.prodParam.enter(functionFlags(isAsync, node2.generator));
    this.parseFunctionParams(node2, isConstructor);
    const finishedNode = this.parseFunctionBodyAndFinish(node2, type, true);
    this.prodParam.exit();
    this.scope.exit();
    return finishedNode;
  }
  parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
    if (isTuple) {
      this.expectPlugin("recordAndTuple");
    }
    const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
    this.state.inFSharpPipelineDirectBody = false;
    const node2 = this.startNode();
    this.next();
    node2.elements = this.parseExprList(close, !isTuple, refExpressionErrors, node2);
    this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
    return this.finishNode(node2, isTuple ? "TupleExpression" : "ArrayExpression");
  }
  parseArrowExpression(node2, params, isAsync, trailingCommaLoc) {
    this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
    let flags = functionFlags(isAsync, false);
    if (!this.match(5) && this.prodParam.hasIn) {
      flags |= PARAM_IN;
    }
    this.prodParam.enter(flags);
    this.initFunction(node2, isAsync);
    const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
    if (params) {
      this.state.maybeInArrowParameters = true;
      this.setArrowFunctionParameters(node2, params, trailingCommaLoc);
    }
    this.state.maybeInArrowParameters = false;
    this.parseFunctionBody(node2, true);
    this.prodParam.exit();
    this.scope.exit();
    this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
    return this.finishNode(node2, "ArrowFunctionExpression");
  }
  setArrowFunctionParameters(node2, params, trailingCommaLoc) {
    this.toAssignableList(params, trailingCommaLoc, false);
    node2.params = params;
  }
  parseFunctionBodyAndFinish(node2, type, isMethod = false) {
    this.parseFunctionBody(node2, false, isMethod);
    return this.finishNode(node2, type);
  }
  parseFunctionBody(node2, allowExpression, isMethod = false) {
    const isExpression = allowExpression && !this.match(5);
    this.expressionScope.enter(newExpressionScope());
    if (isExpression) {
      node2.body = this.parseMaybeAssign();
      this.checkParams(node2, false, allowExpression, false);
    } else {
      const oldStrict = this.state.strict;
      const oldLabels = this.state.labels;
      this.state.labels = [];
      this.prodParam.enter(this.prodParam.currentFlags() | PARAM_RETURN);
      node2.body = this.parseBlock(true, false, (hasStrictModeDirective) => {
        const nonSimple = !this.isSimpleParamList(node2.params);
        if (hasStrictModeDirective && nonSimple) {
          this.raise(Errors.IllegalLanguageModeDirective, {
            at: (node2.kind === "method" || node2.kind === "constructor") && !!node2.key ? node2.key.loc.end : node2
          });
        }
        const strictModeChanged = !oldStrict && this.state.strict;
        this.checkParams(node2, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged);
        if (this.state.strict && node2.id) {
          this.checkIdentifier(node2.id, BIND_OUTSIDE, strictModeChanged);
        }
      });
      this.prodParam.exit();
      this.state.labels = oldLabels;
    }
    this.expressionScope.exit();
  }
  isSimpleParameter(node2) {
    return node2.type === "Identifier";
  }
  isSimpleParamList(params) {
    for (let i = 0, len = params.length; i < len; i++) {
      if (!this.isSimpleParameter(params[i]))
        return false;
    }
    return true;
  }
  checkParams(node2, allowDuplicates, isArrowFunction, strictModeChanged = true) {
    const checkClashes = !allowDuplicates && /* @__PURE__ */ new Set();
    const formalParameters = {
      type: "FormalParameters"
    };
    for (const param of node2.params) {
      this.checkLVal(param, {
        in: formalParameters,
        binding: BIND_VAR,
        checkClashes,
        strictModeChanged
      });
    }
  }
  parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) {
    const elts = [];
    let first2 = true;
    while (!this.eat(close)) {
      if (first2) {
        first2 = false;
      } else {
        this.expect(12);
        if (this.match(close)) {
          if (nodeForExtra) {
            this.addTrailingCommaExtraToNode(nodeForExtra);
          }
          this.next();
          break;
        }
      }
      elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors));
    }
    return elts;
  }
  parseExprListItem(allowEmpty, refExpressionErrors, allowPlaceholder) {
    let elt;
    if (this.match(12)) {
      if (!allowEmpty) {
        this.raise(Errors.UnexpectedToken, {
          at: this.state.curPosition(),
          unexpected: ","
        });
      }
      elt = null;
    } else if (this.match(21)) {
      const spreadNodeStartLoc = this.state.startLoc;
      elt = this.parseParenItem(this.parseSpread(refExpressionErrors), spreadNodeStartLoc);
    } else if (this.match(17)) {
      this.expectPlugin("partialApplication");
      if (!allowPlaceholder) {
        this.raise(Errors.UnexpectedArgumentPlaceholder, {
          at: this.state.startLoc
        });
      }
      const node2 = this.startNode();
      this.next();
      elt = this.finishNode(node2, "ArgumentPlaceholder");
    } else {
      elt = this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem);
    }
    return elt;
  }
  parseIdentifier(liberal) {
    const node2 = this.startNode();
    const name = this.parseIdentifierName(liberal);
    return this.createIdentifier(node2, name);
  }
  createIdentifier(node2, name) {
    node2.name = name;
    node2.loc.identifierName = name;
    return this.finishNode(node2, "Identifier");
  }
  parseIdentifierName(liberal) {
    let name;
    const {
      startLoc,
      type
    } = this.state;
    if (tokenIsKeywordOrIdentifier(type)) {
      name = this.state.value;
    } else {
      this.unexpected();
    }
    const tokenIsKeyword2 = tokenKeywordOrIdentifierIsKeyword(type);
    if (liberal) {
      if (tokenIsKeyword2) {
        this.replaceToken(130);
      }
    } else {
      this.checkReservedWord(name, startLoc, tokenIsKeyword2, false);
    }
    this.next();
    return name;
  }
  checkReservedWord(word2, startLoc, checkKeywords, isBinding) {
    if (word2.length > 10) {
      return;
    }
    if (!canBeReservedWord(word2)) {
      return;
    }
    if (checkKeywords && isKeyword(word2)) {
      this.raise(Errors.UnexpectedKeyword, {
        at: startLoc,
        keyword: word2
      });
      return;
    }
    const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord;
    if (reservedTest(word2, this.inModule)) {
      this.raise(Errors.UnexpectedReservedWord, {
        at: startLoc,
        reservedWord: word2
      });
      return;
    } else if (word2 === "yield") {
      if (this.prodParam.hasYield) {
        this.raise(Errors.YieldBindingIdentifier, {
          at: startLoc
        });
        return;
      }
    } else if (word2 === "await") {
      if (this.prodParam.hasAwait) {
        this.raise(Errors.AwaitBindingIdentifier, {
          at: startLoc
        });
        return;
      }
      if (this.scope.inStaticBlock) {
        this.raise(Errors.AwaitBindingIdentifierInStaticBlock, {
          at: startLoc
        });
        return;
      }
      this.expressionScope.recordAsyncArrowParametersError({
        at: startLoc
      });
    } else if (word2 === "arguments") {
      if (this.scope.inClassAndNotInNonArrowFunction) {
        this.raise(Errors.ArgumentsInClass, {
          at: startLoc
        });
        return;
      }
    }
  }
  isAwaitAllowed() {
    if (this.prodParam.hasAwait)
      return true;
    if (this.options.allowAwaitOutsideFunction && !this.scope.inFunction) {
      return true;
    }
    return false;
  }
  parseAwait(startLoc) {
    const node2 = this.startNodeAt(startLoc);
    this.expressionScope.recordParameterInitializerError(Errors.AwaitExpressionFormalParameter, {
      at: node2
    });
    if (this.eat(55)) {
      this.raise(Errors.ObsoleteAwaitStar, {
        at: node2
      });
    }
    if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) {
      if (this.isAmbiguousAwait()) {
        this.ambiguousScriptDifferentAst = true;
      } else {
        this.sawUnambiguousESM = true;
      }
    }
    if (!this.state.soloAwait) {
      node2.argument = this.parseMaybeUnary(null, true);
    }
    return this.finishNode(node2, "AwaitExpression");
  }
  isAmbiguousAwait() {
    if (this.hasPrecedingLineBreak())
      return true;
    const {
      type
    } = this.state;
    return type === 53 || type === 10 || type === 0 || tokenIsTemplate(type) || type === 101 && !this.state.containsEsc || type === 135 || type === 56 || this.hasPlugin("v8intrinsic") && type === 54;
  }
  parseYield() {
    const node2 = this.startNode();
    this.expressionScope.recordParameterInitializerError(Errors.YieldInParameter, {
      at: node2
    });
    this.next();
    let delegating = false;
    let argument = null;
    if (!this.hasPrecedingLineBreak()) {
      delegating = this.eat(55);
      switch (this.state.type) {
        case 13:
        case 137:
        case 8:
        case 11:
        case 3:
        case 9:
        case 14:
        case 12:
          if (!delegating)
            break;
        default:
          argument = this.parseMaybeAssign();
      }
    }
    node2.delegate = delegating;
    node2.argument = argument;
    return this.finishNode(node2, "YieldExpression");
  }
  checkPipelineAtInfixOperator(left, leftStartLoc) {
    if (this.hasPlugin(["pipelineOperator", {
      proposal: "smart"
    }])) {
      if (left.type === "SequenceExpression") {
        this.raise(Errors.PipelineHeadSequenceExpression, {
          at: leftStartLoc
        });
      }
    }
  }
  parseSmartPipelineBodyInStyle(childExpr, startLoc) {
    if (this.isSimpleReference(childExpr)) {
      const bodyNode = this.startNodeAt(startLoc);
      bodyNode.callee = childExpr;
      return this.finishNode(bodyNode, "PipelineBareFunction");
    } else {
      const bodyNode = this.startNodeAt(startLoc);
      this.checkSmartPipeTopicBodyEarlyErrors(startLoc);
      bodyNode.expression = childExpr;
      return this.finishNode(bodyNode, "PipelineTopicExpression");
    }
  }
  isSimpleReference(expression) {
    switch (expression.type) {
      case "MemberExpression":
        return !expression.computed && this.isSimpleReference(expression.object);
      case "Identifier":
        return true;
      default:
        return false;
    }
  }
  checkSmartPipeTopicBodyEarlyErrors(startLoc) {
    if (this.match(19)) {
      throw this.raise(Errors.PipelineBodyNoArrow, {
        at: this.state.startLoc
      });
    }
    if (!this.topicReferenceWasUsedInCurrentContext()) {
      this.raise(Errors.PipelineTopicUnused, {
        at: startLoc
      });
    }
  }
  withTopicBindingContext(callback) {
    const outerContextTopicState = this.state.topicContext;
    this.state.topicContext = {
      maxNumOfResolvableTopics: 1,
      maxTopicIndex: null
    };
    try {
      return callback();
    } finally {
      this.state.topicContext = outerContextTopicState;
    }
  }
  withSmartMixTopicForbiddingContext(callback) {
    if (this.hasPlugin(["pipelineOperator", {
      proposal: "smart"
    }])) {
      const outerContextTopicState = this.state.topicContext;
      this.state.topicContext = {
        maxNumOfResolvableTopics: 0,
        maxTopicIndex: null
      };
      try {
        return callback();
      } finally {
        this.state.topicContext = outerContextTopicState;
      }
    } else {
      return callback();
    }
  }
  withSoloAwaitPermittingContext(callback) {
    const outerContextSoloAwaitState = this.state.soloAwait;
    this.state.soloAwait = true;
    try {
      return callback();
    } finally {
      this.state.soloAwait = outerContextSoloAwaitState;
    }
  }
  allowInAnd(callback) {
    const flags = this.prodParam.currentFlags();
    const prodParamToSet = PARAM_IN & ~flags;
    if (prodParamToSet) {
      this.prodParam.enter(flags | PARAM_IN);
      try {
        return callback();
      } finally {
        this.prodParam.exit();
      }
    }
    return callback();
  }
  disallowInAnd(callback) {
    const flags = this.prodParam.currentFlags();
    const prodParamToClear = PARAM_IN & flags;
    if (prodParamToClear) {
      this.prodParam.enter(flags & ~PARAM_IN);
      try {
        return callback();
      } finally {
        this.prodParam.exit();
      }
    }
    return callback();
  }
  registerTopicReference() {
    this.state.topicContext.maxTopicIndex = 0;
  }
  topicReferenceIsAllowedInCurrentContext() {
    return this.state.topicContext.maxNumOfResolvableTopics >= 1;
  }
  topicReferenceWasUsedInCurrentContext() {
    return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0;
  }
  parseFSharpPipelineBody(prec) {
    const startLoc = this.state.startLoc;
    this.state.potentialArrowAt = this.state.start;
    const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
    this.state.inFSharpPipelineDirectBody = true;
    const ret = this.parseExprOp(this.parseMaybeUnaryOrPrivate(), startLoc, prec);
    this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
    return ret;
  }
  parseModuleExpression() {
    this.expectPlugin("moduleBlocks");
    const node2 = this.startNode();
    this.next();
    if (!this.match(5)) {
      this.unexpected(null, 5);
    }
    const program = this.startNodeAt(this.state.endLoc);
    this.next();
    const revertScopes = this.initializeScopes(true);
    this.enterInitialScopes();
    try {
      node2.body = this.parseProgram(program, 8, "module");
    } finally {
      revertScopes();
    }
    return this.finishNode(node2, "ModuleExpression");
  }
  parsePropertyNamePrefixOperator(prop) {
  }
}
const loopLabel = {
  kind: "loop"
}, switchLabel = {
  kind: "switch"
};
const loneSurrogate = /[\uD800-\uDFFF]/u;
const keywordRelationalOperator = /in(?:stanceof)?/y;
function babel7CompatTokens(tokens, input2) {
  for (let i = 0; i < tokens.length; i++) {
    const token = tokens[i];
    const {
      type
    } = token;
    if (typeof type === "number") {
      {
        if (type === 136) {
          const {
            loc,
            start,
            value,
            end
          } = token;
          const hashEndPos = start + 1;
          const hashEndLoc = createPositionWithColumnOffset(loc.start, 1);
          tokens.splice(i, 1, new Token3({
            type: getExportedToken(27),
            value: "#",
            start,
            end: hashEndPos,
            startLoc: loc.start,
            endLoc: hashEndLoc
          }), new Token3({
            type: getExportedToken(130),
            value,
            start: hashEndPos,
            end,
            startLoc: hashEndLoc,
            endLoc: loc.end
          }));
          i++;
          continue;
        }
        if (tokenIsTemplate(type)) {
          const {
            loc,
            start,
            value,
            end
          } = token;
          const backquoteEnd = start + 1;
          const backquoteEndLoc = createPositionWithColumnOffset(loc.start, 1);
          let startToken;
          if (input2.charCodeAt(start) === 96) {
            startToken = new Token3({
              type: getExportedToken(22),
              value: "`",
              start,
              end: backquoteEnd,
              startLoc: loc.start,
              endLoc: backquoteEndLoc
            });
          } else {
            startToken = new Token3({
              type: getExportedToken(8),
              value: "}",
              start,
              end: backquoteEnd,
              startLoc: loc.start,
              endLoc: backquoteEndLoc
            });
          }
          let templateValue, templateElementEnd, templateElementEndLoc, endToken;
          if (type === 24) {
            templateElementEnd = end - 1;
            templateElementEndLoc = createPositionWithColumnOffset(loc.end, -1);
            templateValue = value === null ? null : value.slice(1, -1);
            endToken = new Token3({
              type: getExportedToken(22),
              value: "`",
              start: templateElementEnd,
              end,
              startLoc: templateElementEndLoc,
              endLoc: loc.end
            });
          } else {
            templateElementEnd = end - 2;
            templateElementEndLoc = createPositionWithColumnOffset(loc.end, -2);
            templateValue = value === null ? null : value.slice(1, -2);
            endToken = new Token3({
              type: getExportedToken(23),
              value: "${",
              start: templateElementEnd,
              end,
              startLoc: templateElementEndLoc,
              endLoc: loc.end
            });
          }
          tokens.splice(i, 1, startToken, new Token3({
            type: getExportedToken(20),
            value: templateValue,
            start: backquoteEnd,
            end: templateElementEnd,
            startLoc: backquoteEndLoc,
            endLoc: templateElementEndLoc
          }), endToken);
          i += 2;
          continue;
        }
      }
      token.type = getExportedToken(type);
    }
  }
  return tokens;
}
class StatementParser extends ExpressionParser {
  parseTopLevel(file, program) {
    file.program = this.parseProgram(program);
    file.comments = this.state.comments;
    if (this.options.tokens) {
      file.tokens = babel7CompatTokens(this.tokens, this.input);
    }
    return this.finishNode(file, "File");
  }
  parseProgram(program, end = 137, sourceType = this.options.sourceType) {
    program.sourceType = sourceType;
    program.interpreter = this.parseInterpreterDirective();
    this.parseBlockBody(program, true, true, end);
    if (this.inModule && !this.options.allowUndeclaredExports && this.scope.undefinedExports.size > 0) {
      for (const [localName, at2] of Array.from(this.scope.undefinedExports)) {
        this.raise(Errors.ModuleExportUndefined, {
          at: at2,
          localName
        });
      }
    }
    let finishedProgram;
    if (end === 137) {
      finishedProgram = this.finishNode(program, "Program");
    } else {
      finishedProgram = this.finishNodeAt(program, "Program", createPositionWithColumnOffset(this.state.startLoc, -1));
    }
    return finishedProgram;
  }
  stmtToDirective(stmt) {
    const directive = stmt;
    directive.type = "Directive";
    directive.value = directive.expression;
    delete directive.expression;
    const directiveLiteral = directive.value;
    const expressionValue = directiveLiteral.value;
    const raw = this.input.slice(directiveLiteral.start, directiveLiteral.end);
    const val = directiveLiteral.value = raw.slice(1, -1);
    this.addExtra(directiveLiteral, "raw", raw);
    this.addExtra(directiveLiteral, "rawValue", val);
    this.addExtra(directiveLiteral, "expressionValue", expressionValue);
    directiveLiteral.type = "DirectiveLiteral";
    return directive;
  }
  parseInterpreterDirective() {
    if (!this.match(28)) {
      return null;
    }
    const node2 = this.startNode();
    node2.value = this.state.value;
    this.next();
    return this.finishNode(node2, "InterpreterDirective");
  }
  isLet() {
    if (!this.isContextual(99)) {
      return false;
    }
    return this.hasFollowingBindingAtom();
  }
  chStartsBindingIdentifier(ch, pos) {
    if (isIdentifierStart(ch)) {
      keywordRelationalOperator.lastIndex = pos;
      if (keywordRelationalOperator.test(this.input)) {
        const endCh = this.codePointAtPos(keywordRelationalOperator.lastIndex);
        if (!isIdentifierChar(endCh) && endCh !== 92) {
          return false;
        }
      }
      return true;
    } else if (ch === 92) {
      return true;
    } else {
      return false;
    }
  }
  chStartsBindingPattern(ch) {
    return ch === 91 || ch === 123;
  }
  hasFollowingBindingAtom() {
    const next = this.nextTokenStart();
    const nextCh = this.codePointAtPos(next);
    return this.chStartsBindingPattern(nextCh) || this.chStartsBindingIdentifier(nextCh, next);
  }
  hasFollowingBindingIdentifier() {
    const next = this.nextTokenStart();
    const nextCh = this.codePointAtPos(next);
    return this.chStartsBindingIdentifier(nextCh, next);
  }
  startsUsingForOf() {
    const lookahead = this.lookahead();
    if (lookahead.type === 101 && !lookahead.containsEsc) {
      return false;
    } else {
      this.expectPlugin("explicitResourceManagement");
      return true;
    }
  }
  parseModuleItem() {
    return this.parseStatementLike(1 | 2 | 4 | 8);
  }
  parseStatementListItem() {
    return this.parseStatementLike(2 | 4 | (!this.options.annexB || this.state.strict ? 0 : 8));
  }
  parseStatementOrSloppyAnnexBFunctionDeclaration(allowLabeledFunction = false) {
    let flags = 0;
    if (this.options.annexB && !this.state.strict) {
      flags |= 4;
      if (allowLabeledFunction) {
        flags |= 8;
      }
    }
    return this.parseStatementLike(flags);
  }
  parseStatement() {
    return this.parseStatementLike(0);
  }
  parseStatementLike(flags) {
    let decorators = null;
    if (this.match(26)) {
      decorators = this.parseDecorators(true);
    }
    return this.parseStatementContent(flags, decorators);
  }
  parseStatementContent(flags, decorators) {
    const starttype = this.state.type;
    const node2 = this.startNode();
    const allowDeclaration = !!(flags & 2);
    const allowFunctionDeclaration = !!(flags & 4);
    const topLevel = flags & 1;
    switch (starttype) {
      case 60:
        return this.parseBreakContinueStatement(node2, true);
      case 63:
        return this.parseBreakContinueStatement(node2, false);
      case 64:
        return this.parseDebuggerStatement(node2);
      case 90:
        return this.parseDoWhileStatement(node2);
      case 91:
        return this.parseForStatement(node2);
      case 68:
        if (this.lookaheadCharCode() === 46)
          break;
        if (!allowFunctionDeclaration) {
          this.raise(this.state.strict ? Errors.StrictFunction : this.options.annexB ? Errors.SloppyFunctionAnnexB : Errors.SloppyFunction, {
            at: this.state.startLoc
          });
        }
        return this.parseFunctionStatement(node2, false, !allowDeclaration && allowFunctionDeclaration);
      case 80:
        if (!allowDeclaration)
          this.unexpected();
        return this.parseClass(this.maybeTakeDecorators(decorators, node2), true);
      case 69:
        return this.parseIfStatement(node2);
      case 70:
        return this.parseReturnStatement(node2);
      case 71:
        return this.parseSwitchStatement(node2);
      case 72:
        return this.parseThrowStatement(node2);
      case 73:
        return this.parseTryStatement(node2);
      case 105:
        if (this.hasFollowingLineBreak() || this.state.containsEsc || !this.hasFollowingBindingIdentifier()) {
          break;
        }
        this.expectPlugin("explicitResourceManagement");
        if (!this.scope.inModule && this.scope.inTopLevel) {
          this.raise(Errors.UnexpectedUsingDeclaration, {
            at: this.state.startLoc
          });
        } else if (!allowDeclaration) {
          this.raise(Errors.UnexpectedLexicalDeclaration, {
            at: this.state.startLoc
          });
        }
        return this.parseVarStatement(node2, "using");
      case 99: {
        if (this.state.containsEsc) {
          break;
        }
        const next = this.nextTokenStart();
        const nextCh = this.codePointAtPos(next);
        if (nextCh !== 91) {
          if (!allowDeclaration && this.hasFollowingLineBreak())
            break;
          if (!this.chStartsBindingIdentifier(nextCh, next) && nextCh !== 123) {
            break;
          }
        }
      }
      case 75: {
        if (!allowDeclaration) {
          this.raise(Errors.UnexpectedLexicalDeclaration, {
            at: this.state.startLoc
          });
        }
      }
      case 74: {
        const kind = this.state.value;
        return this.parseVarStatement(node2, kind);
      }
      case 92:
        return this.parseWhileStatement(node2);
      case 76:
        return this.parseWithStatement(node2);
      case 5:
        return this.parseBlock();
      case 13:
        return this.parseEmptyStatement(node2);
      case 83: {
        const nextTokenCharCode = this.lookaheadCharCode();
        if (nextTokenCharCode === 40 || nextTokenCharCode === 46) {
          break;
        }
      }
      case 82: {
        if (!this.options.allowImportExportEverywhere && !topLevel) {
          this.raise(Errors.UnexpectedImportExport, {
            at: this.state.startLoc
          });
        }
        this.next();
        let result2;
        if (starttype === 83) {
          result2 = this.parseImport(node2);
          if (result2.type === "ImportDeclaration" && (!result2.importKind || result2.importKind === "value")) {
            this.sawUnambiguousESM = true;
          }
        } else {
          result2 = this.parseExport(node2, decorators);
          if (result2.type === "ExportNamedDeclaration" && (!result2.exportKind || result2.exportKind === "value") || result2.type === "ExportAllDeclaration" && (!result2.exportKind || result2.exportKind === "value") || result2.type === "ExportDefaultDeclaration") {
            this.sawUnambiguousESM = true;
          }
        }
        this.assertModuleNodeAllowed(result2);
        return result2;
      }
      default: {
        if (this.isAsyncFunction()) {
          if (!allowDeclaration) {
            this.raise(Errors.AsyncFunctionInSingleStatementContext, {
              at: this.state.startLoc
            });
          }
          this.next();
          return this.parseFunctionStatement(node2, true, !allowDeclaration && allowFunctionDeclaration);
        }
      }
    }
    const maybeName = this.state.value;
    const expr = this.parseExpression();
    if (tokenIsIdentifier(starttype) && expr.type === "Identifier" && this.eat(14)) {
      return this.parseLabeledStatement(node2, maybeName, expr, flags);
    } else {
      return this.parseExpressionStatement(node2, expr, decorators);
    }
  }
  assertModuleNodeAllowed(node2) {
    if (!this.options.allowImportExportEverywhere && !this.inModule) {
      this.raise(Errors.ImportOutsideModule, {
        at: node2
      });
    }
  }
  decoratorsEnabledBeforeExport() {
    if (this.hasPlugin("decorators-legacy"))
      return true;
    return this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport") !== false;
  }
  maybeTakeDecorators(maybeDecorators, classNode, exportNode) {
    if (maybeDecorators) {
      if (classNode.decorators && classNode.decorators.length > 0) {
        if (typeof this.getPluginOption("decorators", "decoratorsBeforeExport") !== "boolean") {
          this.raise(Errors.DecoratorsBeforeAfterExport, {
            at: classNode.decorators[0]
          });
        }
        classNode.decorators.unshift(...maybeDecorators);
      } else {
        classNode.decorators = maybeDecorators;
      }
      this.resetStartLocationFromNode(classNode, maybeDecorators[0]);
      if (exportNode)
        this.resetStartLocationFromNode(exportNode, classNode);
    }
    return classNode;
  }
  canHaveLeadingDecorator() {
    return this.match(80);
  }
  parseDecorators(allowExport) {
    const decorators = [];
    do {
      decorators.push(this.parseDecorator());
    } while (this.match(26));
    if (this.match(82)) {
      if (!allowExport) {
        this.unexpected();
      }
      if (!this.decoratorsEnabledBeforeExport()) {
        this.raise(Errors.DecoratorExportClass, {
          at: this.state.startLoc
        });
      }
    } else if (!this.canHaveLeadingDecorator()) {
      throw this.raise(Errors.UnexpectedLeadingDecorator, {
        at: this.state.startLoc
      });
    }
    return decorators;
  }
  parseDecorator() {
    this.expectOnePlugin(["decorators", "decorators-legacy"]);
    const node2 = this.startNode();
    this.next();
    if (this.hasPlugin("decorators")) {
      const startLoc = this.state.startLoc;
      let expr;
      if (this.match(10)) {
        const startLoc2 = this.state.startLoc;
        this.next();
        expr = this.parseExpression();
        this.expect(11);
        expr = this.wrapParenthesis(startLoc2, expr);
        const paramsStartLoc = this.state.startLoc;
        node2.expression = this.parseMaybeDecoratorArguments(expr);
        if (this.getPluginOption("decorators", "allowCallParenthesized") === false && node2.expression !== expr) {
          this.raise(Errors.DecoratorArgumentsOutsideParentheses, {
            at: paramsStartLoc
          });
        }
      } else {
        expr = this.parseIdentifier(false);
        while (this.eat(16)) {
          const node3 = this.startNodeAt(startLoc);
          node3.object = expr;
          if (this.match(136)) {
            this.classScope.usePrivateName(this.state.value, this.state.startLoc);
            node3.property = this.parsePrivateName();
          } else {
            node3.property = this.parseIdentifier(true);
          }
          node3.computed = false;
          expr = this.finishNode(node3, "MemberExpression");
        }
        node2.expression = this.parseMaybeDecoratorArguments(expr);
      }
    } else {
      node2.expression = this.parseExprSubscripts();
    }
    return this.finishNode(node2, "Decorator");
  }
  parseMaybeDecoratorArguments(expr) {
    if (this.eat(10)) {
      const node2 = this.startNodeAtNode(expr);
      node2.callee = expr;
      node2.arguments = this.parseCallExpressionArguments(11, false);
      this.toReferencedList(node2.arguments);
      return this.finishNode(node2, "CallExpression");
    }
    return expr;
  }
  parseBreakContinueStatement(node2, isBreak) {
    this.next();
    if (this.isLineTerminator()) {
      node2.label = null;
    } else {
      node2.label = this.parseIdentifier();
      this.semicolon();
    }
    this.verifyBreakContinue(node2, isBreak);
    return this.finishNode(node2, isBreak ? "BreakStatement" : "ContinueStatement");
  }
  verifyBreakContinue(node2, isBreak) {
    let i;
    for (i = 0; i < this.state.labels.length; ++i) {
      const lab = this.state.labels[i];
      if (node2.label == null || lab.name === node2.label.name) {
        if (lab.kind != null && (isBreak || lab.kind === "loop"))
          break;
        if (node2.label && isBreak)
          break;
      }
    }
    if (i === this.state.labels.length) {
      const type = isBreak ? "BreakStatement" : "ContinueStatement";
      this.raise(Errors.IllegalBreakContinue, {
        at: node2,
        type
      });
    }
  }
  parseDebuggerStatement(node2) {
    this.next();
    this.semicolon();
    return this.finishNode(node2, "DebuggerStatement");
  }
  parseHeaderExpression() {
    this.expect(10);
    const val = this.parseExpression();
    this.expect(11);
    return val;
  }
  parseDoWhileStatement(node2) {
    this.next();
    this.state.labels.push(loopLabel);
    node2.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
    this.state.labels.pop();
    this.expect(92);
    node2.test = this.parseHeaderExpression();
    this.eat(13);
    return this.finishNode(node2, "DoWhileStatement");
  }
  parseForStatement(node2) {
    this.next();
    this.state.labels.push(loopLabel);
    let awaitAt = null;
    if (this.isAwaitAllowed() && this.eatContextual(96)) {
      awaitAt = this.state.lastTokStartLoc;
    }
    this.scope.enter(SCOPE_OTHER);
    this.expect(10);
    if (this.match(13)) {
      if (awaitAt !== null) {
        this.unexpected(awaitAt);
      }
      return this.parseFor(node2, null);
    }
    const startsWithLet = this.isContextual(99);
    const startsWithUsing = this.isContextual(105) && !this.hasFollowingLineBreak();
    const isLetOrUsing = startsWithLet && this.hasFollowingBindingAtom() || startsWithUsing && this.hasFollowingBindingIdentifier() && this.startsUsingForOf();
    if (this.match(74) || this.match(75) || isLetOrUsing) {
      const initNode = this.startNode();
      const kind = this.state.value;
      this.next();
      this.parseVar(initNode, true, kind);
      const init3 = this.finishNode(initNode, "VariableDeclaration");
      const isForIn = this.match(58);
      if (isForIn && startsWithUsing) {
        this.raise(Errors.ForInUsing, {
          at: init3
        });
      }
      if ((isForIn || this.isContextual(101)) && init3.declarations.length === 1) {
        return this.parseForIn(node2, init3, awaitAt);
      }
      if (awaitAt !== null) {
        this.unexpected(awaitAt);
      }
      return this.parseFor(node2, init3);
    }
    const startsWithAsync = this.isContextual(95);
    const refExpressionErrors = new ExpressionErrors();
    const init2 = this.parseExpression(true, refExpressionErrors);
    const isForOf = this.isContextual(101);
    if (isForOf) {
      if (startsWithLet) {
        this.raise(Errors.ForOfLet, {
          at: init2
        });
      }
      if (awaitAt === null && startsWithAsync && init2.type === "Identifier") {
        this.raise(Errors.ForOfAsync, {
          at: init2
        });
      }
    }
    if (isForOf || this.match(58)) {
      this.checkDestructuringPrivate(refExpressionErrors);
      this.toAssignable(init2, true);
      const type = isForOf ? "ForOfStatement" : "ForInStatement";
      this.checkLVal(init2, {
        in: {
          type
        }
      });
      return this.parseForIn(node2, init2, awaitAt);
    } else {
      this.checkExpressionErrors(refExpressionErrors, true);
    }
    if (awaitAt !== null) {
      this.unexpected(awaitAt);
    }
    return this.parseFor(node2, init2);
  }
  parseFunctionStatement(node2, isAsync, isHangingDeclaration) {
    this.next();
    return this.parseFunction(node2, 1 | (isHangingDeclaration ? 2 : 0) | (isAsync ? 8 : 0));
  }
  parseIfStatement(node2) {
    this.next();
    node2.test = this.parseHeaderExpression();
    node2.consequent = this.parseStatementOrSloppyAnnexBFunctionDeclaration();
    node2.alternate = this.eat(66) ? this.parseStatementOrSloppyAnnexBFunctionDeclaration() : null;
    return this.finishNode(node2, "IfStatement");
  }
  parseReturnStatement(node2) {
    if (!this.prodParam.hasReturn && !this.options.allowReturnOutsideFunction) {
      this.raise(Errors.IllegalReturn, {
        at: this.state.startLoc
      });
    }
    this.next();
    if (this.isLineTerminator()) {
      node2.argument = null;
    } else {
      node2.argument = this.parseExpression();
      this.semicolon();
    }
    return this.finishNode(node2, "ReturnStatement");
  }
  parseSwitchStatement(node2) {
    this.next();
    node2.discriminant = this.parseHeaderExpression();
    const cases = node2.cases = [];
    this.expect(5);
    this.state.labels.push(switchLabel);
    this.scope.enter(SCOPE_OTHER);
    let cur;
    for (let sawDefault; !this.match(8); ) {
      if (this.match(61) || this.match(65)) {
        const isCase = this.match(61);
        if (cur)
          this.finishNode(cur, "SwitchCase");
        cases.push(cur = this.startNode());
        cur.consequent = [];
        this.next();
        if (isCase) {
          cur.test = this.parseExpression();
        } else {
          if (sawDefault) {
            this.raise(Errors.MultipleDefaultsInSwitch, {
              at: this.state.lastTokStartLoc
            });
          }
          sawDefault = true;
          cur.test = null;
        }
        this.expect(14);
      } else {
        if (cur) {
          cur.consequent.push(this.parseStatementListItem());
        } else {
          this.unexpected();
        }
      }
    }
    this.scope.exit();
    if (cur)
      this.finishNode(cur, "SwitchCase");
    this.next();
    this.state.labels.pop();
    return this.finishNode(node2, "SwitchStatement");
  }
  parseThrowStatement(node2) {
    this.next();
    if (this.hasPrecedingLineBreak()) {
      this.raise(Errors.NewlineAfterThrow, {
        at: this.state.lastTokEndLoc
      });
    }
    node2.argument = this.parseExpression();
    this.semicolon();
    return this.finishNode(node2, "ThrowStatement");
  }
  parseCatchClauseParam() {
    const param = this.parseBindingAtom();
    this.scope.enter(this.options.annexB && param.type === "Identifier" ? SCOPE_SIMPLE_CATCH : 0);
    this.checkLVal(param, {
      in: {
        type: "CatchClause"
      },
      binding: BIND_CATCH_PARAM
    });
    return param;
  }
  parseTryStatement(node2) {
    this.next();
    node2.block = this.parseBlock();
    node2.handler = null;
    if (this.match(62)) {
      const clause = this.startNode();
      this.next();
      if (this.match(10)) {
        this.expect(10);
        clause.param = this.parseCatchClauseParam();
        this.expect(11);
      } else {
        clause.param = null;
        this.scope.enter(SCOPE_OTHER);
      }
      clause.body = this.withSmartMixTopicForbiddingContext(() => this.parseBlock(false, false));
      this.scope.exit();
      node2.handler = this.finishNode(clause, "CatchClause");
    }
    node2.finalizer = this.eat(67) ? this.parseBlock() : null;
    if (!node2.handler && !node2.finalizer) {
      this.raise(Errors.NoCatchOrFinally, {
        at: node2
      });
    }
    return this.finishNode(node2, "TryStatement");
  }
  parseVarStatement(node2, kind, allowMissingInitializer = false) {
    this.next();
    this.parseVar(node2, false, kind, allowMissingInitializer);
    this.semicolon();
    return this.finishNode(node2, "VariableDeclaration");
  }
  parseWhileStatement(node2) {
    this.next();
    node2.test = this.parseHeaderExpression();
    this.state.labels.push(loopLabel);
    node2.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
    this.state.labels.pop();
    return this.finishNode(node2, "WhileStatement");
  }
  parseWithStatement(node2) {
    if (this.state.strict) {
      this.raise(Errors.StrictWith, {
        at: this.state.startLoc
      });
    }
    this.next();
    node2.object = this.parseHeaderExpression();
    node2.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
    return this.finishNode(node2, "WithStatement");
  }
  parseEmptyStatement(node2) {
    this.next();
    return this.finishNode(node2, "EmptyStatement");
  }
  parseLabeledStatement(node2, maybeName, expr, flags) {
    for (const label of this.state.labels) {
      if (label.name === maybeName) {
        this.raise(Errors.LabelRedeclaration, {
          at: expr,
          labelName: maybeName
        });
      }
    }
    const kind = tokenIsLoop(this.state.type) ? "loop" : this.match(71) ? "switch" : null;
    for (let i = this.state.labels.length - 1; i >= 0; i--) {
      const label = this.state.labels[i];
      if (label.statementStart === node2.start) {
        label.statementStart = this.state.start;
        label.kind = kind;
      } else {
        break;
      }
    }
    this.state.labels.push({
      name: maybeName,
      kind,
      statementStart: this.state.start
    });
    node2.body = flags & 8 ? this.parseStatementOrSloppyAnnexBFunctionDeclaration(true) : this.parseStatement();
    this.state.labels.pop();
    node2.label = expr;
    return this.finishNode(node2, "LabeledStatement");
  }
  parseExpressionStatement(node2, expr, decorators) {
    node2.expression = expr;
    this.semicolon();
    return this.finishNode(node2, "ExpressionStatement");
  }
  parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) {
    const node2 = this.startNode();
    if (allowDirectives) {
      this.state.strictErrors.clear();
    }
    this.expect(5);
    if (createNewLexicalScope) {
      this.scope.enter(SCOPE_OTHER);
    }
    this.parseBlockBody(node2, allowDirectives, false, 8, afterBlockParse);
    if (createNewLexicalScope) {
      this.scope.exit();
    }
    return this.finishNode(node2, "BlockStatement");
  }
  isValidDirective(stmt) {
    return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized;
  }
  parseBlockBody(node2, allowDirectives, topLevel, end, afterBlockParse) {
    const body = node2.body = [];
    const directives = node2.directives = [];
    this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : void 0, topLevel, end, afterBlockParse);
  }
  parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) {
    const oldStrict = this.state.strict;
    let hasStrictModeDirective = false;
    let parsedNonDirective = false;
    while (!this.match(end)) {
      const stmt = topLevel ? this.parseModuleItem() : this.parseStatementListItem();
      if (directives && !parsedNonDirective) {
        if (this.isValidDirective(stmt)) {
          const directive = this.stmtToDirective(stmt);
          directives.push(directive);
          if (!hasStrictModeDirective && directive.value.value === "use strict") {
            hasStrictModeDirective = true;
            this.setStrict(true);
          }
          continue;
        }
        parsedNonDirective = true;
        this.state.strictErrors.clear();
      }
      body.push(stmt);
    }
    if (afterBlockParse) {
      afterBlockParse.call(this, hasStrictModeDirective);
    }
    if (!oldStrict) {
      this.setStrict(false);
    }
    this.next();
  }
  parseFor(node2, init2) {
    node2.init = init2;
    this.semicolon(false);
    node2.test = this.match(13) ? null : this.parseExpression();
    this.semicolon(false);
    node2.update = this.match(11) ? null : this.parseExpression();
    this.expect(11);
    node2.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
    this.scope.exit();
    this.state.labels.pop();
    return this.finishNode(node2, "ForStatement");
  }
  parseForIn(node2, init2, awaitAt) {
    const isForIn = this.match(58);
    this.next();
    if (isForIn) {
      if (awaitAt !== null)
        this.unexpected(awaitAt);
    } else {
      node2.await = awaitAt !== null;
    }
    if (init2.type === "VariableDeclaration" && init2.declarations[0].init != null && (!isForIn || !this.options.annexB || this.state.strict || init2.kind !== "var" || init2.declarations[0].id.type !== "Identifier")) {
      this.raise(Errors.ForInOfLoopInitializer, {
        at: init2,
        type: isForIn ? "ForInStatement" : "ForOfStatement"
      });
    }
    if (init2.type === "AssignmentPattern") {
      this.raise(Errors.InvalidLhs, {
        at: init2,
        ancestor: {
          type: "ForStatement"
        }
      });
    }
    node2.left = init2;
    node2.right = isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn();
    this.expect(11);
    node2.body = this.withSmartMixTopicForbiddingContext(() => this.parseStatement());
    this.scope.exit();
    this.state.labels.pop();
    return this.finishNode(node2, isForIn ? "ForInStatement" : "ForOfStatement");
  }
  parseVar(node2, isFor, kind, allowMissingInitializer = false) {
    const declarations = node2.declarations = [];
    node2.kind = kind;
    for (; ; ) {
      const decl = this.startNode();
      this.parseVarId(decl, kind);
      decl.init = !this.eat(29) ? null : isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn();
      if (decl.init === null && !allowMissingInitializer) {
        if (decl.id.type !== "Identifier" && !(isFor && (this.match(58) || this.isContextual(101)))) {
          this.raise(Errors.DeclarationMissingInitializer, {
            at: this.state.lastTokEndLoc,
            kind: "destructuring"
          });
        } else if (kind === "const" && !(this.match(58) || this.isContextual(101))) {
          this.raise(Errors.DeclarationMissingInitializer, {
            at: this.state.lastTokEndLoc,
            kind: "const"
          });
        }
      }
      declarations.push(this.finishNode(decl, "VariableDeclarator"));
      if (!this.eat(12))
        break;
    }
    return node2;
  }
  parseVarId(decl, kind) {
    if (kind === "using" && !this.inModule && this.match(96)) {
      this.raise(Errors.AwaitInUsingBinding, {
        at: this.state.startLoc
      });
    }
    const id3 = this.parseBindingAtom();
    this.checkLVal(id3, {
      in: {
        type: "VariableDeclarator"
      },
      binding: kind === "var" ? BIND_VAR : BIND_LEXICAL
    });
    decl.id = id3;
  }
  parseAsyncFunctionExpression(node2) {
    return this.parseFunction(node2, 8);
  }
  parseFunction(node2, flags = 0) {
    const hangingDeclaration = flags & 2;
    const isDeclaration = !!(flags & 1);
    const requireId = isDeclaration && !(flags & 4);
    const isAsync = !!(flags & 8);
    this.initFunction(node2, isAsync);
    if (this.match(55)) {
      if (hangingDeclaration) {
        this.raise(Errors.GeneratorInSingleStatementContext, {
          at: this.state.startLoc
        });
      }
      this.next();
      node2.generator = true;
    }
    if (isDeclaration) {
      node2.id = this.parseFunctionId(requireId);
    }
    const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
    this.state.maybeInArrowParameters = false;
    this.scope.enter(SCOPE_FUNCTION);
    this.prodParam.enter(functionFlags(isAsync, node2.generator));
    if (!isDeclaration) {
      node2.id = this.parseFunctionId();
    }
    this.parseFunctionParams(node2, false);
    this.withSmartMixTopicForbiddingContext(() => {
      this.parseFunctionBodyAndFinish(node2, isDeclaration ? "FunctionDeclaration" : "FunctionExpression");
    });
    this.prodParam.exit();
    this.scope.exit();
    if (isDeclaration && !hangingDeclaration) {
      this.registerFunctionStatementId(node2);
    }
    this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
    return node2;
  }
  parseFunctionId(requireId) {
    return requireId || tokenIsIdentifier(this.state.type) ? this.parseIdentifier() : null;
  }
  parseFunctionParams(node2, isConstructor) {
    this.expect(10);
    this.expressionScope.enter(newParameterDeclarationScope());
    node2.params = this.parseBindingList(11, 41, 2 | (isConstructor ? 4 : 0));
    this.expressionScope.exit();
  }
  registerFunctionStatementId(node2) {
    if (!node2.id)
      return;
    this.scope.declareName(node2.id.name, !this.options.annexB || this.state.strict || node2.generator || node2.async ? this.scope.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION, node2.id.loc.start);
  }
  parseClass(node2, isStatement, optionalId) {
    this.next();
    const oldStrict = this.state.strict;
    this.state.strict = true;
    this.parseClassId(node2, isStatement, optionalId);
    this.parseClassSuper(node2);
    node2.body = this.parseClassBody(!!node2.superClass, oldStrict);
    return this.finishNode(node2, isStatement ? "ClassDeclaration" : "ClassExpression");
  }
  isClassProperty() {
    return this.match(29) || this.match(13) || this.match(8);
  }
  isClassMethod() {
    return this.match(10);
  }
  isNonstaticConstructor(method) {
    return !method.computed && !method.static && (method.key.name === "constructor" || method.key.value === "constructor");
  }
  parseClassBody(hadSuperClass, oldStrict) {
    this.classScope.enter();
    const state = {
      hadConstructor: false,
      hadSuperClass
    };
    let decorators = [];
    const classBody = this.startNode();
    classBody.body = [];
    this.expect(5);
    this.withSmartMixTopicForbiddingContext(() => {
      while (!this.match(8)) {
        if (this.eat(13)) {
          if (decorators.length > 0) {
            throw this.raise(Errors.DecoratorSemicolon, {
              at: this.state.lastTokEndLoc
            });
          }
          continue;
        }
        if (this.match(26)) {
          decorators.push(this.parseDecorator());
          continue;
        }
        const member = this.startNode();
        if (decorators.length) {
          member.decorators = decorators;
          this.resetStartLocationFromNode(member, decorators[0]);
          decorators = [];
        }
        this.parseClassMember(classBody, member, state);
        if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) {
          this.raise(Errors.DecoratorConstructor, {
            at: member
          });
        }
      }
    });
    this.state.strict = oldStrict;
    this.next();
    if (decorators.length) {
      throw this.raise(Errors.TrailingDecorator, {
        at: this.state.startLoc
      });
    }
    this.classScope.exit();
    return this.finishNode(classBody, "ClassBody");
  }
  parseClassMemberFromModifier(classBody, member) {
    const key = this.parseIdentifier(true);
    if (this.isClassMethod()) {
      const method = member;
      method.kind = "method";
      method.computed = false;
      method.key = key;
      method.static = false;
      this.pushClassMethod(classBody, method, false, false, false, false);
      return true;
    } else if (this.isClassProperty()) {
      const prop = member;
      prop.computed = false;
      prop.key = key;
      prop.static = false;
      classBody.body.push(this.parseClassProperty(prop));
      return true;
    }
    this.resetPreviousNodeTrailingComments(key);
    return false;
  }
  parseClassMember(classBody, member, state) {
    const isStatic = this.isContextual(104);
    if (isStatic) {
      if (this.parseClassMemberFromModifier(classBody, member)) {
        return;
      }
      if (this.eat(5)) {
        this.parseClassStaticBlock(classBody, member);
        return;
      }
    }
    this.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  }
  parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
    const publicMethod = member;
    const privateMethod = member;
    const publicProp = member;
    const privateProp = member;
    const accessorProp = member;
    const method = publicMethod;
    const publicMember = publicMethod;
    member.static = isStatic;
    this.parsePropertyNamePrefixOperator(member);
    if (this.eat(55)) {
      method.kind = "method";
      const isPrivateName = this.match(136);
      this.parseClassElementName(method);
      if (isPrivateName) {
        this.pushClassPrivateMethod(classBody, privateMethod, true, false);
        return;
      }
      if (this.isNonstaticConstructor(publicMethod)) {
        this.raise(Errors.ConstructorIsGenerator, {
          at: publicMethod.key
        });
      }
      this.pushClassMethod(classBody, publicMethod, true, false, false, false);
      return;
    }
    const isContextual = tokenIsIdentifier(this.state.type) && !this.state.containsEsc;
    const isPrivate = this.match(136);
    const key = this.parseClassElementName(member);
    const maybeQuestionTokenStartLoc = this.state.startLoc;
    this.parsePostMemberNameModifiers(publicMember);
    if (this.isClassMethod()) {
      method.kind = "method";
      if (isPrivate) {
        this.pushClassPrivateMethod(classBody, privateMethod, false, false);
        return;
      }
      const isConstructor = this.isNonstaticConstructor(publicMethod);
      let allowsDirectSuper = false;
      if (isConstructor) {
        publicMethod.kind = "constructor";
        if (state.hadConstructor && !this.hasPlugin("typescript")) {
          this.raise(Errors.DuplicateConstructor, {
            at: key
          });
        }
        if (isConstructor && this.hasPlugin("typescript") && member.override) {
          this.raise(Errors.OverrideOnConstructor, {
            at: key
          });
        }
        state.hadConstructor = true;
        allowsDirectSuper = state.hadSuperClass;
      }
      this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper);
    } else if (this.isClassProperty()) {
      if (isPrivate) {
        this.pushClassPrivateProperty(classBody, privateProp);
      } else {
        this.pushClassProperty(classBody, publicProp);
      }
    } else if (isContextual && key.name === "async" && !this.isLineTerminator()) {
      this.resetPreviousNodeTrailingComments(key);
      const isGenerator = this.eat(55);
      if (publicMember.optional) {
        this.unexpected(maybeQuestionTokenStartLoc);
      }
      method.kind = "method";
      const isPrivate2 = this.match(136);
      this.parseClassElementName(method);
      this.parsePostMemberNameModifiers(publicMember);
      if (isPrivate2) {
        this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true);
      } else {
        if (this.isNonstaticConstructor(publicMethod)) {
          this.raise(Errors.ConstructorIsAsync, {
            at: publicMethod.key
          });
        }
        this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false);
      }
    } else if (isContextual && (key.name === "get" || key.name === "set") && !(this.match(55) && this.isLineTerminator())) {
      this.resetPreviousNodeTrailingComments(key);
      method.kind = key.name;
      const isPrivate2 = this.match(136);
      this.parseClassElementName(publicMethod);
      if (isPrivate2) {
        this.pushClassPrivateMethod(classBody, privateMethod, false, false);
      } else {
        if (this.isNonstaticConstructor(publicMethod)) {
          this.raise(Errors.ConstructorIsAccessor, {
            at: publicMethod.key
          });
        }
        this.pushClassMethod(classBody, publicMethod, false, false, false, false);
      }
      this.checkGetterSetterParams(publicMethod);
    } else if (isContextual && key.name === "accessor" && !this.isLineTerminator()) {
      this.expectPlugin("decoratorAutoAccessors");
      this.resetPreviousNodeTrailingComments(key);
      const isPrivate2 = this.match(136);
      this.parseClassElementName(publicProp);
      this.pushClassAccessorProperty(classBody, accessorProp, isPrivate2);
    } else if (this.isLineTerminator()) {
      if (isPrivate) {
        this.pushClassPrivateProperty(classBody, privateProp);
      } else {
        this.pushClassProperty(classBody, publicProp);
      }
    } else {
      this.unexpected();
    }
  }
  parseClassElementName(member) {
    const {
      type,
      value
    } = this.state;
    if ((type === 130 || type === 131) && member.static && value === "prototype") {
      this.raise(Errors.StaticPrototype, {
        at: this.state.startLoc
      });
    }
    if (type === 136) {
      if (value === "constructor") {
        this.raise(Errors.ConstructorClassPrivateField, {
          at: this.state.startLoc
        });
      }
      const key = this.parsePrivateName();
      member.key = key;
      return key;
    }
    return this.parsePropertyName(member);
  }
  parseClassStaticBlock(classBody, member) {
    var _member$decorators;
    this.scope.enter(SCOPE_CLASS | SCOPE_STATIC_BLOCK | SCOPE_SUPER);
    const oldLabels = this.state.labels;
    this.state.labels = [];
    this.prodParam.enter(PARAM);
    const body = member.body = [];
    this.parseBlockOrModuleBlockBody(body, void 0, false, 8);
    this.prodParam.exit();
    this.scope.exit();
    this.state.labels = oldLabels;
    classBody.body.push(this.finishNode(member, "StaticBlock"));
    if ((_member$decorators = member.decorators) != null && _member$decorators.length) {
      this.raise(Errors.DecoratorStaticBlock, {
        at: member
      });
    }
  }
  pushClassProperty(classBody, prop) {
    if (!prop.computed && (prop.key.name === "constructor" || prop.key.value === "constructor")) {
      this.raise(Errors.ConstructorClassField, {
        at: prop.key
      });
    }
    classBody.body.push(this.parseClassProperty(prop));
  }
  pushClassPrivateProperty(classBody, prop) {
    const node2 = this.parseClassPrivateProperty(prop);
    classBody.body.push(node2);
    this.classScope.declarePrivateName(this.getPrivateNameSV(node2.key), CLASS_ELEMENT_OTHER, node2.key.loc.start);
  }
  pushClassAccessorProperty(classBody, prop, isPrivate) {
    if (!isPrivate && !prop.computed) {
      const key = prop.key;
      if (key.name === "constructor" || key.value === "constructor") {
        this.raise(Errors.ConstructorClassField, {
          at: key
        });
      }
    }
    const node2 = this.parseClassAccessorProperty(prop);
    classBody.body.push(node2);
    if (isPrivate) {
      this.classScope.declarePrivateName(this.getPrivateNameSV(node2.key), CLASS_ELEMENT_OTHER, node2.key.loc.start);
    }
  }
  pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
    classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true));
  }
  pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
    const node2 = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true);
    classBody.body.push(node2);
    const kind = node2.kind === "get" ? node2.static ? CLASS_ELEMENT_STATIC_GETTER : CLASS_ELEMENT_INSTANCE_GETTER : node2.kind === "set" ? node2.static ? CLASS_ELEMENT_STATIC_SETTER : CLASS_ELEMENT_INSTANCE_SETTER : CLASS_ELEMENT_OTHER;
    this.declareClassPrivateMethodInScope(node2, kind);
  }
  declareClassPrivateMethodInScope(node2, kind) {
    this.classScope.declarePrivateName(this.getPrivateNameSV(node2.key), kind, node2.key.loc.start);
  }
  parsePostMemberNameModifiers(methodOrProp) {
  }
  parseClassPrivateProperty(node2) {
    this.parseInitializer(node2);
    this.semicolon();
    return this.finishNode(node2, "ClassPrivateProperty");
  }
  parseClassProperty(node2) {
    this.parseInitializer(node2);
    this.semicolon();
    return this.finishNode(node2, "ClassProperty");
  }
  parseClassAccessorProperty(node2) {
    this.parseInitializer(node2);
    this.semicolon();
    return this.finishNode(node2, "ClassAccessorProperty");
  }
  parseInitializer(node2) {
    this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
    this.expressionScope.enter(newExpressionScope());
    this.prodParam.enter(PARAM);
    node2.value = this.eat(29) ? this.parseMaybeAssignAllowIn() : null;
    this.expressionScope.exit();
    this.prodParam.exit();
    this.scope.exit();
  }
  parseClassId(node2, isStatement, optionalId, bindingType = BIND_CLASS) {
    if (tokenIsIdentifier(this.state.type)) {
      node2.id = this.parseIdentifier();
      if (isStatement) {
        this.declareNameFromIdentifier(node2.id, bindingType);
      }
    } else {
      if (optionalId || !isStatement) {
        node2.id = null;
      } else {
        throw this.raise(Errors.MissingClassName, {
          at: this.state.startLoc
        });
      }
    }
  }
  parseClassSuper(node2) {
    node2.superClass = this.eat(81) ? this.parseExprSubscripts() : null;
  }
  parseExport(node2, decorators) {
    const hasDefault = this.maybeParseExportDefaultSpecifier(node2);
    const parseAfterDefault = !hasDefault || this.eat(12);
    const hasStar = parseAfterDefault && this.eatExportStar(node2);
    const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node2);
    const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(12));
    const isFromRequired = hasDefault || hasStar;
    if (hasStar && !hasNamespace) {
      if (hasDefault)
        this.unexpected();
      if (decorators) {
        throw this.raise(Errors.UnsupportedDecoratorExport, {
          at: node2
        });
      }
      this.parseExportFrom(node2, true);
      return this.finishNode(node2, "ExportAllDeclaration");
    }
    const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node2);
    if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers) {
      this.unexpected(null, 5);
    }
    if (hasNamespace && parseAfterNamespace) {
      this.unexpected(null, 97);
    }
    let hasDeclaration;
    if (isFromRequired || hasSpecifiers) {
      hasDeclaration = false;
      if (decorators) {
        throw this.raise(Errors.UnsupportedDecoratorExport, {
          at: node2
        });
      }
      this.parseExportFrom(node2, isFromRequired);
    } else {
      hasDeclaration = this.maybeParseExportDeclaration(node2);
    }
    if (isFromRequired || hasSpecifiers || hasDeclaration) {
      var _node2$declaration;
      const node22 = node2;
      this.checkExport(node22, true, false, !!node22.source);
      if (((_node2$declaration = node22.declaration) == null ? void 0 : _node2$declaration.type) === "ClassDeclaration") {
        this.maybeTakeDecorators(decorators, node22.declaration, node22);
      } else if (decorators) {
        throw this.raise(Errors.UnsupportedDecoratorExport, {
          at: node2
        });
      }
      return this.finishNode(node22, "ExportNamedDeclaration");
    }
    if (this.eat(65)) {
      const node22 = node2;
      const decl = this.parseExportDefaultExpression();
      node22.declaration = decl;
      if (decl.type === "ClassDeclaration") {
        this.maybeTakeDecorators(decorators, decl, node22);
      } else if (decorators) {
        throw this.raise(Errors.UnsupportedDecoratorExport, {
          at: node2
        });
      }
      this.checkExport(node22, true, true);
      return this.finishNode(node22, "ExportDefaultDeclaration");
    }
    this.unexpected(null, 5);
  }
  eatExportStar(node2) {
    return this.eat(55);
  }
  maybeParseExportDefaultSpecifier(node2) {
    if (this.isExportDefaultSpecifier()) {
      this.expectPlugin("exportDefaultFrom");
      const specifier = this.startNode();
      specifier.exported = this.parseIdentifier(true);
      node2.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
      return true;
    }
    return false;
  }
  maybeParseExportNamespaceSpecifier(node2) {
    if (this.isContextual(93)) {
      if (!node2.specifiers)
        node2.specifiers = [];
      const specifier = this.startNodeAt(this.state.lastTokStartLoc);
      this.next();
      specifier.exported = this.parseModuleExportName();
      node2.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"));
      return true;
    }
    return false;
  }
  maybeParseExportNamedSpecifiers(node2) {
    if (this.match(5)) {
      if (!node2.specifiers)
        node2.specifiers = [];
      const isTypeExport = node2.exportKind === "type";
      node2.specifiers.push(...this.parseExportSpecifiers(isTypeExport));
      node2.source = null;
      node2.declaration = null;
      if (this.hasPlugin("importAssertions")) {
        node2.assertions = [];
      }
      return true;
    }
    return false;
  }
  maybeParseExportDeclaration(node2) {
    if (this.shouldParseExportDeclaration()) {
      node2.specifiers = [];
      node2.source = null;
      if (this.hasPlugin("importAssertions")) {
        node2.assertions = [];
      }
      node2.declaration = this.parseExportDeclaration(node2);
      return true;
    }
    return false;
  }
  isAsyncFunction() {
    if (!this.isContextual(95))
      return false;
    const next = this.nextTokenStart();
    return !lineBreak.test(this.input.slice(this.state.pos, next)) && this.isUnparsedContextual(next, "function");
  }
  parseExportDefaultExpression() {
    const expr = this.startNode();
    if (this.match(68)) {
      this.next();
      return this.parseFunction(expr, 1 | 4);
    } else if (this.isAsyncFunction()) {
      this.next();
      this.next();
      return this.parseFunction(expr, 1 | 4 | 8);
    }
    if (this.match(80)) {
      return this.parseClass(expr, true, true);
    }
    if (this.match(26)) {
      if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport") === true) {
        this.raise(Errors.DecoratorBeforeExport, {
          at: this.state.startLoc
        });
      }
      return this.parseClass(this.maybeTakeDecorators(this.parseDecorators(false), this.startNode()), true, true);
    }
    if (this.match(75) || this.match(74) || this.isLet()) {
      throw this.raise(Errors.UnsupportedDefaultExport, {
        at: this.state.startLoc
      });
    }
    const res = this.parseMaybeAssignAllowIn();
    this.semicolon();
    return res;
  }
  parseExportDeclaration(node2) {
    if (this.match(80)) {
      const node3 = this.parseClass(this.startNode(), true, false);
      return node3;
    }
    return this.parseStatementListItem();
  }
  isExportDefaultSpecifier() {
    const {
      type
    } = this.state;
    if (tokenIsIdentifier(type)) {
      if (type === 95 && !this.state.containsEsc || type === 99) {
        return false;
      }
      if ((type === 128 || type === 127) && !this.state.containsEsc) {
        const {
          type: nextType
        } = this.lookahead();
        if (tokenIsIdentifier(nextType) && nextType !== 97 || nextType === 5) {
          this.expectOnePlugin(["flow", "typescript"]);
          return false;
        }
      }
    } else if (!this.match(65)) {
      return false;
    }
    const next = this.nextTokenStart();
    const hasFrom = this.isUnparsedContextual(next, "from");
    if (this.input.charCodeAt(next) === 44 || tokenIsIdentifier(this.state.type) && hasFrom) {
      return true;
    }
    if (this.match(65) && hasFrom) {
      const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next + 4));
      return nextAfterFrom === 34 || nextAfterFrom === 39;
    }
    return false;
  }
  parseExportFrom(node2, expect) {
    if (this.eatContextual(97)) {
      node2.source = this.parseImportSource();
      this.checkExport(node2);
      const assertions = this.maybeParseImportAssertions();
      if (assertions) {
        node2.assertions = assertions;
        this.checkJSONModuleImport(node2);
      }
    } else if (expect) {
      this.unexpected();
    }
    this.semicolon();
  }
  shouldParseExportDeclaration() {
    const {
      type
    } = this.state;
    if (type === 26) {
      this.expectOnePlugin(["decorators", "decorators-legacy"]);
      if (this.hasPlugin("decorators")) {
        if (this.getPluginOption("decorators", "decoratorsBeforeExport") === true) {
          this.raise(Errors.DecoratorBeforeExport, {
            at: this.state.startLoc
          });
        }
        return true;
      }
    }
    return type === 74 || type === 75 || type === 68 || type === 80 || this.isLet() || this.isAsyncFunction();
  }
  checkExport(node2, checkNames, isDefault, isFrom) {
    if (checkNames) {
      if (isDefault) {
        this.checkDuplicateExports(node2, "default");
        if (this.hasPlugin("exportDefaultFrom")) {
          var _declaration$extra;
          const declaration2 = node2.declaration;
          if (declaration2.type === "Identifier" && declaration2.name === "from" && declaration2.end - declaration2.start === 4 && !((_declaration$extra = declaration2.extra) != null && _declaration$extra.parenthesized)) {
            this.raise(Errors.ExportDefaultFromAsIdentifier, {
              at: declaration2
            });
          }
        }
      } else if (node2.specifiers && node2.specifiers.length) {
        for (const specifier of node2.specifiers) {
          const {
            exported
          } = specifier;
          const exportName = exported.type === "Identifier" ? exported.name : exported.value;
          this.checkDuplicateExports(specifier, exportName);
          if (!isFrom && specifier.local) {
            const {
              local
            } = specifier;
            if (local.type !== "Identifier") {
              this.raise(Errors.ExportBindingIsString, {
                at: specifier,
                localName: local.value,
                exportName
              });
            } else {
              this.checkReservedWord(local.name, local.loc.start, true, false);
              this.scope.checkLocalExport(local);
            }
          }
        }
      } else if (node2.declaration) {
        if (node2.declaration.type === "FunctionDeclaration" || node2.declaration.type === "ClassDeclaration") {
          const id3 = node2.declaration.id;
          if (!id3)
            throw new Error("Assertion failure");
          this.checkDuplicateExports(node2, id3.name);
        } else if (node2.declaration.type === "VariableDeclaration") {
          for (const declaration2 of node2.declaration.declarations) {
            this.checkDeclaration(declaration2.id);
          }
        }
      }
    }
  }
  checkDeclaration(node2) {
    if (node2.type === "Identifier") {
      this.checkDuplicateExports(node2, node2.name);
    } else if (node2.type === "ObjectPattern") {
      for (const prop of node2.properties) {
        this.checkDeclaration(prop);
      }
    } else if (node2.type === "ArrayPattern") {
      for (const elem of node2.elements) {
        if (elem) {
          this.checkDeclaration(elem);
        }
      }
    } else if (node2.type === "ObjectProperty") {
      this.checkDeclaration(node2.value);
    } else if (node2.type === "RestElement") {
      this.checkDeclaration(node2.argument);
    } else if (node2.type === "AssignmentPattern") {
      this.checkDeclaration(node2.left);
    }
  }
  checkDuplicateExports(node2, exportName) {
    if (this.exportedIdentifiers.has(exportName)) {
      if (exportName === "default") {
        this.raise(Errors.DuplicateDefaultExport, {
          at: node2
        });
      } else {
        this.raise(Errors.DuplicateExport, {
          at: node2,
          exportName
        });
      }
    }
    this.exportedIdentifiers.add(exportName);
  }
  parseExportSpecifiers(isInTypeExport) {
    const nodes = [];
    let first2 = true;
    this.expect(5);
    while (!this.eat(8)) {
      if (first2) {
        first2 = false;
      } else {
        this.expect(12);
        if (this.eat(8))
          break;
      }
      const isMaybeTypeOnly = this.isContextual(128);
      const isString2 = this.match(131);
      const node2 = this.startNode();
      node2.local = this.parseModuleExportName();
      nodes.push(this.parseExportSpecifier(node2, isString2, isInTypeExport, isMaybeTypeOnly));
    }
    return nodes;
  }
  parseExportSpecifier(node2, isString2, isInTypeExport, isMaybeTypeOnly) {
    if (this.eatContextual(93)) {
      node2.exported = this.parseModuleExportName();
    } else if (isString2) {
      node2.exported = cloneStringLiteral(node2.local);
    } else if (!node2.exported) {
      node2.exported = cloneIdentifier(node2.local);
    }
    return this.finishNode(node2, "ExportSpecifier");
  }
  parseModuleExportName() {
    if (this.match(131)) {
      const result2 = this.parseStringLiteral(this.state.value);
      const surrogate = result2.value.match(loneSurrogate);
      if (surrogate) {
        this.raise(Errors.ModuleExportNameHasLoneSurrogate, {
          at: result2,
          surrogateCharCode: surrogate[0].charCodeAt(0)
        });
      }
      return result2;
    }
    return this.parseIdentifier(true);
  }
  isJSONModuleImport(node2) {
    if (node2.assertions != null) {
      return node2.assertions.some(({
        key,
        value
      }) => {
        return value.value === "json" && (key.type === "Identifier" ? key.name === "type" : key.value === "type");
      });
    }
    return false;
  }
  checkImportReflection(node2) {
    if (node2.module) {
      var _node$assertions;
      if (node2.specifiers.length !== 1 || node2.specifiers[0].type !== "ImportDefaultSpecifier") {
        this.raise(Errors.ImportReflectionNotBinding, {
          at: node2.specifiers[0].loc.start
        });
      }
      if (((_node$assertions = node2.assertions) == null ? void 0 : _node$assertions.length) > 0) {
        this.raise(Errors.ImportReflectionHasAssertion, {
          at: node2.specifiers[0].loc.start
        });
      }
    }
  }
  checkJSONModuleImport(node2) {
    if (this.isJSONModuleImport(node2) && node2.type !== "ExportAllDeclaration") {
      const {
        specifiers
      } = node2;
      if (specifiers != null) {
        const nonDefaultNamedSpecifier = specifiers.find((specifier) => {
          let imported;
          if (specifier.type === "ExportSpecifier") {
            imported = specifier.local;
          } else if (specifier.type === "ImportSpecifier") {
            imported = specifier.imported;
          }
          if (imported !== void 0) {
            return imported.type === "Identifier" ? imported.name !== "default" : imported.value !== "default";
          }
        });
        if (nonDefaultNamedSpecifier !== void 0) {
          this.raise(Errors.ImportJSONBindingNotDefault, {
            at: nonDefaultNamedSpecifier.loc.start
          });
        }
      }
    }
  }
  parseMaybeImportReflection(node2) {
    let isImportReflection = false;
    if (this.isContextual(125)) {
      const lookahead = this.lookahead();
      const nextType = lookahead.type;
      if (tokenIsIdentifier(nextType)) {
        if (nextType !== 97) {
          isImportReflection = true;
        } else {
          const nextNextTokenFirstChar = this.input.charCodeAt(this.nextTokenStartSince(lookahead.end));
          if (nextNextTokenFirstChar === 102) {
            isImportReflection = true;
          }
        }
      } else if (nextType !== 12) {
        isImportReflection = true;
      }
    }
    if (isImportReflection) {
      this.expectPlugin("importReflection");
      this.next();
      node2.module = true;
    } else if (this.hasPlugin("importReflection")) {
      node2.module = false;
    }
  }
  parseImport(node2) {
    node2.specifiers = [];
    if (!this.match(131)) {
      this.parseMaybeImportReflection(node2);
      const hasDefault = this.maybeParseDefaultImportSpecifier(node2);
      const parseNext = !hasDefault || this.eat(12);
      const hasStar = parseNext && this.maybeParseStarImportSpecifier(node2);
      if (parseNext && !hasStar)
        this.parseNamedImportSpecifiers(node2);
      this.expectContextual(97);
    }
    node2.source = this.parseImportSource();
    const assertions = this.maybeParseImportAssertions();
    if (assertions) {
      node2.assertions = assertions;
    } else {
      const attributes = this.maybeParseModuleAttributes();
      if (attributes) {
        node2.attributes = attributes;
      }
    }
    this.checkImportReflection(node2);
    this.checkJSONModuleImport(node2);
    this.semicolon();
    return this.finishNode(node2, "ImportDeclaration");
  }
  parseImportSource() {
    if (!this.match(131))
      this.unexpected();
    return this.parseExprAtom();
  }
  shouldParseDefaultImport(node2) {
    return tokenIsIdentifier(this.state.type);
  }
  parseImportSpecifierLocal(node2, specifier, type) {
    specifier.local = this.parseIdentifier();
    node2.specifiers.push(this.finishImportSpecifier(specifier, type));
  }
  finishImportSpecifier(specifier, type, bindingType = BIND_LEXICAL) {
    this.checkLVal(specifier.local, {
      in: {
        type
      },
      binding: bindingType
    });
    return this.finishNode(specifier, type);
  }
  parseAssertEntries() {
    const attrs = [];
    const attrNames = /* @__PURE__ */ new Set();
    do {
      if (this.match(8)) {
        break;
      }
      const node2 = this.startNode();
      const keyName = this.state.value;
      if (attrNames.has(keyName)) {
        this.raise(Errors.ModuleAttributesWithDuplicateKeys, {
          at: this.state.startLoc,
          key: keyName
        });
      }
      attrNames.add(keyName);
      if (this.match(131)) {
        node2.key = this.parseStringLiteral(keyName);
      } else {
        node2.key = this.parseIdentifier(true);
      }
      this.expect(14);
      if (!this.match(131)) {
        throw this.raise(Errors.ModuleAttributeInvalidValue, {
          at: this.state.startLoc
        });
      }
      node2.value = this.parseStringLiteral(this.state.value);
      attrs.push(this.finishNode(node2, "ImportAttribute"));
    } while (this.eat(12));
    return attrs;
  }
  maybeParseModuleAttributes() {
    if (this.match(76) && !this.hasPrecedingLineBreak()) {
      this.expectPlugin("moduleAttributes");
      this.next();
    } else {
      if (this.hasPlugin("moduleAttributes"))
        return [];
      return null;
    }
    const attrs = [];
    const attributes = /* @__PURE__ */ new Set();
    do {
      const node2 = this.startNode();
      node2.key = this.parseIdentifier(true);
      if (node2.key.name !== "type") {
        this.raise(Errors.ModuleAttributeDifferentFromType, {
          at: node2.key
        });
      }
      if (attributes.has(node2.key.name)) {
        this.raise(Errors.ModuleAttributesWithDuplicateKeys, {
          at: node2.key,
          key: node2.key.name
        });
      }
      attributes.add(node2.key.name);
      this.expect(14);
      if (!this.match(131)) {
        throw this.raise(Errors.ModuleAttributeInvalidValue, {
          at: this.state.startLoc
        });
      }
      node2.value = this.parseStringLiteral(this.state.value);
      this.finishNode(node2, "ImportAttribute");
      attrs.push(node2);
    } while (this.eat(12));
    return attrs;
  }
  maybeParseImportAssertions() {
    if (this.isContextual(94) && !this.hasPrecedingLineBreak()) {
      this.expectPlugin("importAssertions");
      this.next();
    } else {
      if (this.hasPlugin("importAssertions"))
        return [];
      return null;
    }
    this.eat(5);
    const attrs = this.parseAssertEntries();
    this.eat(8);
    return attrs;
  }
  maybeParseDefaultImportSpecifier(node2) {
    if (this.shouldParseDefaultImport(node2)) {
      this.parseImportSpecifierLocal(node2, this.startNode(), "ImportDefaultSpecifier");
      return true;
    }
    return false;
  }
  maybeParseStarImportSpecifier(node2) {
    if (this.match(55)) {
      const specifier = this.startNode();
      this.next();
      this.expectContextual(93);
      this.parseImportSpecifierLocal(node2, specifier, "ImportNamespaceSpecifier");
      return true;
    }
    return false;
  }
  parseNamedImportSpecifiers(node2) {
    let first2 = true;
    this.expect(5);
    while (!this.eat(8)) {
      if (first2) {
        first2 = false;
      } else {
        if (this.eat(14)) {
          throw this.raise(Errors.DestructureNamedImport, {
            at: this.state.startLoc
          });
        }
        this.expect(12);
        if (this.eat(8))
          break;
      }
      const specifier = this.startNode();
      const importedIsString = this.match(131);
      const isMaybeTypeOnly = this.isContextual(128);
      specifier.imported = this.parseModuleExportName();
      const importSpecifier = this.parseImportSpecifier(specifier, importedIsString, node2.importKind === "type" || node2.importKind === "typeof", isMaybeTypeOnly, void 0);
      node2.specifiers.push(importSpecifier);
    }
  }
  parseImportSpecifier(specifier, importedIsString, isInTypeOnlyImport, isMaybeTypeOnly, bindingType) {
    if (this.eatContextual(93)) {
      specifier.local = this.parseIdentifier();
    } else {
      const {
        imported
      } = specifier;
      if (importedIsString) {
        throw this.raise(Errors.ImportBindingIsString, {
          at: specifier,
          importName: imported.value
        });
      }
      this.checkReservedWord(imported.name, specifier.loc.start, true, true);
      if (!specifier.local) {
        specifier.local = cloneIdentifier(imported);
      }
    }
    return this.finishImportSpecifier(specifier, "ImportSpecifier", bindingType);
  }
  isThisParam(param) {
    return param.type === "Identifier" && param.name === "this";
  }
}
let Parser$2 = class Parser3 extends StatementParser {
  constructor(options, input2) {
    options = getOptions(options);
    super(options, input2);
    this.options = options;
    this.initializeScopes();
    this.plugins = pluginsMap(this.options.plugins);
    this.filename = options.sourceFilename;
  }
  getScopeHandler() {
    return ScopeHandler;
  }
  parse() {
    this.enterInitialScopes();
    const file = this.startNode();
    const program = this.startNode();
    this.nextToken();
    file.errors = null;
    this.parseTopLevel(file, program);
    file.errors = this.state.errors;
    return file;
  }
};
function pluginsMap(plugins) {
  const pluginMap = /* @__PURE__ */ new Map();
  for (const plugin2 of plugins) {
    const [name, options] = Array.isArray(plugin2) ? plugin2 : [plugin2, {}];
    if (!pluginMap.has(name))
      pluginMap.set(name, options || {});
  }
  return pluginMap;
}
function parse$9(input2, options) {
  var _options;
  if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") {
    options = Object.assign({}, options);
    try {
      options.sourceType = "module";
      const parser2 = getParser(options, input2);
      const ast = parser2.parse();
      if (parser2.sawUnambiguousESM) {
        return ast;
      }
      if (parser2.ambiguousScriptDifferentAst) {
        try {
          options.sourceType = "script";
          return getParser(options, input2).parse();
        } catch (_unused) {
        }
      } else {
        ast.program.sourceType = "script";
      }
      return ast;
    } catch (moduleError) {
      try {
        options.sourceType = "script";
        return getParser(options, input2).parse();
      } catch (_unused2) {
      }
      throw moduleError;
    }
  } else {
    return getParser(options, input2).parse();
  }
}
function parseExpression(input2, options) {
  const parser2 = getParser(options, input2);
  if (parser2.options.strictMode) {
    parser2.state.strict = true;
  }
  return parser2.getExpression();
}
function generateExportedTokenTypes(internalTokenTypes) {
  const tokenTypes2 = {};
  for (const typeName of Object.keys(internalTokenTypes)) {
    tokenTypes2[typeName] = getExportedToken(internalTokenTypes[typeName]);
  }
  return tokenTypes2;
}
const tokTypes = generateExportedTokenTypes(tt);
function getParser(options, input2) {
  let cls = Parser$2;
  if (options != null && options.plugins) {
    validatePlugins(options.plugins);
    cls = getParserClass(options.plugins);
  }
  return new cls(options, input2);
}
const parserClassCache = {};
function getParserClass(pluginsFromOptions) {
  const pluginList = mixinPluginNames.filter((name) => hasPlugin(pluginsFromOptions, name));
  const key = pluginList.join("/");
  let cls = parserClassCache[key];
  if (!cls) {
    cls = Parser$2;
    for (const plugin2 of pluginList) {
      cls = mixinPlugins[plugin2](cls);
    }
    parserClassCache[key] = cls;
  }
  return cls;
}
var parse_1$1 = lib$1.parse = parse$9;
var parseExpression_1 = lib$1.parseExpression = parseExpression;
lib$1.tokTypes = tokTypes;
const isStaticExp = (p2) => p2.type === 4 && p2.isStatic;
const isBuiltInType = (tag3, expected) => tag3 === expected || tag3 === hyphenate(expected);
function isCoreComponent(tag3) {
  if (isBuiltInType(tag3, "Teleport")) {
    return TELEPORT;
  } else if (isBuiltInType(tag3, "Suspense")) {
    return SUSPENSE;
  } else if (isBuiltInType(tag3, "KeepAlive")) {
    return KEEP_ALIVE;
  } else if (isBuiltInType(tag3, "BaseTransition")) {
    return BASE_TRANSITION;
  }
}
const nonIdentifierRE = /^\d|[^\$\w]/;
const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
const validFirstIdentCharRE = /[A-Za-z_$\xA0-\uFFFF]/;
const validIdentCharRE = /[\.\?\w$\xA0-\uFFFF]/;
const whitespaceRE = /\s+[.[]\s*|\s*[.[]\s+/g;
const isMemberExpressionBrowser = (path2) => {
  path2 = path2.trim().replace(whitespaceRE, (s) => s.trim());
  let state = 0;
  let stateStack = [];
  let currentOpenBracketCount = 0;
  let currentOpenParensCount = 0;
  let currentStringType = null;
  for (let i = 0; i < path2.length; i++) {
    const char = path2.charAt(i);
    switch (state) {
      case 0:
        if (char === "[") {
          stateStack.push(state);
          state = 1;
          currentOpenBracketCount++;
        } else if (char === "(") {
          stateStack.push(state);
          state = 2;
          currentOpenParensCount++;
        } else if (!(i === 0 ? validFirstIdentCharRE : validIdentCharRE).test(char)) {
          return false;
        }
        break;
      case 1:
        if (char === `'` || char === `"` || char === "`") {
          stateStack.push(state);
          state = 3;
          currentStringType = char;
        } else if (char === `[`) {
          currentOpenBracketCount++;
        } else if (char === `]`) {
          if (!--currentOpenBracketCount) {
            state = stateStack.pop();
          }
        }
        break;
      case 2:
        if (char === `'` || char === `"` || char === "`") {
          stateStack.push(state);
          state = 3;
          currentStringType = char;
        } else if (char === `(`) {
          currentOpenParensCount++;
        } else if (char === `)`) {
          if (i === path2.length - 1) {
            return false;
          }
          if (!--currentOpenParensCount) {
            state = stateStack.pop();
          }
        }
        break;
      case 3:
        if (char === currentStringType) {
          state = stateStack.pop();
          currentStringType = null;
        }
        break;
    }
  }
  return !currentOpenBracketCount && !currentOpenParensCount;
};
const isMemberExpressionNode = (path2, context) => {
  try {
    let ret = parseExpression_1(path2, {
      plugins: context.expressionPlugins
    });
    if (ret.type === "TSAsExpression" || ret.type === "TSTypeAssertion") {
      ret = ret.expression;
    }
    return ret.type === "MemberExpression" || ret.type === "OptionalMemberExpression" || ret.type === "Identifier";
  } catch (e) {
    return false;
  }
};
const isMemberExpression = isMemberExpressionNode;
function getInnerRange(loc, offset, length2) {
  const source = loc.source.slice(offset, offset + length2);
  const newLoc = {
    source,
    start: advancePositionWithClone(loc.start, loc.source, offset),
    end: loc.end
  };
  if (length2 != null) {
    newLoc.end = advancePositionWithClone(
      loc.start,
      loc.source,
      offset + length2
    );
  }
  return newLoc;
}
function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
  return advancePositionWithMutation(
    extend({}, pos),
    source,
    numberOfCharacters
  );
}
function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
  let linesCount = 0;
  let lastNewLinePos = -1;
  for (let i = 0; i < numberOfCharacters; i++) {
    if (source.charCodeAt(i) === 10) {
      linesCount++;
      lastNewLinePos = i;
    }
  }
  pos.offset += numberOfCharacters;
  pos.line += linesCount;
  pos.column = lastNewLinePos === -1 ? pos.column + numberOfCharacters : numberOfCharacters - lastNewLinePos;
  return pos;
}
function assert(condition, msg) {
  if (!condition) {
    throw new Error(msg || `unexpected compiler condition`);
  }
}
function findDir(node2, name, allowEmpty = false) {
  for (let i = 0; i < node2.props.length; i++) {
    const p2 = node2.props[i];
    if (p2.type === 7 && (allowEmpty || p2.exp) && (isString$2(name) ? p2.name === name : name.test(p2.name))) {
      return p2;
    }
  }
}
function findProp(node2, name, dynamicOnly = false, allowEmpty = false) {
  for (let i = 0; i < node2.props.length; i++) {
    const p2 = node2.props[i];
    if (p2.type === 6) {
      if (dynamicOnly)
        continue;
      if (p2.name === name && (p2.value || allowEmpty)) {
        return p2;
      }
    } else if (p2.name === "bind" && (p2.exp || allowEmpty) && isStaticArgOf(p2.arg, name)) {
      return p2;
    }
  }
}
function isStaticArgOf(arg, name) {
  return !!(arg && isStaticExp(arg) && arg.content === name);
}
function hasDynamicKeyVBind(node2) {
  return node2.props.some(
    (p2) => p2.type === 7 && p2.name === "bind" && (!p2.arg || // v-bind="obj"
    p2.arg.type !== 4 || // v-bind:[_ctx.foo]
    !p2.arg.isStatic)
    // v-bind:[foo]
  );
}
function isText$1(node2) {
  return node2.type === 5 || node2.type === 2;
}
function isVSlot(p2) {
  return p2.type === 7 && p2.name === "slot";
}
function isTemplateNode(node2) {
  return node2.type === 1 && node2.tagType === 3;
}
function isSlotOutlet(node2) {
  return node2.type === 1 && node2.tagType === 2;
}
const propsHelperSet = /* @__PURE__ */ new Set([NORMALIZE_PROPS, GUARD_REACTIVE_PROPS]);
function getUnnormalizedProps(props, callPath = []) {
  if (props && !isString$2(props) && props.type === 14) {
    const callee = props.callee;
    if (!isString$2(callee) && propsHelperSet.has(callee)) {
      return getUnnormalizedProps(
        props.arguments[0],
        callPath.concat(props)
      );
    }
  }
  return [props, callPath];
}
function injectProp(node2, prop, context) {
  let propsWithInjection;
  let props = node2.type === 13 ? node2.props : node2.arguments[2];
  let callPath = [];
  let parentCall;
  if (props && !isString$2(props) && props.type === 14) {
    const ret = getUnnormalizedProps(props);
    props = ret[0];
    callPath = ret[1];
    parentCall = callPath[callPath.length - 1];
  }
  if (props == null || isString$2(props)) {
    propsWithInjection = createObjectExpression([prop]);
  } else if (props.type === 14) {
    const first2 = props.arguments[0];
    if (!isString$2(first2) && first2.type === 15) {
      if (!hasProp(prop, first2)) {
        first2.properties.unshift(prop);
      }
    } else {
      if (props.callee === TO_HANDLERS) {
        propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
          createObjectExpression([prop]),
          props
        ]);
      } else {
        props.arguments.unshift(createObjectExpression([prop]));
      }
    }
    !propsWithInjection && (propsWithInjection = props);
  } else if (props.type === 15) {
    if (!hasProp(prop, props)) {
      props.properties.unshift(prop);
    }
    propsWithInjection = props;
  } else {
    propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
      createObjectExpression([prop]),
      props
    ]);
    if (parentCall && parentCall.callee === GUARD_REACTIVE_PROPS) {
      parentCall = callPath[callPath.length - 2];
    }
  }
  if (node2.type === 13) {
    if (parentCall) {
      parentCall.arguments[0] = propsWithInjection;
    } else {
      node2.props = propsWithInjection;
    }
  } else {
    if (parentCall) {
      parentCall.arguments[0] = propsWithInjection;
    } else {
      node2.arguments[2] = propsWithInjection;
    }
  }
}
function hasProp(prop, props) {
  let result2 = false;
  if (prop.key.type === 4) {
    const propKeyName = prop.key.content;
    result2 = props.properties.some(
      (p2) => p2.key.type === 4 && p2.key.content === propKeyName
    );
  }
  return result2;
}
function toValidAssetId(name, type) {
  return `_${type}_${name.replace(/[^\w]/g, (searchValue, replaceValue) => {
    return searchValue === "-" ? "_" : name.charCodeAt(replaceValue).toString();
  })}`;
}
function hasScopeRef(node2, ids) {
  if (!node2 || Object.keys(ids).length === 0) {
    return false;
  }
  switch (node2.type) {
    case 1:
      for (let i = 0; i < node2.props.length; i++) {
        const p2 = node2.props[i];
        if (p2.type === 7 && (hasScopeRef(p2.arg, ids) || hasScopeRef(p2.exp, ids))) {
          return true;
        }
      }
      return node2.children.some((c) => hasScopeRef(c, ids));
    case 11:
      if (hasScopeRef(node2.source, ids)) {
        return true;
      }
      return node2.children.some((c) => hasScopeRef(c, ids));
    case 9:
      return node2.branches.some((b) => hasScopeRef(b, ids));
    case 10:
      if (hasScopeRef(node2.condition, ids)) {
        return true;
      }
      return node2.children.some((c) => hasScopeRef(c, ids));
    case 4:
      return !node2.isStatic && isSimpleIdentifier(node2.content) && !!ids[node2.content];
    case 8:
      return node2.children.some((c) => isObject$2(c) && hasScopeRef(c, ids));
    case 5:
    case 12:
      return hasScopeRef(node2.content, ids);
    case 2:
    case 3:
      return false;
    default:
      return false;
  }
}
function getMemoedVNodeCall(node2) {
  if (node2.type === 14 && node2.callee === WITH_MEMO) {
    return node2.arguments[1].returns;
  } else {
    return node2;
  }
}
const deprecationData = {
  ["COMPILER_IS_ON_ELEMENT"]: {
    message: `Platform-native elements with "is" prop will no longer be treated as components in Vue 3 unless the "is" value is explicitly prefixed with "vue:".`,
    link: `https://v3-migration.vuejs.org/breaking-changes/custom-elements-interop.html`
  },
  ["COMPILER_V_BIND_SYNC"]: {
    message: (key) => `.sync modifier for v-bind has been removed. Use v-model with argument instead. \`v-bind:${key}.sync\` should be changed to \`v-model:${key}\`.`,
    link: `https://v3-migration.vuejs.org/breaking-changes/v-model.html`
  },
  ["COMPILER_V_BIND_PROP"]: {
    message: `.prop modifier for v-bind has been removed and no longer necessary. Vue 3 will automatically set a binding as DOM property when appropriate.`
  },
  ["COMPILER_V_BIND_OBJECT_ORDER"]: {
    message: `v-bind="obj" usage is now order sensitive and behaves like JavaScript object spread: it will now overwrite an existing non-mergeable attribute that appears before v-bind in the case of conflict. To retain 2.x behavior, move v-bind to make it the first attribute. You can also suppress this warning if the usage is intended.`,
    link: `https://v3-migration.vuejs.org/breaking-changes/v-bind.html`
  },
  ["COMPILER_V_ON_NATIVE"]: {
    message: `.native modifier for v-on has been removed as is no longer necessary.`,
    link: `https://v3-migration.vuejs.org/breaking-changes/v-on-native-modifier-removed.html`
  },
  ["COMPILER_V_IF_V_FOR_PRECEDENCE"]: {
    message: `v-if / v-for precedence when used on the same element has changed in Vue 3: v-if now takes higher precedence and will no longer have access to v-for scope variables. It is best to avoid the ambiguity with <template> tags or use a computed property that filters v-for data source.`,
    link: `https://v3-migration.vuejs.org/breaking-changes/v-if-v-for.html`
  },
  ["COMPILER_NATIVE_TEMPLATE"]: {
    message: `<template> with no special directives will render as a native template element instead of its inner content in Vue 3.`
  },
  ["COMPILER_INLINE_TEMPLATE"]: {
    message: `"inline-template" has been removed in Vue 3.`,
    link: `https://v3-migration.vuejs.org/breaking-changes/inline-template-attribute.html`
  },
  ["COMPILER_FILTER"]: {
    message: `filters have been removed in Vue 3. The "|" symbol will be treated as native JavaScript bitwise OR operator. Use method calls or computed properties instead.`,
    link: `https://v3-migration.vuejs.org/breaking-changes/filters.html`
  }
};
function getCompatValue(key, context) {
  const config2 = context.options ? context.options.compatConfig : context.compatConfig;
  const value = config2 && config2[key];
  if (key === "MODE") {
    return value || 3;
  } else {
    return value;
  }
}
function isCompatEnabled(key, context) {
  const mode = getCompatValue("MODE", context);
  const value = getCompatValue(key, context);
  return mode === 3 ? value === true : value !== false;
}
function checkCompatEnabled(key, context, loc, ...args) {
  const enabled = isCompatEnabled(key, context);
  if (enabled) {
    warnDeprecation(key, context, loc, ...args);
  }
  return enabled;
}
function warnDeprecation(key, context, loc, ...args) {
  const val = getCompatValue(key, context);
  if (val === "suppress-warning") {
    return;
  }
  const { message, link: link2 } = deprecationData[key];
  const msg = `(deprecation ${key}) ${typeof message === "function" ? message(...args) : message}${link2 ? `
  Details: ${link2}` : ``}`;
  const err = new SyntaxError(msg);
  err.code = key;
  if (loc)
    err.loc = loc;
  context.onWarn(err);
}
const decodeRE = /&(gt|lt|amp|apos|quot);/g;
const decodeMap = {
  gt: ">",
  lt: "<",
  amp: "&",
  apos: "'",
  quot: '"'
};
const defaultParserOptions = {
  delimiters: [`{{`, `}}`],
  getNamespace: () => 0,
  getTextMode: () => 0,
  isVoidTag: NO,
  isPreTag: NO,
  isCustomElement: NO,
  decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
  onError: defaultOnError,
  onWarn: defaultOnWarn,
  comments: true
};
function baseParse(content, options = {}) {
  const context = createParserContext(content, options);
  const start = getCursor(context);
  return createRoot(
    parseChildren(context, 0, []),
    getSelection(context, start)
  );
}
function createParserContext(content, rawOptions) {
  const options = extend({}, defaultParserOptions);
  let key;
  for (key in rawOptions) {
    options[key] = rawOptions[key] === void 0 ? defaultParserOptions[key] : rawOptions[key];
  }
  return {
    options,
    column: 1,
    line: 1,
    offset: 0,
    originalSource: content,
    source: content,
    inPre: false,
    inVPre: false,
    onWarn: options.onWarn
  };
}
function parseChildren(context, mode, ancestors) {
  const parent = last(ancestors);
  const ns = parent ? parent.ns : 0;
  const nodes = [];
  while (!isEnd(context, mode, ancestors)) {
    const s = context.source;
    let node2 = void 0;
    if (mode === 0 || mode === 1) {
      if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
        node2 = parseInterpolation(context, mode);
      } else if (mode === 0 && s[0] === "<") {
        if (s.length === 1) {
          emitError(context, 5, 1);
        } else if (s[1] === "!") {
          if (startsWith(s, "<!--")) {
            node2 = parseComment(context);
          } else if (startsWith(s, "<!DOCTYPE")) {
            node2 = parseBogusComment(context);
          } else if (startsWith(s, "<![CDATA[")) {
            if (ns !== 0) {
              node2 = parseCDATA(context, ancestors);
            } else {
              emitError(context, 1);
              node2 = parseBogusComment(context);
            }
          } else {
            emitError(context, 11);
            node2 = parseBogusComment(context);
          }
        } else if (s[1] === "/") {
          if (s.length === 2) {
            emitError(context, 5, 2);
          } else if (s[2] === ">") {
            emitError(context, 14, 2);
            advanceBy(context, 3);
            continue;
          } else if (/[a-z]/i.test(s[2])) {
            emitError(context, 23);
            parseTag(context, TagType.End, parent);
            continue;
          } else {
            emitError(
              context,
              12,
              2
            );
            node2 = parseBogusComment(context);
          }
        } else if (/[a-z]/i.test(s[1])) {
          node2 = parseElement(context, ancestors);
        } else if (s[1] === "?") {
          emitError(
            context,
            21,
            1
          );
          node2 = parseBogusComment(context);
        } else {
          emitError(context, 12, 1);
        }
      }
    }
    if (!node2) {
      node2 = parseText(context, mode);
    }
    if (isArray$3(node2)) {
      for (let i = 0; i < node2.length; i++) {
        pushNode(nodes, node2[i]);
      }
    } else {
      pushNode(nodes, node2);
    }
  }
  let removedWhitespace = false;
  if (mode !== 2 && mode !== 1) {
    const shouldCondense = context.options.whitespace !== "preserve";
    for (let i = 0; i < nodes.length; i++) {
      const node2 = nodes[i];
      if (node2.type === 2) {
        if (!context.inPre) {
          if (!/[^\t\r\n\f ]/.test(node2.content)) {
            const prev = nodes[i - 1];
            const next = nodes[i + 1];
            if (!prev || !next || shouldCondense && (prev.type === 3 && next.type === 3 || prev.type === 3 && next.type === 1 || prev.type === 1 && next.type === 3 || prev.type === 1 && next.type === 1 && /[\r\n]/.test(node2.content))) {
              removedWhitespace = true;
              nodes[i] = null;
            } else {
              node2.content = " ";
            }
          } else if (shouldCondense) {
            node2.content = node2.content.replace(/[\t\r\n\f ]+/g, " ");
          }
        } else {
          node2.content = node2.content.replace(/\r\n/g, "\n");
        }
      } else if (node2.type === 3 && !context.options.comments) {
        removedWhitespace = true;
        nodes[i] = null;
      }
    }
    if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
      const first2 = nodes[0];
      if (first2 && first2.type === 2) {
        first2.content = first2.content.replace(/^\r?\n/, "");
      }
    }
  }
  return removedWhitespace ? nodes.filter(Boolean) : nodes;
}
function pushNode(nodes, node2) {
  if (node2.type === 2) {
    const prev = last(nodes);
    if (prev && prev.type === 2 && prev.loc.end.offset === node2.loc.start.offset) {
      prev.content += node2.content;
      prev.loc.end = node2.loc.end;
      prev.loc.source += node2.loc.source;
      return;
    }
  }
  nodes.push(node2);
}
function parseCDATA(context, ancestors) {
  advanceBy(context, 9);
  const nodes = parseChildren(context, 3, ancestors);
  if (context.source.length === 0) {
    emitError(context, 6);
  } else {
    advanceBy(context, 3);
  }
  return nodes;
}
function parseComment(context) {
  const start = getCursor(context);
  let content;
  const match2 = /--(\!)?>/.exec(context.source);
  if (!match2) {
    content = context.source.slice(4);
    advanceBy(context, context.source.length);
    emitError(context, 7);
  } else {
    if (match2.index <= 3) {
      emitError(context, 0);
    }
    if (match2[1]) {
      emitError(context, 10);
    }
    content = context.source.slice(4, match2.index);
    const s = context.source.slice(0, match2.index);
    let prevIndex = 1, nestedIndex = 0;
    while ((nestedIndex = s.indexOf("<!--", prevIndex)) !== -1) {
      advanceBy(context, nestedIndex - prevIndex + 1);
      if (nestedIndex + 4 < s.length) {
        emitError(context, 16);
      }
      prevIndex = nestedIndex + 1;
    }
    advanceBy(context, match2.index + match2[0].length - prevIndex + 1);
  }
  return {
    type: 3,
    content,
    loc: getSelection(context, start)
  };
}
function parseBogusComment(context) {
  const start = getCursor(context);
  const contentStart = context.source[1] === "?" ? 1 : 2;
  let content;
  const closeIndex = context.source.indexOf(">");
  if (closeIndex === -1) {
    content = context.source.slice(contentStart);
    advanceBy(context, context.source.length);
  } else {
    content = context.source.slice(contentStart, closeIndex);
    advanceBy(context, closeIndex + 1);
  }
  return {
    type: 3,
    content,
    loc: getSelection(context, start)
  };
}
function parseElement(context, ancestors) {
  const wasInPre = context.inPre;
  const wasInVPre = context.inVPre;
  const parent = last(ancestors);
  const element = parseTag(context, TagType.Start, parent);
  const isPreBoundary = context.inPre && !wasInPre;
  const isVPreBoundary = context.inVPre && !wasInVPre;
  if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
    if (isPreBoundary) {
      context.inPre = false;
    }
    if (isVPreBoundary) {
      context.inVPre = false;
    }
    return element;
  }
  ancestors.push(element);
  const mode = context.options.getTextMode(element, parent);
  const children = parseChildren(context, mode, ancestors);
  ancestors.pop();
  element.children = children;
  if (startsWithEndTagOpen(context.source, element.tag)) {
    parseTag(context, TagType.End, parent);
  } else {
    emitError(context, 24, 0, element.loc.start);
    if (context.source.length === 0 && element.tag.toLowerCase() === "script") {
      const first2 = children[0];
      if (first2 && startsWith(first2.loc.source, "<!--")) {
        emitError(context, 8);
      }
    }
  }
  element.loc = getSelection(context, element.loc.start);
  if (isPreBoundary) {
    context.inPre = false;
  }
  if (isVPreBoundary) {
    context.inVPre = false;
  }
  return element;
}
var TagType = /* @__PURE__ */ ((TagType2) => {
  TagType2[TagType2["Start"] = 0] = "Start";
  TagType2[TagType2["End"] = 1] = "End";
  return TagType2;
})(TagType || {});
const isSpecialTemplateDirective = /* @__PURE__ */ makeMap(
  `if,else,else-if,for,slot`
);
function parseTag(context, type, parent) {
  const start = getCursor(context);
  const match2 = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
  const tag3 = match2[1];
  const ns = context.options.getNamespace(tag3, parent);
  advanceBy(context, match2[0].length);
  advanceSpaces(context);
  const cursor = getCursor(context);
  const currentSource = context.source;
  if (context.options.isPreTag(tag3)) {
    context.inPre = true;
  }
  let props = parseAttributes(context, type);
  if (type === 0 && !context.inVPre && props.some((p2) => p2.type === 7 && p2.name === "pre")) {
    context.inVPre = true;
    extend(context, cursor);
    context.source = currentSource;
    props = parseAttributes(context, type).filter((p2) => p2.name !== "v-pre");
  }
  let isSelfClosing = false;
  if (context.source.length === 0) {
    emitError(context, 9);
  } else {
    isSelfClosing = startsWith(context.source, "/>");
    if (type === 1 && isSelfClosing) {
      emitError(context, 4);
    }
    advanceBy(context, isSelfClosing ? 2 : 1);
  }
  if (type === 1) {
    return;
  }
  let tagType = 0;
  if (!context.inVPre) {
    if (tag3 === "slot") {
      tagType = 2;
    } else if (tag3 === "template") {
      if (props.some(
        (p2) => p2.type === 7 && isSpecialTemplateDirective(p2.name)
      )) {
        tagType = 3;
      }
    } else if (isComponent(tag3, props, context)) {
      tagType = 1;
    }
  }
  return {
    type: 1,
    ns,
    tag: tag3,
    tagType,
    props,
    isSelfClosing,
    children: [],
    loc: getSelection(context, start),
    codegenNode: void 0
    // to be created during transform phase
  };
}
function isComponent(tag3, props, context) {
  const options = context.options;
  if (options.isCustomElement(tag3)) {
    return false;
  }
  if (tag3 === "component" || /^[A-Z]/.test(tag3) || isCoreComponent(tag3) || options.isBuiltInComponent && options.isBuiltInComponent(tag3) || options.isNativeTag && !options.isNativeTag(tag3)) {
    return true;
  }
  for (let i = 0; i < props.length; i++) {
    const p2 = props[i];
    if (p2.type === 6) {
      if (p2.name === "is" && p2.value) {
        if (p2.value.content.startsWith("vue:")) {
          return true;
        }
      }
    } else {
      if (p2.name === "is") {
        return true;
      } else if (
        // :is on plain element - only treat as component in compat mode
        p2.name === "bind" && isStaticArgOf(p2.arg, "is") && false
      ) {
        return true;
      }
    }
  }
}
function parseAttributes(context, type) {
  const props = [];
  const attributeNames = /* @__PURE__ */ new Set();
  while (context.source.length > 0 && !startsWith(context.source, ">") && !startsWith(context.source, "/>")) {
    if (startsWith(context.source, "/")) {
      emitError(context, 22);
      advanceBy(context, 1);
      advanceSpaces(context);
      continue;
    }
    if (type === 1) {
      emitError(context, 3);
    }
    const attr = parseAttribute(context, attributeNames);
    if (attr.type === 6 && attr.value && attr.name === "class") {
      attr.value.content = attr.value.content.replace(/\s+/g, " ").trim();
    }
    if (type === 0) {
      props.push(attr);
    }
    if (/^[^\t\r\n\f />]/.test(context.source)) {
      emitError(context, 15);
    }
    advanceSpaces(context);
  }
  return props;
}
function parseAttribute(context, nameSet) {
  var _a2;
  const start = getCursor(context);
  const match2 = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
  const name = match2[0];
  if (nameSet.has(name)) {
    emitError(context, 2);
  }
  nameSet.add(name);
  if (name[0] === "=") {
    emitError(context, 19);
  }
  {
    const pattern = /["'<]/g;
    let m;
    while (m = pattern.exec(name)) {
      emitError(
        context,
        17,
        m.index
      );
    }
  }
  advanceBy(context, name.length);
  let value = void 0;
  if (/^[\t\r\n\f ]*=/.test(context.source)) {
    advanceSpaces(context);
    advanceBy(context, 1);
    advanceSpaces(context);
    value = parseAttributeValue(context);
    if (!value) {
      emitError(context, 13);
    }
  }
  const loc = getSelection(context, start);
  if (!context.inVPre && /^(v-[A-Za-z0-9-]|:|\.|@|#)/.test(name)) {
    const match22 = /(?:^v-([a-z0-9-]+))?(?:(?::|^\.|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(
      name
    );
    let isPropShorthand = startsWith(name, ".");
    let dirName = match22[1] || (isPropShorthand || startsWith(name, ":") ? "bind" : startsWith(name, "@") ? "on" : "slot");
    let arg;
    if (match22[2]) {
      const isSlot = dirName === "slot";
      const startOffset = name.lastIndexOf(
        match22[2],
        name.length - (((_a2 = match22[3]) == null ? void 0 : _a2.length) || 0)
      );
      const loc2 = getSelection(
        context,
        getNewPosition(context, start, startOffset),
        getNewPosition(
          context,
          start,
          startOffset + match22[2].length + (isSlot && match22[3] || "").length
        )
      );
      let content = match22[2];
      let isStatic = true;
      if (content.startsWith("[")) {
        isStatic = false;
        if (!content.endsWith("]")) {
          emitError(
            context,
            27
          );
          content = content.slice(1);
        } else {
          content = content.slice(1, content.length - 1);
        }
      } else if (isSlot) {
        content += match22[3] || "";
      }
      arg = {
        type: 4,
        content,
        isStatic,
        constType: isStatic ? 3 : 0,
        loc: loc2
      };
    }
    if (value && value.isQuoted) {
      const valueLoc = value.loc;
      valueLoc.start.offset++;
      valueLoc.start.column++;
      valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
      valueLoc.source = valueLoc.source.slice(1, -1);
    }
    const modifiers = match22[3] ? match22[3].slice(1).split(".") : [];
    if (isPropShorthand)
      modifiers.push("prop");
    return {
      type: 7,
      name: dirName,
      exp: value && {
        type: 4,
        content: value.content,
        isStatic: false,
        // Treat as non-constant by default. This can be potentially set to
        // other values by `transformExpression` to make it eligible for hoisting.
        constType: 0,
        loc: value.loc
      },
      arg,
      modifiers,
      loc
    };
  }
  if (!context.inVPre && startsWith(name, "v-")) {
    emitError(context, 26);
  }
  return {
    type: 6,
    name,
    value: value && {
      type: 2,
      content: value.content,
      loc: value.loc
    },
    loc
  };
}
function parseAttributeValue(context) {
  const start = getCursor(context);
  let content;
  const quote = context.source[0];
  const isQuoted = quote === `"` || quote === `'`;
  if (isQuoted) {
    advanceBy(context, 1);
    const endIndex = context.source.indexOf(quote);
    if (endIndex === -1) {
      content = parseTextData(
        context,
        context.source.length,
        4
      );
    } else {
      content = parseTextData(context, endIndex, 4);
      advanceBy(context, 1);
    }
  } else {
    const match2 = /^[^\t\r\n\f >]+/.exec(context.source);
    if (!match2) {
      return void 0;
    }
    const unexpectedChars = /["'<=`]/g;
    let m;
    while (m = unexpectedChars.exec(match2[0])) {
      emitError(
        context,
        18,
        m.index
      );
    }
    content = parseTextData(context, match2[0].length, 4);
  }
  return { content, isQuoted, loc: getSelection(context, start) };
}
function parseInterpolation(context, mode) {
  const [open, close] = context.options.delimiters;
  const closeIndex = context.source.indexOf(close, open.length);
  if (closeIndex === -1) {
    emitError(context, 25);
    return void 0;
  }
  const start = getCursor(context);
  advanceBy(context, open.length);
  const innerStart = getCursor(context);
  const innerEnd = getCursor(context);
  const rawContentLength = closeIndex - open.length;
  const rawContent = context.source.slice(0, rawContentLength);
  const preTrimContent = parseTextData(context, rawContentLength, mode);
  const content = preTrimContent.trim();
  const startOffset = preTrimContent.indexOf(content);
  if (startOffset > 0) {
    advancePositionWithMutation(innerStart, rawContent, startOffset);
  }
  const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
  advancePositionWithMutation(innerEnd, rawContent, endOffset);
  advanceBy(context, close.length);
  return {
    type: 5,
    content: {
      type: 4,
      isStatic: false,
      // Set `isConstant` to false by default and will decide in transformExpression
      constType: 0,
      content,
      loc: getSelection(context, innerStart, innerEnd)
    },
    loc: getSelection(context, start)
  };
}
function parseText(context, mode) {
  const endTokens = mode === 3 ? ["]]>"] : ["<", context.options.delimiters[0]];
  let endIndex = context.source.length;
  for (let i = 0; i < endTokens.length; i++) {
    const index = context.source.indexOf(endTokens[i], 1);
    if (index !== -1 && endIndex > index) {
      endIndex = index;
    }
  }
  const start = getCursor(context);
  const content = parseTextData(context, endIndex, mode);
  return {
    type: 2,
    content,
    loc: getSelection(context, start)
  };
}
function parseTextData(context, length2, mode) {
  const rawText = context.source.slice(0, length2);
  advanceBy(context, length2);
  if (mode === 2 || mode === 3 || !rawText.includes("&")) {
    return rawText;
  } else {
    return context.options.decodeEntities(
      rawText,
      mode === 4
    );
  }
}
function getCursor(context) {
  const { column, line, offset } = context;
  return { column, line, offset };
}
function getSelection(context, start, end) {
  end = end || getCursor(context);
  return {
    start,
    end,
    source: context.originalSource.slice(start.offset, end.offset)
  };
}
function last(xs) {
  return xs[xs.length - 1];
}
function startsWith(source, searchString) {
  return source.startsWith(searchString);
}
function advanceBy(context, numberOfCharacters) {
  const { source } = context;
  advancePositionWithMutation(context, source, numberOfCharacters);
  context.source = source.slice(numberOfCharacters);
}
function advanceSpaces(context) {
  const match2 = /^[\t\r\n\f ]+/.exec(context.source);
  if (match2) {
    advanceBy(context, match2[0].length);
  }
}
function getNewPosition(context, start, numberOfCharacters) {
  return advancePositionWithClone(
    start,
    context.originalSource.slice(start.offset, numberOfCharacters),
    numberOfCharacters
  );
}
function emitError(context, code, offset, loc = getCursor(context)) {
  if (offset) {
    loc.offset += offset;
    loc.column += offset;
  }
  context.options.onError(
    createCompilerError(code, {
      start: loc,
      end: loc,
      source: ""
    })
  );
}
function isEnd(context, mode, ancestors) {
  const s = context.source;
  switch (mode) {
    case 0:
      if (startsWith(s, "</")) {
        for (let i = ancestors.length - 1; i >= 0; --i) {
          if (startsWithEndTagOpen(s, ancestors[i].tag)) {
            return true;
          }
        }
      }
      break;
    case 1:
    case 2: {
      const parent = last(ancestors);
      if (parent && startsWithEndTagOpen(s, parent.tag)) {
        return true;
      }
      break;
    }
    case 3:
      if (startsWith(s, "]]>")) {
        return true;
      }
      break;
  }
  return !s;
}
function startsWithEndTagOpen(source, tag3) {
  return startsWith(source, "</") && source.slice(2, 2 + tag3.length).toLowerCase() === tag3.toLowerCase() && /[\t\r\n\f />]/.test(source[2 + tag3.length] || ">");
}
function hoistStatic(root3, context) {
  walk$2(
    root3,
    context,
    // Root node is unfortunately non-hoistable due to potential parent
    // fallthrough attributes.
    isSingleElementRoot(root3, root3.children[0])
  );
}
function isSingleElementRoot(root3, child) {
  const { children } = root3;
  return children.length === 1 && child.type === 1 && !isSlotOutlet(child);
}
function walk$2(node2, context, doNotHoistNode = false) {
  const { children } = node2;
  const originalCount = children.length;
  let hoistedCount = 0;
  for (let i = 0; i < children.length; i++) {
    const child = children[i];
    if (child.type === 1 && child.tagType === 0) {
      const constantType = doNotHoistNode ? 0 : getConstantType(child, context);
      if (constantType > 0) {
        if (constantType >= 2) {
          child.codegenNode.patchFlag = `-1 /* HOISTED */`;
          child.codegenNode = context.hoist(child.codegenNode);
          hoistedCount++;
          continue;
        }
      } else {
        const codegenNode = child.codegenNode;
        if (codegenNode.type === 13) {
          const flag = getPatchFlag(codegenNode);
          if ((!flag || flag === 512 || flag === 1) && getGeneratedPropsConstantType(child, context) >= 2) {
            const props = getNodeProps(child);
            if (props) {
              codegenNode.props = context.hoist(props);
            }
          }
          if (codegenNode.dynamicProps) {
            codegenNode.dynamicProps = context.hoist(codegenNode.dynamicProps);
          }
        }
      }
    }
    if (child.type === 1) {
      const isComponent2 = child.tagType === 1;
      if (isComponent2) {
        context.scopes.vSlot++;
      }
      walk$2(child, context);
      if (isComponent2) {
        context.scopes.vSlot--;
      }
    } else if (child.type === 11) {
      walk$2(child, context, child.children.length === 1);
    } else if (child.type === 9) {
      for (let i2 = 0; i2 < child.branches.length; i2++) {
        walk$2(
          child.branches[i2],
          context,
          child.branches[i2].children.length === 1
        );
      }
    }
  }
  if (hoistedCount && context.transformHoist) {
    context.transformHoist(children, context, node2);
  }
  if (hoistedCount && hoistedCount === originalCount && node2.type === 1 && node2.tagType === 0 && node2.codegenNode && node2.codegenNode.type === 13 && isArray$3(node2.codegenNode.children)) {
    node2.codegenNode.children = context.hoist(
      createArrayExpression(node2.codegenNode.children)
    );
  }
}
function getConstantType(node2, context) {
  const { constantCache } = context;
  switch (node2.type) {
    case 1:
      if (node2.tagType !== 0) {
        return 0;
      }
      const cached = constantCache.get(node2);
      if (cached !== void 0) {
        return cached;
      }
      const codegenNode = node2.codegenNode;
      if (codegenNode.type !== 13) {
        return 0;
      }
      if (codegenNode.isBlock && node2.tag !== "svg" && node2.tag !== "foreignObject") {
        return 0;
      }
      const flag = getPatchFlag(codegenNode);
      if (!flag) {
        let returnType2 = 3;
        const generatedPropsType = getGeneratedPropsConstantType(node2, context);
        if (generatedPropsType === 0) {
          constantCache.set(node2, 0);
          return 0;
        }
        if (generatedPropsType < returnType2) {
          returnType2 = generatedPropsType;
        }
        for (let i = 0; i < node2.children.length; i++) {
          const childType = getConstantType(node2.children[i], context);
          if (childType === 0) {
            constantCache.set(node2, 0);
            return 0;
          }
          if (childType < returnType2) {
            returnType2 = childType;
          }
        }
        if (returnType2 > 1) {
          for (let i = 0; i < node2.props.length; i++) {
            const p2 = node2.props[i];
            if (p2.type === 7 && p2.name === "bind" && p2.exp) {
              const expType = getConstantType(p2.exp, context);
              if (expType === 0) {
                constantCache.set(node2, 0);
                return 0;
              }
              if (expType < returnType2) {
                returnType2 = expType;
              }
            }
          }
        }
        if (codegenNode.isBlock) {
          for (let i = 0; i < node2.props.length; i++) {
            const p2 = node2.props[i];
            if (p2.type === 7) {
              constantCache.set(node2, 0);
              return 0;
            }
          }
          context.removeHelper(OPEN_BLOCK);
          context.removeHelper(
            getVNodeBlockHelper(context.inSSR, codegenNode.isComponent)
          );
          codegenNode.isBlock = false;
          context.helper(getVNodeHelper(context.inSSR, codegenNode.isComponent));
        }
        constantCache.set(node2, returnType2);
        return returnType2;
      } else {
        constantCache.set(node2, 0);
        return 0;
      }
    case 2:
    case 3:
      return 3;
    case 9:
    case 11:
    case 10:
      return 0;
    case 5:
    case 12:
      return getConstantType(node2.content, context);
    case 4:
      return node2.constType;
    case 8:
      let returnType = 3;
      for (let i = 0; i < node2.children.length; i++) {
        const child = node2.children[i];
        if (isString$2(child) || isSymbol$1(child)) {
          continue;
        }
        const childType = getConstantType(child, context);
        if (childType === 0) {
          return 0;
        } else if (childType < returnType) {
          returnType = childType;
        }
      }
      return returnType;
    default:
      return 0;
  }
}
const allowHoistedHelperSet = /* @__PURE__ */ new Set([
  NORMALIZE_CLASS,
  NORMALIZE_STYLE,
  NORMALIZE_PROPS,
  GUARD_REACTIVE_PROPS
]);
function getConstantTypeOfHelperCall(value, context) {
  if (value.type === 14 && !isString$2(value.callee) && allowHoistedHelperSet.has(value.callee)) {
    const arg = value.arguments[0];
    if (arg.type === 4) {
      return getConstantType(arg, context);
    } else if (arg.type === 14) {
      return getConstantTypeOfHelperCall(arg, context);
    }
  }
  return 0;
}
function getGeneratedPropsConstantType(node2, context) {
  let returnType = 3;
  const props = getNodeProps(node2);
  if (props && props.type === 15) {
    const { properties } = props;
    for (let i = 0; i < properties.length; i++) {
      const { key, value } = properties[i];
      const keyType = getConstantType(key, context);
      if (keyType === 0) {
        return keyType;
      }
      if (keyType < returnType) {
        returnType = keyType;
      }
      let valueType;
      if (value.type === 4) {
        valueType = getConstantType(value, context);
      } else if (value.type === 14) {
        valueType = getConstantTypeOfHelperCall(value, context);
      } else {
        valueType = 0;
      }
      if (valueType === 0) {
        return valueType;
      }
      if (valueType < returnType) {
        returnType = valueType;
      }
    }
  }
  return returnType;
}
function getNodeProps(node2) {
  const codegenNode = node2.codegenNode;
  if (codegenNode.type === 13) {
    return codegenNode.props;
  }
}
function getPatchFlag(node2) {
  const flag = node2.patchFlag;
  return flag ? parseInt(flag, 10) : void 0;
}
function createTransformContext(root3, {
  filename = "",
  prefixIdentifiers = false,
  hoistStatic: hoistStatic2 = false,
  cacheHandlers = false,
  nodeTransforms = [],
  directiveTransforms = {},
  transformHoist = null,
  isBuiltInComponent = NOOP,
  isCustomElement = NOOP,
  expressionPlugins = [],
  scopeId = null,
  slotted = true,
  ssr = false,
  inSSR = false,
  ssrCssVars = ``,
  bindingMetadata = EMPTY_OBJ,
  inline = false,
  isTS = false,
  onError = defaultOnError,
  onWarn = defaultOnWarn,
  compatConfig
}) {
  const nameMatch = filename.replace(/\?.*$/, "").match(/([^/\\]+)\.\w+$/);
  const context = {
    // options
    selfName: nameMatch && capitalize$1(camelize(nameMatch[1])),
    prefixIdentifiers,
    hoistStatic: hoistStatic2,
    cacheHandlers,
    nodeTransforms,
    directiveTransforms,
    transformHoist,
    isBuiltInComponent,
    isCustomElement,
    expressionPlugins,
    scopeId,
    slotted,
    ssr,
    inSSR,
    ssrCssVars,
    bindingMetadata,
    inline,
    isTS,
    onError,
    onWarn,
    compatConfig,
    // state
    root: root3,
    helpers: /* @__PURE__ */ new Map(),
    components: /* @__PURE__ */ new Set(),
    directives: /* @__PURE__ */ new Set(),
    hoists: [],
    imports: [],
    constantCache: /* @__PURE__ */ new Map(),
    temps: 0,
    cached: 0,
    identifiers: /* @__PURE__ */ Object.create(null),
    scopes: {
      vFor: 0,
      vSlot: 0,
      vPre: 0,
      vOnce: 0
    },
    parent: null,
    currentNode: root3,
    childIndex: 0,
    inVOnce: false,
    // methods
    helper(name) {
      const count = context.helpers.get(name) || 0;
      context.helpers.set(name, count + 1);
      return name;
    },
    removeHelper(name) {
      const count = context.helpers.get(name);
      if (count) {
        const currentCount = count - 1;
        if (!currentCount) {
          context.helpers.delete(name);
        } else {
          context.helpers.set(name, currentCount);
        }
      }
    },
    helperString(name) {
      return `_${helperNameMap[context.helper(name)]}`;
    },
    replaceNode(node2) {
      {
        if (!context.currentNode) {
          throw new Error(`Node being replaced is already removed.`);
        }
        if (!context.parent) {
          throw new Error(`Cannot replace root node.`);
        }
      }
      context.parent.children[context.childIndex] = context.currentNode = node2;
    },
    removeNode(node2) {
      if (!context.parent) {
        throw new Error(`Cannot remove root node.`);
      }
      const list2 = context.parent.children;
      const removalIndex = node2 ? list2.indexOf(node2) : context.currentNode ? context.childIndex : -1;
      if (removalIndex < 0) {
        throw new Error(`node being removed is not a child of current parent`);
      }
      if (!node2 || node2 === context.currentNode) {
        context.currentNode = null;
        context.onNodeRemoved();
      } else {
        if (context.childIndex > removalIndex) {
          context.childIndex--;
          context.onNodeRemoved();
        }
      }
      context.parent.children.splice(removalIndex, 1);
    },
    onNodeRemoved: () => {
    },
    addIdentifiers(exp) {
      {
        if (isString$2(exp)) {
          addId(exp);
        } else if (exp.identifiers) {
          exp.identifiers.forEach(addId);
        } else if (exp.type === 4) {
          addId(exp.content);
        }
      }
    },
    removeIdentifiers(exp) {
      {
        if (isString$2(exp)) {
          removeId(exp);
        } else if (exp.identifiers) {
          exp.identifiers.forEach(removeId);
        } else if (exp.type === 4) {
          removeId(exp.content);
        }
      }
    },
    hoist(exp) {
      if (isString$2(exp))
        exp = createSimpleExpression(exp);
      context.hoists.push(exp);
      const identifier = createSimpleExpression(
        `_hoisted_${context.hoists.length}`,
        false,
        exp.loc,
        2
      );
      identifier.hoisted = exp;
      return identifier;
    },
    cache(exp, isVNode2 = false) {
      return createCacheExpression(context.cached++, exp, isVNode2);
    }
  };
  function addId(id3) {
    const { identifiers } = context;
    if (identifiers[id3] === void 0) {
      identifiers[id3] = 0;
    }
    identifiers[id3]++;
  }
  function removeId(id3) {
    context.identifiers[id3]--;
  }
  return context;
}
function transform$1(root3, options) {
  const context = createTransformContext(root3, options);
  traverseNode(root3, context);
  if (options.hoistStatic) {
    hoistStatic(root3, context);
  }
  if (!options.ssr) {
    createRootCodegen(root3, context);
  }
  root3.helpers = /* @__PURE__ */ new Set([...context.helpers.keys()]);
  root3.components = [...context.components];
  root3.directives = [...context.directives];
  root3.imports = context.imports;
  root3.hoists = context.hoists;
  root3.temps = context.temps;
  root3.cached = context.cached;
}
function createRootCodegen(root3, context) {
  const { helper } = context;
  const { children } = root3;
  if (children.length === 1) {
    const child = children[0];
    if (isSingleElementRoot(root3, child) && child.codegenNode) {
      const codegenNode = child.codegenNode;
      if (codegenNode.type === 13) {
        convertToBlock(codegenNode, context);
      }
      root3.codegenNode = codegenNode;
    } else {
      root3.codegenNode = child;
    }
  } else if (children.length > 1) {
    let patchFlag = 64;
    let patchFlagText = PatchFlagNames[64];
    if (children.filter((c) => c.type !== 3).length === 1) {
      patchFlag |= 2048;
      patchFlagText += `, ${PatchFlagNames[2048]}`;
    }
    root3.codegenNode = createVNodeCall(
      context,
      helper(FRAGMENT),
      void 0,
      root3.children,
      patchFlag + ` /* ${patchFlagText} */`,
      void 0,
      void 0,
      true,
      void 0,
      false
      /* isComponent */
    );
  } else
    ;
}
function traverseChildren(parent, context) {
  let i = 0;
  const nodeRemoved = () => {
    i--;
  };
  for (; i < parent.children.length; i++) {
    const child = parent.children[i];
    if (isString$2(child))
      continue;
    context.parent = parent;
    context.childIndex = i;
    context.onNodeRemoved = nodeRemoved;
    traverseNode(child, context);
  }
}
function traverseNode(node2, context) {
  context.currentNode = node2;
  const { nodeTransforms } = context;
  const exitFns = [];
  for (let i2 = 0; i2 < nodeTransforms.length; i2++) {
    const onExit = nodeTransforms[i2](node2, context);
    if (onExit) {
      if (isArray$3(onExit)) {
        exitFns.push(...onExit);
      } else {
        exitFns.push(onExit);
      }
    }
    if (!context.currentNode) {
      return;
    } else {
      node2 = context.currentNode;
    }
  }
  switch (node2.type) {
    case 3:
      if (!context.ssr) {
        context.helper(CREATE_COMMENT);
      }
      break;
    case 5:
      if (!context.ssr) {
        context.helper(TO_DISPLAY_STRING);
      }
      break;
    case 9:
      for (let i2 = 0; i2 < node2.branches.length; i2++) {
        traverseNode(node2.branches[i2], context);
      }
      break;
    case 10:
    case 11:
    case 1:
    case 0:
      traverseChildren(node2, context);
      break;
  }
  context.currentNode = node2;
  let i = exitFns.length;
  while (i--) {
    exitFns[i]();
  }
}
function createStructuralDirectiveTransform(name, fn) {
  const matches = isString$2(name) ? (n2) => n2 === name : (n2) => name.test(n2);
  return (node2, context) => {
    if (node2.type === 1) {
      const { props } = node2;
      if (node2.tagType === 3 && props.some(isVSlot)) {
        return;
      }
      const exitFns = [];
      for (let i = 0; i < props.length; i++) {
        const prop = props[i];
        if (prop.type === 7 && matches(prop.name)) {
          props.splice(i, 1);
          i--;
          const onExit = fn(node2, prop, context);
          if (onExit)
            exitFns.push(onExit);
        }
      }
      return exitFns;
    }
  };
}
var sourceMap$2 = {};
var sourceMapGenerator$1 = {};
var base64Vlq$1 = {};
var base64$3 = {};
var intToCharMap$1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
base64$3.encode = function(number) {
  if (0 <= number && number < intToCharMap$1.length) {
    return intToCharMap$1[number];
  }
  throw new TypeError("Must be between 0 and 63: " + number);
};
base64$3.decode = function(charCode) {
  var bigA = 65;
  var bigZ = 90;
  var littleA = 97;
  var littleZ = 122;
  var zero = 48;
  var nine = 57;
  var plus2 = 43;
  var slash2 = 47;
  var littleOffset = 26;
  var numberOffset = 52;
  if (bigA <= charCode && charCode <= bigZ) {
    return charCode - bigA;
  }
  if (littleA <= charCode && charCode <= littleZ) {
    return charCode - littleA + littleOffset;
  }
  if (zero <= charCode && charCode <= nine) {
    return charCode - zero + numberOffset;
  }
  if (charCode == plus2) {
    return 62;
  }
  if (charCode == slash2) {
    return 63;
  }
  return -1;
};
var base64$2 = base64$3;
var VLQ_BASE_SHIFT$1 = 5;
var VLQ_BASE$1 = 1 << VLQ_BASE_SHIFT$1;
var VLQ_BASE_MASK$1 = VLQ_BASE$1 - 1;
var VLQ_CONTINUATION_BIT$1 = VLQ_BASE$1;
function toVLQSigned$1(aValue) {
  return aValue < 0 ? (-aValue << 1) + 1 : (aValue << 1) + 0;
}
function fromVLQSigned$1(aValue) {
  var isNegative = (aValue & 1) === 1;
  var shifted = aValue >> 1;
  return isNegative ? -shifted : shifted;
}
base64Vlq$1.encode = function base64VLQ_encode(aValue) {
  var encoded = "";
  var digit;
  var vlq = toVLQSigned$1(aValue);
  do {
    digit = vlq & VLQ_BASE_MASK$1;
    vlq >>>= VLQ_BASE_SHIFT$1;
    if (vlq > 0) {
      digit |= VLQ_CONTINUATION_BIT$1;
    }
    encoded += base64$2.encode(digit);
  } while (vlq > 0);
  return encoded;
};
base64Vlq$1.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  var strLen = aStr.length;
  var result2 = 0;
  var shift2 = 0;
  var continuation, digit;
  do {
    if (aIndex >= strLen) {
      throw new Error("Expected more digits in base 64 VLQ value.");
    }
    digit = base64$2.decode(aStr.charCodeAt(aIndex++));
    if (digit === -1) {
      throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
    }
    continuation = !!(digit & VLQ_CONTINUATION_BIT$1);
    digit &= VLQ_BASE_MASK$1;
    result2 = result2 + (digit << shift2);
    shift2 += VLQ_BASE_SHIFT$1;
  } while (continuation);
  aOutParam.value = fromVLQSigned$1(result2);
  aOutParam.rest = aIndex;
};
var util$c = {};
(function(exports2) {
  function getArg(aArgs, aName, aDefaultValue) {
    if (aName in aArgs) {
      return aArgs[aName];
    } else if (arguments.length === 3) {
      return aDefaultValue;
    } else {
      throw new Error('"' + aName + '" is a required argument.');
    }
  }
  exports2.getArg = getArg;
  var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  var dataUrlRegexp = /^data:.+\,.+$/;
  function urlParse2(aUrl) {
    var match2 = aUrl.match(urlRegexp);
    if (!match2) {
      return null;
    }
    return {
      scheme: match2[1],
      auth: match2[2],
      host: match2[3],
      port: match2[4],
      path: match2[5]
    };
  }
  exports2.urlParse = urlParse2;
  function urlGenerate(aParsedUrl) {
    var url = "";
    if (aParsedUrl.scheme) {
      url += aParsedUrl.scheme + ":";
    }
    url += "//";
    if (aParsedUrl.auth) {
      url += aParsedUrl.auth + "@";
    }
    if (aParsedUrl.host) {
      url += aParsedUrl.host;
    }
    if (aParsedUrl.port) {
      url += ":" + aParsedUrl.port;
    }
    if (aParsedUrl.path) {
      url += aParsedUrl.path;
    }
    return url;
  }
  exports2.urlGenerate = urlGenerate;
  var MAX_CACHED_INPUTS = 32;
  function lruMemoize(f) {
    var cache2 = [];
    return function(input2) {
      for (var i = 0; i < cache2.length; i++) {
        if (cache2[i].input === input2) {
          var temp = cache2[0];
          cache2[0] = cache2[i];
          cache2[i] = temp;
          return cache2[0].result;
        }
      }
      var result2 = f(input2);
      cache2.unshift({
        input: input2,
        result: result2
      });
      if (cache2.length > MAX_CACHED_INPUTS) {
        cache2.pop();
      }
      return result2;
    };
  }
  var normalize2 = lruMemoize(function normalize3(aPath) {
    var path2 = aPath;
    var url = urlParse2(aPath);
    if (url) {
      if (!url.path) {
        return aPath;
      }
      path2 = url.path;
    }
    var isAbsolute2 = exports2.isAbsolute(path2);
    var parts = [];
    var start = 0;
    var i = 0;
    while (true) {
      start = i;
      i = path2.indexOf("/", start);
      if (i === -1) {
        parts.push(path2.slice(start));
        break;
      } else {
        parts.push(path2.slice(start, i));
        while (i < path2.length && path2[i] === "/") {
          i++;
        }
      }
    }
    for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
      part = parts[i];
      if (part === ".") {
        parts.splice(i, 1);
      } else if (part === "..") {
        up++;
      } else if (up > 0) {
        if (part === "") {
          parts.splice(i + 1, up);
          up = 0;
        } else {
          parts.splice(i, 2);
          up--;
        }
      }
    }
    path2 = parts.join("/");
    if (path2 === "") {
      path2 = isAbsolute2 ? "/" : ".";
    }
    if (url) {
      url.path = path2;
      return urlGenerate(url);
    }
    return path2;
  });
  exports2.normalize = normalize2;
  function join2(aRoot, aPath) {
    if (aRoot === "") {
      aRoot = ".";
    }
    if (aPath === "") {
      aPath = ".";
    }
    var aPathUrl = urlParse2(aPath);
    var aRootUrl = urlParse2(aRoot);
    if (aRootUrl) {
      aRoot = aRootUrl.path || "/";
    }
    if (aPathUrl && !aPathUrl.scheme) {
      if (aRootUrl) {
        aPathUrl.scheme = aRootUrl.scheme;
      }
      return urlGenerate(aPathUrl);
    }
    if (aPathUrl || aPath.match(dataUrlRegexp)) {
      return aPath;
    }
    if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
      aRootUrl.host = aPath;
      return urlGenerate(aRootUrl);
    }
    var joined = aPath.charAt(0) === "/" ? aPath : normalize2(aRoot.replace(/\/+$/, "") + "/" + aPath);
    if (aRootUrl) {
      aRootUrl.path = joined;
      return urlGenerate(aRootUrl);
    }
    return joined;
  }
  exports2.join = join2;
  exports2.isAbsolute = function(aPath) {
    return aPath.charAt(0) === "/" || urlRegexp.test(aPath);
  };
  function relative2(aRoot, aPath) {
    if (aRoot === "") {
      aRoot = ".";
    }
    aRoot = aRoot.replace(/\/$/, "");
    var level = 0;
    while (aPath.indexOf(aRoot + "/") !== 0) {
      var index = aRoot.lastIndexOf("/");
      if (index < 0) {
        return aPath;
      }
      aRoot = aRoot.slice(0, index);
      if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
        return aPath;
      }
      ++level;
    }
    return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  }
  exports2.relative = relative2;
  var supportsNullProto = function() {
    var obj = /* @__PURE__ */ Object.create(null);
    return !("__proto__" in obj);
  }();
  function identity(s) {
    return s;
  }
  function toSetString(aStr) {
    if (isProtoString(aStr)) {
      return "$" + aStr;
    }
    return aStr;
  }
  exports2.toSetString = supportsNullProto ? identity : toSetString;
  function fromSetString(aStr) {
    if (isProtoString(aStr)) {
      return aStr.slice(1);
    }
    return aStr;
  }
  exports2.fromSetString = supportsNullProto ? identity : fromSetString;
  function isProtoString(s) {
    if (!s) {
      return false;
    }
    var length2 = s.length;
    if (length2 < 9) {
      return false;
    }
    if (s.charCodeAt(length2 - 1) !== 95 || s.charCodeAt(length2 - 2) !== 95 || s.charCodeAt(length2 - 3) !== 111 || s.charCodeAt(length2 - 4) !== 116 || s.charCodeAt(length2 - 5) !== 111 || s.charCodeAt(length2 - 6) !== 114 || s.charCodeAt(length2 - 7) !== 112 || s.charCodeAt(length2 - 8) !== 95 || s.charCodeAt(length2 - 9) !== 95) {
      return false;
    }
    for (var i = length2 - 10; i >= 0; i--) {
      if (s.charCodeAt(i) !== 36) {
        return false;
      }
    }
    return true;
  }
  function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
    var cmp3 = strcmp2(mappingA.source, mappingB.source);
    if (cmp3 !== 0) {
      return cmp3;
    }
    cmp3 = mappingA.originalLine - mappingB.originalLine;
    if (cmp3 !== 0) {
      return cmp3;
    }
    cmp3 = mappingA.originalColumn - mappingB.originalColumn;
    if (cmp3 !== 0 || onlyCompareOriginal) {
      return cmp3;
    }
    cmp3 = mappingA.generatedColumn - mappingB.generatedColumn;
    if (cmp3 !== 0) {
      return cmp3;
    }
    cmp3 = mappingA.generatedLine - mappingB.generatedLine;
    if (cmp3 !== 0) {
      return cmp3;
    }
    return strcmp2(mappingA.name, mappingB.name);
  }
  exports2.compareByOriginalPositions = compareByOriginalPositions;
  function compareByOriginalPositionsNoSource(mappingA, mappingB, onlyCompareOriginal) {
    var cmp3;
    cmp3 = mappingA.originalLine - mappingB.originalLine;
    if (cmp3 !== 0) {
      return cmp3;
    }
    cmp3 = mappingA.originalColumn - mappingB.originalColumn;
    if (cmp3 !== 0 || onlyCompareOriginal) {
      return cmp3;
    }
    cmp3 = mappingA.generatedColumn - mappingB.generatedColumn;
    if (cmp3 !== 0) {
      return cmp3;
    }
    cmp3 = mappingA.generatedLine - mappingB.generatedLine;
    if (cmp3 !== 0) {
      return cmp3;
    }
    return strcmp2(mappingA.name, mappingB.name);
  }
  exports2.compareByOriginalPositionsNoSource = compareByOriginalPositionsNoSource;
  function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
    var cmp3 = mappingA.generatedLine - mappingB.generatedLine;
    if (cmp3 !== 0) {
      return cmp3;
    }
    cmp3 = mappingA.generatedColumn - mappingB.generatedColumn;
    if (cmp3 !== 0 || onlyCompareGenerated) {
      return cmp3;
    }
    cmp3 = strcmp2(mappingA.source, mappingB.source);
    if (cmp3 !== 0) {
      return cmp3;
    }
    cmp3 = mappingA.originalLine - mappingB.originalLine;
    if (cmp3 !== 0) {
      return cmp3;
    }
    cmp3 = mappingA.originalColumn - mappingB.originalColumn;
    if (cmp3 !== 0) {
      return cmp3;
    }
    return strcmp2(mappingA.name, mappingB.name);
  }
  exports2.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  function compareByGeneratedPositionsDeflatedNoLine(mappingA, mappingB, onlyCompareGenerated) {
    var cmp3 = mappingA.generatedColumn - mappingB.generatedColumn;
    if (cmp3 !== 0 || onlyCompareGenerated) {
      return cmp3;
    }
    cmp3 = strcmp2(mappingA.source, mappingB.source);
    if (cmp3 !== 0) {
      return cmp3;
    }
    cmp3 = mappingA.originalLine - mappingB.originalLine;
    if (cmp3 !== 0) {
      return cmp3;
    }
    cmp3 = mappingA.originalColumn - mappingB.originalColumn;
    if (cmp3 !== 0) {
      return cmp3;
    }
    return strcmp2(mappingA.name, mappingB.name);
  }
  exports2.compareByGeneratedPositionsDeflatedNoLine = compareByGeneratedPositionsDeflatedNoLine;
  function strcmp2(aStr1, aStr2) {
    if (aStr1 === aStr2) {
      return 0;
    }
    if (aStr1 === null) {
      return 1;
    }
    if (aStr2 === null) {
      return -1;
    }
    if (aStr1 > aStr2) {
      return 1;
    }
    return -1;
  }
  function compareByGeneratedPositionsInflated(mappingA, mappingB) {
    var cmp3 = mappingA.generatedLine - mappingB.generatedLine;
    if (cmp3 !== 0) {
      return cmp3;
    }
    cmp3 = mappingA.generatedColumn - mappingB.generatedColumn;
    if (cmp3 !== 0) {
      return cmp3;
    }
    cmp3 = strcmp2(mappingA.source, mappingB.source);
    if (cmp3 !== 0) {
      return cmp3;
    }
    cmp3 = mappingA.originalLine - mappingB.originalLine;
    if (cmp3 !== 0) {
      return cmp3;
    }
    cmp3 = mappingA.originalColumn - mappingB.originalColumn;
    if (cmp3 !== 0) {
      return cmp3;
    }
    return strcmp2(mappingA.name, mappingB.name);
  }
  exports2.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  function parseSourceMapInput(str2) {
    return JSON.parse(str2.replace(/^\)]}'[^\n]*\n/, ""));
  }
  exports2.parseSourceMapInput = parseSourceMapInput;
  function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
    sourceURL = sourceURL || "";
    if (sourceRoot) {
      if (sourceRoot[sourceRoot.length - 1] !== "/" && sourceURL[0] !== "/") {
        sourceRoot += "/";
      }
      sourceURL = sourceRoot + sourceURL;
    }
    if (sourceMapURL) {
      var parsed = urlParse2(sourceMapURL);
      if (!parsed) {
        throw new Error("sourceMapURL could not be parsed");
      }
      if (parsed.path) {
        var index = parsed.path.lastIndexOf("/");
        if (index >= 0) {
          parsed.path = parsed.path.substring(0, index + 1);
        }
      }
      sourceURL = join2(urlGenerate(parsed), sourceURL);
    }
    return normalize2(sourceURL);
  }
  exports2.computeSourceURL = computeSourceURL;
})(util$c);
var arraySet$1 = {};
var util$b = util$c;
var has$1 = Object.prototype.hasOwnProperty;
var hasNativeMap$1 = typeof Map !== "undefined";
function ArraySet$5() {
  this._array = [];
  this._set = hasNativeMap$1 ? /* @__PURE__ */ new Map() : /* @__PURE__ */ Object.create(null);
}
ArraySet$5.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  var set2 = new ArraySet$5();
  for (var i = 0, len = aArray.length; i < len; i++) {
    set2.add(aArray[i], aAllowDuplicates);
  }
  return set2;
};
ArraySet$5.prototype.size = function ArraySet_size() {
  return hasNativeMap$1 ? this._set.size : Object.getOwnPropertyNames(this._set).length;
};
ArraySet$5.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  var sStr = hasNativeMap$1 ? aStr : util$b.toSetString(aStr);
  var isDuplicate = hasNativeMap$1 ? this.has(aStr) : has$1.call(this._set, sStr);
  var idx = this._array.length;
  if (!isDuplicate || aAllowDuplicates) {
    this._array.push(aStr);
  }
  if (!isDuplicate) {
    if (hasNativeMap$1) {
      this._set.set(aStr, idx);
    } else {
      this._set[sStr] = idx;
    }
  }
};
ArraySet$5.prototype.has = function ArraySet_has(aStr) {
  if (hasNativeMap$1) {
    return this._set.has(aStr);
  } else {
    var sStr = util$b.toSetString(aStr);
    return has$1.call(this._set, sStr);
  }
};
ArraySet$5.prototype.indexOf = function ArraySet_indexOf(aStr) {
  if (hasNativeMap$1) {
    var idx = this._set.get(aStr);
    if (idx >= 0) {
      return idx;
    }
  } else {
    var sStr = util$b.toSetString(aStr);
    if (has$1.call(this._set, sStr)) {
      return this._set[sStr];
    }
  }
  throw new Error('"' + aStr + '" is not in the set.');
};
ArraySet$5.prototype.at = function ArraySet_at(aIdx) {
  if (aIdx >= 0 && aIdx < this._array.length) {
    return this._array[aIdx];
  }
  throw new Error("No element indexed by " + aIdx);
};
ArraySet$5.prototype.toArray = function ArraySet_toArray() {
  return this._array.slice();
};
arraySet$1.ArraySet = ArraySet$5;
var mappingList$1 = {};
var util$a = util$c;
function generatedPositionAfter$1(mappingA, mappingB) {
  var lineA = mappingA.generatedLine;
  var lineB = mappingB.generatedLine;
  var columnA = mappingA.generatedColumn;
  var columnB = mappingB.generatedColumn;
  return lineB > lineA || lineB == lineA && columnB >= columnA || util$a.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
}
function MappingList$3() {
  this._array = [];
  this._sorted = true;
  this._last = { generatedLine: -1, generatedColumn: 0 };
}
MappingList$3.prototype.unsortedForEach = function MappingList_forEach(aCallback, aThisArg) {
  this._array.forEach(aCallback, aThisArg);
};
MappingList$3.prototype.add = function MappingList_add(aMapping) {
  if (generatedPositionAfter$1(this._last, aMapping)) {
    this._last = aMapping;
    this._array.push(aMapping);
  } else {
    this._sorted = false;
    this._array.push(aMapping);
  }
};
MappingList$3.prototype.toArray = function MappingList_toArray() {
  if (!this._sorted) {
    this._array.sort(util$a.compareByGeneratedPositionsInflated);
    this._sorted = true;
  }
  return this._array;
};
mappingList$1.MappingList = MappingList$3;
var base64VLQ$3 = base64Vlq$1;
var util$9 = util$c;
var ArraySet$4 = arraySet$1.ArraySet;
var MappingList$2 = mappingList$1.MappingList;
function SourceMapGenerator$8(aArgs) {
  if (!aArgs) {
    aArgs = {};
  }
  this._file = util$9.getArg(aArgs, "file", null);
  this._sourceRoot = util$9.getArg(aArgs, "sourceRoot", null);
  this._skipValidation = util$9.getArg(aArgs, "skipValidation", false);
  this._sources = new ArraySet$4();
  this._names = new ArraySet$4();
  this._mappings = new MappingList$2();
  this._sourcesContents = null;
}
SourceMapGenerator$8.prototype._version = 3;
SourceMapGenerator$8.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  var sourceRoot = aSourceMapConsumer.sourceRoot;
  var generator = new SourceMapGenerator$8({
    file: aSourceMapConsumer.file,
    sourceRoot
  });
  aSourceMapConsumer.eachMapping(function(mapping) {
    var newMapping = {
      generated: {
        line: mapping.generatedLine,
        column: mapping.generatedColumn
      }
    };
    if (mapping.source != null) {
      newMapping.source = mapping.source;
      if (sourceRoot != null) {
        newMapping.source = util$9.relative(sourceRoot, newMapping.source);
      }
      newMapping.original = {
        line: mapping.originalLine,
        column: mapping.originalColumn
      };
      if (mapping.name != null) {
        newMapping.name = mapping.name;
      }
    }
    generator.addMapping(newMapping);
  });
  aSourceMapConsumer.sources.forEach(function(sourceFile) {
    var sourceRelative = sourceFile;
    if (sourceRoot !== null) {
      sourceRelative = util$9.relative(sourceRoot, sourceFile);
    }
    if (!generator._sources.has(sourceRelative)) {
      generator._sources.add(sourceRelative);
    }
    var content = aSourceMapConsumer.sourceContentFor(sourceFile);
    if (content != null) {
      generator.setSourceContent(sourceFile, content);
    }
  });
  return generator;
};
SourceMapGenerator$8.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) {
  var generated = util$9.getArg(aArgs, "generated");
  var original = util$9.getArg(aArgs, "original", null);
  var source = util$9.getArg(aArgs, "source", null);
  var name = util$9.getArg(aArgs, "name", null);
  if (!this._skipValidation) {
    this._validateMapping(generated, original, source, name);
  }
  if (source != null) {
    source = String(source);
    if (!this._sources.has(source)) {
      this._sources.add(source);
    }
  }
  if (name != null) {
    name = String(name);
    if (!this._names.has(name)) {
      this._names.add(name);
    }
  }
  this._mappings.add({
    generatedLine: generated.line,
    generatedColumn: generated.column,
    originalLine: original != null && original.line,
    originalColumn: original != null && original.column,
    source,
    name
  });
};
SourceMapGenerator$8.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  var source = aSourceFile;
  if (this._sourceRoot != null) {
    source = util$9.relative(this._sourceRoot, source);
  }
  if (aSourceContent != null) {
    if (!this._sourcesContents) {
      this._sourcesContents = /* @__PURE__ */ Object.create(null);
    }
    this._sourcesContents[util$9.toSetString(source)] = aSourceContent;
  } else if (this._sourcesContents) {
    delete this._sourcesContents[util$9.toSetString(source)];
    if (Object.keys(this._sourcesContents).length === 0) {
      this._sourcesContents = null;
    }
  }
};
SourceMapGenerator$8.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  var sourceFile = aSourceFile;
  if (aSourceFile == null) {
    if (aSourceMapConsumer.file == null) {
      throw new Error(
        `SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`
      );
    }
    sourceFile = aSourceMapConsumer.file;
  }
  var sourceRoot = this._sourceRoot;
  if (sourceRoot != null) {
    sourceFile = util$9.relative(sourceRoot, sourceFile);
  }
  var newSources = new ArraySet$4();
  var newNames = new ArraySet$4();
  this._mappings.unsortedForEach(function(mapping) {
    if (mapping.source === sourceFile && mapping.originalLine != null) {
      var original = aSourceMapConsumer.originalPositionFor({
        line: mapping.originalLine,
        column: mapping.originalColumn
      });
      if (original.source != null) {
        mapping.source = original.source;
        if (aSourceMapPath != null) {
          mapping.source = util$9.join(aSourceMapPath, mapping.source);
        }
        if (sourceRoot != null) {
          mapping.source = util$9.relative(sourceRoot, mapping.source);
        }
        mapping.originalLine = original.line;
        mapping.originalColumn = original.column;
        if (original.name != null) {
          mapping.name = original.name;
        }
      }
    }
    var source = mapping.source;
    if (source != null && !newSources.has(source)) {
      newSources.add(source);
    }
    var name = mapping.name;
    if (name != null && !newNames.has(name)) {
      newNames.add(name);
    }
  }, this);
  this._sources = newSources;
  this._names = newNames;
  aSourceMapConsumer.sources.forEach(function(sourceFile2) {
    var content = aSourceMapConsumer.sourceContentFor(sourceFile2);
    if (content != null) {
      if (aSourceMapPath != null) {
        sourceFile2 = util$9.join(aSourceMapPath, sourceFile2);
      }
      if (sourceRoot != null) {
        sourceFile2 = util$9.relative(sourceRoot, sourceFile2);
      }
      this.setSourceContent(sourceFile2, content);
    }
  }, this);
};
SourceMapGenerator$8.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) {
  if (aOriginal && typeof aOriginal.line !== "number" && typeof aOriginal.column !== "number") {
    throw new Error(
      "original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values."
    );
  }
  if (aGenerated && "line" in aGenerated && "column" in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) {
    return;
  } else if (aGenerated && "line" in aGenerated && "column" in aGenerated && aOriginal && "line" in aOriginal && "column" in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) {
    return;
  } else {
    throw new Error("Invalid mapping: " + JSON.stringify({
      generated: aGenerated,
      source: aSource,
      original: aOriginal,
      name: aName
    }));
  }
};
SourceMapGenerator$8.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() {
  var previousGeneratedColumn = 0;
  var previousGeneratedLine = 1;
  var previousOriginalColumn = 0;
  var previousOriginalLine = 0;
  var previousName = 0;
  var previousSource = 0;
  var result2 = "";
  var next;
  var mapping;
  var nameIdx;
  var sourceIdx;
  var mappings = this._mappings.toArray();
  for (var i = 0, len = mappings.length; i < len; i++) {
    mapping = mappings[i];
    next = "";
    if (mapping.generatedLine !== previousGeneratedLine) {
      previousGeneratedColumn = 0;
      while (mapping.generatedLine !== previousGeneratedLine) {
        next += ";";
        previousGeneratedLine++;
      }
    } else {
      if (i > 0) {
        if (!util$9.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
          continue;
        }
        next += ",";
      }
    }
    next += base64VLQ$3.encode(mapping.generatedColumn - previousGeneratedColumn);
    previousGeneratedColumn = mapping.generatedColumn;
    if (mapping.source != null) {
      sourceIdx = this._sources.indexOf(mapping.source);
      next += base64VLQ$3.encode(sourceIdx - previousSource);
      previousSource = sourceIdx;
      next += base64VLQ$3.encode(mapping.originalLine - 1 - previousOriginalLine);
      previousOriginalLine = mapping.originalLine - 1;
      next += base64VLQ$3.encode(mapping.originalColumn - previousOriginalColumn);
      previousOriginalColumn = mapping.originalColumn;
      if (mapping.name != null) {
        nameIdx = this._names.indexOf(mapping.name);
        next += base64VLQ$3.encode(nameIdx - previousName);
        previousName = nameIdx;
      }
    }
    result2 += next;
  }
  return result2;
};
SourceMapGenerator$8.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  return aSources.map(function(source) {
    if (!this._sourcesContents) {
      return null;
    }
    if (aSourceRoot != null) {
      source = util$9.relative(aSourceRoot, source);
    }
    var key = util$9.toSetString(source);
    return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null;
  }, this);
};
SourceMapGenerator$8.prototype.toJSON = function SourceMapGenerator_toJSON() {
  var map2 = {
    version: this._version,
    sources: this._sources.toArray(),
    names: this._names.toArray(),
    mappings: this._serializeMappings()
  };
  if (this._file != null) {
    map2.file = this._file;
  }
  if (this._sourceRoot != null) {
    map2.sourceRoot = this._sourceRoot;
  }
  if (this._sourcesContents) {
    map2.sourcesContent = this._generateSourcesContent(map2.sources, map2.sourceRoot);
  }
  return map2;
};
SourceMapGenerator$8.prototype.toString = function SourceMapGenerator_toString() {
  return JSON.stringify(this.toJSON());
};
sourceMapGenerator$1.SourceMapGenerator = SourceMapGenerator$8;
var sourceMapConsumer$1 = {};
var binarySearch$3 = {};
(function(exports2) {
  exports2.GREATEST_LOWER_BOUND = 1;
  exports2.LEAST_UPPER_BOUND = 2;
  function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
    var mid = Math.floor((aHigh - aLow) / 2) + aLow;
    var cmp3 = aCompare(aNeedle, aHaystack[mid], true);
    if (cmp3 === 0) {
      return mid;
    } else if (cmp3 > 0) {
      if (aHigh - mid > 1) {
        return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
      }
      if (aBias == exports2.LEAST_UPPER_BOUND) {
        return aHigh < aHaystack.length ? aHigh : -1;
      } else {
        return mid;
      }
    } else {
      if (mid - aLow > 1) {
        return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
      }
      if (aBias == exports2.LEAST_UPPER_BOUND) {
        return mid;
      } else {
        return aLow < 0 ? -1 : aLow;
      }
    }
  }
  exports2.search = function search2(aNeedle, aHaystack, aCompare, aBias) {
    if (aHaystack.length === 0) {
      return -1;
    }
    var index = recursiveSearch(
      -1,
      aHaystack.length,
      aNeedle,
      aHaystack,
      aCompare,
      aBias || exports2.GREATEST_LOWER_BOUND
    );
    if (index < 0) {
      return -1;
    }
    while (index - 1 >= 0) {
      if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
        break;
      }
      --index;
    }
    return index;
  };
})(binarySearch$3);
var quickSort$3 = {};
function SortTemplate(comparator2) {
  function swap2(ary, x, y) {
    var temp = ary[x];
    ary[x] = ary[y];
    ary[y] = temp;
  }
  function randomIntInRange2(low, high) {
    return Math.round(low + Math.random() * (high - low));
  }
  function doQuickSort2(ary, comparator3, p2, r) {
    if (p2 < r) {
      var pivotIndex = randomIntInRange2(p2, r);
      var i = p2 - 1;
      swap2(ary, pivotIndex, r);
      var pivot = ary[r];
      for (var j = p2; j < r; j++) {
        if (comparator3(ary[j], pivot, false) <= 0) {
          i += 1;
          swap2(ary, i, j);
        }
      }
      swap2(ary, i + 1, j);
      var q = i + 1;
      doQuickSort2(ary, comparator3, p2, q - 1);
      doQuickSort2(ary, comparator3, q + 1, r);
    }
  }
  return doQuickSort2;
}
function cloneSort(comparator2) {
  let template = SortTemplate.toString();
  let templateFn = new Function(`return ${template}`)();
  return templateFn(comparator2);
}
let sortCache = /* @__PURE__ */ new WeakMap();
quickSort$3.quickSort = function(ary, comparator2, start = 0) {
  let doQuickSort2 = sortCache.get(comparator2);
  if (doQuickSort2 === void 0) {
    doQuickSort2 = cloneSort(comparator2);
    sortCache.set(comparator2, doQuickSort2);
  }
  doQuickSort2(ary, comparator2, start, ary.length - 1);
};
var util$8 = util$c;
var binarySearch$2 = binarySearch$3;
var ArraySet$3 = arraySet$1.ArraySet;
var base64VLQ$2 = base64Vlq$1;
var quickSort$2 = quickSort$3.quickSort;
function SourceMapConsumer$6(aSourceMap, aSourceMapURL) {
  var sourceMap = aSourceMap;
  if (typeof aSourceMap === "string") {
    sourceMap = util$8.parseSourceMapInput(aSourceMap);
  }
  return sourceMap.sections != null ? new IndexedSourceMapConsumer$1(sourceMap, aSourceMapURL) : new BasicSourceMapConsumer$1(sourceMap, aSourceMapURL);
}
SourceMapConsumer$6.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  return BasicSourceMapConsumer$1.fromSourceMap(aSourceMap, aSourceMapURL);
};
SourceMapConsumer$6.prototype._version = 3;
SourceMapConsumer$6.prototype.__generatedMappings = null;
Object.defineProperty(SourceMapConsumer$6.prototype, "_generatedMappings", {
  configurable: true,
  enumerable: true,
  get: function() {
    if (!this.__generatedMappings) {
      this._parseMappings(this._mappings, this.sourceRoot);
    }
    return this.__generatedMappings;
  }
});
SourceMapConsumer$6.prototype.__originalMappings = null;
Object.defineProperty(SourceMapConsumer$6.prototype, "_originalMappings", {
  configurable: true,
  enumerable: true,
  get: function() {
    if (!this.__originalMappings) {
      this._parseMappings(this._mappings, this.sourceRoot);
    }
    return this.__originalMappings;
  }
});
SourceMapConsumer$6.prototype._charIsMappingSeparator = function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  var c = aStr.charAt(index);
  return c === ";" || c === ",";
};
SourceMapConsumer$6.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  throw new Error("Subclasses must implement _parseMappings");
};
SourceMapConsumer$6.GENERATED_ORDER = 1;
SourceMapConsumer$6.ORIGINAL_ORDER = 2;
SourceMapConsumer$6.GREATEST_LOWER_BOUND = 1;
SourceMapConsumer$6.LEAST_UPPER_BOUND = 2;
SourceMapConsumer$6.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  var context = aContext || null;
  var order = aOrder || SourceMapConsumer$6.GENERATED_ORDER;
  var mappings;
  switch (order) {
    case SourceMapConsumer$6.GENERATED_ORDER:
      mappings = this._generatedMappings;
      break;
    case SourceMapConsumer$6.ORIGINAL_ORDER:
      mappings = this._originalMappings;
      break;
    default:
      throw new Error("Unknown order of iteration.");
  }
  var sourceRoot = this.sourceRoot;
  var boundCallback = aCallback.bind(context);
  var names = this._names;
  var sources = this._sources;
  var sourceMapURL = this._sourceMapURL;
  for (var i = 0, n2 = mappings.length; i < n2; i++) {
    var mapping = mappings[i];
    var source = mapping.source === null ? null : sources.at(mapping.source);
    source = util$8.computeSourceURL(sourceRoot, source, sourceMapURL);
    boundCallback({
      source,
      generatedLine: mapping.generatedLine,
      generatedColumn: mapping.generatedColumn,
      originalLine: mapping.originalLine,
      originalColumn: mapping.originalColumn,
      name: mapping.name === null ? null : names.at(mapping.name)
    });
  }
};
SourceMapConsumer$6.prototype.allGeneratedPositionsFor = function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  var line = util$8.getArg(aArgs, "line");
  var needle = {
    source: util$8.getArg(aArgs, "source"),
    originalLine: line,
    originalColumn: util$8.getArg(aArgs, "column", 0)
  };
  needle.source = this._findSourceIndex(needle.source);
  if (needle.source < 0) {
    return [];
  }
  var mappings = [];
  var index = this._findMapping(
    needle,
    this._originalMappings,
    "originalLine",
    "originalColumn",
    util$8.compareByOriginalPositions,
    binarySearch$2.LEAST_UPPER_BOUND
  );
  if (index >= 0) {
    var mapping = this._originalMappings[index];
    if (aArgs.column === void 0) {
      var originalLine = mapping.originalLine;
      while (mapping && mapping.originalLine === originalLine) {
        mappings.push({
          line: util$8.getArg(mapping, "generatedLine", null),
          column: util$8.getArg(mapping, "generatedColumn", null),
          lastColumn: util$8.getArg(mapping, "lastGeneratedColumn", null)
        });
        mapping = this._originalMappings[++index];
      }
    } else {
      var originalColumn = mapping.originalColumn;
      while (mapping && mapping.originalLine === line && mapping.originalColumn == originalColumn) {
        mappings.push({
          line: util$8.getArg(mapping, "generatedLine", null),
          column: util$8.getArg(mapping, "generatedColumn", null),
          lastColumn: util$8.getArg(mapping, "lastGeneratedColumn", null)
        });
        mapping = this._originalMappings[++index];
      }
    }
  }
  return mappings;
};
sourceMapConsumer$1.SourceMapConsumer = SourceMapConsumer$6;
function BasicSourceMapConsumer$1(aSourceMap, aSourceMapURL) {
  var sourceMap = aSourceMap;
  if (typeof aSourceMap === "string") {
    sourceMap = util$8.parseSourceMapInput(aSourceMap);
  }
  var version2 = util$8.getArg(sourceMap, "version");
  var sources = util$8.getArg(sourceMap, "sources");
  var names = util$8.getArg(sourceMap, "names", []);
  var sourceRoot = util$8.getArg(sourceMap, "sourceRoot", null);
  var sourcesContent = util$8.getArg(sourceMap, "sourcesContent", null);
  var mappings = util$8.getArg(sourceMap, "mappings");
  var file = util$8.getArg(sourceMap, "file", null);
  if (version2 != this._version) {
    throw new Error("Unsupported version: " + version2);
  }
  if (sourceRoot) {
    sourceRoot = util$8.normalize(sourceRoot);
  }
  sources = sources.map(String).map(util$8.normalize).map(function(source) {
    return sourceRoot && util$8.isAbsolute(sourceRoot) && util$8.isAbsolute(source) ? util$8.relative(sourceRoot, source) : source;
  });
  this._names = ArraySet$3.fromArray(names.map(String), true);
  this._sources = ArraySet$3.fromArray(sources, true);
  this._absoluteSources = this._sources.toArray().map(function(s) {
    return util$8.computeSourceURL(sourceRoot, s, aSourceMapURL);
  });
  this.sourceRoot = sourceRoot;
  this.sourcesContent = sourcesContent;
  this._mappings = mappings;
  this._sourceMapURL = aSourceMapURL;
  this.file = file;
}
BasicSourceMapConsumer$1.prototype = Object.create(SourceMapConsumer$6.prototype);
BasicSourceMapConsumer$1.prototype.consumer = SourceMapConsumer$6;
BasicSourceMapConsumer$1.prototype._findSourceIndex = function(aSource) {
  var relativeSource = aSource;
  if (this.sourceRoot != null) {
    relativeSource = util$8.relative(this.sourceRoot, relativeSource);
  }
  if (this._sources.has(relativeSource)) {
    return this._sources.indexOf(relativeSource);
  }
  var i;
  for (i = 0; i < this._absoluteSources.length; ++i) {
    if (this._absoluteSources[i] == aSource) {
      return i;
    }
  }
  return -1;
};
BasicSourceMapConsumer$1.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) {
  var smc = Object.create(BasicSourceMapConsumer$1.prototype);
  var names = smc._names = ArraySet$3.fromArray(aSourceMap._names.toArray(), true);
  var sources = smc._sources = ArraySet$3.fromArray(aSourceMap._sources.toArray(), true);
  smc.sourceRoot = aSourceMap._sourceRoot;
  smc.sourcesContent = aSourceMap._generateSourcesContent(
    smc._sources.toArray(),
    smc.sourceRoot
  );
  smc.file = aSourceMap._file;
  smc._sourceMapURL = aSourceMapURL;
  smc._absoluteSources = smc._sources.toArray().map(function(s) {
    return util$8.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  });
  var generatedMappings = aSourceMap._mappings.toArray().slice();
  var destGeneratedMappings = smc.__generatedMappings = [];
  var destOriginalMappings = smc.__originalMappings = [];
  for (var i = 0, length2 = generatedMappings.length; i < length2; i++) {
    var srcMapping = generatedMappings[i];
    var destMapping = new Mapping$1();
    destMapping.generatedLine = srcMapping.generatedLine;
    destMapping.generatedColumn = srcMapping.generatedColumn;
    if (srcMapping.source) {
      destMapping.source = sources.indexOf(srcMapping.source);
      destMapping.originalLine = srcMapping.originalLine;
      destMapping.originalColumn = srcMapping.originalColumn;
      if (srcMapping.name) {
        destMapping.name = names.indexOf(srcMapping.name);
      }
      destOriginalMappings.push(destMapping);
    }
    destGeneratedMappings.push(destMapping);
  }
  quickSort$2(smc.__originalMappings, util$8.compareByOriginalPositions);
  return smc;
};
BasicSourceMapConsumer$1.prototype._version = 3;
Object.defineProperty(BasicSourceMapConsumer$1.prototype, "sources", {
  get: function() {
    return this._absoluteSources.slice();
  }
});
function Mapping$1() {
  this.generatedLine = 0;
  this.generatedColumn = 0;
  this.source = null;
  this.originalLine = null;
  this.originalColumn = null;
  this.name = null;
}
const compareGenerated = util$8.compareByGeneratedPositionsDeflatedNoLine;
function sortGenerated(array2, start) {
  let l = array2.length;
  let n2 = array2.length - start;
  if (n2 <= 1) {
    return;
  } else if (n2 == 2) {
    let a = array2[start];
    let b = array2[start + 1];
    if (compareGenerated(a, b) > 0) {
      array2[start] = b;
      array2[start + 1] = a;
    }
  } else if (n2 < 20) {
    for (let i = start; i < l; i++) {
      for (let j = i; j > start; j--) {
        let a = array2[j - 1];
        let b = array2[j];
        if (compareGenerated(a, b) <= 0) {
          break;
        }
        array2[j - 1] = b;
        array2[j] = a;
      }
    }
  } else {
    quickSort$2(array2, compareGenerated, start);
  }
}
BasicSourceMapConsumer$1.prototype._parseMappings = function SourceMapConsumer_parseMappings2(aStr, aSourceRoot) {
  var generatedLine = 1;
  var previousGeneratedColumn = 0;
  var previousOriginalLine = 0;
  var previousOriginalColumn = 0;
  var previousSource = 0;
  var previousName = 0;
  var length2 = aStr.length;
  var index = 0;
  var temp = {};
  var originalMappings = [];
  var generatedMappings = [];
  var mapping, segment, end, value;
  let subarrayStart = 0;
  while (index < length2) {
    if (aStr.charAt(index) === ";") {
      generatedLine++;
      index++;
      previousGeneratedColumn = 0;
      sortGenerated(generatedMappings, subarrayStart);
      subarrayStart = generatedMappings.length;
    } else if (aStr.charAt(index) === ",") {
      index++;
    } else {
      mapping = new Mapping$1();
      mapping.generatedLine = generatedLine;
      for (end = index; end < length2; end++) {
        if (this._charIsMappingSeparator(aStr, end)) {
          break;
        }
      }
      aStr.slice(index, end);
      segment = [];
      while (index < end) {
        base64VLQ$2.decode(aStr, index, temp);
        value = temp.value;
        index = temp.rest;
        segment.push(value);
      }
      if (segment.length === 2) {
        throw new Error("Found a source, but no line and column");
      }
      if (segment.length === 3) {
        throw new Error("Found a source and line, but no column");
      }
      mapping.generatedColumn = previousGeneratedColumn + segment[0];
      previousGeneratedColumn = mapping.generatedColumn;
      if (segment.length > 1) {
        mapping.source = previousSource + segment[1];
        previousSource += segment[1];
        mapping.originalLine = previousOriginalLine + segment[2];
        previousOriginalLine = mapping.originalLine;
        mapping.originalLine += 1;
        mapping.originalColumn = previousOriginalColumn + segment[3];
        previousOriginalColumn = mapping.originalColumn;
        if (segment.length > 4) {
          mapping.name = previousName + segment[4];
          previousName += segment[4];
        }
      }
      generatedMappings.push(mapping);
      if (typeof mapping.originalLine === "number") {
        let currentSource = mapping.source;
        while (originalMappings.length <= currentSource) {
          originalMappings.push(null);
        }
        if (originalMappings[currentSource] === null) {
          originalMappings[currentSource] = [];
        }
        originalMappings[currentSource].push(mapping);
      }
    }
  }
  sortGenerated(generatedMappings, subarrayStart);
  this.__generatedMappings = generatedMappings;
  for (var i = 0; i < originalMappings.length; i++) {
    if (originalMappings[i] != null) {
      quickSort$2(originalMappings[i], util$8.compareByOriginalPositionsNoSource);
    }
  }
  this.__originalMappings = [].concat(...originalMappings);
};
BasicSourceMapConsumer$1.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator, aBias) {
  if (aNeedle[aLineName] <= 0) {
    throw new TypeError("Line must be greater than or equal to 1, got " + aNeedle[aLineName]);
  }
  if (aNeedle[aColumnName] < 0) {
    throw new TypeError("Column must be greater than or equal to 0, got " + aNeedle[aColumnName]);
  }
  return binarySearch$2.search(aNeedle, aMappings, aComparator, aBias);
};
BasicSourceMapConsumer$1.prototype.computeColumnSpans = function SourceMapConsumer_computeColumnSpans() {
  for (var index = 0; index < this._generatedMappings.length; ++index) {
    var mapping = this._generatedMappings[index];
    if (index + 1 < this._generatedMappings.length) {
      var nextMapping = this._generatedMappings[index + 1];
      if (mapping.generatedLine === nextMapping.generatedLine) {
        mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
        continue;
      }
    }
    mapping.lastGeneratedColumn = Infinity;
  }
};
BasicSourceMapConsumer$1.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) {
  var needle = {
    generatedLine: util$8.getArg(aArgs, "line"),
    generatedColumn: util$8.getArg(aArgs, "column")
  };
  var index = this._findMapping(
    needle,
    this._generatedMappings,
    "generatedLine",
    "generatedColumn",
    util$8.compareByGeneratedPositionsDeflated,
    util$8.getArg(aArgs, "bias", SourceMapConsumer$6.GREATEST_LOWER_BOUND)
  );
  if (index >= 0) {
    var mapping = this._generatedMappings[index];
    if (mapping.generatedLine === needle.generatedLine) {
      var source = util$8.getArg(mapping, "source", null);
      if (source !== null) {
        source = this._sources.at(source);
        source = util$8.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
      }
      var name = util$8.getArg(mapping, "name", null);
      if (name !== null) {
        name = this._names.at(name);
      }
      return {
        source,
        line: util$8.getArg(mapping, "originalLine", null),
        column: util$8.getArg(mapping, "originalColumn", null),
        name
      };
    }
  }
  return {
    source: null,
    line: null,
    column: null,
    name: null
  };
};
BasicSourceMapConsumer$1.prototype.hasContentsOfAllSources = function BasicSourceMapConsumer_hasContentsOfAllSources() {
  if (!this.sourcesContent) {
    return false;
  }
  return this.sourcesContent.length >= this._sources.size() && !this.sourcesContent.some(function(sc) {
    return sc == null;
  });
};
BasicSourceMapConsumer$1.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  if (!this.sourcesContent) {
    return null;
  }
  var index = this._findSourceIndex(aSource);
  if (index >= 0) {
    return this.sourcesContent[index];
  }
  var relativeSource = aSource;
  if (this.sourceRoot != null) {
    relativeSource = util$8.relative(this.sourceRoot, relativeSource);
  }
  var url;
  if (this.sourceRoot != null && (url = util$8.urlParse(this.sourceRoot))) {
    var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
    if (url.scheme == "file" && this._sources.has(fileUriAbsPath)) {
      return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)];
    }
    if ((!url.path || url.path == "/") && this._sources.has("/" + relativeSource)) {
      return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
    }
  }
  if (nullOnMissing) {
    return null;
  } else {
    throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  }
};
BasicSourceMapConsumer$1.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) {
  var source = util$8.getArg(aArgs, "source");
  source = this._findSourceIndex(source);
  if (source < 0) {
    return {
      line: null,
      column: null,
      lastColumn: null
    };
  }
  var needle = {
    source,
    originalLine: util$8.getArg(aArgs, "line"),
    originalColumn: util$8.getArg(aArgs, "column")
  };
  var index = this._findMapping(
    needle,
    this._originalMappings,
    "originalLine",
    "originalColumn",
    util$8.compareByOriginalPositions,
    util$8.getArg(aArgs, "bias", SourceMapConsumer$6.GREATEST_LOWER_BOUND)
  );
  if (index >= 0) {
    var mapping = this._originalMappings[index];
    if (mapping.source === needle.source) {
      return {
        line: util$8.getArg(mapping, "generatedLine", null),
        column: util$8.getArg(mapping, "generatedColumn", null),
        lastColumn: util$8.getArg(mapping, "lastGeneratedColumn", null)
      };
    }
  }
  return {
    line: null,
    column: null,
    lastColumn: null
  };
};
sourceMapConsumer$1.BasicSourceMapConsumer = BasicSourceMapConsumer$1;
function IndexedSourceMapConsumer$1(aSourceMap, aSourceMapURL) {
  var sourceMap = aSourceMap;
  if (typeof aSourceMap === "string") {
    sourceMap = util$8.parseSourceMapInput(aSourceMap);
  }
  var version2 = util$8.getArg(sourceMap, "version");
  var sections = util$8.getArg(sourceMap, "sections");
  if (version2 != this._version) {
    throw new Error("Unsupported version: " + version2);
  }
  this._sources = new ArraySet$3();
  this._names = new ArraySet$3();
  var lastOffset = {
    line: -1,
    column: 0
  };
  this._sections = sections.map(function(s) {
    if (s.url) {
      throw new Error("Support for url field in sections not implemented.");
    }
    var offset = util$8.getArg(s, "offset");
    var offsetLine = util$8.getArg(offset, "line");
    var offsetColumn = util$8.getArg(offset, "column");
    if (offsetLine < lastOffset.line || offsetLine === lastOffset.line && offsetColumn < lastOffset.column) {
      throw new Error("Section offsets must be ordered and non-overlapping.");
    }
    lastOffset = offset;
    return {
      generatedOffset: {
        // The offset fields are 0-based, but we use 1-based indices when
        // encoding/decoding from VLQ.
        generatedLine: offsetLine + 1,
        generatedColumn: offsetColumn + 1
      },
      consumer: new SourceMapConsumer$6(util$8.getArg(s, "map"), aSourceMapURL)
    };
  });
}
IndexedSourceMapConsumer$1.prototype = Object.create(SourceMapConsumer$6.prototype);
IndexedSourceMapConsumer$1.prototype.constructor = SourceMapConsumer$6;
IndexedSourceMapConsumer$1.prototype._version = 3;
Object.defineProperty(IndexedSourceMapConsumer$1.prototype, "sources", {
  get: function() {
    var sources = [];
    for (var i = 0; i < this._sections.length; i++) {
      for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
        sources.push(this._sections[i].consumer.sources[j]);
      }
    }
    return sources;
  }
});
IndexedSourceMapConsumer$1.prototype.originalPositionFor = function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  var needle = {
    generatedLine: util$8.getArg(aArgs, "line"),
    generatedColumn: util$8.getArg(aArgs, "column")
  };
  var sectionIndex = binarySearch$2.search(
    needle,
    this._sections,
    function(needle2, section2) {
      var cmp3 = needle2.generatedLine - section2.generatedOffset.generatedLine;
      if (cmp3) {
        return cmp3;
      }
      return needle2.generatedColumn - section2.generatedOffset.generatedColumn;
    }
  );
  var section = this._sections[sectionIndex];
  if (!section) {
    return {
      source: null,
      line: null,
      column: null,
      name: null
    };
  }
  return section.consumer.originalPositionFor({
    line: needle.generatedLine - (section.generatedOffset.generatedLine - 1),
    column: needle.generatedColumn - (section.generatedOffset.generatedLine === needle.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0),
    bias: aArgs.bias
  });
};
IndexedSourceMapConsumer$1.prototype.hasContentsOfAllSources = function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  return this._sections.every(function(s) {
    return s.consumer.hasContentsOfAllSources();
  });
};
IndexedSourceMapConsumer$1.prototype.sourceContentFor = function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  for (var i = 0; i < this._sections.length; i++) {
    var section = this._sections[i];
    var content = section.consumer.sourceContentFor(aSource, true);
    if (content) {
      return content;
    }
  }
  if (nullOnMissing) {
    return null;
  } else {
    throw new Error('"' + aSource + '" is not in the SourceMap.');
  }
};
IndexedSourceMapConsumer$1.prototype.generatedPositionFor = function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  for (var i = 0; i < this._sections.length; i++) {
    var section = this._sections[i];
    if (section.consumer._findSourceIndex(util$8.getArg(aArgs, "source")) === -1) {
      continue;
    }
    var generatedPosition = section.consumer.generatedPositionFor(aArgs);
    if (generatedPosition) {
      var ret = {
        line: generatedPosition.line + (section.generatedOffset.generatedLine - 1),
        column: generatedPosition.column + (section.generatedOffset.generatedLine === generatedPosition.line ? section.generatedOffset.generatedColumn - 1 : 0)
      };
      return ret;
    }
  }
  return {
    line: null,
    column: null
  };
};
IndexedSourceMapConsumer$1.prototype._parseMappings = function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  this.__generatedMappings = [];
  this.__originalMappings = [];
  for (var i = 0; i < this._sections.length; i++) {
    var section = this._sections[i];
    var sectionMappings = section.consumer._generatedMappings;
    for (var j = 0; j < sectionMappings.length; j++) {
      var mapping = sectionMappings[j];
      var source = section.consumer._sources.at(mapping.source);
      source = util$8.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
      this._sources.add(source);
      source = this._sources.indexOf(source);
      var name = null;
      if (mapping.name) {
        name = section.consumer._names.at(mapping.name);
        this._names.add(name);
        name = this._names.indexOf(name);
      }
      var adjustedMapping = {
        source,
        generatedLine: mapping.generatedLine + (section.generatedOffset.generatedLine - 1),
        generatedColumn: mapping.generatedColumn + (section.generatedOffset.generatedLine === mapping.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0),
        originalLine: mapping.originalLine,
        originalColumn: mapping.originalColumn,
        name
      };
      this.__generatedMappings.push(adjustedMapping);
      if (typeof adjustedMapping.originalLine === "number") {
        this.__originalMappings.push(adjustedMapping);
      }
    }
  }
  quickSort$2(this.__generatedMappings, util$8.compareByGeneratedPositionsDeflated);
  quickSort$2(this.__originalMappings, util$8.compareByOriginalPositions);
};
sourceMapConsumer$1.IndexedSourceMapConsumer = IndexedSourceMapConsumer$1;
var sourceNode$1 = {};
var SourceMapGenerator$7 = sourceMapGenerator$1.SourceMapGenerator;
var util$7 = util$c;
var REGEX_NEWLINE$1 = /(\r?\n)/;
var NEWLINE_CODE$1 = 10;
var isSourceNode$1 = "$$$isSourceNode$$$";
function SourceNode$1(aLine, aColumn, aSource, aChunks, aName) {
  this.children = [];
  this.sourceContents = {};
  this.line = aLine == null ? null : aLine;
  this.column = aColumn == null ? null : aColumn;
  this.source = aSource == null ? null : aSource;
  this.name = aName == null ? null : aName;
  this[isSourceNode$1] = true;
  if (aChunks != null)
    this.add(aChunks);
}
SourceNode$1.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  var node2 = new SourceNode$1();
  var remainingLines = aGeneratedCode.split(REGEX_NEWLINE$1);
  var remainingLinesIndex = 0;
  var shiftNextLine = function() {
    var lineContents = getNextLine();
    var newLine = getNextLine() || "";
    return lineContents + newLine;
    function getNextLine() {
      return remainingLinesIndex < remainingLines.length ? remainingLines[remainingLinesIndex++] : void 0;
    }
  };
  var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  var lastMapping = null;
  aSourceMapConsumer.eachMapping(function(mapping) {
    if (lastMapping !== null) {
      if (lastGeneratedLine < mapping.generatedLine) {
        addMappingWithCode(lastMapping, shiftNextLine());
        lastGeneratedLine++;
        lastGeneratedColumn = 0;
      } else {
        var nextLine = remainingLines[remainingLinesIndex] || "";
        var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn);
        remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn);
        lastGeneratedColumn = mapping.generatedColumn;
        addMappingWithCode(lastMapping, code);
        lastMapping = mapping;
        return;
      }
    }
    while (lastGeneratedLine < mapping.generatedLine) {
      node2.add(shiftNextLine());
      lastGeneratedLine++;
    }
    if (lastGeneratedColumn < mapping.generatedColumn) {
      var nextLine = remainingLines[remainingLinesIndex] || "";
      node2.add(nextLine.substr(0, mapping.generatedColumn));
      remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
      lastGeneratedColumn = mapping.generatedColumn;
    }
    lastMapping = mapping;
  }, this);
  if (remainingLinesIndex < remainingLines.length) {
    if (lastMapping) {
      addMappingWithCode(lastMapping, shiftNextLine());
    }
    node2.add(remainingLines.splice(remainingLinesIndex).join(""));
  }
  aSourceMapConsumer.sources.forEach(function(sourceFile) {
    var content = aSourceMapConsumer.sourceContentFor(sourceFile);
    if (content != null) {
      if (aRelativePath != null) {
        sourceFile = util$7.join(aRelativePath, sourceFile);
      }
      node2.setSourceContent(sourceFile, content);
    }
  });
  return node2;
  function addMappingWithCode(mapping, code) {
    if (mapping === null || mapping.source === void 0) {
      node2.add(code);
    } else {
      var source = aRelativePath ? util$7.join(aRelativePath, mapping.source) : mapping.source;
      node2.add(new SourceNode$1(
        mapping.originalLine,
        mapping.originalColumn,
        source,
        code,
        mapping.name
      ));
    }
  }
};
SourceNode$1.prototype.add = function SourceNode_add(aChunk) {
  if (Array.isArray(aChunk)) {
    aChunk.forEach(function(chunk) {
      this.add(chunk);
    }, this);
  } else if (aChunk[isSourceNode$1] || typeof aChunk === "string") {
    if (aChunk) {
      this.children.push(aChunk);
    }
  } else {
    throw new TypeError(
      "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
    );
  }
  return this;
};
SourceNode$1.prototype.prepend = function SourceNode_prepend(aChunk) {
  if (Array.isArray(aChunk)) {
    for (var i = aChunk.length - 1; i >= 0; i--) {
      this.prepend(aChunk[i]);
    }
  } else if (aChunk[isSourceNode$1] || typeof aChunk === "string") {
    this.children.unshift(aChunk);
  } else {
    throw new TypeError(
      "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
    );
  }
  return this;
};
SourceNode$1.prototype.walk = function SourceNode_walk(aFn) {
  var chunk;
  for (var i = 0, len = this.children.length; i < len; i++) {
    chunk = this.children[i];
    if (chunk[isSourceNode$1]) {
      chunk.walk(aFn);
    } else {
      if (chunk !== "") {
        aFn(chunk, {
          source: this.source,
          line: this.line,
          column: this.column,
          name: this.name
        });
      }
    }
  }
};
SourceNode$1.prototype.join = function SourceNode_join(aSep) {
  var newChildren;
  var i;
  var len = this.children.length;
  if (len > 0) {
    newChildren = [];
    for (i = 0; i < len - 1; i++) {
      newChildren.push(this.children[i]);
      newChildren.push(aSep);
    }
    newChildren.push(this.children[i]);
    this.children = newChildren;
  }
  return this;
};
SourceNode$1.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  var lastChild = this.children[this.children.length - 1];
  if (lastChild[isSourceNode$1]) {
    lastChild.replaceRight(aPattern, aReplacement);
  } else if (typeof lastChild === "string") {
    this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  } else {
    this.children.push("".replace(aPattern, aReplacement));
  }
  return this;
};
SourceNode$1.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  this.sourceContents[util$7.toSetString(aSourceFile)] = aSourceContent;
};
SourceNode$1.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) {
  for (var i = 0, len = this.children.length; i < len; i++) {
    if (this.children[i][isSourceNode$1]) {
      this.children[i].walkSourceContents(aFn);
    }
  }
  var sources = Object.keys(this.sourceContents);
  for (var i = 0, len = sources.length; i < len; i++) {
    aFn(util$7.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  }
};
SourceNode$1.prototype.toString = function SourceNode_toString() {
  var str2 = "";
  this.walk(function(chunk) {
    str2 += chunk;
  });
  return str2;
};
SourceNode$1.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  var generated = {
    code: "",
    line: 1,
    column: 0
  };
  var map2 = new SourceMapGenerator$7(aArgs);
  var sourceMappingActive = false;
  var lastOriginalSource = null;
  var lastOriginalLine = null;
  var lastOriginalColumn = null;
  var lastOriginalName = null;
  this.walk(function(chunk, original) {
    generated.code += chunk;
    if (original.source !== null && original.line !== null && original.column !== null) {
      if (lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) {
        map2.addMapping({
          source: original.source,
          original: {
            line: original.line,
            column: original.column
          },
          generated: {
            line: generated.line,
            column: generated.column
          },
          name: original.name
        });
      }
      lastOriginalSource = original.source;
      lastOriginalLine = original.line;
      lastOriginalColumn = original.column;
      lastOriginalName = original.name;
      sourceMappingActive = true;
    } else if (sourceMappingActive) {
      map2.addMapping({
        generated: {
          line: generated.line,
          column: generated.column
        }
      });
      lastOriginalSource = null;
      sourceMappingActive = false;
    }
    for (var idx = 0, length2 = chunk.length; idx < length2; idx++) {
      if (chunk.charCodeAt(idx) === NEWLINE_CODE$1) {
        generated.line++;
        generated.column = 0;
        if (idx + 1 === length2) {
          lastOriginalSource = null;
          sourceMappingActive = false;
        } else if (sourceMappingActive) {
          map2.addMapping({
            source: original.source,
            original: {
              line: original.line,
              column: original.column
            },
            generated: {
              line: generated.line,
              column: generated.column
            },
            name: original.name
          });
        }
      } else {
        generated.column++;
      }
    }
  });
  this.walkSourceContents(function(sourceFile, sourceContent) {
    map2.setSourceContent(sourceFile, sourceContent);
  });
  return { code: generated.code, map: map2 };
};
sourceNode$1.SourceNode = SourceNode$1;
var SourceMapGenerator$6 = sourceMap$2.SourceMapGenerator = sourceMapGenerator$1.SourceMapGenerator;
sourceMap$2.SourceMapConsumer = sourceMapConsumer$1.SourceMapConsumer;
sourceMap$2.SourceNode = sourceNode$1.SourceNode;
const PURE_ANNOTATION = `/*#__PURE__*/`;
const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
function createCodegenContext(ast, {
  mode = "function",
  prefixIdentifiers = mode === "module",
  sourceMap = false,
  filename = `template.vue.html`,
  scopeId = null,
  optimizeImports = false,
  runtimeGlobalName = `Vue`,
  runtimeModuleName = `vue`,
  ssrRuntimeModuleName = "vue/server-renderer",
  ssr = false,
  isTS = false,
  inSSR = false
}) {
  const context = {
    mode,
    prefixIdentifiers,
    sourceMap,
    filename,
    scopeId,
    optimizeImports,
    runtimeGlobalName,
    runtimeModuleName,
    ssrRuntimeModuleName,
    ssr,
    isTS,
    inSSR,
    source: ast.loc.source,
    code: ``,
    column: 1,
    line: 1,
    offset: 0,
    indentLevel: 0,
    pure: false,
    map: void 0,
    helper(key) {
      return `_${helperNameMap[key]}`;
    },
    push(code, node2) {
      context.code += code;
      if (context.map) {
        if (node2) {
          let name;
          if (node2.type === 4 && !node2.isStatic) {
            const content = node2.content.replace(/^_ctx\./, "");
            if (content !== node2.content && isSimpleIdentifier(content)) {
              name = content;
            }
          }
          addMapping(node2.loc.start, name);
        }
        advancePositionWithMutation(context, code);
        if (node2 && node2.loc !== locStub) {
          addMapping(node2.loc.end);
        }
      }
    },
    indent() {
      newline2(++context.indentLevel);
    },
    deindent(withoutNewLine = false) {
      if (withoutNewLine) {
        --context.indentLevel;
      } else {
        newline2(--context.indentLevel);
      }
    },
    newline() {
      newline2(context.indentLevel);
    }
  };
  function newline2(n2) {
    context.push("\n" + `  `.repeat(n2));
  }
  function addMapping(loc, name) {
    context.map.addMapping({
      name,
      source: context.filename,
      original: {
        line: loc.line,
        column: loc.column - 1
        // source-map column is 0 based
      },
      generated: {
        line: context.line,
        column: context.column - 1
      }
    });
  }
  if (sourceMap) {
    context.map = new SourceMapGenerator$6();
    context.map.setSourceContent(filename, context.source);
  }
  return context;
}
function generate(ast, options = {}) {
  const context = createCodegenContext(ast, options);
  if (options.onContextCreated)
    options.onContextCreated(context);
  const {
    mode,
    push: push2,
    prefixIdentifiers,
    indent,
    deindent,
    newline: newline2,
    scopeId,
    ssr
  } = context;
  const helpers = Array.from(ast.helpers);
  const hasHelpers = helpers.length > 0;
  const useWithBlock = !prefixIdentifiers && mode !== "module";
  const genScopeId = scopeId != null && mode === "module";
  const isSetupInlined = !!options.inline;
  const preambleContext = isSetupInlined ? createCodegenContext(ast, options) : context;
  if (mode === "module") {
    genModulePreamble(ast, preambleContext, genScopeId, isSetupInlined);
  } else {
    genFunctionPreamble(ast, preambleContext);
  }
  const functionName = ssr ? `ssrRender` : `render`;
  const args = ssr ? ["_ctx", "_push", "_parent", "_attrs"] : ["_ctx", "_cache"];
  if (options.bindingMetadata && !options.inline) {
    args.push("$props", "$setup", "$data", "$options");
  }
  const signature = options.isTS ? args.map((arg) => `${arg}: any`).join(",") : args.join(", ");
  if (isSetupInlined) {
    push2(`(${signature}) => {`);
  } else {
    push2(`function ${functionName}(${signature}) {`);
  }
  indent();
  if (useWithBlock) {
    push2(`with (_ctx) {`);
    indent();
    if (hasHelpers) {
      push2(`const { ${helpers.map(aliasHelper).join(", ")} } = _Vue`);
      push2(`
`);
      newline2();
    }
  }
  if (ast.components.length) {
    genAssets(ast.components, "component", context);
    if (ast.directives.length || ast.temps > 0) {
      newline2();
    }
  }
  if (ast.directives.length) {
    genAssets(ast.directives, "directive", context);
    if (ast.temps > 0) {
      newline2();
    }
  }
  if (ast.temps > 0) {
    push2(`let `);
    for (let i = 0; i < ast.temps; i++) {
      push2(`${i > 0 ? `, ` : ``}_temp${i}`);
    }
  }
  if (ast.components.length || ast.directives.length || ast.temps) {
    push2(`
`);
    newline2();
  }
  if (!ssr) {
    push2(`return `);
  }
  if (ast.codegenNode) {
    genNode(ast.codegenNode, context);
  } else {
    push2(`null`);
  }
  if (useWithBlock) {
    deindent();
    push2(`}`);
  }
  deindent();
  push2(`}`);
  return {
    ast,
    code: context.code,
    preamble: isSetupInlined ? preambleContext.code : ``,
    // SourceMapGenerator does have toJSON() method but it's not in the types
    map: context.map ? context.map.toJSON() : void 0
  };
}
function genFunctionPreamble(ast, context) {
  const {
    ssr,
    prefixIdentifiers,
    push: push2,
    newline: newline2,
    runtimeModuleName,
    runtimeGlobalName,
    ssrRuntimeModuleName
  } = context;
  const VueBinding = ssr ? `require(${JSON.stringify(runtimeModuleName)})` : runtimeGlobalName;
  const helpers = Array.from(ast.helpers);
  if (helpers.length > 0) {
    if (prefixIdentifiers) {
      push2(`const { ${helpers.map(aliasHelper).join(", ")} } = ${VueBinding}
`);
    } else {
      push2(`const _Vue = ${VueBinding}
`);
      if (ast.hoists.length) {
        const staticHelpers = [
          CREATE_VNODE,
          CREATE_ELEMENT_VNODE,
          CREATE_COMMENT,
          CREATE_TEXT,
          CREATE_STATIC
        ].filter((helper) => helpers.includes(helper)).map(aliasHelper).join(", ");
        push2(`const { ${staticHelpers} } = _Vue
`);
      }
    }
  }
  if (ast.ssrHelpers && ast.ssrHelpers.length) {
    push2(
      `const { ${ast.ssrHelpers.map(aliasHelper).join(", ")} } = require("${ssrRuntimeModuleName}")
`
    );
  }
  genHoists(ast.hoists, context);
  newline2();
  push2(`return `);
}
function genModulePreamble(ast, context, genScopeId, inline) {
  const {
    push: push2,
    newline: newline2,
    optimizeImports,
    runtimeModuleName,
    ssrRuntimeModuleName
  } = context;
  if (genScopeId && ast.hoists.length) {
    ast.helpers.add(PUSH_SCOPE_ID);
    ast.helpers.add(POP_SCOPE_ID);
  }
  if (ast.helpers.size) {
    const helpers = Array.from(ast.helpers);
    if (optimizeImports) {
      push2(
        `import { ${helpers.map((s) => helperNameMap[s]).join(", ")} } from ${JSON.stringify(runtimeModuleName)}
`
      );
      push2(
        `
// Binding optimization for webpack code-split
const ${helpers.map((s) => `_${helperNameMap[s]} = ${helperNameMap[s]}`).join(", ")}
`
      );
    } else {
      push2(
        `import { ${helpers.map((s) => `${helperNameMap[s]} as _${helperNameMap[s]}`).join(", ")} } from ${JSON.stringify(runtimeModuleName)}
`
      );
    }
  }
  if (ast.ssrHelpers && ast.ssrHelpers.length) {
    push2(
      `import { ${ast.ssrHelpers.map((s) => `${helperNameMap[s]} as _${helperNameMap[s]}`).join(", ")} } from "${ssrRuntimeModuleName}"
`
    );
  }
  if (ast.imports.length) {
    genImports(ast.imports, context);
    newline2();
  }
  genHoists(ast.hoists, context);
  newline2();
  if (!inline) {
    push2(`export `);
  }
}
function genAssets(assets, type, { helper, push: push2, newline: newline2, isTS }) {
  const resolver = helper(
    type === "component" ? RESOLVE_COMPONENT : RESOLVE_DIRECTIVE
  );
  for (let i = 0; i < assets.length; i++) {
    let id3 = assets[i];
    const maybeSelfReference = id3.endsWith("__self");
    if (maybeSelfReference) {
      id3 = id3.slice(0, -6);
    }
    push2(
      `const ${toValidAssetId(id3, type)} = ${resolver}(${JSON.stringify(id3)}${maybeSelfReference ? `, true` : ``})${isTS ? `!` : ``}`
    );
    if (i < assets.length - 1) {
      newline2();
    }
  }
}
function genHoists(hoists, context) {
  if (!hoists.length) {
    return;
  }
  context.pure = true;
  const { push: push2, newline: newline2, helper, scopeId, mode } = context;
  const genScopeId = scopeId != null && mode !== "function";
  newline2();
  if (genScopeId) {
    push2(
      `const _withScopeId = n => (${helper(
        PUSH_SCOPE_ID
      )}("${scopeId}"),n=n(),${helper(POP_SCOPE_ID)}(),n)`
    );
    newline2();
  }
  for (let i = 0; i < hoists.length; i++) {
    const exp = hoists[i];
    if (exp) {
      const needScopeIdWrapper = genScopeId && exp.type === 13;
      push2(
        `const _hoisted_${i + 1} = ${needScopeIdWrapper ? `${PURE_ANNOTATION} _withScopeId(() => ` : ``}`
      );
      genNode(exp, context);
      if (needScopeIdWrapper) {
        push2(`)`);
      }
      newline2();
    }
  }
  context.pure = false;
}
function genImports(importsOptions, context) {
  if (!importsOptions.length) {
    return;
  }
  importsOptions.forEach((imports) => {
    context.push(`import `);
    genNode(imports.exp, context);
    context.push(` from '${imports.path}'`);
    context.newline();
  });
}
function isText(n2) {
  return isString$2(n2) || n2.type === 4 || n2.type === 2 || n2.type === 5 || n2.type === 8;
}
function genNodeListAsArray(nodes, context) {
  const multilines = nodes.length > 3 || nodes.some((n2) => isArray$3(n2) || !isText(n2));
  context.push(`[`);
  multilines && context.indent();
  genNodeList(nodes, context, multilines);
  multilines && context.deindent();
  context.push(`]`);
}
function genNodeList(nodes, context, multilines = false, comma = true) {
  const { push: push2, newline: newline2 } = context;
  for (let i = 0; i < nodes.length; i++) {
    const node2 = nodes[i];
    if (isString$2(node2)) {
      push2(node2);
    } else if (isArray$3(node2)) {
      genNodeListAsArray(node2, context);
    } else {
      genNode(node2, context);
    }
    if (i < nodes.length - 1) {
      if (multilines) {
        comma && push2(",");
        newline2();
      } else {
        comma && push2(", ");
      }
    }
  }
}
function genNode(node2, context) {
  if (isString$2(node2)) {
    context.push(node2);
    return;
  }
  if (isSymbol$1(node2)) {
    context.push(context.helper(node2));
    return;
  }
  switch (node2.type) {
    case 1:
    case 9:
    case 11:
      assert(
        node2.codegenNode != null,
        `Codegen node is missing for element/if/for node. Apply appropriate transforms first.`
      );
      genNode(node2.codegenNode, context);
      break;
    case 2:
      genText(node2, context);
      break;
    case 4:
      genExpression(node2, context);
      break;
    case 5:
      genInterpolation(node2, context);
      break;
    case 12:
      genNode(node2.codegenNode, context);
      break;
    case 8:
      genCompoundExpression(node2, context);
      break;
    case 3:
      genComment(node2, context);
      break;
    case 13:
      genVNodeCall(node2, context);
      break;
    case 14:
      genCallExpression(node2, context);
      break;
    case 15:
      genObjectExpression(node2, context);
      break;
    case 17:
      genArrayExpression(node2, context);
      break;
    case 18:
      genFunctionExpression(node2, context);
      break;
    case 19:
      genConditionalExpression(node2, context);
      break;
    case 20:
      genCacheExpression(node2, context);
      break;
    case 21:
      genNodeList(node2.body, context, true, false);
      break;
    case 22:
      genTemplateLiteral(node2, context);
      break;
    case 23:
      genIfStatement(node2, context);
      break;
    case 24:
      genAssignmentExpression(node2, context);
      break;
    case 25:
      genSequenceExpression(node2, context);
      break;
    case 26:
      genReturnStatement(node2, context);
      break;
    case 10:
      break;
    default: {
      assert(false, `unhandled codegen node type: ${node2.type}`);
      const exhaustiveCheck = node2;
      return exhaustiveCheck;
    }
  }
}
function genText(node2, context) {
  context.push(JSON.stringify(node2.content), node2);
}
function genExpression(node2, context) {
  const { content, isStatic } = node2;
  context.push(isStatic ? JSON.stringify(content) : content, node2);
}
function genInterpolation(node2, context) {
  const { push: push2, helper, pure } = context;
  if (pure)
    push2(PURE_ANNOTATION);
  push2(`${helper(TO_DISPLAY_STRING)}(`);
  genNode(node2.content, context);
  push2(`)`);
}
function genCompoundExpression(node2, context) {
  for (let i = 0; i < node2.children.length; i++) {
    const child = node2.children[i];
    if (isString$2(child)) {
      context.push(child);
    } else {
      genNode(child, context);
    }
  }
}
function genExpressionAsPropertyKey(node2, context) {
  const { push: push2 } = context;
  if (node2.type === 8) {
    push2(`[`);
    genCompoundExpression(node2, context);
    push2(`]`);
  } else if (node2.isStatic) {
    const text2 = isSimpleIdentifier(node2.content) ? node2.content : JSON.stringify(node2.content);
    push2(text2, node2);
  } else {
    push2(`[${node2.content}]`, node2);
  }
}
function genComment(node2, context) {
  const { push: push2, helper, pure } = context;
  if (pure) {
    push2(PURE_ANNOTATION);
  }
  push2(`${helper(CREATE_COMMENT)}(${JSON.stringify(node2.content)})`, node2);
}
function genVNodeCall(node2, context) {
  const { push: push2, helper, pure } = context;
  const {
    tag: tag3,
    props,
    children,
    patchFlag,
    dynamicProps,
    directives,
    isBlock,
    disableTracking,
    isComponent: isComponent2
  } = node2;
  if (directives) {
    push2(helper(WITH_DIRECTIVES) + `(`);
  }
  if (isBlock) {
    push2(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
  }
  if (pure) {
    push2(PURE_ANNOTATION);
  }
  const callHelper = isBlock ? getVNodeBlockHelper(context.inSSR, isComponent2) : getVNodeHelper(context.inSSR, isComponent2);
  push2(helper(callHelper) + `(`, node2);
  genNodeList(
    genNullableArgs([tag3, props, children, patchFlag, dynamicProps]),
    context
  );
  push2(`)`);
  if (isBlock) {
    push2(`)`);
  }
  if (directives) {
    push2(`, `);
    genNode(directives, context);
    push2(`)`);
  }
}
function genNullableArgs(args) {
  let i = args.length;
  while (i--) {
    if (args[i] != null)
      break;
  }
  return args.slice(0, i + 1).map((arg) => arg || `null`);
}
function genCallExpression(node2, context) {
  const { push: push2, helper, pure } = context;
  const callee = isString$2(node2.callee) ? node2.callee : helper(node2.callee);
  if (pure) {
    push2(PURE_ANNOTATION);
  }
  push2(callee + `(`, node2);
  genNodeList(node2.arguments, context);
  push2(`)`);
}
function genObjectExpression(node2, context) {
  const { push: push2, indent, deindent, newline: newline2 } = context;
  const { properties } = node2;
  if (!properties.length) {
    push2(`{}`, node2);
    return;
  }
  const multilines = properties.length > 1 || properties.some((p2) => p2.value.type !== 4);
  push2(multilines ? `{` : `{ `);
  multilines && indent();
  for (let i = 0; i < properties.length; i++) {
    const { key, value } = properties[i];
    genExpressionAsPropertyKey(key, context);
    push2(`: `);
    genNode(value, context);
    if (i < properties.length - 1) {
      push2(`,`);
      newline2();
    }
  }
  multilines && deindent();
  push2(multilines ? `}` : ` }`);
}
function genArrayExpression(node2, context) {
  genNodeListAsArray(node2.elements, context);
}
function genFunctionExpression(node2, context) {
  const { push: push2, indent, deindent } = context;
  const { params, returns, body, newline: newline2, isSlot } = node2;
  if (isSlot) {
    push2(`_${helperNameMap[WITH_CTX]}(`);
  }
  push2(`(`, node2);
  if (isArray$3(params)) {
    genNodeList(params, context);
  } else if (params) {
    genNode(params, context);
  }
  push2(`) => `);
  if (newline2 || body) {
    push2(`{`);
    indent();
  }
  if (returns) {
    if (newline2) {
      push2(`return `);
    }
    if (isArray$3(returns)) {
      genNodeListAsArray(returns, context);
    } else {
      genNode(returns, context);
    }
  } else if (body) {
    genNode(body, context);
  }
  if (newline2 || body) {
    deindent();
    push2(`}`);
  }
  if (isSlot) {
    push2(`)`);
  }
}
function genConditionalExpression(node2, context) {
  const { test, consequent, alternate, newline: needNewline } = node2;
  const { push: push2, indent, deindent, newline: newline2 } = context;
  if (test.type === 4) {
    const needsParens = !isSimpleIdentifier(test.content);
    needsParens && push2(`(`);
    genExpression(test, context);
    needsParens && push2(`)`);
  } else {
    push2(`(`);
    genNode(test, context);
    push2(`)`);
  }
  needNewline && indent();
  context.indentLevel++;
  needNewline || push2(` `);
  push2(`? `);
  genNode(consequent, context);
  context.indentLevel--;
  needNewline && newline2();
  needNewline || push2(` `);
  push2(`: `);
  const isNested = alternate.type === 19;
  if (!isNested) {
    context.indentLevel++;
  }
  genNode(alternate, context);
  if (!isNested) {
    context.indentLevel--;
  }
  needNewline && deindent(
    true
    /* without newline */
  );
}
function genCacheExpression(node2, context) {
  const { push: push2, helper, indent, deindent, newline: newline2 } = context;
  push2(`_cache[${node2.index}] || (`);
  if (node2.isVNode) {
    indent();
    push2(`${helper(SET_BLOCK_TRACKING)}(-1),`);
    newline2();
  }
  push2(`_cache[${node2.index}] = `);
  genNode(node2.value, context);
  if (node2.isVNode) {
    push2(`,`);
    newline2();
    push2(`${helper(SET_BLOCK_TRACKING)}(1),`);
    newline2();
    push2(`_cache[${node2.index}]`);
    deindent();
  }
  push2(`)`);
}
function genTemplateLiteral(node2, context) {
  const { push: push2, indent, deindent } = context;
  push2("`");
  const l = node2.elements.length;
  const multilines = l > 3;
  for (let i = 0; i < l; i++) {
    const e = node2.elements[i];
    if (isString$2(e)) {
      push2(e.replace(/(`|\$|\\)/g, "\\$1"));
    } else {
      push2("${");
      if (multilines)
        indent();
      genNode(e, context);
      if (multilines)
        deindent();
      push2("}");
    }
  }
  push2("`");
}
function genIfStatement(node2, context) {
  const { push: push2, indent, deindent } = context;
  const { test, consequent, alternate } = node2;
  push2(`if (`);
  genNode(test, context);
  push2(`) {`);
  indent();
  genNode(consequent, context);
  deindent();
  push2(`}`);
  if (alternate) {
    push2(` else `);
    if (alternate.type === 23) {
      genIfStatement(alternate, context);
    } else {
      push2(`{`);
      indent();
      genNode(alternate, context);
      deindent();
      push2(`}`);
    }
  }
}
function genAssignmentExpression(node2, context) {
  genNode(node2.left, context);
  context.push(` = `);
  genNode(node2.right, context);
}
function genSequenceExpression(node2, context) {
  context.push(`(`);
  genNodeList(node2.expressions, context);
  context.push(`)`);
}
function genReturnStatement({ returns }, context) {
  context.push(`return `);
  if (isArray$3(returns)) {
    genNodeListAsArray(returns, context);
  } else {
    genNode(returns, context);
  }
}
class WalkerBase {
  constructor() {
    this.should_skip = false;
    this.should_remove = false;
    this.replacement = null;
    this.context = {
      skip: () => this.should_skip = true,
      remove: () => this.should_remove = true,
      replace: (node2) => this.replacement = node2
    };
  }
  /**
   *
   * @param {any} parent
   * @param {string} prop
   * @param {number} index
   * @param {BaseNode} node
   */
  replace(parent, prop, index, node2) {
    if (parent) {
      if (index !== null) {
        parent[prop][index] = node2;
      } else {
        parent[prop] = node2;
      }
    }
  }
  /**
   *
   * @param {any} parent
   * @param {string} prop
   * @param {number} index
   */
  remove(parent, prop, index) {
    if (parent) {
      if (index !== null) {
        parent[prop].splice(index, 1);
      } else {
        delete parent[prop];
      }
    }
  }
}
class SyncWalker extends WalkerBase {
  /**
   *
   * @param {SyncHandler} enter
   * @param {SyncHandler} leave
   */
  constructor(enter, leave) {
    super();
    this.enter = enter;
    this.leave = leave;
  }
  /**
   *
   * @param {BaseNode} node
   * @param {BaseNode} parent
   * @param {string} [prop]
   * @param {number} [index]
   * @returns {BaseNode}
   */
  visit(node2, parent, prop, index) {
    if (node2) {
      if (this.enter) {
        const _should_skip = this.should_skip;
        const _should_remove = this.should_remove;
        const _replacement = this.replacement;
        this.should_skip = false;
        this.should_remove = false;
        this.replacement = null;
        this.enter.call(this.context, node2, parent, prop, index);
        if (this.replacement) {
          node2 = this.replacement;
          this.replace(parent, prop, index, node2);
        }
        if (this.should_remove) {
          this.remove(parent, prop, index);
        }
        const skipped = this.should_skip;
        const removed = this.should_remove;
        this.should_skip = _should_skip;
        this.should_remove = _should_remove;
        this.replacement = _replacement;
        if (skipped)
          return node2;
        if (removed)
          return null;
      }
      for (const key in node2) {
        const value = node2[key];
        if (typeof value !== "object") {
          continue;
        } else if (Array.isArray(value)) {
          for (let i = 0; i < value.length; i += 1) {
            if (value[i] !== null && typeof value[i].type === "string") {
              if (!this.visit(value[i], node2, key, i)) {
                i--;
              }
            }
          }
        } else if (value !== null && typeof value.type === "string") {
          this.visit(value, node2, key, null);
        }
      }
      if (this.leave) {
        const _replacement = this.replacement;
        const _should_remove = this.should_remove;
        this.replacement = null;
        this.should_remove = false;
        this.leave.call(this.context, node2, parent, prop, index);
        if (this.replacement) {
          node2 = this.replacement;
          this.replace(parent, prop, index, node2);
        }
        if (this.should_remove) {
          this.remove(parent, prop, index);
        }
        const removed = this.should_remove;
        this.replacement = _replacement;
        this.should_remove = _should_remove;
        if (removed)
          return null;
      }
    }
    return node2;
  }
}
function walk$1(ast, { enter, leave }) {
  const instance = new SyncWalker(enter, leave);
  return instance.visit(ast, null);
}
function walkIdentifiers(root3, onIdentifier, includeAll = false, parentStack = [], knownIds = /* @__PURE__ */ Object.create(null)) {
  const rootExp = root3.type === "Program" && root3.body[0].type === "ExpressionStatement" && root3.body[0].expression;
  walk$1(root3, {
    enter(node2, parent) {
      parent && parentStack.push(parent);
      if (parent && parent.type.startsWith("TS") && !TS_NODE_TYPES.includes(parent.type)) {
        return this.skip();
      }
      if (node2.type === "Identifier") {
        const isLocal = !!knownIds[node2.name];
        const isRefed = isReferencedIdentifier(node2, parent, parentStack);
        if (includeAll || isRefed && !isLocal) {
          onIdentifier(node2, parent, parentStack, isRefed, isLocal);
        }
      } else if (node2.type === "ObjectProperty" && parent.type === "ObjectPattern") {
        node2.inPattern = true;
      } else if (isFunctionType(node2)) {
        walkFunctionParams(node2, (id3) => markScopeIdentifier(node2, id3, knownIds));
      } else if (node2.type === "BlockStatement") {
        walkBlockDeclarations(
          node2,
          (id3) => markScopeIdentifier(node2, id3, knownIds)
        );
      }
    },
    leave(node2, parent) {
      parent && parentStack.pop();
      if (node2 !== rootExp && node2.scopeIds) {
        for (const id3 of node2.scopeIds) {
          knownIds[id3]--;
          if (knownIds[id3] === 0) {
            delete knownIds[id3];
          }
        }
      }
    }
  });
}
function isReferencedIdentifier(id3, parent, parentStack) {
  if (!parent) {
    return true;
  }
  if (id3.name === "arguments") {
    return false;
  }
  if (isReferenced(id3, parent)) {
    return true;
  }
  switch (parent.type) {
    case "AssignmentExpression":
    case "AssignmentPattern":
      return true;
    case "ObjectPattern":
    case "ArrayPattern":
      return isInDestructureAssignment(parent, parentStack);
  }
  return false;
}
function isInDestructureAssignment(parent, parentStack) {
  if (parent && (parent.type === "ObjectProperty" || parent.type === "ArrayPattern")) {
    let i = parentStack.length;
    while (i--) {
      const p2 = parentStack[i];
      if (p2.type === "AssignmentExpression") {
        return true;
      } else if (p2.type !== "ObjectProperty" && !p2.type.endsWith("Pattern")) {
        break;
      }
    }
  }
  return false;
}
function walkFunctionParams(node2, onIdent) {
  for (const p2 of node2.params) {
    for (const id3 of extractIdentifiers(p2)) {
      onIdent(id3);
    }
  }
}
function walkBlockDeclarations(block, onIdent) {
  for (const stmt of block.body) {
    if (stmt.type === "VariableDeclaration") {
      if (stmt.declare)
        continue;
      for (const decl of stmt.declarations) {
        for (const id3 of extractIdentifiers(decl.id)) {
          onIdent(id3);
        }
      }
    } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") {
      if (stmt.declare || !stmt.id)
        continue;
      onIdent(stmt.id);
    }
  }
}
function extractIdentifiers(param, nodes = []) {
  switch (param.type) {
    case "Identifier":
      nodes.push(param);
      break;
    case "MemberExpression":
      let object2 = param;
      while (object2.type === "MemberExpression") {
        object2 = object2.object;
      }
      nodes.push(object2);
      break;
    case "ObjectPattern":
      for (const prop of param.properties) {
        if (prop.type === "RestElement") {
          extractIdentifiers(prop.argument, nodes);
        } else {
          extractIdentifiers(prop.value, nodes);
        }
      }
      break;
    case "ArrayPattern":
      param.elements.forEach((element) => {
        if (element)
          extractIdentifiers(element, nodes);
      });
      break;
    case "RestElement":
      extractIdentifiers(param.argument, nodes);
      break;
    case "AssignmentPattern":
      extractIdentifiers(param.left, nodes);
      break;
  }
  return nodes;
}
function markScopeIdentifier(node2, child, knownIds) {
  const { name } = child;
  if (node2.scopeIds && node2.scopeIds.has(name)) {
    return;
  }
  if (name in knownIds) {
    knownIds[name]++;
  } else {
    knownIds[name] = 1;
  }
  (node2.scopeIds || (node2.scopeIds = /* @__PURE__ */ new Set())).add(name);
}
const isFunctionType = (node2) => {
  return /Function(?:Expression|Declaration)$|Method$/.test(node2.type);
};
const isStaticProperty = (node2) => node2 && (node2.type === "ObjectProperty" || node2.type === "ObjectMethod") && !node2.computed;
const isStaticPropertyKey = (node2, parent) => isStaticProperty(parent) && parent.key === node2;
function isReferenced(node2, parent, grandparent) {
  switch (parent.type) {
    case "MemberExpression":
    case "OptionalMemberExpression":
      if (parent.property === node2) {
        return !!parent.computed;
      }
      return parent.object === node2;
    case "JSXMemberExpression":
      return parent.object === node2;
    case "VariableDeclarator":
      return parent.init === node2;
    case "ArrowFunctionExpression":
      return parent.body === node2;
    case "PrivateName":
      return false;
    case "ClassMethod":
    case "ClassPrivateMethod":
    case "ObjectMethod":
      if (parent.key === node2) {
        return !!parent.computed;
      }
      return false;
    case "ObjectProperty":
      if (parent.key === node2) {
        return !!parent.computed;
      }
      return !grandparent || grandparent.type !== "ObjectPattern";
    case "ClassProperty":
      if (parent.key === node2) {
        return !!parent.computed;
      }
      return true;
    case "ClassPrivateProperty":
      return parent.key !== node2;
    case "ClassDeclaration":
    case "ClassExpression":
      return parent.superClass === node2;
    case "AssignmentExpression":
      return parent.right === node2;
    case "AssignmentPattern":
      return parent.right === node2;
    case "LabeledStatement":
      return false;
    case "CatchClause":
      return false;
    case "RestElement":
      return false;
    case "BreakStatement":
    case "ContinueStatement":
      return false;
    case "FunctionDeclaration":
    case "FunctionExpression":
      return false;
    case "ExportNamespaceSpecifier":
    case "ExportDefaultSpecifier":
      return false;
    case "ExportSpecifier":
      if (grandparent == null ? void 0 : grandparent.source) {
        return false;
      }
      return parent.local === node2;
    case "ImportDefaultSpecifier":
    case "ImportNamespaceSpecifier":
    case "ImportSpecifier":
      return false;
    case "ImportAttribute":
      return false;
    case "JSXAttribute":
      return false;
    case "ObjectPattern":
    case "ArrayPattern":
      return false;
    case "MetaProperty":
      return false;
    case "ObjectTypeProperty":
      return parent.key !== node2;
    case "TSEnumMember":
      return parent.id !== node2;
    case "TSPropertySignature":
      if (parent.key === node2) {
        return !!parent.computed;
      }
      return true;
  }
  return true;
}
const TS_NODE_TYPES = [
  "TSAsExpression",
  // foo as number
  "TSTypeAssertion",
  // (<number>foo)
  "TSNonNullExpression",
  // foo!
  "TSInstantiationExpression",
  // foo<string>
  "TSSatisfiesExpression"
  // foo satisfies T
];
const isLiteralWhitelisted = /* @__PURE__ */ makeMap("true,false,null,this");
const constantBailRE = /\w\s*\(|\.[^\d]/;
const transformExpression = (node2, context) => {
  if (node2.type === 5) {
    node2.content = processExpression(
      node2.content,
      context
    );
  } else if (node2.type === 1) {
    for (let i = 0; i < node2.props.length; i++) {
      const dir = node2.props[i];
      if (dir.type === 7 && dir.name !== "for") {
        const exp = dir.exp;
        const arg = dir.arg;
        if (exp && exp.type === 4 && !(dir.name === "on" && arg)) {
          dir.exp = processExpression(
            exp,
            context,
            // slot args must be processed as function params
            dir.name === "slot"
          );
        }
        if (arg && arg.type === 4 && !arg.isStatic) {
          dir.arg = processExpression(arg, context);
        }
      }
    }
  }
};
function processExpression(node2, context, asParams = false, asRawStatements = false, localVars = Object.create(context.identifiers)) {
  if (!context.prefixIdentifiers || !node2.content.trim()) {
    return node2;
  }
  const { inline, bindingMetadata } = context;
  const rewriteIdentifier = (raw, parent, id3) => {
    const type = hasOwn(bindingMetadata, raw) && bindingMetadata[raw];
    if (inline) {
      const isAssignmentLVal = parent && parent.type === "AssignmentExpression" && parent.left === id3;
      const isUpdateArg = parent && parent.type === "UpdateExpression" && parent.argument === id3;
      const isDestructureAssignment = parent && isInDestructureAssignment(parent, parentStack);
      if (isConst(type) || type === "setup-reactive-const" || localVars[raw]) {
        return raw;
      } else if (type === "setup-ref") {
        return `${raw}.value`;
      } else if (type === "setup-maybe-ref") {
        return isAssignmentLVal || isUpdateArg || isDestructureAssignment ? `${raw}.value` : `${context.helperString(UNREF)}(${raw})`;
      } else if (type === "setup-let") {
        if (isAssignmentLVal) {
          const { right: rVal, operator } = parent;
          const rExp = rawExp.slice(rVal.start - 1, rVal.end - 1);
          const rExpString = stringifyExpression(
            processExpression(
              createSimpleExpression(rExp, false),
              context,
              false,
              false,
              knownIds
            )
          );
          return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore
` : ``} ? ${raw}.value ${operator} ${rExpString} : ${raw}`;
        } else if (isUpdateArg) {
          id3.start = parent.start;
          id3.end = parent.end;
          const { prefix: isPrefix, operator } = parent;
          const prefix2 = isPrefix ? operator : ``;
          const postfix2 = isPrefix ? `` : operator;
          return `${context.helperString(IS_REF)}(${raw})${context.isTS ? ` //@ts-ignore
` : ``} ? ${prefix2}${raw}.value${postfix2} : ${prefix2}${raw}${postfix2}`;
        } else if (isDestructureAssignment) {
          return raw;
        } else {
          return `${context.helperString(UNREF)}(${raw})`;
        }
      } else if (type === "props") {
        return genPropsAccessExp(raw);
      } else if (type === "props-aliased") {
        return genPropsAccessExp(bindingMetadata.__propsAliases[raw]);
      }
    } else {
      if (type && type.startsWith("setup") || type === "literal-const") {
        return `$setup.${raw}`;
      } else if (type === "props-aliased") {
        return `$props['${bindingMetadata.__propsAliases[raw]}']`;
      } else if (type) {
        return `$${type}.${raw}`;
      }
    }
    return `_ctx.${raw}`;
  };
  const rawExp = node2.content;
  const bailConstant = constantBailRE.test(rawExp);
  if (isSimpleIdentifier(rawExp)) {
    const isScopeVarReference = context.identifiers[rawExp];
    const isAllowedGlobal = isGloballyWhitelisted(rawExp);
    const isLiteral = isLiteralWhitelisted(rawExp);
    if (!asParams && !isScopeVarReference && !isAllowedGlobal && !isLiteral) {
      if (isConst(bindingMetadata[node2.content])) {
        node2.constType = 1;
      }
      node2.content = rewriteIdentifier(rawExp);
    } else if (!isScopeVarReference) {
      if (isLiteral) {
        node2.constType = 3;
      } else {
        node2.constType = 2;
      }
    }
    return node2;
  }
  let ast;
  const source = asRawStatements ? ` ${rawExp} ` : `(${rawExp})${asParams ? `=>{}` : ``}`;
  try {
    ast = parse_1$1(source, {
      plugins: context.expressionPlugins
    }).program;
  } catch (e) {
    context.onError(
      createCompilerError(
        45,
        node2.loc,
        void 0,
        e.message
      )
    );
    return node2;
  }
  const ids = [];
  const parentStack = [];
  const knownIds = Object.create(context.identifiers);
  walkIdentifiers(
    ast,
    (node22, parent, _, isReferenced2, isLocal) => {
      if (isStaticPropertyKey(node22, parent)) {
        return;
      }
      const needPrefix = isReferenced2 && canPrefix(node22);
      if (needPrefix && !isLocal) {
        if (isStaticProperty(parent) && parent.shorthand) {
          node22.prefix = `${node22.name}: `;
        }
        node22.name = rewriteIdentifier(node22.name, parent, node22);
        ids.push(node22);
      } else {
        if (!(needPrefix && isLocal) && !bailConstant) {
          node22.isConstant = true;
        }
        ids.push(node22);
      }
    },
    true,
    // invoke on ALL identifiers
    parentStack,
    knownIds
  );
  const children = [];
  ids.sort((a, b) => a.start - b.start);
  ids.forEach((id3, i) => {
    const start = id3.start - 1;
    const end = id3.end - 1;
    const last2 = ids[i - 1];
    const leadingText = rawExp.slice(last2 ? last2.end - 1 : 0, start);
    if (leadingText.length || id3.prefix) {
      children.push(leadingText + (id3.prefix || ``));
    }
    const source2 = rawExp.slice(start, end);
    children.push(
      createSimpleExpression(
        id3.name,
        false,
        {
          source: source2,
          start: advancePositionWithClone(node2.loc.start, source2, start),
          end: advancePositionWithClone(node2.loc.start, source2, end)
        },
        id3.isConstant ? 3 : 0
      )
    );
    if (i === ids.length - 1 && end < rawExp.length) {
      children.push(rawExp.slice(end));
    }
  });
  let ret;
  if (children.length) {
    ret = createCompoundExpression(children, node2.loc);
  } else {
    ret = node2;
    ret.constType = bailConstant ? 0 : 3;
  }
  ret.identifiers = Object.keys(knownIds);
  return ret;
}
function canPrefix(id3) {
  if (isGloballyWhitelisted(id3.name)) {
    return false;
  }
  if (id3.name === "require") {
    return false;
  }
  return true;
}
function stringifyExpression(exp) {
  if (isString$2(exp)) {
    return exp;
  } else if (exp.type === 4) {
    return exp.content;
  } else {
    return exp.children.map(stringifyExpression).join("");
  }
}
function isConst(type) {
  return type === "setup-const" || type === "literal-const";
}
const transformIf = createStructuralDirectiveTransform(
  /^(if|else|else-if)$/,
  (node2, dir, context) => {
    return processIf(node2, dir, context, (ifNode, branch, isRoot2) => {
      const siblings = context.parent.children;
      let i = siblings.indexOf(ifNode);
      let key = 0;
      while (i-- >= 0) {
        const sibling = siblings[i];
        if (sibling && sibling.type === 9) {
          key += sibling.branches.length;
        }
      }
      return () => {
        if (isRoot2) {
          ifNode.codegenNode = createCodegenNodeForBranch(
            branch,
            key,
            context
          );
        } else {
          const parentCondition = getParentCondition(ifNode.codegenNode);
          parentCondition.alternate = createCodegenNodeForBranch(
            branch,
            key + ifNode.branches.length - 1,
            context
          );
        }
      };
    });
  }
);
function processIf(node2, dir, context, processCodegen) {
  if (dir.name !== "else" && (!dir.exp || !dir.exp.content.trim())) {
    const loc = dir.exp ? dir.exp.loc : node2.loc;
    context.onError(
      createCompilerError(28, dir.loc)
    );
    dir.exp = createSimpleExpression(`true`, false, loc);
  }
  if (context.prefixIdentifiers && dir.exp) {
    dir.exp = processExpression(dir.exp, context);
  }
  if (dir.name === "if") {
    const branch = createIfBranch(node2, dir);
    const ifNode = {
      type: 9,
      loc: node2.loc,
      branches: [branch]
    };
    context.replaceNode(ifNode);
    if (processCodegen) {
      return processCodegen(ifNode, branch, true);
    }
  } else {
    const siblings = context.parent.children;
    const comments = [];
    let i = siblings.indexOf(node2);
    while (i-- >= -1) {
      const sibling = siblings[i];
      if (sibling && sibling.type === 3) {
        context.removeNode(sibling);
        comments.unshift(sibling);
        continue;
      }
      if (sibling && sibling.type === 2 && !sibling.content.trim().length) {
        context.removeNode(sibling);
        continue;
      }
      if (sibling && sibling.type === 9) {
        if (dir.name === "else-if" && sibling.branches[sibling.branches.length - 1].condition === void 0) {
          context.onError(
            createCompilerError(30, node2.loc)
          );
        }
        context.removeNode();
        const branch = createIfBranch(node2, dir);
        if (comments.length && // #3619 ignore comments if the v-if is direct child of <transition>
        !(context.parent && context.parent.type === 1 && isBuiltInType(context.parent.tag, "transition"))) {
          branch.children = [...comments, ...branch.children];
        }
        {
          const key = branch.userKey;
          if (key) {
            sibling.branches.forEach(({ userKey }) => {
              if (isSameKey(userKey, key)) {
                context.onError(
                  createCompilerError(
                    29,
                    branch.userKey.loc
                  )
                );
              }
            });
          }
        }
        sibling.branches.push(branch);
        const onExit = processCodegen && processCodegen(sibling, branch, false);
        traverseNode(branch, context);
        if (onExit)
          onExit();
        context.currentNode = null;
      } else {
        context.onError(
          createCompilerError(30, node2.loc)
        );
      }
      break;
    }
  }
}
function createIfBranch(node2, dir) {
  const isTemplateIf = node2.tagType === 3;
  return {
    type: 10,
    loc: node2.loc,
    condition: dir.name === "else" ? void 0 : dir.exp,
    children: isTemplateIf && !findDir(node2, "for") ? node2.children : [node2],
    userKey: findProp(node2, `key`),
    isTemplateIf
  };
}
function createCodegenNodeForBranch(branch, keyIndex, context) {
  if (branch.condition) {
    return createConditionalExpression(
      branch.condition,
      createChildrenCodegenNode(branch, keyIndex, context),
      // make sure to pass in asBlock: true so that the comment node call
      // closes the current block.
      createCallExpression(context.helper(CREATE_COMMENT), [
        '"v-if"',
        "true"
      ])
    );
  } else {
    return createChildrenCodegenNode(branch, keyIndex, context);
  }
}
function createChildrenCodegenNode(branch, keyIndex, context) {
  const { helper } = context;
  const keyProperty = createObjectProperty(
    `key`,
    createSimpleExpression(
      `${keyIndex}`,
      false,
      locStub,
      2
    )
  );
  const { children } = branch;
  const firstChild = children[0];
  const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1;
  if (needFragmentWrapper) {
    if (children.length === 1 && firstChild.type === 11) {
      const vnodeCall = firstChild.codegenNode;
      injectProp(vnodeCall, keyProperty, context);
      return vnodeCall;
    } else {
      let patchFlag = 64;
      let patchFlagText = PatchFlagNames[64];
      if (!branch.isTemplateIf && children.filter((c) => c.type !== 3).length === 1) {
        patchFlag |= 2048;
        patchFlagText += `, ${PatchFlagNames[2048]}`;
      }
      return createVNodeCall(
        context,
        helper(FRAGMENT),
        createObjectExpression([keyProperty]),
        children,
        patchFlag + ` /* ${patchFlagText} */`,
        void 0,
        void 0,
        true,
        false,
        false,
        branch.loc
      );
    }
  } else {
    const ret = firstChild.codegenNode;
    const vnodeCall = getMemoedVNodeCall(ret);
    if (vnodeCall.type === 13) {
      convertToBlock(vnodeCall, context);
    }
    injectProp(vnodeCall, keyProperty, context);
    return ret;
  }
}
function isSameKey(a, b) {
  if (!a || a.type !== b.type) {
    return false;
  }
  if (a.type === 6) {
    if (a.value.content !== b.value.content) {
      return false;
    }
  } else {
    const exp = a.exp;
    const branchExp = b.exp;
    if (exp.type !== branchExp.type) {
      return false;
    }
    if (exp.type !== 4 || exp.isStatic !== branchExp.isStatic || exp.content !== branchExp.content) {
      return false;
    }
  }
  return true;
}
function getParentCondition(node2) {
  while (true) {
    if (node2.type === 19) {
      if (node2.alternate.type === 19) {
        node2 = node2.alternate;
      } else {
        return node2;
      }
    } else if (node2.type === 20) {
      node2 = node2.value;
    }
  }
}
const transformFor = createStructuralDirectiveTransform(
  "for",
  (node2, dir, context) => {
    const { helper, removeHelper } = context;
    return processFor(node2, dir, context, (forNode) => {
      const renderExp = createCallExpression(helper(RENDER_LIST), [
        forNode.source
      ]);
      const isTemplate = isTemplateNode(node2);
      const memo = findDir(node2, "memo");
      const keyProp = findProp(node2, `key`);
      const keyExp = keyProp && (keyProp.type === 6 ? createSimpleExpression(keyProp.value.content, true) : keyProp.exp);
      const keyProperty = keyProp ? createObjectProperty(`key`, keyExp) : null;
      if (isTemplate) {
        if (memo) {
          memo.exp = processExpression(
            memo.exp,
            context
          );
        }
        if (keyProperty && keyProp.type !== 6) {
          keyProperty.value = processExpression(
            keyProperty.value,
            context
          );
        }
      }
      const isStableFragment = forNode.source.type === 4 && forNode.source.constType > 0;
      const fragmentFlag = isStableFragment ? 64 : keyProp ? 128 : 256;
      forNode.codegenNode = createVNodeCall(
        context,
        helper(FRAGMENT),
        void 0,
        renderExp,
        fragmentFlag + ` /* ${PatchFlagNames[fragmentFlag]} */`,
        void 0,
        void 0,
        true,
        !isStableFragment,
        false,
        node2.loc
      );
      return () => {
        let childBlock;
        const { children } = forNode;
        if (isTemplate) {
          node2.children.some((c) => {
            if (c.type === 1) {
              const key = findProp(c, "key");
              if (key) {
                context.onError(
                  createCompilerError(
                    33,
                    key.loc
                  )
                );
                return true;
              }
            }
          });
        }
        const needFragmentWrapper = children.length !== 1 || children[0].type !== 1;
        const slotOutlet = isSlotOutlet(node2) ? node2 : isTemplate && node2.children.length === 1 && isSlotOutlet(node2.children[0]) ? node2.children[0] : null;
        if (slotOutlet) {
          childBlock = slotOutlet.codegenNode;
          if (isTemplate && keyProperty) {
            injectProp(childBlock, keyProperty, context);
          }
        } else if (needFragmentWrapper) {
          childBlock = createVNodeCall(
            context,
            helper(FRAGMENT),
            keyProperty ? createObjectExpression([keyProperty]) : void 0,
            node2.children,
            `64 /* ${PatchFlagNames[64]} */`,
            void 0,
            void 0,
            true,
            void 0,
            false
            /* isComponent */
          );
        } else {
          childBlock = children[0].codegenNode;
          if (isTemplate && keyProperty) {
            injectProp(childBlock, keyProperty, context);
          }
          if (childBlock.isBlock !== !isStableFragment) {
            if (childBlock.isBlock) {
              removeHelper(OPEN_BLOCK);
              removeHelper(
                getVNodeBlockHelper(context.inSSR, childBlock.isComponent)
              );
            } else {
              removeHelper(
                getVNodeHelper(context.inSSR, childBlock.isComponent)
              );
            }
          }
          childBlock.isBlock = !isStableFragment;
          if (childBlock.isBlock) {
            helper(OPEN_BLOCK);
            helper(getVNodeBlockHelper(context.inSSR, childBlock.isComponent));
          } else {
            helper(getVNodeHelper(context.inSSR, childBlock.isComponent));
          }
        }
        if (memo) {
          const loop = createFunctionExpression(
            createForLoopParams(forNode.parseResult, [
              createSimpleExpression(`_cached`)
            ])
          );
          loop.body = createBlockStatement([
            createCompoundExpression([`const _memo = (`, memo.exp, `)`]),
            createCompoundExpression([
              `if (_cached`,
              ...keyExp ? [` && _cached.key === `, keyExp] : [],
              ` && ${context.helperString(
                IS_MEMO_SAME
              )}(_cached, _memo)) return _cached`
            ]),
            createCompoundExpression([`const _item = `, childBlock]),
            createSimpleExpression(`_item.memo = _memo`),
            createSimpleExpression(`return _item`)
          ]);
          renderExp.arguments.push(
            loop,
            createSimpleExpression(`_cache`),
            createSimpleExpression(String(context.cached++))
          );
        } else {
          renderExp.arguments.push(
            createFunctionExpression(
              createForLoopParams(forNode.parseResult),
              childBlock,
              true
              /* force newline */
            )
          );
        }
      };
    });
  }
);
function processFor(node2, dir, context, processCodegen) {
  if (!dir.exp) {
    context.onError(
      createCompilerError(31, dir.loc)
    );
    return;
  }
  const parseResult = parseForExpression(
    // can only be simple expression because vFor transform is applied
    // before expression transform.
    dir.exp,
    context
  );
  if (!parseResult) {
    context.onError(
      createCompilerError(32, dir.loc)
    );
    return;
  }
  const { addIdentifiers, removeIdentifiers, scopes } = context;
  const { source, value, key, index } = parseResult;
  const forNode = {
    type: 11,
    loc: dir.loc,
    source,
    valueAlias: value,
    keyAlias: key,
    objectIndexAlias: index,
    parseResult,
    children: isTemplateNode(node2) ? node2.children : [node2]
  };
  context.replaceNode(forNode);
  scopes.vFor++;
  if (context.prefixIdentifiers) {
    value && addIdentifiers(value);
    key && addIdentifiers(key);
    index && addIdentifiers(index);
  }
  const onExit = processCodegen && processCodegen(forNode);
  return () => {
    scopes.vFor--;
    if (context.prefixIdentifiers) {
      value && removeIdentifiers(value);
      key && removeIdentifiers(key);
      index && removeIdentifiers(index);
    }
    if (onExit)
      onExit();
  };
}
const forAliasRE$1 = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
const stripParensRE = /^\(|\)$/g;
function parseForExpression(input2, context) {
  const loc = input2.loc;
  const exp = input2.content;
  const inMatch = exp.match(forAliasRE$1);
  if (!inMatch)
    return;
  const [, LHS, RHS] = inMatch;
  const result2 = {
    source: createAliasExpression(
      loc,
      RHS.trim(),
      exp.indexOf(RHS, LHS.length)
    ),
    value: void 0,
    key: void 0,
    index: void 0
  };
  if (context.prefixIdentifiers) {
    result2.source = processExpression(
      result2.source,
      context
    );
  }
  let valueContent = LHS.trim().replace(stripParensRE, "").trim();
  const trimmedOffset = LHS.indexOf(valueContent);
  const iteratorMatch = valueContent.match(forIteratorRE);
  if (iteratorMatch) {
    valueContent = valueContent.replace(forIteratorRE, "").trim();
    const keyContent = iteratorMatch[1].trim();
    let keyOffset;
    if (keyContent) {
      keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
      result2.key = createAliasExpression(loc, keyContent, keyOffset);
      if (context.prefixIdentifiers) {
        result2.key = processExpression(result2.key, context, true);
      }
    }
    if (iteratorMatch[2]) {
      const indexContent = iteratorMatch[2].trim();
      if (indexContent) {
        result2.index = createAliasExpression(
          loc,
          indexContent,
          exp.indexOf(
            indexContent,
            result2.key ? keyOffset + keyContent.length : trimmedOffset + valueContent.length
          )
        );
        if (context.prefixIdentifiers) {
          result2.index = processExpression(result2.index, context, true);
        }
      }
    }
  }
  if (valueContent) {
    result2.value = createAliasExpression(loc, valueContent, trimmedOffset);
    if (context.prefixIdentifiers) {
      result2.value = processExpression(result2.value, context, true);
    }
  }
  return result2;
}
function createAliasExpression(range2, content, offset) {
  return createSimpleExpression(
    content,
    false,
    getInnerRange(range2, offset, content.length)
  );
}
function createForLoopParams({ value, key, index }, memoArgs = []) {
  return createParamsList([value, key, index, ...memoArgs]);
}
function createParamsList(args) {
  let i = args.length;
  while (i--) {
    if (args[i])
      break;
  }
  return args.slice(0, i + 1).map((arg, i2) => arg || createSimpleExpression(`_`.repeat(i2 + 1), false));
}
const defaultFallback = createSimpleExpression(`undefined`, false);
const trackSlotScopes = (node2, context) => {
  if (node2.type === 1 && (node2.tagType === 1 || node2.tagType === 3)) {
    const vSlot = findDir(node2, "slot");
    if (vSlot) {
      const slotProps = vSlot.exp;
      if (context.prefixIdentifiers) {
        slotProps && context.addIdentifiers(slotProps);
      }
      context.scopes.vSlot++;
      return () => {
        if (context.prefixIdentifiers) {
          slotProps && context.removeIdentifiers(slotProps);
        }
        context.scopes.vSlot--;
      };
    }
  }
};
const trackVForSlotScopes = (node2, context) => {
  let vFor;
  if (isTemplateNode(node2) && node2.props.some(isVSlot) && (vFor = findDir(node2, "for"))) {
    const result2 = vFor.parseResult = parseForExpression(
      vFor.exp,
      context
    );
    if (result2) {
      const { value, key, index } = result2;
      const { addIdentifiers, removeIdentifiers } = context;
      value && addIdentifiers(value);
      key && addIdentifiers(key);
      index && addIdentifiers(index);
      return () => {
        value && removeIdentifiers(value);
        key && removeIdentifiers(key);
        index && removeIdentifiers(index);
      };
    }
  }
};
const buildClientSlotFn = (props, children, loc) => createFunctionExpression(
  props,
  children,
  false,
  true,
  children.length ? children[0].loc : loc
);
function buildSlots(node2, context, buildSlotFn = buildClientSlotFn) {
  context.helper(WITH_CTX);
  const { children, loc } = node2;
  const slotsProperties = [];
  const dynamicSlots = [];
  let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
  if (!context.ssr && context.prefixIdentifiers) {
    hasDynamicSlots = hasScopeRef(node2, context.identifiers);
  }
  const onComponentSlot = findDir(node2, "slot", true);
  if (onComponentSlot) {
    const { arg, exp } = onComponentSlot;
    if (arg && !isStaticExp(arg)) {
      hasDynamicSlots = true;
    }
    slotsProperties.push(
      createObjectProperty(
        arg || createSimpleExpression("default", true),
        buildSlotFn(exp, children, loc)
      )
    );
  }
  let hasTemplateSlots = false;
  let hasNamedDefaultSlot = false;
  const implicitDefaultChildren = [];
  const seenSlotNames = /* @__PURE__ */ new Set();
  let conditionalBranchIndex = 0;
  for (let i = 0; i < children.length; i++) {
    const slotElement = children[i];
    let slotDir;
    if (!isTemplateNode(slotElement) || !(slotDir = findDir(slotElement, "slot", true))) {
      if (slotElement.type !== 3) {
        implicitDefaultChildren.push(slotElement);
      }
      continue;
    }
    if (onComponentSlot) {
      context.onError(
        createCompilerError(37, slotDir.loc)
      );
      break;
    }
    hasTemplateSlots = true;
    const { children: slotChildren, loc: slotLoc } = slotElement;
    const {
      arg: slotName = createSimpleExpression(`default`, true),
      exp: slotProps,
      loc: dirLoc
    } = slotDir;
    let staticSlotName;
    if (isStaticExp(slotName)) {
      staticSlotName = slotName ? slotName.content : `default`;
    } else {
      hasDynamicSlots = true;
    }
    const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
    let vIf;
    let vElse;
    let vFor;
    if (vIf = findDir(slotElement, "if")) {
      hasDynamicSlots = true;
      dynamicSlots.push(
        createConditionalExpression(
          vIf.exp,
          buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++),
          defaultFallback
        )
      );
    } else if (vElse = findDir(
      slotElement,
      /^else(-if)?$/,
      true
      /* allowEmpty */
    )) {
      let j = i;
      let prev;
      while (j--) {
        prev = children[j];
        if (prev.type !== 3) {
          break;
        }
      }
      if (prev && isTemplateNode(prev) && findDir(prev, "if")) {
        children.splice(i, 1);
        i--;
        let conditional = dynamicSlots[dynamicSlots.length - 1];
        while (conditional.alternate.type === 19) {
          conditional = conditional.alternate;
        }
        conditional.alternate = vElse.exp ? createConditionalExpression(
          vElse.exp,
          buildDynamicSlot(
            slotName,
            slotFunction,
            conditionalBranchIndex++
          ),
          defaultFallback
        ) : buildDynamicSlot(slotName, slotFunction, conditionalBranchIndex++);
      } else {
        context.onError(
          createCompilerError(30, vElse.loc)
        );
      }
    } else if (vFor = findDir(slotElement, "for")) {
      hasDynamicSlots = true;
      const parseResult = vFor.parseResult || parseForExpression(vFor.exp, context);
      if (parseResult) {
        dynamicSlots.push(
          createCallExpression(context.helper(RENDER_LIST), [
            parseResult.source,
            createFunctionExpression(
              createForLoopParams(parseResult),
              buildDynamicSlot(slotName, slotFunction),
              true
              /* force newline */
            )
          ])
        );
      } else {
        context.onError(
          createCompilerError(32, vFor.loc)
        );
      }
    } else {
      if (staticSlotName) {
        if (seenSlotNames.has(staticSlotName)) {
          context.onError(
            createCompilerError(
              38,
              dirLoc
            )
          );
          continue;
        }
        seenSlotNames.add(staticSlotName);
        if (staticSlotName === "default") {
          hasNamedDefaultSlot = true;
        }
      }
      slotsProperties.push(createObjectProperty(slotName, slotFunction));
    }
  }
  if (!onComponentSlot) {
    const buildDefaultSlotProperty = (props, children2) => {
      const fn = buildSlotFn(props, children2, loc);
      return createObjectProperty(`default`, fn);
    };
    if (!hasTemplateSlots) {
      slotsProperties.push(buildDefaultSlotProperty(void 0, children));
    } else if (implicitDefaultChildren.length && // #3766
    // with whitespace: 'preserve', whitespaces between slots will end up in
    // implicitDefaultChildren. Ignore if all implicit children are whitespaces.
    implicitDefaultChildren.some((node22) => isNonWhitespaceContent(node22))) {
      if (hasNamedDefaultSlot) {
        context.onError(
          createCompilerError(
            39,
            implicitDefaultChildren[0].loc
          )
        );
      } else {
        slotsProperties.push(
          buildDefaultSlotProperty(void 0, implicitDefaultChildren)
        );
      }
    }
  }
  const slotFlag = hasDynamicSlots ? 2 : hasForwardedSlots(node2.children) ? 3 : 1;
  let slots = createObjectExpression(
    slotsProperties.concat(
      createObjectProperty(
        `_`,
        // 2 = compiled but dynamic = can skip normalization, but must run diff
        // 1 = compiled and static = can skip normalization AND diff as optimized
        createSimpleExpression(
          slotFlag + ` /* ${slotFlagsText[slotFlag]} */`,
          false
        )
      )
    ),
    loc
  );
  if (dynamicSlots.length) {
    slots = createCallExpression(context.helper(CREATE_SLOTS), [
      slots,
      createArrayExpression(dynamicSlots)
    ]);
  }
  return {
    slots,
    hasDynamicSlots
  };
}
function buildDynamicSlot(name, fn, index) {
  const props = [
    createObjectProperty(`name`, name),
    createObjectProperty(`fn`, fn)
  ];
  if (index != null) {
    props.push(
      createObjectProperty(`key`, createSimpleExpression(String(index), true))
    );
  }
  return createObjectExpression(props);
}
function hasForwardedSlots(children) {
  for (let i = 0; i < children.length; i++) {
    const child = children[i];
    switch (child.type) {
      case 1:
        if (child.tagType === 2 || hasForwardedSlots(child.children)) {
          return true;
        }
        break;
      case 9:
        if (hasForwardedSlots(child.branches))
          return true;
        break;
      case 10:
      case 11:
        if (hasForwardedSlots(child.children))
          return true;
        break;
    }
  }
  return false;
}
function isNonWhitespaceContent(node2) {
  if (node2.type !== 2 && node2.type !== 12)
    return true;
  return node2.type === 2 ? !!node2.content.trim() : isNonWhitespaceContent(node2.content);
}
const directiveImportMap = /* @__PURE__ */ new WeakMap();
const transformElement = (node2, context) => {
  return function postTransformElement() {
    node2 = context.currentNode;
    if (!(node2.type === 1 && (node2.tagType === 0 || node2.tagType === 1))) {
      return;
    }
    const { tag: tag3, props } = node2;
    const isComponent2 = node2.tagType === 1;
    let vnodeTag = isComponent2 ? resolveComponentType(node2, context) : `"${tag3}"`;
    const isDynamicComponent = isObject$2(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
    let vnodeProps;
    let vnodeChildren;
    let vnodePatchFlag;
    let patchFlag = 0;
    let vnodeDynamicProps;
    let dynamicPropNames;
    let vnodeDirectives;
    let shouldUseBlock = (
      // dynamic component may resolve to plain elements
      isDynamicComponent || vnodeTag === TELEPORT || vnodeTag === SUSPENSE || !isComponent2 && // <svg> and <foreignObject> must be forced into blocks so that block
      // updates inside get proper isSVG flag at runtime. (#639, #643)
      // This is technically web-specific, but splitting the logic out of core
      // leads to too much unnecessary complexity.
      (tag3 === "svg" || tag3 === "foreignObject")
    );
    if (props.length > 0) {
      const propsBuildResult = buildProps(
        node2,
        context,
        void 0,
        isComponent2,
        isDynamicComponent
      );
      vnodeProps = propsBuildResult.props;
      patchFlag = propsBuildResult.patchFlag;
      dynamicPropNames = propsBuildResult.dynamicPropNames;
      const directives = propsBuildResult.directives;
      vnodeDirectives = directives && directives.length ? createArrayExpression(
        directives.map((dir) => buildDirectiveArgs(dir, context))
      ) : void 0;
      if (propsBuildResult.shouldUseBlock) {
        shouldUseBlock = true;
      }
    }
    if (node2.children.length > 0) {
      if (vnodeTag === KEEP_ALIVE) {
        shouldUseBlock = true;
        patchFlag |= 1024;
        if (node2.children.length > 1) {
          context.onError(
            createCompilerError(46, {
              start: node2.children[0].loc.start,
              end: node2.children[node2.children.length - 1].loc.end,
              source: ""
            })
          );
        }
      }
      const shouldBuildAsSlots = isComponent2 && // Teleport is not a real component and has dedicated runtime handling
      vnodeTag !== TELEPORT && // explained above.
      vnodeTag !== KEEP_ALIVE;
      if (shouldBuildAsSlots) {
        const { slots, hasDynamicSlots } = buildSlots(node2, context);
        vnodeChildren = slots;
        if (hasDynamicSlots) {
          patchFlag |= 1024;
        }
      } else if (node2.children.length === 1 && vnodeTag !== TELEPORT) {
        const child = node2.children[0];
        const type = child.type;
        const hasDynamicTextChild = type === 5 || type === 8;
        if (hasDynamicTextChild && getConstantType(child, context) === 0) {
          patchFlag |= 1;
        }
        if (hasDynamicTextChild || type === 2) {
          vnodeChildren = child;
        } else {
          vnodeChildren = node2.children;
        }
      } else {
        vnodeChildren = node2.children;
      }
    }
    if (patchFlag !== 0) {
      {
        if (patchFlag < 0) {
          vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
        } else {
          const flagNames = Object.keys(PatchFlagNames).map(Number).filter((n2) => n2 > 0 && patchFlag & n2).map((n2) => PatchFlagNames[n2]).join(`, `);
          vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
        }
      }
      if (dynamicPropNames && dynamicPropNames.length) {
        vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
      }
    }
    node2.codegenNode = createVNodeCall(
      context,
      vnodeTag,
      vnodeProps,
      vnodeChildren,
      vnodePatchFlag,
      vnodeDynamicProps,
      vnodeDirectives,
      !!shouldUseBlock,
      false,
      isComponent2,
      node2.loc
    );
  };
};
function resolveComponentType(node2, context, ssr = false) {
  let { tag: tag3 } = node2;
  const isExplicitDynamic = isComponentTag(tag3);
  const isProp = findProp(node2, "is");
  if (isProp) {
    if (isExplicitDynamic || false) {
      const exp = isProp.type === 6 ? isProp.value && createSimpleExpression(isProp.value.content, true) : isProp.exp;
      if (exp) {
        return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
          exp
        ]);
      }
    } else if (isProp.type === 6 && isProp.value.content.startsWith("vue:")) {
      tag3 = isProp.value.content.slice(4);
    }
  }
  const isDir = !isExplicitDynamic && findDir(node2, "is");
  if (isDir && isDir.exp) {
    {
      context.onWarn(
        createCompilerError(52, isDir.loc)
      );
    }
    return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
      isDir.exp
    ]);
  }
  const builtIn = isCoreComponent(tag3) || context.isBuiltInComponent(tag3);
  if (builtIn) {
    if (!ssr)
      context.helper(builtIn);
    return builtIn;
  }
  {
    const fromSetup = resolveSetupReference(tag3, context);
    if (fromSetup) {
      return fromSetup;
    }
    const dotIndex = tag3.indexOf(".");
    if (dotIndex > 0) {
      const ns = resolveSetupReference(tag3.slice(0, dotIndex), context);
      if (ns) {
        return ns + tag3.slice(dotIndex);
      }
    }
  }
  if (context.selfName && capitalize$1(camelize(tag3)) === context.selfName) {
    context.helper(RESOLVE_COMPONENT);
    context.components.add(tag3 + `__self`);
    return toValidAssetId(tag3, `component`);
  }
  context.helper(RESOLVE_COMPONENT);
  context.components.add(tag3);
  return toValidAssetId(tag3, `component`);
}
function resolveSetupReference(name, context) {
  const bindings = context.bindingMetadata;
  if (!bindings || bindings.__isScriptSetup === false) {
    return;
  }
  const camelName = camelize(name);
  const PascalName = capitalize$1(camelName);
  const checkType = (type) => {
    if (bindings[name] === type) {
      return name;
    }
    if (bindings[camelName] === type) {
      return camelName;
    }
    if (bindings[PascalName] === type) {
      return PascalName;
    }
  };
  const fromConst = checkType("setup-const") || checkType("setup-reactive-const") || checkType("literal-const");
  if (fromConst) {
    return context.inline ? (
      // in inline mode, const setup bindings (e.g. imports) can be used as-is
      fromConst
    ) : `$setup[${JSON.stringify(fromConst)}]`;
  }
  const fromMaybeRef = checkType("setup-let") || checkType("setup-ref") || checkType("setup-maybe-ref");
  if (fromMaybeRef) {
    return context.inline ? (
      // setup scope bindings that may be refs need to be unrefed
      `${context.helperString(UNREF)}(${fromMaybeRef})`
    ) : `$setup[${JSON.stringify(fromMaybeRef)}]`;
  }
}
function buildProps(node2, context, props = node2.props, isComponent2, isDynamicComponent, ssr = false) {
  const { tag: tag3, loc: elementLoc, children } = node2;
  let properties = [];
  const mergeArgs = [];
  const runtimeDirectives = [];
  const hasChildren = children.length > 0;
  let shouldUseBlock = false;
  let patchFlag = 0;
  let hasRef = false;
  let hasClassBinding = false;
  let hasStyleBinding = false;
  let hasHydrationEventBinding = false;
  let hasDynamicKeys = false;
  let hasVnodeHook = false;
  const dynamicPropNames = [];
  const pushMergeArg = (arg) => {
    if (properties.length) {
      mergeArgs.push(
        createObjectExpression(dedupeProperties(properties), elementLoc)
      );
      properties = [];
    }
    if (arg)
      mergeArgs.push(arg);
  };
  const analyzePatchFlag = ({ key, value }) => {
    if (isStaticExp(key)) {
      const name = key.content;
      const isEventHandler = isOn(name);
      if (isEventHandler && (!isComponent2 || isDynamicComponent) && // omit the flag for click handlers because hydration gives click
      // dedicated fast path.
      name.toLowerCase() !== "onclick" && // omit v-model handlers
      name !== "onUpdate:modelValue" && // omit onVnodeXXX hooks
      !isReservedProp(name)) {
        hasHydrationEventBinding = true;
      }
      if (isEventHandler && isReservedProp(name)) {
        hasVnodeHook = true;
      }
      if (value.type === 20 || (value.type === 4 || value.type === 8) && getConstantType(value, context) > 0) {
        return;
      }
      if (name === "ref") {
        hasRef = true;
      } else if (name === "class") {
        hasClassBinding = true;
      } else if (name === "style") {
        hasStyleBinding = true;
      } else if (name !== "key" && !dynamicPropNames.includes(name)) {
        dynamicPropNames.push(name);
      }
      if (isComponent2 && (name === "class" || name === "style") && !dynamicPropNames.includes(name)) {
        dynamicPropNames.push(name);
      }
    } else {
      hasDynamicKeys = true;
    }
  };
  for (let i = 0; i < props.length; i++) {
    const prop = props[i];
    if (prop.type === 6) {
      const { loc, name, value } = prop;
      let isStatic = true;
      if (name === "ref") {
        hasRef = true;
        if (context.scopes.vFor > 0) {
          properties.push(
            createObjectProperty(
              createSimpleExpression("ref_for", true),
              createSimpleExpression("true")
            )
          );
        }
        if (value && context.inline) {
          const binding2 = context.bindingMetadata[value.content];
          if (binding2 === "setup-let" || binding2 === "setup-ref" || binding2 === "setup-maybe-ref") {
            isStatic = false;
            properties.push(
              createObjectProperty(
                createSimpleExpression("ref_key", true),
                createSimpleExpression(value.content, true, value.loc)
              )
            );
          }
        }
      }
      if (name === "is" && (isComponentTag(tag3) || value && value.content.startsWith("vue:") || false)) {
        continue;
      }
      properties.push(
        createObjectProperty(
          createSimpleExpression(
            name,
            true,
            getInnerRange(loc, 0, name.length)
          ),
          createSimpleExpression(
            value ? value.content : "",
            isStatic,
            value ? value.loc : loc
          )
        )
      );
    } else {
      const { name, arg, exp, loc } = prop;
      const isVBind = name === "bind";
      const isVOn = name === "on";
      if (name === "slot") {
        if (!isComponent2) {
          context.onError(
            createCompilerError(40, loc)
          );
        }
        continue;
      }
      if (name === "once" || name === "memo") {
        continue;
      }
      if (name === "is" || isVBind && isStaticArgOf(arg, "is") && (isComponentTag(tag3) || false)) {
        continue;
      }
      if (isVOn && ssr) {
        continue;
      }
      if (
        // #938: elements with dynamic keys should be forced into blocks
        isVBind && isStaticArgOf(arg, "key") || // inline before-update hooks need to force block so that it is invoked
        // before children
        isVOn && hasChildren && isStaticArgOf(arg, "vue:before-update")
      ) {
        shouldUseBlock = true;
      }
      if (isVBind && isStaticArgOf(arg, "ref") && context.scopes.vFor > 0) {
        properties.push(
          createObjectProperty(
            createSimpleExpression("ref_for", true),
            createSimpleExpression("true")
          )
        );
      }
      if (!arg && (isVBind || isVOn)) {
        hasDynamicKeys = true;
        if (exp) {
          if (isVBind) {
            pushMergeArg();
            mergeArgs.push(exp);
          } else {
            pushMergeArg({
              type: 14,
              loc,
              callee: context.helper(TO_HANDLERS),
              arguments: isComponent2 ? [exp] : [exp, `true`]
            });
          }
        } else {
          context.onError(
            createCompilerError(
              isVBind ? 34 : 35,
              loc
            )
          );
        }
        continue;
      }
      const directiveTransform = context.directiveTransforms[name];
      if (directiveTransform) {
        const { props: props2, needRuntime } = directiveTransform(prop, node2, context);
        !ssr && props2.forEach(analyzePatchFlag);
        if (isVOn && arg && !isStaticExp(arg)) {
          pushMergeArg(createObjectExpression(props2, elementLoc));
        } else {
          properties.push(...props2);
        }
        if (needRuntime) {
          runtimeDirectives.push(prop);
          if (isSymbol$1(needRuntime)) {
            directiveImportMap.set(prop, needRuntime);
          }
        }
      } else if (!isBuiltInDirective(name)) {
        runtimeDirectives.push(prop);
        if (hasChildren) {
          shouldUseBlock = true;
        }
      }
    }
  }
  let propsExpression = void 0;
  if (mergeArgs.length) {
    pushMergeArg();
    if (mergeArgs.length > 1) {
      propsExpression = createCallExpression(
        context.helper(MERGE_PROPS),
        mergeArgs,
        elementLoc
      );
    } else {
      propsExpression = mergeArgs[0];
    }
  } else if (properties.length) {
    propsExpression = createObjectExpression(
      dedupeProperties(properties),
      elementLoc
    );
  }
  if (hasDynamicKeys) {
    patchFlag |= 16;
  } else {
    if (hasClassBinding && !isComponent2) {
      patchFlag |= 2;
    }
    if (hasStyleBinding && !isComponent2) {
      patchFlag |= 4;
    }
    if (dynamicPropNames.length) {
      patchFlag |= 8;
    }
    if (hasHydrationEventBinding) {
      patchFlag |= 32;
    }
  }
  if (!shouldUseBlock && (patchFlag === 0 || patchFlag === 32) && (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
    patchFlag |= 512;
  }
  if (!context.inSSR && propsExpression) {
    switch (propsExpression.type) {
      case 15:
        let classKeyIndex = -1;
        let styleKeyIndex = -1;
        let hasDynamicKey = false;
        for (let i = 0; i < propsExpression.properties.length; i++) {
          const key = propsExpression.properties[i].key;
          if (isStaticExp(key)) {
            if (key.content === "class") {
              classKeyIndex = i;
            } else if (key.content === "style") {
              styleKeyIndex = i;
            }
          } else if (!key.isHandlerKey) {
            hasDynamicKey = true;
          }
        }
        const classProp = propsExpression.properties[classKeyIndex];
        const styleProp = propsExpression.properties[styleKeyIndex];
        if (!hasDynamicKey) {
          if (classProp && !isStaticExp(classProp.value)) {
            classProp.value = createCallExpression(
              context.helper(NORMALIZE_CLASS),
              [classProp.value]
            );
          }
          if (styleProp && // the static style is compiled into an object,
          // so use `hasStyleBinding` to ensure that it is a dynamic style binding
          (hasStyleBinding || styleProp.value.type === 4 && styleProp.value.content.trim()[0] === `[` || // v-bind:style and style both exist,
          // v-bind:style with static literal object
          styleProp.value.type === 17)) {
            styleProp.value = createCallExpression(
              context.helper(NORMALIZE_STYLE),
              [styleProp.value]
            );
          }
        } else {
          propsExpression = createCallExpression(
            context.helper(NORMALIZE_PROPS),
            [propsExpression]
          );
        }
        break;
      case 14:
        break;
      default:
        propsExpression = createCallExpression(
          context.helper(NORMALIZE_PROPS),
          [
            createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [
              propsExpression
            ])
          ]
        );
        break;
    }
  }
  return {
    props: propsExpression,
    directives: runtimeDirectives,
    patchFlag,
    dynamicPropNames,
    shouldUseBlock
  };
}
function dedupeProperties(properties) {
  const knownProps = /* @__PURE__ */ new Map();
  const deduped = [];
  for (let i = 0; i < properties.length; i++) {
    const prop = properties[i];
    if (prop.key.type === 8 || !prop.key.isStatic) {
      deduped.push(prop);
      continue;
    }
    const name = prop.key.content;
    const existing = knownProps.get(name);
    if (existing) {
      if (name === "style" || name === "class" || isOn(name)) {
        mergeAsArray(existing, prop);
      }
    } else {
      knownProps.set(name, prop);
      deduped.push(prop);
    }
  }
  return deduped;
}
function mergeAsArray(existing, incoming) {
  if (existing.value.type === 17) {
    existing.value.elements.push(incoming.value);
  } else {
    existing.value = createArrayExpression(
      [existing.value, incoming.value],
      existing.loc
    );
  }
}
function buildDirectiveArgs(dir, context) {
  const dirArgs = [];
  const runtime = directiveImportMap.get(dir);
  if (runtime) {
    dirArgs.push(context.helperString(runtime));
  } else {
    const fromSetup = resolveSetupReference("v-" + dir.name, context);
    if (fromSetup) {
      dirArgs.push(fromSetup);
    } else {
      context.helper(RESOLVE_DIRECTIVE);
      context.directives.add(dir.name);
      dirArgs.push(toValidAssetId(dir.name, `directive`));
    }
  }
  const { loc } = dir;
  if (dir.exp)
    dirArgs.push(dir.exp);
  if (dir.arg) {
    if (!dir.exp) {
      dirArgs.push(`void 0`);
    }
    dirArgs.push(dir.arg);
  }
  if (Object.keys(dir.modifiers).length) {
    if (!dir.arg) {
      if (!dir.exp) {
        dirArgs.push(`void 0`);
      }
      dirArgs.push(`void 0`);
    }
    const trueExpression = createSimpleExpression(`true`, false, loc);
    dirArgs.push(
      createObjectExpression(
        dir.modifiers.map(
          (modifier) => createObjectProperty(modifier, trueExpression)
        ),
        loc
      )
    );
  }
  return createArrayExpression(dirArgs, dir.loc);
}
function stringifyDynamicPropNames(props) {
  let propsNamesString = `[`;
  for (let i = 0, l = props.length; i < l; i++) {
    propsNamesString += JSON.stringify(props[i]);
    if (i < l - 1)
      propsNamesString += ", ";
  }
  return propsNamesString + `]`;
}
function isComponentTag(tag3) {
  return tag3 === "component" || tag3 === "Component";
}
const transformSlotOutlet = (node2, context) => {
  if (isSlotOutlet(node2)) {
    const { children, loc } = node2;
    const { slotName, slotProps } = processSlotOutlet(node2, context);
    const slotArgs = [
      context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
      slotName,
      "{}",
      "undefined",
      "true"
    ];
    let expectedLen = 2;
    if (slotProps) {
      slotArgs[2] = slotProps;
      expectedLen = 3;
    }
    if (children.length) {
      slotArgs[3] = createFunctionExpression([], children, false, false, loc);
      expectedLen = 4;
    }
    if (context.scopeId && !context.slotted) {
      expectedLen = 5;
    }
    slotArgs.splice(expectedLen);
    node2.codegenNode = createCallExpression(
      context.helper(RENDER_SLOT),
      slotArgs,
      loc
    );
  }
};
function processSlotOutlet(node2, context) {
  let slotName = `"default"`;
  let slotProps = void 0;
  const nonNameProps = [];
  for (let i = 0; i < node2.props.length; i++) {
    const p2 = node2.props[i];
    if (p2.type === 6) {
      if (p2.value) {
        if (p2.name === "name") {
          slotName = JSON.stringify(p2.value.content);
        } else {
          p2.name = camelize(p2.name);
          nonNameProps.push(p2);
        }
      }
    } else {
      if (p2.name === "bind" && isStaticArgOf(p2.arg, "name")) {
        if (p2.exp)
          slotName = p2.exp;
      } else {
        if (p2.name === "bind" && p2.arg && isStaticExp(p2.arg)) {
          p2.arg.content = camelize(p2.arg.content);
        }
        nonNameProps.push(p2);
      }
    }
  }
  if (nonNameProps.length > 0) {
    const { props, directives } = buildProps(
      node2,
      context,
      nonNameProps,
      false,
      false
    );
    slotProps = props;
    if (directives.length) {
      context.onError(
        createCompilerError(
          36,
          directives[0].loc
        )
      );
    }
  }
  return {
    slotName,
    slotProps
  };
}
const fnExpRE = /^\s*([\w$_]+|(async\s*)?\([^)]*?\))\s*(:[^=]+)?=>|^\s*(async\s+)?function(?:\s+[\w$]+)?\s*\(/;
const transformOn$1 = (dir, node2, context, augmentor) => {
  const { loc, modifiers, arg } = dir;
  if (!dir.exp && !modifiers.length) {
    context.onError(createCompilerError(35, loc));
  }
  let eventName;
  if (arg.type === 4) {
    if (arg.isStatic) {
      let rawName = arg.content;
      if (rawName.startsWith("vnode")) {
        context.onWarn(
          createCompilerError(51, arg.loc)
        );
      }
      if (rawName.startsWith("vue:")) {
        rawName = `vnode-${rawName.slice(4)}`;
      }
      const eventString = node2.tagType !== 0 || rawName.startsWith("vnode") || !/[A-Z]/.test(rawName) ? (
        // for non-element and vnode lifecycle event listeners, auto convert
        // it to camelCase. See issue #2249
        toHandlerKey(camelize(rawName))
      ) : (
        // preserve case for plain element listeners that have uppercase
        // letters, as these may be custom elements' custom events
        `on:${rawName}`
      );
      eventName = createSimpleExpression(eventString, true, arg.loc);
    } else {
      eventName = createCompoundExpression([
        `${context.helperString(TO_HANDLER_KEY)}(`,
        arg,
        `)`
      ]);
    }
  } else {
    eventName = arg;
    eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
    eventName.children.push(`)`);
  }
  let exp = dir.exp;
  if (exp && !exp.content.trim()) {
    exp = void 0;
  }
  let shouldCache = context.cacheHandlers && !exp && !context.inVOnce;
  if (exp) {
    const isMemberExp = isMemberExpression(exp.content, context);
    const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
    const hasMultipleStatements = exp.content.includes(`;`);
    if (context.prefixIdentifiers) {
      isInlineStatement && context.addIdentifiers(`$event`);
      exp = dir.exp = processExpression(
        exp,
        context,
        false,
        hasMultipleStatements
      );
      isInlineStatement && context.removeIdentifiers(`$event`);
      shouldCache = context.cacheHandlers && // unnecessary to cache inside v-once
      !context.inVOnce && // runtime constants don't need to be cached
      // (this is analyzed by compileScript in SFC <script setup>)
      !(exp.type === 4 && exp.constType > 0) && // #1541 bail if this is a member exp handler passed to a component -
      // we need to use the original function to preserve arity,
      // e.g. <transition> relies on checking cb.length to determine
      // transition end handling. Inline function is ok since its arity
      // is preserved even when cached.
      !(isMemberExp && node2.tagType === 1) && // bail if the function references closure variables (v-for, v-slot)
      // it must be passed fresh to avoid stale values.
      !hasScopeRef(exp, context.identifiers);
      if (shouldCache && isMemberExp) {
        if (exp.type === 4) {
          exp.content = `${exp.content} && ${exp.content}(...args)`;
        } else {
          exp.children = [...exp.children, ` && `, ...exp.children, `(...args)`];
        }
      }
    }
    if (isInlineStatement || shouldCache && isMemberExp) {
      exp = createCompoundExpression([
        `${isInlineStatement ? context.isTS ? `($event: any)` : `$event` : `${context.isTS ? `
//@ts-ignore
` : ``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
        exp,
        hasMultipleStatements ? `}` : `)`
      ]);
    }
  }
  let ret = {
    props: [
      createObjectProperty(
        eventName,
        exp || createSimpleExpression(`() => {}`, false, loc)
      )
    ]
  };
  if (augmentor) {
    ret = augmentor(ret);
  }
  if (shouldCache) {
    ret.props[0].value = context.cache(ret.props[0].value);
  }
  ret.props.forEach((p2) => p2.key.isHandlerKey = true);
  return ret;
};
const transformBind = (dir, _node, context) => {
  const { exp, modifiers, loc } = dir;
  const arg = dir.arg;
  if (arg.type !== 4) {
    arg.children.unshift(`(`);
    arg.children.push(`) || ""`);
  } else if (!arg.isStatic) {
    arg.content = `${arg.content} || ""`;
  }
  if (modifiers.includes("camel")) {
    if (arg.type === 4) {
      if (arg.isStatic) {
        arg.content = camelize(arg.content);
      } else {
        arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
      }
    } else {
      arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
      arg.children.push(`)`);
    }
  }
  if (!context.inSSR) {
    if (modifiers.includes("prop")) {
      injectPrefix(arg, ".");
    }
    if (modifiers.includes("attr")) {
      injectPrefix(arg, "^");
    }
  }
  if (!exp || exp.type === 4 && !exp.content.trim()) {
    context.onError(createCompilerError(34, loc));
    return {
      props: [createObjectProperty(arg, createSimpleExpression("", true, loc))]
    };
  }
  return {
    props: [createObjectProperty(arg, exp)]
  };
};
const injectPrefix = (arg, prefix2) => {
  if (arg.type === 4) {
    if (arg.isStatic) {
      arg.content = prefix2 + arg.content;
    } else {
      arg.content = `\`${prefix2}\${${arg.content}}\``;
    }
  } else {
    arg.children.unshift(`'${prefix2}' + (`);
    arg.children.push(`)`);
  }
};
const transformText = (node2, context) => {
  if (node2.type === 0 || node2.type === 1 || node2.type === 11 || node2.type === 10) {
    return () => {
      const children = node2.children;
      let currentContainer = void 0;
      let hasText = false;
      for (let i = 0; i < children.length; i++) {
        const child = children[i];
        if (isText$1(child)) {
          hasText = true;
          for (let j = i + 1; j < children.length; j++) {
            const next = children[j];
            if (isText$1(next)) {
              if (!currentContainer) {
                currentContainer = children[i] = createCompoundExpression(
                  [child],
                  child.loc
                );
              }
              currentContainer.children.push(` + `, next);
              children.splice(j, 1);
              j--;
            } else {
              currentContainer = void 0;
              break;
            }
          }
        }
      }
      if (!hasText || // if this is a plain element with a single text child, leave it
      // as-is since the runtime has dedicated fast path for this by directly
      // setting textContent of the element.
      // for component root it's always normalized anyway.
      children.length === 1 && (node2.type === 0 || node2.type === 1 && node2.tagType === 0 && // #3756
      // custom directives can potentially add DOM elements arbitrarily,
      // we need to avoid setting textContent of the element at runtime
      // to avoid accidentally overwriting the DOM elements added
      // by the user through custom directives.
      !node2.props.find(
        (p2) => p2.type === 7 && !context.directiveTransforms[p2.name]
      ) && // in compat mode, <template> tags with no special directives
      // will be rendered as a fragment so its children must be
      // converted into vnodes.
      true)) {
        return;
      }
      for (let i = 0; i < children.length; i++) {
        const child = children[i];
        if (isText$1(child) || child.type === 8) {
          const callArgs = [];
          if (child.type !== 2 || child.content !== " ") {
            callArgs.push(child);
          }
          if (!context.ssr && getConstantType(child, context) === 0) {
            callArgs.push(
              `1 /* ${PatchFlagNames[1]} */`
            );
          }
          children[i] = {
            type: 12,
            content: child,
            loc: child.loc,
            codegenNode: createCallExpression(
              context.helper(CREATE_TEXT),
              callArgs
            )
          };
        }
      }
    };
  }
};
const seen$1 = /* @__PURE__ */ new WeakSet();
const transformOnce = (node2, context) => {
  if (node2.type === 1 && findDir(node2, "once", true)) {
    if (seen$1.has(node2) || context.inVOnce || context.inSSR) {
      return;
    }
    seen$1.add(node2);
    context.inVOnce = true;
    context.helper(SET_BLOCK_TRACKING);
    return () => {
      context.inVOnce = false;
      const cur = context.currentNode;
      if (cur.codegenNode) {
        cur.codegenNode = context.cache(
          cur.codegenNode,
          true
          /* isVNode */
        );
      }
    };
  }
};
const transformModel$1 = (dir, node2, context) => {
  const { exp, arg } = dir;
  if (!exp) {
    context.onError(
      createCompilerError(41, dir.loc)
    );
    return createTransformProps();
  }
  const rawExp = exp.loc.source;
  const expString = exp.type === 4 ? exp.content : rawExp;
  const bindingType = context.bindingMetadata[rawExp];
  if (bindingType === "props" || bindingType === "props-aliased") {
    context.onError(createCompilerError(44, exp.loc));
    return createTransformProps();
  }
  const maybeRef = context.inline && (bindingType === "setup-let" || bindingType === "setup-ref" || bindingType === "setup-maybe-ref");
  if (!expString.trim() || !isMemberExpression(expString, context) && !maybeRef) {
    context.onError(
      createCompilerError(42, exp.loc)
    );
    return createTransformProps();
  }
  if (context.prefixIdentifiers && isSimpleIdentifier(expString) && context.identifiers[expString]) {
    context.onError(
      createCompilerError(43, exp.loc)
    );
    return createTransformProps();
  }
  const propName = arg ? arg : createSimpleExpression("modelValue", true);
  const eventName = arg ? isStaticExp(arg) ? `onUpdate:${camelize(arg.content)}` : createCompoundExpression(['"onUpdate:" + ', arg]) : `onUpdate:modelValue`;
  let assignmentExp;
  const eventArg = context.isTS ? `($event: any)` : `$event`;
  if (maybeRef) {
    if (bindingType === "setup-ref") {
      assignmentExp = createCompoundExpression([
        `${eventArg} => ((`,
        createSimpleExpression(rawExp, false, exp.loc),
        `).value = $event)`
      ]);
    } else {
      const altAssignment = bindingType === "setup-let" ? `${rawExp} = $event` : `null`;
      assignmentExp = createCompoundExpression([
        `${eventArg} => (${context.helperString(IS_REF)}(${rawExp}) ? (`,
        createSimpleExpression(rawExp, false, exp.loc),
        `).value = $event : ${altAssignment})`
      ]);
    }
  } else {
    assignmentExp = createCompoundExpression([
      `${eventArg} => ((`,
      exp,
      `) = $event)`
    ]);
  }
  const props = [
    // modelValue: foo
    createObjectProperty(propName, dir.exp),
    // "onUpdate:modelValue": $event => (foo = $event)
    createObjectProperty(eventName, assignmentExp)
  ];
  if (context.prefixIdentifiers && !context.inVOnce && context.cacheHandlers && !hasScopeRef(exp, context.identifiers)) {
    props[1].value = context.cache(props[1].value);
  }
  if (dir.modifiers.length && node2.tagType === 1) {
    const modifiers = dir.modifiers.map((m) => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`).join(`, `);
    const modifiersKey = arg ? isStaticExp(arg) ? `${arg.content}Modifiers` : createCompoundExpression([arg, ' + "Modifiers"']) : `modelModifiers`;
    props.push(
      createObjectProperty(
        modifiersKey,
        createSimpleExpression(
          `{ ${modifiers} }`,
          false,
          dir.loc,
          2
        )
      )
    );
  }
  return createTransformProps(props);
};
function createTransformProps(props = []) {
  return { props };
}
const seen = /* @__PURE__ */ new WeakSet();
const transformMemo = (node2, context) => {
  if (node2.type === 1) {
    const dir = findDir(node2, "memo");
    if (!dir || seen.has(node2)) {
      return;
    }
    seen.add(node2);
    return () => {
      const codegenNode = node2.codegenNode || context.currentNode.codegenNode;
      if (codegenNode && codegenNode.type === 13) {
        if (node2.tagType !== 1) {
          convertToBlock(codegenNode, context);
        }
        node2.codegenNode = createCallExpression(context.helper(WITH_MEMO), [
          dir.exp,
          createFunctionExpression(void 0, codegenNode),
          `_cache`,
          String(context.cached++)
        ]);
      }
    };
  }
};
function getBaseTransformPreset(prefixIdentifiers) {
  return [
    [
      transformOnce,
      transformIf,
      transformMemo,
      transformFor,
      ...[],
      ...prefixIdentifiers ? [
        // order is important
        trackVForSlotScopes,
        transformExpression
      ] : [],
      transformSlotOutlet,
      transformElement,
      trackSlotScopes,
      transformText
    ],
    {
      on: transformOn$1,
      bind: transformBind,
      model: transformModel$1
    }
  ];
}
function baseCompile(template, options = {}) {
  const onError = options.onError || defaultOnError;
  const isModuleMode = options.mode === "module";
  const prefixIdentifiers = options.prefixIdentifiers === true || isModuleMode;
  if (!prefixIdentifiers && options.cacheHandlers) {
    onError(createCompilerError(49));
  }
  if (options.scopeId && !isModuleMode) {
    onError(createCompilerError(50));
  }
  const ast = isString$2(template) ? baseParse(template, options) : template;
  const [nodeTransforms, directiveTransforms] = getBaseTransformPreset(prefixIdentifiers);
  if (options.isTS) {
    const { expressionPlugins } = options;
    if (!expressionPlugins || !expressionPlugins.includes("typescript")) {
      options.expressionPlugins = [...expressionPlugins || [], "typescript"];
    }
  }
  transform$1(
    ast,
    extend({}, options, {
      prefixIdentifiers,
      nodeTransforms: [
        ...nodeTransforms,
        ...options.nodeTransforms || []
        // user transforms
      ],
      directiveTransforms: extend(
        {},
        directiveTransforms,
        options.directiveTransforms || {}
        // user transforms
      )
    })
  );
  return generate(
    ast,
    extend({}, options, {
      prefixIdentifiers
    })
  );
}
const noopDirectiveTransform = () => ({ props: [] });
const V_MODEL_RADIO = Symbol(`vModelRadio`);
const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox`);
const V_MODEL_TEXT = Symbol(`vModelText`);
const V_MODEL_SELECT = Symbol(`vModelSelect`);
const V_MODEL_DYNAMIC = Symbol(`vModelDynamic`);
const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard`);
const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard`);
const V_SHOW = Symbol(`vShow`);
const TRANSITION = Symbol(`Transition`);
const TRANSITION_GROUP = Symbol(`TransitionGroup`);
registerRuntimeHelpers({
  [V_MODEL_RADIO]: `vModelRadio`,
  [V_MODEL_CHECKBOX]: `vModelCheckbox`,
  [V_MODEL_TEXT]: `vModelText`,
  [V_MODEL_SELECT]: `vModelSelect`,
  [V_MODEL_DYNAMIC]: `vModelDynamic`,
  [V_ON_WITH_MODIFIERS]: `withModifiers`,
  [V_ON_WITH_KEYS]: `withKeys`,
  [V_SHOW]: `vShow`,
  [TRANSITION]: `Transition`,
  [TRANSITION_GROUP]: `TransitionGroup`
});
var namedCharacterReferences = {
  GT: ">",
  gt: ">",
  LT: "<",
  lt: "<",
  "ac;": "∾",
  "af;": "⁡",
  AMP: "&",
  amp: "&",
  "ap;": "≈",
  "DD;": "ⅅ",
  "dd;": "ⅆ",
  deg: "°",
  "ee;": "ⅇ",
  "eg;": "⪚",
  "el;": "⪙",
  ETH: "Ð",
  eth: "ð",
  "gE;": "≧",
  "ge;": "≥",
  "Gg;": "⋙",
  "gg;": "≫",
  "gl;": "≷",
  "GT;": ">",
  "Gt;": "≫",
  "gt;": ">",
  "ic;": "⁣",
  "ii;": "ⅈ",
  "Im;": "ℑ",
  "in;": "∈",
  "it;": "⁢",
  "lE;": "≦",
  "le;": "≤",
  "lg;": "≶",
  "Ll;": "⋘",
  "ll;": "≪",
  "LT;": "<",
  "Lt;": "≪",
  "lt;": "<",
  "mp;": "∓",
  "Mu;": "Μ",
  "mu;": "μ",
  "ne;": "≠",
  "ni;": "∋",
  not: "¬",
  "Nu;": "Ν",
  "nu;": "ν",
  "Or;": "⩔",
  "or;": "∨",
  "oS;": "Ⓢ",
  "Pi;": "Π",
  "pi;": "π",
  "pm;": "±",
  "Pr;": "⪻",
  "pr;": "≺",
  "Re;": "ℜ",
  REG: "®",
  reg: "®",
  "rx;": "℞",
  "Sc;": "⪼",
  "sc;": "≻",
  shy: "­",
  uml: "¨",
  "wp;": "℘",
  "wr;": "≀",
  "Xi;": "Ξ",
  "xi;": "ξ",
  yen: "¥",
  "acd;": "∿",
  "acE;": "∾̳",
  "Acy;": "А",
  "acy;": "а",
  "Afr;": "𝔄",
  "afr;": "𝔞",
  "AMP;": "&",
  "amp;": "&",
  "And;": "⩓",
  "and;": "∧",
  "ang;": "∠",
  "apE;": "⩰",
  "ape;": "≊",
  "ast;": "*",
  Auml: "Ä",
  auml: "ä",
  "Bcy;": "Б",
  "bcy;": "б",
  "Bfr;": "𝔅",
  "bfr;": "𝔟",
  "bne;": "=⃥",
  "bot;": "⊥",
  "Cap;": "⋒",
  "cap;": "∩",
  cent: "¢",
  "Cfr;": "ℭ",
  "cfr;": "𝔠",
  "Chi;": "Χ",
  "chi;": "χ",
  "cir;": "○",
  COPY: "©",
  copy: "©",
  "Cup;": "⋓",
  "cup;": "∪",
  "Dcy;": "Д",
  "dcy;": "д",
  "deg;": "°",
  "Del;": "∇",
  "Dfr;": "𝔇",
  "dfr;": "𝔡",
  "die;": "¨",
  "div;": "÷",
  "Dot;": "¨",
  "dot;": "˙",
  "Ecy;": "Э",
  "ecy;": "э",
  "Efr;": "𝔈",
  "efr;": "𝔢",
  "egs;": "⪖",
  "ell;": "ℓ",
  "els;": "⪕",
  "ENG;": "Ŋ",
  "eng;": "ŋ",
  "Eta;": "Η",
  "eta;": "η",
  "ETH;": "Ð",
  "eth;": "ð",
  Euml: "Ë",
  euml: "ë",
  "Fcy;": "Ф",
  "fcy;": "ф",
  "Ffr;": "𝔉",
  "ffr;": "𝔣",
  "gap;": "⪆",
  "Gcy;": "Г",
  "gcy;": "г",
  "gEl;": "⪌",
  "gel;": "⋛",
  "geq;": "≥",
  "ges;": "⩾",
  "Gfr;": "𝔊",
  "gfr;": "𝔤",
  "ggg;": "⋙",
  "gla;": "⪥",
  "glE;": "⪒",
  "glj;": "⪤",
  "gnE;": "≩",
  "gne;": "⪈",
  "Hat;": "^",
  "Hfr;": "ℌ",
  "hfr;": "𝔥",
  "Icy;": "И",
  "icy;": "и",
  "iff;": "⇔",
  "Ifr;": "ℑ",
  "ifr;": "𝔦",
  "Int;": "∬",
  "int;": "∫",
  Iuml: "Ï",
  iuml: "ï",
  "Jcy;": "Й",
  "jcy;": "й",
  "Jfr;": "𝔍",
  "jfr;": "𝔧",
  "Kcy;": "К",
  "kcy;": "к",
  "Kfr;": "𝔎",
  "kfr;": "𝔨",
  "lap;": "⪅",
  "lat;": "⪫",
  "Lcy;": "Л",
  "lcy;": "л",
  "lEg;": "⪋",
  "leg;": "⋚",
  "leq;": "≤",
  "les;": "⩽",
  "Lfr;": "𝔏",
  "lfr;": "𝔩",
  "lgE;": "⪑",
  "lnE;": "≨",
  "lne;": "⪇",
  "loz;": "◊",
  "lrm;": "‎",
  "Lsh;": "↰",
  "lsh;": "↰",
  macr: "¯",
  "Map;": "⤅",
  "map;": "↦",
  "Mcy;": "М",
  "mcy;": "м",
  "Mfr;": "𝔐",
  "mfr;": "𝔪",
  "mho;": "℧",
  "mid;": "∣",
  "nap;": "≉",
  nbsp: " ",
  "Ncy;": "Н",
  "ncy;": "н",
  "Nfr;": "𝔑",
  "nfr;": "𝔫",
  "ngE;": "≧̸",
  "nge;": "≱",
  "nGg;": "⋙̸",
  "nGt;": "≫⃒",
  "ngt;": "≯",
  "nis;": "⋼",
  "niv;": "∋",
  "nlE;": "≦̸",
  "nle;": "≰",
  "nLl;": "⋘̸",
  "nLt;": "≪⃒",
  "nlt;": "≮",
  "Not;": "⫬",
  "not;": "¬",
  "npr;": "⊀",
  "nsc;": "⊁",
  "num;": "#",
  "Ocy;": "О",
  "ocy;": "о",
  "Ofr;": "𝔒",
  "ofr;": "𝔬",
  "ogt;": "⧁",
  "ohm;": "Ω",
  "olt;": "⧀",
  "ord;": "⩝",
  ordf: "ª",
  ordm: "º",
  "orv;": "⩛",
  Ouml: "Ö",
  ouml: "ö",
  "par;": "∥",
  para: "¶",
  "Pcy;": "П",
  "pcy;": "п",
  "Pfr;": "𝔓",
  "pfr;": "𝔭",
  "Phi;": "Φ",
  "phi;": "φ",
  "piv;": "ϖ",
  "prE;": "⪳",
  "pre;": "⪯",
  "Psi;": "Ψ",
  "psi;": "ψ",
  "Qfr;": "𝔔",
  "qfr;": "𝔮",
  QUOT: '"',
  quot: '"',
  "Rcy;": "Р",
  "rcy;": "р",
  "REG;": "®",
  "reg;": "®",
  "Rfr;": "ℜ",
  "rfr;": "𝔯",
  "Rho;": "Ρ",
  "rho;": "ρ",
  "rlm;": "‏",
  "Rsh;": "↱",
  "rsh;": "↱",
  "scE;": "⪴",
  "sce;": "⪰",
  "Scy;": "С",
  "scy;": "с",
  sect: "§",
  "Sfr;": "𝔖",
  "sfr;": "𝔰",
  "shy;": "­",
  "sim;": "∼",
  "smt;": "⪪",
  "sol;": "/",
  "squ;": "□",
  "Sub;": "⋐",
  "sub;": "⊂",
  "Sum;": "∑",
  "sum;": "∑",
  "Sup;": "⋑",
  "sup;": "⊃",
  sup1: "¹",
  sup2: "²",
  sup3: "³",
  "Tab;": "	",
  "Tau;": "Τ",
  "tau;": "τ",
  "Tcy;": "Т",
  "tcy;": "т",
  "Tfr;": "𝔗",
  "tfr;": "𝔱",
  "top;": "⊤",
  "Ucy;": "У",
  "ucy;": "у",
  "Ufr;": "𝔘",
  "ufr;": "𝔲",
  "uml;": "¨",
  Uuml: "Ü",
  uuml: "ü",
  "Vcy;": "В",
  "vcy;": "в",
  "Vee;": "⋁",
  "vee;": "∨",
  "Vfr;": "𝔙",
  "vfr;": "𝔳",
  "Wfr;": "𝔚",
  "wfr;": "𝔴",
  "Xfr;": "𝔛",
  "xfr;": "𝔵",
  "Ycy;": "Ы",
  "ycy;": "ы",
  "yen;": "¥",
  "Yfr;": "𝔜",
  "yfr;": "𝔶",
  yuml: "ÿ",
  "Zcy;": "З",
  "zcy;": "з",
  "Zfr;": "ℨ",
  "zfr;": "𝔷",
  "zwj;": "‍",
  Acirc: "Â",
  acirc: "â",
  acute: "´",
  AElig: "Æ",
  aelig: "æ",
  "andd;": "⩜",
  "andv;": "⩚",
  "ange;": "⦤",
  "Aopf;": "𝔸",
  "aopf;": "𝕒",
  "apid;": "≋",
  "apos;": "'",
  Aring: "Å",
  aring: "å",
  "Ascr;": "𝒜",
  "ascr;": "𝒶",
  "Auml;": "Ä",
  "auml;": "ä",
  "Barv;": "⫧",
  "bbrk;": "⎵",
  "Beta;": "Β",
  "beta;": "β",
  "beth;": "ℶ",
  "bNot;": "⫭",
  "bnot;": "⌐",
  "Bopf;": "𝔹",
  "bopf;": "𝕓",
  "boxH;": "═",
  "boxh;": "─",
  "boxV;": "║",
  "boxv;": "│",
  "Bscr;": "ℬ",
  "bscr;": "𝒷",
  "bsim;": "∽",
  "bsol;": "\\",
  "bull;": "•",
  "bump;": "≎",
  "caps;": "∩︀",
  "Cdot;": "Ċ",
  "cdot;": "ċ",
  cedil: "¸",
  "cent;": "¢",
  "CHcy;": "Ч",
  "chcy;": "ч",
  "circ;": "ˆ",
  "cirE;": "⧃",
  "cire;": "≗",
  "comp;": "∁",
  "cong;": "≅",
  "Copf;": "ℂ",
  "copf;": "𝕔",
  "COPY;": "©",
  "copy;": "©",
  "Cscr;": "𝒞",
  "cscr;": "𝒸",
  "csub;": "⫏",
  "csup;": "⫐",
  "cups;": "∪︀",
  "Darr;": "↡",
  "dArr;": "⇓",
  "darr;": "↓",
  "dash;": "‐",
  "dHar;": "⥥",
  "diam;": "⋄",
  "DJcy;": "Ђ",
  "djcy;": "ђ",
  "Dopf;": "𝔻",
  "dopf;": "𝕕",
  "Dscr;": "𝒟",
  "dscr;": "𝒹",
  "DScy;": "Ѕ",
  "dscy;": "ѕ",
  "dsol;": "⧶",
  "dtri;": "▿",
  "DZcy;": "Џ",
  "dzcy;": "џ",
  "ecir;": "≖",
  Ecirc: "Ê",
  ecirc: "ê",
  "Edot;": "Ė",
  "eDot;": "≑",
  "edot;": "ė",
  "emsp;": " ",
  "ensp;": " ",
  "Eopf;": "𝔼",
  "eopf;": "𝕖",
  "epar;": "⋕",
  "epsi;": "ε",
  "Escr;": "ℰ",
  "escr;": "ℯ",
  "Esim;": "⩳",
  "esim;": "≂",
  "Euml;": "Ë",
  "euml;": "ë",
  "euro;": "€",
  "excl;": "!",
  "flat;": "♭",
  "fnof;": "ƒ",
  "Fopf;": "𝔽",
  "fopf;": "𝕗",
  "fork;": "⋔",
  "Fscr;": "ℱ",
  "fscr;": "𝒻",
  "Gdot;": "Ġ",
  "gdot;": "ġ",
  "geqq;": "≧",
  "gesl;": "⋛︀",
  "GJcy;": "Ѓ",
  "gjcy;": "ѓ",
  "gnap;": "⪊",
  "gneq;": "⪈",
  "Gopf;": "𝔾",
  "gopf;": "𝕘",
  "Gscr;": "𝒢",
  "gscr;": "ℊ",
  "gsim;": "≳",
  "gtcc;": "⪧",
  "gvnE;": "≩︀",
  "half;": "½",
  "hArr;": "⇔",
  "harr;": "↔",
  "hbar;": "ℏ",
  "Hopf;": "ℍ",
  "hopf;": "𝕙",
  "Hscr;": "ℋ",
  "hscr;": "𝒽",
  Icirc: "Î",
  icirc: "î",
  "Idot;": "İ",
  "IEcy;": "Е",
  "iecy;": "е",
  iexcl: "¡",
  "imof;": "⊷",
  "IOcy;": "Ё",
  "iocy;": "ё",
  "Iopf;": "𝕀",
  "iopf;": "𝕚",
  "Iota;": "Ι",
  "iota;": "ι",
  "Iscr;": "ℐ",
  "iscr;": "𝒾",
  "isin;": "∈",
  "Iuml;": "Ï",
  "iuml;": "ï",
  "Jopf;": "𝕁",
  "jopf;": "𝕛",
  "Jscr;": "𝒥",
  "jscr;": "𝒿",
  "KHcy;": "Х",
  "khcy;": "х",
  "KJcy;": "Ќ",
  "kjcy;": "ќ",
  "Kopf;": "𝕂",
  "kopf;": "𝕜",
  "Kscr;": "𝒦",
  "kscr;": "𝓀",
  "Lang;": "⟪",
  "lang;": "⟨",
  laquo: "«",
  "Larr;": "↞",
  "lArr;": "⇐",
  "larr;": "←",
  "late;": "⪭",
  "lcub;": "{",
  "ldca;": "⤶",
  "ldsh;": "↲",
  "leqq;": "≦",
  "lesg;": "⋚︀",
  "lHar;": "⥢",
  "LJcy;": "Љ",
  "ljcy;": "љ",
  "lnap;": "⪉",
  "lneq;": "⪇",
  "Lopf;": "𝕃",
  "lopf;": "𝕝",
  "lozf;": "⧫",
  "lpar;": "(",
  "Lscr;": "ℒ",
  "lscr;": "𝓁",
  "lsim;": "≲",
  "lsqb;": "[",
  "ltcc;": "⪦",
  "ltri;": "◃",
  "lvnE;": "≨︀",
  "macr;": "¯",
  "male;": "♂",
  "malt;": "✠",
  micro: "µ",
  "mlcp;": "⫛",
  "mldr;": "…",
  "Mopf;": "𝕄",
  "mopf;": "𝕞",
  "Mscr;": "ℳ",
  "mscr;": "𝓂",
  "nang;": "∠⃒",
  "napE;": "⩰̸",
  "nbsp;": " ",
  "ncap;": "⩃",
  "ncup;": "⩂",
  "ngeq;": "≱",
  "nges;": "⩾̸",
  "ngtr;": "≯",
  "nGtv;": "≫̸",
  "nisd;": "⋺",
  "NJcy;": "Њ",
  "njcy;": "њ",
  "nldr;": "‥",
  "nleq;": "≰",
  "nles;": "⩽̸",
  "nLtv;": "≪̸",
  "nmid;": "∤",
  "Nopf;": "ℕ",
  "nopf;": "𝕟",
  "npar;": "∦",
  "npre;": "⪯̸",
  "nsce;": "⪰̸",
  "Nscr;": "𝒩",
  "nscr;": "𝓃",
  "nsim;": "≁",
  "nsub;": "⊄",
  "nsup;": "⊅",
  "ntgl;": "≹",
  "ntlg;": "≸",
  "nvap;": "≍⃒",
  "nvge;": "≥⃒",
  "nvgt;": ">⃒",
  "nvle;": "≤⃒",
  "nvlt;": "<⃒",
  "oast;": "⊛",
  "ocir;": "⊚",
  Ocirc: "Ô",
  ocirc: "ô",
  "odiv;": "⨸",
  "odot;": "⊙",
  "ogon;": "˛",
  "oint;": "∮",
  "omid;": "⦶",
  "Oopf;": "𝕆",
  "oopf;": "𝕠",
  "opar;": "⦷",
  "ordf;": "ª",
  "ordm;": "º",
  "oror;": "⩖",
  "Oscr;": "𝒪",
  "oscr;": "ℴ",
  "osol;": "⊘",
  "Ouml;": "Ö",
  "ouml;": "ö",
  "para;": "¶",
  "part;": "∂",
  "perp;": "⊥",
  "phiv;": "ϕ",
  "plus;": "+",
  "Popf;": "ℙ",
  "popf;": "𝕡",
  pound: "£",
  "prap;": "⪷",
  "prec;": "≺",
  "prnE;": "⪵",
  "prod;": "∏",
  "prop;": "∝",
  "Pscr;": "𝒫",
  "pscr;": "𝓅",
  "qint;": "⨌",
  "Qopf;": "ℚ",
  "qopf;": "𝕢",
  "Qscr;": "𝒬",
  "qscr;": "𝓆",
  "QUOT;": '"',
  "quot;": '"',
  "race;": "∽̱",
  "Rang;": "⟫",
  "rang;": "⟩",
  raquo: "»",
  "Rarr;": "↠",
  "rArr;": "⇒",
  "rarr;": "→",
  "rcub;": "}",
  "rdca;": "⤷",
  "rdsh;": "↳",
  "real;": "ℜ",
  "rect;": "▭",
  "rHar;": "⥤",
  "rhov;": "ϱ",
  "ring;": "˚",
  "Ropf;": "ℝ",
  "ropf;": "𝕣",
  "rpar;": ")",
  "Rscr;": "ℛ",
  "rscr;": "𝓇",
  "rsqb;": "]",
  "rtri;": "▹",
  "scap;": "⪸",
  "scnE;": "⪶",
  "sdot;": "⋅",
  "sect;": "§",
  "semi;": ";",
  "sext;": "✶",
  "SHcy;": "Ш",
  "shcy;": "ш",
  "sime;": "≃",
  "simg;": "⪞",
  "siml;": "⪝",
  "smid;": "∣",
  "smte;": "⪬",
  "solb;": "⧄",
  "Sopf;": "𝕊",
  "sopf;": "𝕤",
  "spar;": "∥",
  "Sqrt;": "√",
  "squf;": "▪",
  "Sscr;": "𝒮",
  "sscr;": "𝓈",
  "Star;": "⋆",
  "star;": "☆",
  "subE;": "⫅",
  "sube;": "⊆",
  "succ;": "≻",
  "sung;": "♪",
  "sup1;": "¹",
  "sup2;": "²",
  "sup3;": "³",
  "supE;": "⫆",
  "supe;": "⊇",
  szlig: "ß",
  "tbrk;": "⎴",
  "tdot;": "⃛",
  THORN: "Þ",
  thorn: "þ",
  times: "×",
  "tint;": "∭",
  "toea;": "⤨",
  "Topf;": "𝕋",
  "topf;": "𝕥",
  "tosa;": "⤩",
  "trie;": "≜",
  "Tscr;": "𝒯",
  "tscr;": "𝓉",
  "TScy;": "Ц",
  "tscy;": "ц",
  "Uarr;": "↟",
  "uArr;": "⇑",
  "uarr;": "↑",
  Ucirc: "Û",
  ucirc: "û",
  "uHar;": "⥣",
  "Uopf;": "𝕌",
  "uopf;": "𝕦",
  "Upsi;": "ϒ",
  "upsi;": "υ",
  "Uscr;": "𝒰",
  "uscr;": "𝓊",
  "utri;": "▵",
  "Uuml;": "Ü",
  "uuml;": "ü",
  "vArr;": "⇕",
  "varr;": "↕",
  "Vbar;": "⫫",
  "vBar;": "⫨",
  "Vert;": "‖",
  "vert;": "|",
  "Vopf;": "𝕍",
  "vopf;": "𝕧",
  "Vscr;": "𝒱",
  "vscr;": "𝓋",
  "Wopf;": "𝕎",
  "wopf;": "𝕨",
  "Wscr;": "𝒲",
  "wscr;": "𝓌",
  "xcap;": "⋂",
  "xcup;": "⋃",
  "xmap;": "⟼",
  "xnis;": "⋻",
  "Xopf;": "𝕏",
  "xopf;": "𝕩",
  "Xscr;": "𝒳",
  "xscr;": "𝓍",
  "xvee;": "⋁",
  "YAcy;": "Я",
  "yacy;": "я",
  "YIcy;": "Ї",
  "yicy;": "ї",
  "Yopf;": "𝕐",
  "yopf;": "𝕪",
  "Yscr;": "𝒴",
  "yscr;": "𝓎",
  "YUcy;": "Ю",
  "yucy;": "ю",
  "Yuml;": "Ÿ",
  "yuml;": "ÿ",
  "Zdot;": "Ż",
  "zdot;": "ż",
  "Zeta;": "Ζ",
  "zeta;": "ζ",
  "ZHcy;": "Ж",
  "zhcy;": "ж",
  "Zopf;": "ℤ",
  "zopf;": "𝕫",
  "Zscr;": "𝒵",
  "zscr;": "𝓏",
  "zwnj;": "‌",
  Aacute: "Á",
  aacute: "á",
  "Acirc;": "Â",
  "acirc;": "â",
  "acute;": "´",
  "AElig;": "Æ",
  "aelig;": "æ",
  Agrave: "À",
  agrave: "à",
  "aleph;": "ℵ",
  "Alpha;": "Α",
  "alpha;": "α",
  "Amacr;": "Ā",
  "amacr;": "ā",
  "amalg;": "⨿",
  "angle;": "∠",
  "angrt;": "∟",
  "angst;": "Å",
  "Aogon;": "Ą",
  "aogon;": "ą",
  "Aring;": "Å",
  "aring;": "å",
  "asymp;": "≈",
  Atilde: "Ã",
  atilde: "ã",
  "awint;": "⨑",
  "bcong;": "≌",
  "bdquo;": "„",
  "bepsi;": "϶",
  "blank;": "␣",
  "blk12;": "▒",
  "blk14;": "░",
  "blk34;": "▓",
  "block;": "█",
  "boxDL;": "╗",
  "boxDl;": "╖",
  "boxdL;": "╕",
  "boxdl;": "┐",
  "boxDR;": "╔",
  "boxDr;": "╓",
  "boxdR;": "╒",
  "boxdr;": "┌",
  "boxHD;": "╦",
  "boxHd;": "╤",
  "boxhD;": "╥",
  "boxhd;": "┬",
  "boxHU;": "╩",
  "boxHu;": "╧",
  "boxhU;": "╨",
  "boxhu;": "┴",
  "boxUL;": "╝",
  "boxUl;": "╜",
  "boxuL;": "╛",
  "boxul;": "┘",
  "boxUR;": "╚",
  "boxUr;": "╙",
  "boxuR;": "╘",
  "boxur;": "└",
  "boxVH;": "╬",
  "boxVh;": "╫",
  "boxvH;": "╪",
  "boxvh;": "┼",
  "boxVL;": "╣",
  "boxVl;": "╢",
  "boxvL;": "╡",
  "boxvl;": "┤",
  "boxVR;": "╠",
  "boxVr;": "╟",
  "boxvR;": "╞",
  "boxvr;": "├",
  "Breve;": "˘",
  "breve;": "˘",
  brvbar: "¦",
  "bsemi;": "⁏",
  "bsime;": "⋍",
  "bsolb;": "⧅",
  "bumpE;": "⪮",
  "bumpe;": "≏",
  "caret;": "⁁",
  "caron;": "ˇ",
  "ccaps;": "⩍",
  Ccedil: "Ç",
  ccedil: "ç",
  "Ccirc;": "Ĉ",
  "ccirc;": "ĉ",
  "ccups;": "⩌",
  "cedil;": "¸",
  "check;": "✓",
  "clubs;": "♣",
  "Colon;": "∷",
  "colon;": ":",
  "comma;": ",",
  "crarr;": "↵",
  "Cross;": "⨯",
  "cross;": "✗",
  "csube;": "⫑",
  "csupe;": "⫒",
  "ctdot;": "⋯",
  "cuepr;": "⋞",
  "cuesc;": "⋟",
  "cupor;": "⩅",
  curren: "¤",
  "cuvee;": "⋎",
  "cuwed;": "⋏",
  "cwint;": "∱",
  "Dashv;": "⫤",
  "dashv;": "⊣",
  "dblac;": "˝",
  "ddarr;": "⇊",
  "Delta;": "Δ",
  "delta;": "δ",
  "dharl;": "⇃",
  "dharr;": "⇂",
  "diams;": "♦",
  "disin;": "⋲",
  divide: "÷",
  "doteq;": "≐",
  "dtdot;": "⋱",
  "dtrif;": "▾",
  "duarr;": "⇵",
  "duhar;": "⥯",
  Eacute: "É",
  eacute: "é",
  "Ecirc;": "Ê",
  "ecirc;": "ê",
  "eDDot;": "⩷",
  "efDot;": "≒",
  Egrave: "È",
  egrave: "è",
  "Emacr;": "Ē",
  "emacr;": "ē",
  "empty;": "∅",
  "Eogon;": "Ę",
  "eogon;": "ę",
  "eplus;": "⩱",
  "epsiv;": "ϵ",
  "eqsim;": "≂",
  "Equal;": "⩵",
  "equiv;": "≡",
  "erarr;": "⥱",
  "erDot;": "≓",
  "esdot;": "≐",
  "exist;": "∃",
  "fflig;": "ﬀ",
  "filig;": "ﬁ",
  "fjlig;": "fj",
  "fllig;": "ﬂ",
  "fltns;": "▱",
  "forkv;": "⫙",
  frac12: "½",
  frac14: "¼",
  frac34: "¾",
  "frasl;": "⁄",
  "frown;": "⌢",
  "Gamma;": "Γ",
  "gamma;": "γ",
  "Gcirc;": "Ĝ",
  "gcirc;": "ĝ",
  "gescc;": "⪩",
  "gimel;": "ℷ",
  "gneqq;": "≩",
  "gnsim;": "⋧",
  "grave;": "`",
  "gsime;": "⪎",
  "gsiml;": "⪐",
  "gtcir;": "⩺",
  "gtdot;": "⋗",
  "Hacek;": "ˇ",
  "harrw;": "↭",
  "Hcirc;": "Ĥ",
  "hcirc;": "ĥ",
  "hoarr;": "⇿",
  Iacute: "Í",
  iacute: "í",
  "Icirc;": "Î",
  "icirc;": "î",
  "iexcl;": "¡",
  Igrave: "Ì",
  igrave: "ì",
  "iiint;": "∭",
  "iiota;": "℩",
  "IJlig;": "Ĳ",
  "ijlig;": "ĳ",
  "Imacr;": "Ī",
  "imacr;": "ī",
  "image;": "ℑ",
  "imath;": "ı",
  "imped;": "Ƶ",
  "infin;": "∞",
  "Iogon;": "Į",
  "iogon;": "į",
  "iprod;": "⨼",
  iquest: "¿",
  "isinE;": "⋹",
  "isins;": "⋴",
  "isinv;": "∈",
  "Iukcy;": "І",
  "iukcy;": "і",
  "Jcirc;": "Ĵ",
  "jcirc;": "ĵ",
  "jmath;": "ȷ",
  "Jukcy;": "Є",
  "jukcy;": "є",
  "Kappa;": "Κ",
  "kappa;": "κ",
  "lAarr;": "⇚",
  "langd;": "⦑",
  "laquo;": "«",
  "larrb;": "⇤",
  "lates;": "⪭︀",
  "lBarr;": "⤎",
  "lbarr;": "⤌",
  "lbbrk;": "❲",
  "lbrke;": "⦋",
  "lceil;": "⌈",
  "ldquo;": "“",
  "lescc;": "⪨",
  "lhard;": "↽",
  "lharu;": "↼",
  "lhblk;": "▄",
  "llarr;": "⇇",
  "lltri;": "◺",
  "lneqq;": "≨",
  "lnsim;": "⋦",
  "loang;": "⟬",
  "loarr;": "⇽",
  "lobrk;": "⟦",
  "lopar;": "⦅",
  "lrarr;": "⇆",
  "lrhar;": "⇋",
  "lrtri;": "⊿",
  "lsime;": "⪍",
  "lsimg;": "⪏",
  "lsquo;": "‘",
  "ltcir;": "⩹",
  "ltdot;": "⋖",
  "ltrie;": "⊴",
  "ltrif;": "◂",
  "mdash;": "—",
  "mDDot;": "∺",
  "micro;": "µ",
  middot: "·",
  "minus;": "−",
  "mumap;": "⊸",
  "nabla;": "∇",
  "napid;": "≋̸",
  "napos;": "ŉ",
  "natur;": "♮",
  "nbump;": "≎̸",
  "ncong;": "≇",
  "ndash;": "–",
  "neArr;": "⇗",
  "nearr;": "↗",
  "nedot;": "≐̸",
  "nesim;": "≂̸",
  "ngeqq;": "≧̸",
  "ngsim;": "≵",
  "nhArr;": "⇎",
  "nharr;": "↮",
  "nhpar;": "⫲",
  "nlArr;": "⇍",
  "nlarr;": "↚",
  "nleqq;": "≦̸",
  "nless;": "≮",
  "nlsim;": "≴",
  "nltri;": "⋪",
  "notin;": "∉",
  "notni;": "∌",
  "npart;": "∂̸",
  "nprec;": "⊀",
  "nrArr;": "⇏",
  "nrarr;": "↛",
  "nrtri;": "⋫",
  "nsime;": "≄",
  "nsmid;": "∤",
  "nspar;": "∦",
  "nsubE;": "⫅̸",
  "nsube;": "⊈",
  "nsucc;": "⊁",
  "nsupE;": "⫆̸",
  "nsupe;": "⊉",
  Ntilde: "Ñ",
  ntilde: "ñ",
  "numsp;": " ",
  "nvsim;": "∼⃒",
  "nwArr;": "⇖",
  "nwarr;": "↖",
  Oacute: "Ó",
  oacute: "ó",
  "Ocirc;": "Ô",
  "ocirc;": "ô",
  "odash;": "⊝",
  "OElig;": "Œ",
  "oelig;": "œ",
  "ofcir;": "⦿",
  Ograve: "Ò",
  ograve: "ò",
  "ohbar;": "⦵",
  "olarr;": "↺",
  "olcir;": "⦾",
  "oline;": "‾",
  "Omacr;": "Ō",
  "omacr;": "ō",
  "Omega;": "Ω",
  "omega;": "ω",
  "operp;": "⦹",
  "oplus;": "⊕",
  "orarr;": "↻",
  "order;": "ℴ",
  Oslash: "Ø",
  oslash: "ø",
  Otilde: "Õ",
  otilde: "õ",
  "ovbar;": "⌽",
  "parsl;": "⫽",
  "phone;": "☎",
  "plusb;": "⊞",
  "pluse;": "⩲",
  plusmn: "±",
  "pound;": "£",
  "prcue;": "≼",
  "Prime;": "″",
  "prime;": "′",
  "prnap;": "⪹",
  "prsim;": "≾",
  "quest;": "?",
  "rAarr;": "⇛",
  "radic;": "√",
  "rangd;": "⦒",
  "range;": "⦥",
  "raquo;": "»",
  "rarrb;": "⇥",
  "rarrc;": "⤳",
  "rarrw;": "↝",
  "ratio;": "∶",
  "RBarr;": "⤐",
  "rBarr;": "⤏",
  "rbarr;": "⤍",
  "rbbrk;": "❳",
  "rbrke;": "⦌",
  "rceil;": "⌉",
  "rdquo;": "”",
  "reals;": "ℝ",
  "rhard;": "⇁",
  "rharu;": "⇀",
  "rlarr;": "⇄",
  "rlhar;": "⇌",
  "rnmid;": "⫮",
  "roang;": "⟭",
  "roarr;": "⇾",
  "robrk;": "⟧",
  "ropar;": "⦆",
  "rrarr;": "⇉",
  "rsquo;": "’",
  "rtrie;": "⊵",
  "rtrif;": "▸",
  "sbquo;": "‚",
  "sccue;": "≽",
  "Scirc;": "Ŝ",
  "scirc;": "ŝ",
  "scnap;": "⪺",
  "scsim;": "≿",
  "sdotb;": "⊡",
  "sdote;": "⩦",
  "seArr;": "⇘",
  "searr;": "↘",
  "setmn;": "∖",
  "sharp;": "♯",
  "Sigma;": "Σ",
  "sigma;": "σ",
  "simeq;": "≃",
  "simgE;": "⪠",
  "simlE;": "⪟",
  "simne;": "≆",
  "slarr;": "←",
  "smile;": "⌣",
  "smtes;": "⪬︀",
  "sqcap;": "⊓",
  "sqcup;": "⊔",
  "sqsub;": "⊏",
  "sqsup;": "⊐",
  "srarr;": "→",
  "starf;": "★",
  "strns;": "¯",
  "subnE;": "⫋",
  "subne;": "⊊",
  "supnE;": "⫌",
  "supne;": "⊋",
  "swArr;": "⇙",
  "swarr;": "↙",
  "szlig;": "ß",
  "Theta;": "Θ",
  "theta;": "θ",
  "thkap;": "≈",
  "THORN;": "Þ",
  "thorn;": "þ",
  "Tilde;": "∼",
  "tilde;": "˜",
  "times;": "×",
  "TRADE;": "™",
  "trade;": "™",
  "trisb;": "⧍",
  "TSHcy;": "Ћ",
  "tshcy;": "ћ",
  "twixt;": "≬",
  Uacute: "Ú",
  uacute: "ú",
  "Ubrcy;": "Ў",
  "ubrcy;": "ў",
  "Ucirc;": "Û",
  "ucirc;": "û",
  "udarr;": "⇅",
  "udhar;": "⥮",
  Ugrave: "Ù",
  ugrave: "ù",
  "uharl;": "↿",
  "uharr;": "↾",
  "uhblk;": "▀",
  "ultri;": "◸",
  "Umacr;": "Ū",
  "umacr;": "ū",
  "Union;": "⋃",
  "Uogon;": "Ų",
  "uogon;": "ų",
  "uplus;": "⊎",
  "upsih;": "ϒ",
  "UpTee;": "⊥",
  "Uring;": "Ů",
  "uring;": "ů",
  "urtri;": "◹",
  "utdot;": "⋰",
  "utrif;": "▴",
  "uuarr;": "⇈",
  "varpi;": "ϖ",
  "vBarv;": "⫩",
  "VDash;": "⊫",
  "Vdash;": "⊩",
  "vDash;": "⊨",
  "vdash;": "⊢",
  "veeeq;": "≚",
  "vltri;": "⊲",
  "vnsub;": "⊂⃒",
  "vnsup;": "⊃⃒",
  "vprop;": "∝",
  "vrtri;": "⊳",
  "Wcirc;": "Ŵ",
  "wcirc;": "ŵ",
  "Wedge;": "⋀",
  "wedge;": "∧",
  "xcirc;": "◯",
  "xdtri;": "▽",
  "xhArr;": "⟺",
  "xharr;": "⟷",
  "xlArr;": "⟸",
  "xlarr;": "⟵",
  "xodot;": "⨀",
  "xrArr;": "⟹",
  "xrarr;": "⟶",
  "xutri;": "△",
  Yacute: "Ý",
  yacute: "ý",
  "Ycirc;": "Ŷ",
  "ycirc;": "ŷ",
  "Aacute;": "Á",
  "aacute;": "á",
  "Abreve;": "Ă",
  "abreve;": "ă",
  "Agrave;": "À",
  "agrave;": "à",
  "andand;": "⩕",
  "angmsd;": "∡",
  "angsph;": "∢",
  "apacir;": "⩯",
  "approx;": "≈",
  "Assign;": "≔",
  "Atilde;": "Ã",
  "atilde;": "ã",
  "barvee;": "⊽",
  "Barwed;": "⌆",
  "barwed;": "⌅",
  "becaus;": "∵",
  "bernou;": "ℬ",
  "bigcap;": "⋂",
  "bigcup;": "⋃",
  "bigvee;": "⋁",
  "bkarow;": "⤍",
  "bottom;": "⊥",
  "bowtie;": "⋈",
  "boxbox;": "⧉",
  "bprime;": "‵",
  "brvbar;": "¦",
  "bullet;": "•",
  "Bumpeq;": "≎",
  "bumpeq;": "≏",
  "Cacute;": "Ć",
  "cacute;": "ć",
  "capand;": "⩄",
  "capcap;": "⩋",
  "capcup;": "⩇",
  "capdot;": "⩀",
  "Ccaron;": "Č",
  "ccaron;": "č",
  "Ccedil;": "Ç",
  "ccedil;": "ç",
  "circeq;": "≗",
  "cirmid;": "⫯",
  "Colone;": "⩴",
  "colone;": "≔",
  "commat;": "@",
  "compfn;": "∘",
  "Conint;": "∯",
  "conint;": "∮",
  "coprod;": "∐",
  "copysr;": "℗",
  "cularr;": "↶",
  "CupCap;": "≍",
  "cupcap;": "⩆",
  "cupcup;": "⩊",
  "cupdot;": "⊍",
  "curarr;": "↷",
  "curren;": "¤",
  "cylcty;": "⌭",
  "Dagger;": "‡",
  "dagger;": "†",
  "daleth;": "ℸ",
  "Dcaron;": "Ď",
  "dcaron;": "ď",
  "dfisht;": "⥿",
  "divide;": "÷",
  "divonx;": "⋇",
  "dlcorn;": "⌞",
  "dlcrop;": "⌍",
  "dollar;": "$",
  "DotDot;": "⃜",
  "drcorn;": "⌟",
  "drcrop;": "⌌",
  "Dstrok;": "Đ",
  "dstrok;": "đ",
  "Eacute;": "É",
  "eacute;": "é",
  "easter;": "⩮",
  "Ecaron;": "Ě",
  "ecaron;": "ě",
  "ecolon;": "≕",
  "Egrave;": "È",
  "egrave;": "è",
  "egsdot;": "⪘",
  "elsdot;": "⪗",
  "emptyv;": "∅",
  "emsp13;": " ",
  "emsp14;": " ",
  "eparsl;": "⧣",
  "eqcirc;": "≖",
  "equals;": "=",
  "equest;": "≟",
  "Exists;": "∃",
  "female;": "♀",
  "ffilig;": "ﬃ",
  "ffllig;": "ﬄ",
  "ForAll;": "∀",
  "forall;": "∀",
  "frac12;": "½",
  "frac13;": "⅓",
  "frac14;": "¼",
  "frac15;": "⅕",
  "frac16;": "⅙",
  "frac18;": "⅛",
  "frac23;": "⅔",
  "frac25;": "⅖",
  "frac34;": "¾",
  "frac35;": "⅗",
  "frac38;": "⅜",
  "frac45;": "⅘",
  "frac56;": "⅚",
  "frac58;": "⅝",
  "frac78;": "⅞",
  "gacute;": "ǵ",
  "Gammad;": "Ϝ",
  "gammad;": "ϝ",
  "Gbreve;": "Ğ",
  "gbreve;": "ğ",
  "Gcedil;": "Ģ",
  "gesdot;": "⪀",
  "gesles;": "⪔",
  "gtlPar;": "⦕",
  "gtrarr;": "⥸",
  "gtrdot;": "⋗",
  "gtrsim;": "≳",
  "hairsp;": " ",
  "hamilt;": "ℋ",
  "HARDcy;": "Ъ",
  "hardcy;": "ъ",
  "hearts;": "♥",
  "hellip;": "…",
  "hercon;": "⊹",
  "homtht;": "∻",
  "horbar;": "―",
  "hslash;": "ℏ",
  "Hstrok;": "Ħ",
  "hstrok;": "ħ",
  "hybull;": "⁃",
  "hyphen;": "‐",
  "Iacute;": "Í",
  "iacute;": "í",
  "Igrave;": "Ì",
  "igrave;": "ì",
  "iiiint;": "⨌",
  "iinfin;": "⧜",
  "incare;": "℅",
  "inodot;": "ı",
  "intcal;": "⊺",
  "iquest;": "¿",
  "isinsv;": "⋳",
  "Itilde;": "Ĩ",
  "itilde;": "ĩ",
  "Jsercy;": "Ј",
  "jsercy;": "ј",
  "kappav;": "ϰ",
  "Kcedil;": "Ķ",
  "kcedil;": "ķ",
  "kgreen;": "ĸ",
  "Lacute;": "Ĺ",
  "lacute;": "ĺ",
  "lagran;": "ℒ",
  "Lambda;": "Λ",
  "lambda;": "λ",
  "langle;": "⟨",
  "larrfs;": "⤝",
  "larrhk;": "↩",
  "larrlp;": "↫",
  "larrpl;": "⤹",
  "larrtl;": "↢",
  "lAtail;": "⤛",
  "latail;": "⤙",
  "lbrace;": "{",
  "lbrack;": "[",
  "Lcaron;": "Ľ",
  "lcaron;": "ľ",
  "Lcedil;": "Ļ",
  "lcedil;": "ļ",
  "ldquor;": "„",
  "lesdot;": "⩿",
  "lesges;": "⪓",
  "lfisht;": "⥼",
  "lfloor;": "⌊",
  "lharul;": "⥪",
  "llhard;": "⥫",
  "Lmidot;": "Ŀ",
  "lmidot;": "ŀ",
  "lmoust;": "⎰",
  "loplus;": "⨭",
  "lowast;": "∗",
  "lowbar;": "_",
  "lparlt;": "⦓",
  "lrhard;": "⥭",
  "lsaquo;": "‹",
  "lsquor;": "‚",
  "Lstrok;": "Ł",
  "lstrok;": "ł",
  "lthree;": "⋋",
  "ltimes;": "⋉",
  "ltlarr;": "⥶",
  "ltrPar;": "⦖",
  "mapsto;": "↦",
  "marker;": "▮",
  "mcomma;": "⨩",
  "midast;": "*",
  "midcir;": "⫰",
  "middot;": "·",
  "minusb;": "⊟",
  "minusd;": "∸",
  "mnplus;": "∓",
  "models;": "⊧",
  "mstpos;": "∾",
  "Nacute;": "Ń",
  "nacute;": "ń",
  "nbumpe;": "≏̸",
  "Ncaron;": "Ň",
  "ncaron;": "ň",
  "Ncedil;": "Ņ",
  "ncedil;": "ņ",
  "nearhk;": "⤤",
  "nequiv;": "≢",
  "nesear;": "⤨",
  "nexist;": "∄",
  "nltrie;": "⋬",
  "notinE;": "⋹̸",
  "nparsl;": "⫽⃥",
  "nprcue;": "⋠",
  "nrarrc;": "⤳̸",
  "nrarrw;": "↝̸",
  "nrtrie;": "⋭",
  "nsccue;": "⋡",
  "nsimeq;": "≄",
  "Ntilde;": "Ñ",
  "ntilde;": "ñ",
  "numero;": "№",
  "nVDash;": "⊯",
  "nVdash;": "⊮",
  "nvDash;": "⊭",
  "nvdash;": "⊬",
  "nvHarr;": "⤄",
  "nvlArr;": "⤂",
  "nvrArr;": "⤃",
  "nwarhk;": "⤣",
  "nwnear;": "⤧",
  "Oacute;": "Ó",
  "oacute;": "ó",
  "Odblac;": "Ő",
  "odblac;": "ő",
  "odsold;": "⦼",
  "Ograve;": "Ò",
  "ograve;": "ò",
  "ominus;": "⊖",
  "origof;": "⊶",
  "Oslash;": "Ø",
  "oslash;": "ø",
  "Otilde;": "Õ",
  "otilde;": "õ",
  "Otimes;": "⨷",
  "otimes;": "⊗",
  "parsim;": "⫳",
  "percnt;": "%",
  "period;": ".",
  "permil;": "‰",
  "phmmat;": "ℳ",
  "planck;": "ℏ",
  "plankv;": "ℏ",
  "plusdo;": "∔",
  "plusdu;": "⨥",
  "plusmn;": "±",
  "preceq;": "⪯",
  "primes;": "ℙ",
  "prnsim;": "⋨",
  "propto;": "∝",
  "prurel;": "⊰",
  "puncsp;": " ",
  "qprime;": "⁗",
  "Racute;": "Ŕ",
  "racute;": "ŕ",
  "rangle;": "⟩",
  "rarrap;": "⥵",
  "rarrfs;": "⤞",
  "rarrhk;": "↪",
  "rarrlp;": "↬",
  "rarrpl;": "⥅",
  "Rarrtl;": "⤖",
  "rarrtl;": "↣",
  "rAtail;": "⤜",
  "ratail;": "⤚",
  "rbrace;": "}",
  "rbrack;": "]",
  "Rcaron;": "Ř",
  "rcaron;": "ř",
  "Rcedil;": "Ŗ",
  "rcedil;": "ŗ",
  "rdquor;": "”",
  "rfisht;": "⥽",
  "rfloor;": "⌋",
  "rharul;": "⥬",
  "rmoust;": "⎱",
  "roplus;": "⨮",
  "rpargt;": "⦔",
  "rsaquo;": "›",
  "rsquor;": "’",
  "rthree;": "⋌",
  "rtimes;": "⋊",
  "Sacute;": "Ś",
  "sacute;": "ś",
  "Scaron;": "Š",
  "scaron;": "š",
  "Scedil;": "Ş",
  "scedil;": "ş",
  "scnsim;": "⋩",
  "searhk;": "⤥",
  "seswar;": "⤩",
  "sfrown;": "⌢",
  "SHCHcy;": "Щ",
  "shchcy;": "щ",
  "sigmaf;": "ς",
  "sigmav;": "ς",
  "simdot;": "⩪",
  "smashp;": "⨳",
  "SOFTcy;": "Ь",
  "softcy;": "ь",
  "solbar;": "⌿",
  "spades;": "♠",
  "sqcaps;": "⊓︀",
  "sqcups;": "⊔︀",
  "sqsube;": "⊑",
  "sqsupe;": "⊒",
  "Square;": "□",
  "square;": "□",
  "squarf;": "▪",
  "ssetmn;": "∖",
  "ssmile;": "⌣",
  "sstarf;": "⋆",
  "subdot;": "⪽",
  "Subset;": "⋐",
  "subset;": "⊂",
  "subsim;": "⫇",
  "subsub;": "⫕",
  "subsup;": "⫓",
  "succeq;": "⪰",
  "supdot;": "⪾",
  "Supset;": "⋑",
  "supset;": "⊃",
  "supsim;": "⫈",
  "supsub;": "⫔",
  "supsup;": "⫖",
  "swarhk;": "⤦",
  "swnwar;": "⤪",
  "target;": "⌖",
  "Tcaron;": "Ť",
  "tcaron;": "ť",
  "Tcedil;": "Ţ",
  "tcedil;": "ţ",
  "telrec;": "⌕",
  "there4;": "∴",
  "thetav;": "ϑ",
  "thinsp;": " ",
  "thksim;": "∼",
  "timesb;": "⊠",
  "timesd;": "⨰",
  "topbot;": "⌶",
  "topcir;": "⫱",
  "tprime;": "‴",
  "tridot;": "◬",
  "Tstrok;": "Ŧ",
  "tstrok;": "ŧ",
  "Uacute;": "Ú",
  "uacute;": "ú",
  "Ubreve;": "Ŭ",
  "ubreve;": "ŭ",
  "Udblac;": "Ű",
  "udblac;": "ű",
  "ufisht;": "⥾",
  "Ugrave;": "Ù",
  "ugrave;": "ù",
  "ulcorn;": "⌜",
  "ulcrop;": "⌏",
  "urcorn;": "⌝",
  "urcrop;": "⌎",
  "Utilde;": "Ũ",
  "utilde;": "ũ",
  "vangrt;": "⦜",
  "varphi;": "ϕ",
  "varrho;": "ϱ",
  "Vdashl;": "⫦",
  "veebar;": "⊻",
  "vellip;": "⋮",
  "Verbar;": "‖",
  "verbar;": "|",
  "vsubnE;": "⫋︀",
  "vsubne;": "⊊︀",
  "vsupnE;": "⫌︀",
  "vsupne;": "⊋︀",
  "Vvdash;": "⊪",
  "wedbar;": "⩟",
  "wedgeq;": "≙",
  "weierp;": "℘",
  "wreath;": "≀",
  "xoplus;": "⨁",
  "xotime;": "⨂",
  "xsqcup;": "⨆",
  "xuplus;": "⨄",
  "xwedge;": "⋀",
  "Yacute;": "Ý",
  "yacute;": "ý",
  "Zacute;": "Ź",
  "zacute;": "ź",
  "Zcaron;": "Ž",
  "zcaron;": "ž",
  "zeetrf;": "ℨ",
  "alefsym;": "ℵ",
  "angrtvb;": "⊾",
  "angzarr;": "⍼",
  "asympeq;": "≍",
  "backsim;": "∽",
  "Because;": "∵",
  "because;": "∵",
  "bemptyv;": "⦰",
  "between;": "≬",
  "bigcirc;": "◯",
  "bigodot;": "⨀",
  "bigstar;": "★",
  "bnequiv;": "≡⃥",
  "boxplus;": "⊞",
  "Cayleys;": "ℭ",
  "Cconint;": "∰",
  "ccupssm;": "⩐",
  "Cedilla;": "¸",
  "cemptyv;": "⦲",
  "cirscir;": "⧂",
  "coloneq;": "≔",
  "congdot;": "⩭",
  "cudarrl;": "⤸",
  "cudarrr;": "⤵",
  "cularrp;": "⤽",
  "curarrm;": "⤼",
  "dbkarow;": "⤏",
  "ddagger;": "‡",
  "ddotseq;": "⩷",
  "demptyv;": "⦱",
  "Diamond;": "⋄",
  "diamond;": "⋄",
  "digamma;": "ϝ",
  "dotplus;": "∔",
  "DownTee;": "⊤",
  "dwangle;": "⦦",
  "Element;": "∈",
  "Epsilon;": "Ε",
  "epsilon;": "ε",
  "eqcolon;": "≕",
  "equivDD;": "⩸",
  "gesdoto;": "⪂",
  "gtquest;": "⩼",
  "gtrless;": "≷",
  "harrcir;": "⥈",
  "Implies;": "⇒",
  "intprod;": "⨼",
  "isindot;": "⋵",
  "larrbfs;": "⤟",
  "larrsim;": "⥳",
  "lbrksld;": "⦏",
  "lbrkslu;": "⦍",
  "ldrdhar;": "⥧",
  "LeftTee;": "⊣",
  "lesdoto;": "⪁",
  "lessdot;": "⋖",
  "lessgtr;": "≶",
  "lesssim;": "≲",
  "lotimes;": "⨴",
  "lozenge;": "◊",
  "ltquest;": "⩻",
  "luruhar;": "⥦",
  "maltese;": "✠",
  "minusdu;": "⨪",
  "napprox;": "≉",
  "natural;": "♮",
  "nearrow;": "↗",
  "NewLine;": "\n",
  "nexists;": "∄",
  "NoBreak;": "⁠",
  "notinva;": "∉",
  "notinvb;": "⋷",
  "notinvc;": "⋶",
  "NotLess;": "≮",
  "notniva;": "∌",
  "notnivb;": "⋾",
  "notnivc;": "⋽",
  "npolint;": "⨔",
  "npreceq;": "⪯̸",
  "nsqsube;": "⋢",
  "nsqsupe;": "⋣",
  "nsubset;": "⊂⃒",
  "nsucceq;": "⪰̸",
  "nsupset;": "⊃⃒",
  "nvinfin;": "⧞",
  "nvltrie;": "⊴⃒",
  "nvrtrie;": "⊵⃒",
  "nwarrow;": "↖",
  "olcross;": "⦻",
  "Omicron;": "Ο",
  "omicron;": "ο",
  "orderof;": "ℴ",
  "orslope;": "⩗",
  "OverBar;": "‾",
  "pertenk;": "‱",
  "planckh;": "ℎ",
  "pluscir;": "⨢",
  "plussim;": "⨦",
  "plustwo;": "⨧",
  "precsim;": "≾",
  "Product;": "∏",
  "quatint;": "⨖",
  "questeq;": "≟",
  "rarrbfs;": "⤠",
  "rarrsim;": "⥴",
  "rbrksld;": "⦎",
  "rbrkslu;": "⦐",
  "rdldhar;": "⥩",
  "realine;": "ℛ",
  "rotimes;": "⨵",
  "ruluhar;": "⥨",
  "searrow;": "↘",
  "simplus;": "⨤",
  "simrarr;": "⥲",
  "subedot;": "⫃",
  "submult;": "⫁",
  "subplus;": "⪿",
  "subrarr;": "⥹",
  "succsim;": "≿",
  "supdsub;": "⫘",
  "supedot;": "⫄",
  "suphsol;": "⟉",
  "suphsub;": "⫗",
  "suplarr;": "⥻",
  "supmult;": "⫂",
  "supplus;": "⫀",
  "swarrow;": "↙",
  "topfork;": "⫚",
  "triplus;": "⨹",
  "tritime;": "⨻",
  "UpArrow;": "↑",
  "Uparrow;": "⇑",
  "uparrow;": "↑",
  "Upsilon;": "Υ",
  "upsilon;": "υ",
  "uwangle;": "⦧",
  "vzigzag;": "⦚",
  "zigrarr;": "⇝",
  "andslope;": "⩘",
  "angmsdaa;": "⦨",
  "angmsdab;": "⦩",
  "angmsdac;": "⦪",
  "angmsdad;": "⦫",
  "angmsdae;": "⦬",
  "angmsdaf;": "⦭",
  "angmsdag;": "⦮",
  "angmsdah;": "⦯",
  "angrtvbd;": "⦝",
  "approxeq;": "≊",
  "awconint;": "∳",
  "backcong;": "≌",
  "barwedge;": "⌅",
  "bbrktbrk;": "⎶",
  "bigoplus;": "⨁",
  "bigsqcup;": "⨆",
  "biguplus;": "⨄",
  "bigwedge;": "⋀",
  "boxminus;": "⊟",
  "boxtimes;": "⊠",
  "bsolhsub;": "⟈",
  "capbrcup;": "⩉",
  "circledR;": "®",
  "circledS;": "Ⓢ",
  "cirfnint;": "⨐",
  "clubsuit;": "♣",
  "cupbrcap;": "⩈",
  "curlyvee;": "⋎",
  "cwconint;": "∲",
  "DDotrahd;": "⤑",
  "doteqdot;": "≑",
  "DotEqual;": "≐",
  "dotminus;": "∸",
  "drbkarow;": "⤐",
  "dzigrarr;": "⟿",
  "elinters;": "⏧",
  "emptyset;": "∅",
  "eqvparsl;": "⧥",
  "fpartint;": "⨍",
  "geqslant;": "⩾",
  "gesdotol;": "⪄",
  "gnapprox;": "⪊",
  "hksearow;": "⤥",
  "hkswarow;": "⤦",
  "imagline;": "ℐ",
  "imagpart;": "ℑ",
  "infintie;": "⧝",
  "integers;": "ℤ",
  "Integral;": "∫",
  "intercal;": "⊺",
  "intlarhk;": "⨗",
  "laemptyv;": "⦴",
  "ldrushar;": "⥋",
  "leqslant;": "⩽",
  "lesdotor;": "⪃",
  "LessLess;": "⪡",
  "llcorner;": "⌞",
  "lnapprox;": "⪉",
  "lrcorner;": "⌟",
  "lurdshar;": "⥊",
  "mapstoup;": "↥",
  "multimap;": "⊸",
  "naturals;": "ℕ",
  "ncongdot;": "⩭̸",
  "NotEqual;": "≠",
  "notindot;": "⋵̸",
  "NotTilde;": "≁",
  "otimesas;": "⨶",
  "parallel;": "∥",
  "PartialD;": "∂",
  "plusacir;": "⨣",
  "pointint;": "⨕",
  "Precedes;": "≺",
  "precneqq;": "⪵",
  "precnsim;": "⋨",
  "profalar;": "⌮",
  "profline;": "⌒",
  "profsurf;": "⌓",
  "raemptyv;": "⦳",
  "realpart;": "ℜ",
  "RightTee;": "⊢",
  "rppolint;": "⨒",
  "rtriltri;": "⧎",
  "scpolint;": "⨓",
  "setminus;": "∖",
  "shortmid;": "∣",
  "smeparsl;": "⧤",
  "sqsubset;": "⊏",
  "sqsupset;": "⊐",
  "subseteq;": "⊆",
  "Succeeds;": "≻",
  "succneqq;": "⪶",
  "succnsim;": "⋩",
  "SuchThat;": "∋",
  "Superset;": "⊃",
  "supseteq;": "⊇",
  "thetasym;": "ϑ",
  "thicksim;": "∼",
  "timesbar;": "⨱",
  "triangle;": "▵",
  "triminus;": "⨺",
  "trpezium;": "⏢",
  "Uarrocir;": "⥉",
  "ulcorner;": "⌜",
  "UnderBar;": "_",
  "urcorner;": "⌝",
  "varkappa;": "ϰ",
  "varsigma;": "ς",
  "vartheta;": "ϑ",
  "backprime;": "‵",
  "backsimeq;": "⋍",
  "Backslash;": "∖",
  "bigotimes;": "⨂",
  "CenterDot;": "·",
  "centerdot;": "·",
  "checkmark;": "✓",
  "CircleDot;": "⊙",
  "complexes;": "ℂ",
  "Congruent;": "≡",
  "Coproduct;": "∐",
  "dotsquare;": "⊡",
  "DoubleDot;": "¨",
  "DownArrow;": "↓",
  "Downarrow;": "⇓",
  "downarrow;": "↓",
  "DownBreve;": "̑",
  "gtrapprox;": "⪆",
  "gtreqless;": "⋛",
  "gvertneqq;": "≩︀",
  "heartsuit;": "♥",
  "HumpEqual;": "≏",
  "LeftArrow;": "←",
  "Leftarrow;": "⇐",
  "leftarrow;": "←",
  "LeftFloor;": "⌊",
  "lesseqgtr;": "⋚",
  "LessTilde;": "≲",
  "lvertneqq;": "≨︀",
  "Mellintrf;": "ℳ",
  "MinusPlus;": "∓",
  "ngeqslant;": "⩾̸",
  "nleqslant;": "⩽̸",
  "NotCupCap;": "≭",
  "NotExists;": "∄",
  "NotSubset;": "⊂⃒",
  "nparallel;": "∦",
  "nshortmid;": "∤",
  "nsubseteq;": "⊈",
  "nsupseteq;": "⊉",
  "OverBrace;": "⏞",
  "pitchfork;": "⋔",
  "PlusMinus;": "±",
  "rationals;": "ℚ",
  "spadesuit;": "♠",
  "subseteqq;": "⫅",
  "subsetneq;": "⊊",
  "supseteqq;": "⫆",
  "supsetneq;": "⊋",
  "Therefore;": "∴",
  "therefore;": "∴",
  "ThinSpace;": " ",
  "triangleq;": "≜",
  "TripleDot;": "⃛",
  "UnionPlus;": "⊎",
  "varpropto;": "∝",
  "Bernoullis;": "ℬ",
  "circledast;": "⊛",
  "CirclePlus;": "⊕",
  "complement;": "∁",
  "curlywedge;": "⋏",
  "eqslantgtr;": "⪖",
  "EqualTilde;": "≂",
  "Fouriertrf;": "ℱ",
  "gtreqqless;": "⪌",
  "ImaginaryI;": "ⅈ",
  "Laplacetrf;": "ℒ",
  "LeftVector;": "↼",
  "lessapprox;": "⪅",
  "lesseqqgtr;": "⪋",
  "Lleftarrow;": "⇚",
  "lmoustache;": "⎰",
  "longmapsto;": "⟼",
  "mapstodown;": "↧",
  "mapstoleft;": "↤",
  "nLeftarrow;": "⇍",
  "nleftarrow;": "↚",
  "NotElement;": "∉",
  "NotGreater;": "≯",
  "nsubseteqq;": "⫅̸",
  "nsupseteqq;": "⫆̸",
  "precapprox;": "⪷",
  "Proportion;": "∷",
  "RightArrow;": "→",
  "Rightarrow;": "⇒",
  "rightarrow;": "→",
  "RightFloor;": "⌋",
  "rmoustache;": "⎱",
  "sqsubseteq;": "⊑",
  "sqsupseteq;": "⊒",
  "subsetneqq;": "⫋",
  "succapprox;": "⪸",
  "supsetneqq;": "⫌",
  "ThickSpace;": "  ",
  "TildeEqual;": "≃",
  "TildeTilde;": "≈",
  "UnderBrace;": "⏟",
  "UpArrowBar;": "⤒",
  "UpTeeArrow;": "↥",
  "upuparrows;": "⇈",
  "varepsilon;": "ϵ",
  "varnothing;": "∅",
  "backepsilon;": "϶",
  "blacksquare;": "▪",
  "circledcirc;": "⊚",
  "circleddash;": "⊝",
  "CircleMinus;": "⊖",
  "CircleTimes;": "⊗",
  "curlyeqprec;": "⋞",
  "curlyeqsucc;": "⋟",
  "diamondsuit;": "♦",
  "eqslantless;": "⪕",
  "Equilibrium;": "⇌",
  "expectation;": "ℰ",
  "GreaterLess;": "≷",
  "LeftCeiling;": "⌈",
  "LessGreater;": "≶",
  "MediumSpace;": " ",
  "NotLessLess;": "≪̸",
  "NotPrecedes;": "⊀",
  "NotSucceeds;": "⊁",
  "NotSuperset;": "⊃⃒",
  "nRightarrow;": "⇏",
  "nrightarrow;": "↛",
  "OverBracket;": "⎴",
  "preccurlyeq;": "≼",
  "precnapprox;": "⪹",
  "quaternions;": "ℍ",
  "RightVector;": "⇀",
  "Rrightarrow;": "⇛",
  "RuleDelayed;": "⧴",
  "SmallCircle;": "∘",
  "SquareUnion;": "⊔",
  "straightphi;": "ϕ",
  "SubsetEqual;": "⊆",
  "succcurlyeq;": "≽",
  "succnapprox;": "⪺",
  "thickapprox;": "≈",
  "UpDownArrow;": "↕",
  "Updownarrow;": "⇕",
  "updownarrow;": "↕",
  "VerticalBar;": "∣",
  "blacklozenge;": "⧫",
  "DownArrowBar;": "⤓",
  "DownTeeArrow;": "↧",
  "ExponentialE;": "ⅇ",
  "exponentiale;": "ⅇ",
  "GreaterEqual;": "≥",
  "GreaterTilde;": "≳",
  "HilbertSpace;": "ℋ",
  "HumpDownHump;": "≎",
  "Intersection;": "⋂",
  "LeftArrowBar;": "⇤",
  "LeftTeeArrow;": "↤",
  "LeftTriangle;": "⊲",
  "LeftUpVector;": "↿",
  "NotCongruent;": "≢",
  "NotHumpEqual;": "≏̸",
  "NotLessEqual;": "≰",
  "NotLessTilde;": "≴",
  "Proportional;": "∝",
  "RightCeiling;": "⌉",
  "risingdotseq;": "≓",
  "RoundImplies;": "⥰",
  "ShortUpArrow;": "↑",
  "SquareSubset;": "⊏",
  "triangledown;": "▿",
  "triangleleft;": "◃",
  "UnderBracket;": "⎵",
  "varsubsetneq;": "⊊︀",
  "varsupsetneq;": "⊋︀",
  "VerticalLine;": "|",
  "ApplyFunction;": "⁡",
  "bigtriangleup;": "△",
  "blacktriangle;": "▴",
  "DifferentialD;": "ⅆ",
  "divideontimes;": "⋇",
  "DoubleLeftTee;": "⫤",
  "DoubleUpArrow;": "⇑",
  "fallingdotseq;": "≒",
  "hookleftarrow;": "↩",
  "leftarrowtail;": "↢",
  "leftharpoonup;": "↼",
  "LeftTeeVector;": "⥚",
  "LeftVectorBar;": "⥒",
  "LessFullEqual;": "≦",
  "LongLeftArrow;": "⟵",
  "Longleftarrow;": "⟸",
  "longleftarrow;": "⟵",
  "looparrowleft;": "↫",
  "measuredangle;": "∡",
  "NotEqualTilde;": "≂̸",
  "NotTildeEqual;": "≄",
  "NotTildeTilde;": "≉",
  "ntriangleleft;": "⋪",
  "Poincareplane;": "ℌ",
  "PrecedesEqual;": "⪯",
  "PrecedesTilde;": "≾",
  "RightArrowBar;": "⇥",
  "RightTeeArrow;": "↦",
  "RightTriangle;": "⊳",
  "RightUpVector;": "↾",
  "shortparallel;": "∥",
  "smallsetminus;": "∖",
  "SucceedsEqual;": "⪰",
  "SucceedsTilde;": "≿",
  "SupersetEqual;": "⊇",
  "triangleright;": "▹",
  "UpEquilibrium;": "⥮",
  "upharpoonleft;": "↿",
  "varsubsetneqq;": "⫋︀",
  "varsupsetneqq;": "⫌︀",
  "VerticalTilde;": "≀",
  "VeryThinSpace;": " ",
  "curvearrowleft;": "↶",
  "DiacriticalDot;": "˙",
  "doublebarwedge;": "⌆",
  "DoubleRightTee;": "⊨",
  "downdownarrows;": "⇊",
  "DownLeftVector;": "↽",
  "GreaterGreater;": "⪢",
  "hookrightarrow;": "↪",
  "HorizontalLine;": "─",
  "InvisibleComma;": "⁣",
  "InvisibleTimes;": "⁢",
  "LeftDownVector;": "⇃",
  "leftleftarrows;": "⇇",
  "LeftRightArrow;": "↔",
  "Leftrightarrow;": "⇔",
  "leftrightarrow;": "↔",
  "leftthreetimes;": "⋋",
  "LessSlantEqual;": "⩽",
  "LongRightArrow;": "⟶",
  "Longrightarrow;": "⟹",
  "longrightarrow;": "⟶",
  "looparrowright;": "↬",
  "LowerLeftArrow;": "↙",
  "NestedLessLess;": "≪",
  "NotGreaterLess;": "≹",
  "NotLessGreater;": "≸",
  "NotSubsetEqual;": "⊈",
  "NotVerticalBar;": "∤",
  "nshortparallel;": "∦",
  "ntriangleright;": "⋫",
  "OpenCurlyQuote;": "‘",
  "ReverseElement;": "∋",
  "rightarrowtail;": "↣",
  "rightharpoonup;": "⇀",
  "RightTeeVector;": "⥛",
  "RightVectorBar;": "⥓",
  "ShortDownArrow;": "↓",
  "ShortLeftArrow;": "←",
  "SquareSuperset;": "⊐",
  "TildeFullEqual;": "≅",
  "trianglelefteq;": "⊴",
  "upharpoonright;": "↾",
  "UpperLeftArrow;": "↖",
  "ZeroWidthSpace;": "​",
  "bigtriangledown;": "▽",
  "circlearrowleft;": "↺",
  "CloseCurlyQuote;": "’",
  "ContourIntegral;": "∮",
  "curvearrowright;": "↷",
  "DoubleDownArrow;": "⇓",
  "DoubleLeftArrow;": "⇐",
  "downharpoonleft;": "⇃",
  "DownRightVector;": "⇁",
  "leftharpoondown;": "↽",
  "leftrightarrows;": "⇆",
  "LeftRightVector;": "⥎",
  "LeftTriangleBar;": "⧏",
  "LeftUpTeeVector;": "⥠",
  "LeftUpVectorBar;": "⥘",
  "LowerRightArrow;": "↘",
  "nLeftrightarrow;": "⇎",
  "nleftrightarrow;": "↮",
  "NotGreaterEqual;": "≱",
  "NotGreaterTilde;": "≵",
  "NotHumpDownHump;": "≎̸",
  "NotLeftTriangle;": "⋪",
  "NotSquareSubset;": "⊏̸",
  "ntrianglelefteq;": "⋬",
  "OverParenthesis;": "⏜",
  "RightDownVector;": "⇂",
  "rightleftarrows;": "⇄",
  "rightsquigarrow;": "↝",
  "rightthreetimes;": "⋌",
  "ShortRightArrow;": "→",
  "straightepsilon;": "ϵ",
  "trianglerighteq;": "⊵",
  "UpperRightArrow;": "↗",
  "vartriangleleft;": "⊲",
  "circlearrowright;": "↻",
  "DiacriticalAcute;": "´",
  "DiacriticalGrave;": "`",
  "DiacriticalTilde;": "˜",
  "DoubleRightArrow;": "⇒",
  "DownArrowUpArrow;": "⇵",
  "downharpoonright;": "⇂",
  "EmptySmallSquare;": "◻",
  "GreaterEqualLess;": "⋛",
  "GreaterFullEqual;": "≧",
  "LeftAngleBracket;": "⟨",
  "LeftUpDownVector;": "⥑",
  "LessEqualGreater;": "⋚",
  "NonBreakingSpace;": " ",
  "NotPrecedesEqual;": "⪯̸",
  "NotRightTriangle;": "⋫",
  "NotSucceedsEqual;": "⪰̸",
  "NotSucceedsTilde;": "≿̸",
  "NotSupersetEqual;": "⊉",
  "ntrianglerighteq;": "⋭",
  "rightharpoondown;": "⇁",
  "rightrightarrows;": "⇉",
  "RightTriangleBar;": "⧐",
  "RightUpTeeVector;": "⥜",
  "RightUpVectorBar;": "⥔",
  "twoheadleftarrow;": "↞",
  "UnderParenthesis;": "⏝",
  "UpArrowDownArrow;": "⇅",
  "vartriangleright;": "⊳",
  "blacktriangledown;": "▾",
  "blacktriangleleft;": "◂",
  "DoubleUpDownArrow;": "⇕",
  "DoubleVerticalBar;": "∥",
  "DownLeftTeeVector;": "⥞",
  "DownLeftVectorBar;": "⥖",
  "FilledSmallSquare;": "◼",
  "GreaterSlantEqual;": "⩾",
  "LeftDoubleBracket;": "⟦",
  "LeftDownTeeVector;": "⥡",
  "LeftDownVectorBar;": "⥙",
  "leftrightharpoons;": "⇋",
  "LeftTriangleEqual;": "⊴",
  "NegativeThinSpace;": "​",
  "NotGreaterGreater;": "≫̸",
  "NotLessSlantEqual;": "⩽̸",
  "NotNestedLessLess;": "⪡̸",
  "NotReverseElement;": "∌",
  "NotSquareSuperset;": "⊐̸",
  "NotTildeFullEqual;": "≇",
  "RightAngleBracket;": "⟩",
  "rightleftharpoons;": "⇌",
  "RightUpDownVector;": "⥏",
  "SquareSubsetEqual;": "⊑",
  "twoheadrightarrow;": "↠",
  "VerticalSeparator;": "❘",
  "blacktriangleright;": "▸",
  "DownRightTeeVector;": "⥟",
  "DownRightVectorBar;": "⥗",
  "LongLeftRightArrow;": "⟷",
  "Longleftrightarrow;": "⟺",
  "longleftrightarrow;": "⟷",
  "NegativeThickSpace;": "​",
  "NotLeftTriangleBar;": "⧏̸",
  "PrecedesSlantEqual;": "≼",
  "ReverseEquilibrium;": "⇋",
  "RightDoubleBracket;": "⟧",
  "RightDownTeeVector;": "⥝",
  "RightDownVectorBar;": "⥕",
  "RightTriangleEqual;": "⊵",
  "SquareIntersection;": "⊓",
  "SucceedsSlantEqual;": "≽",
  "DoubleLongLeftArrow;": "⟸",
  "DownLeftRightVector;": "⥐",
  "LeftArrowRightArrow;": "⇆",
  "leftrightsquigarrow;": "↭",
  "NegativeMediumSpace;": "​",
  "NotGreaterFullEqual;": "≧̸",
  "NotRightTriangleBar;": "⧐̸",
  "RightArrowLeftArrow;": "⇄",
  "SquareSupersetEqual;": "⊒",
  "CapitalDifferentialD;": "ⅅ",
  "DoubleLeftRightArrow;": "⇔",
  "DoubleLongRightArrow;": "⟹",
  "EmptyVerySmallSquare;": "▫",
  "NestedGreaterGreater;": "≫",
  "NotDoubleVerticalBar;": "∦",
  "NotGreaterSlantEqual;": "⩾̸",
  "NotLeftTriangleEqual;": "⋬",
  "NotSquareSubsetEqual;": "⋢",
  "OpenCurlyDoubleQuote;": "“",
  "ReverseUpEquilibrium;": "⥯",
  "CloseCurlyDoubleQuote;": "”",
  "DoubleContourIntegral;": "∯",
  "FilledVerySmallSquare;": "▪",
  "NegativeVeryThinSpace;": "​",
  "NotPrecedesSlantEqual;": "⋠",
  "NotRightTriangleEqual;": "⋭",
  "NotSucceedsSlantEqual;": "⋡",
  "DiacriticalDoubleAcute;": "˝",
  "NotSquareSupersetEqual;": "⋣",
  "NotNestedGreaterGreater;": "⪢̸",
  "ClockwiseContourIntegral;": "∲",
  "DoubleLongLeftRightArrow;": "⟺",
  "CounterClockwiseContourIntegral;": "∳"
};
let maxCRNameLength;
const decodeHtml = (rawText, asAttr) => {
  let offset = 0;
  const end = rawText.length;
  let decodedText = "";
  function advance(length2) {
    offset += length2;
    rawText = rawText.slice(length2);
  }
  while (offset < end) {
    const head = /&(?:#x?)?/i.exec(rawText);
    if (!head || offset + head.index >= end) {
      const remaining = end - offset;
      decodedText += rawText.slice(0, remaining);
      advance(remaining);
      break;
    }
    decodedText += rawText.slice(0, head.index);
    advance(head.index);
    if (head[0] === "&") {
      let name = "";
      let value = void 0;
      if (/[0-9a-z]/i.test(rawText[1])) {
        if (!maxCRNameLength) {
          maxCRNameLength = Object.keys(namedCharacterReferences).reduce(
            (max, name2) => Math.max(max, name2.length),
            0
          );
        }
        for (let length2 = maxCRNameLength; !value && length2 > 0; --length2) {
          name = rawText.slice(1, 1 + length2);
          value = namedCharacterReferences[name];
        }
        if (value) {
          const semi = name.endsWith(";");
          if (asAttr && !semi && /[=a-z0-9]/i.test(rawText[name.length + 1] || "")) {
            decodedText += "&" + name;
            advance(1 + name.length);
          } else {
            decodedText += value;
            advance(1 + name.length);
          }
        } else {
          decodedText += "&" + name;
          advance(1 + name.length);
        }
      } else {
        decodedText += "&";
        advance(1);
      }
    } else {
      const hex = head[0] === "&#x";
      const pattern = hex ? /^&#x([0-9a-f]+);?/i : /^&#([0-9]+);?/;
      const body = pattern.exec(rawText);
      if (!body) {
        decodedText += head[0];
        advance(head[0].length);
      } else {
        let cp = Number.parseInt(body[1], hex ? 16 : 10);
        if (cp === 0) {
          cp = 65533;
        } else if (cp > 1114111) {
          cp = 65533;
        } else if (cp >= 55296 && cp <= 57343) {
          cp = 65533;
        } else if (cp >= 64976 && cp <= 65007 || (cp & 65534) === 65534)
          ;
        else if (cp >= 1 && cp <= 8 || cp === 11 || cp >= 13 && cp <= 31 || cp >= 127 && cp <= 159) {
          cp = CCR_REPLACEMENTS[cp] || cp;
        }
        decodedText += String.fromCodePoint(cp);
        advance(body[0].length);
      }
    }
  }
  return decodedText;
};
const CCR_REPLACEMENTS = {
  128: 8364,
  130: 8218,
  131: 402,
  132: 8222,
  133: 8230,
  134: 8224,
  135: 8225,
  136: 710,
  137: 8240,
  138: 352,
  139: 8249,
  140: 338,
  142: 381,
  145: 8216,
  146: 8217,
  147: 8220,
  148: 8221,
  149: 8226,
  150: 8211,
  151: 8212,
  152: 732,
  153: 8482,
  154: 353,
  155: 8250,
  156: 339,
  158: 382,
  159: 376
};
const isRawTextContainer = /* @__PURE__ */ makeMap(
  "style,iframe,script,noscript",
  true
);
const parserOptions = {
  isVoidTag,
  isNativeTag: (tag3) => isHTMLTag(tag3) || isSVGTag(tag3),
  isPreTag: (tag3) => tag3 === "pre",
  decodeEntities: decodeHtml,
  isBuiltInComponent: (tag3) => {
    if (isBuiltInType(tag3, `Transition`)) {
      return TRANSITION;
    } else if (isBuiltInType(tag3, `TransitionGroup`)) {
      return TRANSITION_GROUP;
    }
  },
  // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
  getNamespace(tag3, parent) {
    let ns = parent ? parent.ns : 0;
    if (parent && ns === 2) {
      if (parent.tag === "annotation-xml") {
        if (tag3 === "svg") {
          return 1;
        }
        if (parent.props.some(
          (a) => a.type === 6 && a.name === "encoding" && a.value != null && (a.value.content === "text/html" || a.value.content === "application/xhtml+xml")
        )) {
          ns = 0;
        }
      } else if (/^m(?:[ions]|text)$/.test(parent.tag) && tag3 !== "mglyph" && tag3 !== "malignmark") {
        ns = 0;
      }
    } else if (parent && ns === 1) {
      if (parent.tag === "foreignObject" || parent.tag === "desc" || parent.tag === "title") {
        ns = 0;
      }
    }
    if (ns === 0) {
      if (tag3 === "svg") {
        return 1;
      }
      if (tag3 === "math") {
        return 2;
      }
    }
    return ns;
  },
  // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
  getTextMode({ tag: tag3, ns }) {
    if (ns === 0) {
      if (tag3 === "textarea" || tag3 === "title") {
        return 1;
      }
      if (isRawTextContainer(tag3)) {
        return 2;
      }
    }
    return 0;
  }
};
const transformStyle = (node2) => {
  if (node2.type === 1) {
    node2.props.forEach((p2, i) => {
      if (p2.type === 6 && p2.name === "style" && p2.value) {
        node2.props[i] = {
          type: 7,
          name: `bind`,
          arg: createSimpleExpression(`style`, true, p2.loc),
          exp: parseInlineCSS(p2.value.content, p2.loc),
          modifiers: [],
          loc: p2.loc
        };
      }
    });
  }
};
const parseInlineCSS = (cssText, loc) => {
  const normalized = parseStringStyle(cssText);
  return createSimpleExpression(
    JSON.stringify(normalized),
    false,
    loc,
    3
  );
};
function createDOMCompilerError(code, loc) {
  return createCompilerError(
    code,
    loc,
    DOMErrorMessages
  );
}
const DOMErrorMessages = {
  [53]: `v-html is missing expression.`,
  [54]: `v-html will override element children.`,
  [55]: `v-text is missing expression.`,
  [56]: `v-text will override element children.`,
  [57]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
  [58]: `v-model argument is not supported on plain elements.`,
  [59]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`,
  [60]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
  [61]: `v-show is missing expression.`,
  [62]: `<Transition> expects exactly one child element or component.`,
  [63]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
};
const transformVHtml = (dir, node2, context) => {
  const { exp, loc } = dir;
  if (!exp) {
    context.onError(
      createDOMCompilerError(53, loc)
    );
  }
  if (node2.children.length) {
    context.onError(
      createDOMCompilerError(54, loc)
    );
    node2.children.length = 0;
  }
  return {
    props: [
      createObjectProperty(
        createSimpleExpression(`innerHTML`, true, loc),
        exp || createSimpleExpression("", true)
      )
    ]
  };
};
const transformVText = (dir, node2, context) => {
  const { exp, loc } = dir;
  if (!exp) {
    context.onError(
      createDOMCompilerError(55, loc)
    );
  }
  if (node2.children.length) {
    context.onError(
      createDOMCompilerError(56, loc)
    );
    node2.children.length = 0;
  }
  return {
    props: [
      createObjectProperty(
        createSimpleExpression(`textContent`, true),
        exp ? getConstantType(exp, context) > 0 ? exp : createCallExpression(
          context.helperString(TO_DISPLAY_STRING),
          [exp],
          loc
        ) : createSimpleExpression("", true)
      )
    ]
  };
};
const transformModel = (dir, node2, context) => {
  const baseResult = transformModel$1(dir, node2, context);
  if (!baseResult.props.length || node2.tagType === 1) {
    return baseResult;
  }
  if (dir.arg) {
    context.onError(
      createDOMCompilerError(
        58,
        dir.arg.loc
      )
    );
  }
  function checkDuplicatedValue() {
    const value = findProp(node2, "value");
    if (value) {
      context.onError(
        createDOMCompilerError(
          60,
          value.loc
        )
      );
    }
  }
  const { tag: tag3 } = node2;
  const isCustomElement = context.isCustomElement(tag3);
  if (tag3 === "input" || tag3 === "textarea" || tag3 === "select" || isCustomElement) {
    let directiveToUse = V_MODEL_TEXT;
    let isInvalidType = false;
    if (tag3 === "input" || isCustomElement) {
      const type = findProp(node2, `type`);
      if (type) {
        if (type.type === 7) {
          directiveToUse = V_MODEL_DYNAMIC;
        } else if (type.value) {
          switch (type.value.content) {
            case "radio":
              directiveToUse = V_MODEL_RADIO;
              break;
            case "checkbox":
              directiveToUse = V_MODEL_CHECKBOX;
              break;
            case "file":
              isInvalidType = true;
              context.onError(
                createDOMCompilerError(
                  59,
                  dir.loc
                )
              );
              break;
            default:
              checkDuplicatedValue();
              break;
          }
        }
      } else if (hasDynamicKeyVBind(node2)) {
        directiveToUse = V_MODEL_DYNAMIC;
      } else {
        checkDuplicatedValue();
      }
    } else if (tag3 === "select") {
      directiveToUse = V_MODEL_SELECT;
    } else {
      checkDuplicatedValue();
    }
    if (!isInvalidType) {
      baseResult.needRuntime = context.helper(directiveToUse);
    }
  } else {
    context.onError(
      createDOMCompilerError(
        57,
        dir.loc
      )
    );
  }
  baseResult.props = baseResult.props.filter(
    (p2) => !(p2.key.type === 4 && p2.key.content === "modelValue")
  );
  return baseResult;
};
const isEventOptionModifier = /* @__PURE__ */ makeMap(`passive,once,capture`);
const isNonKeyModifier = /* @__PURE__ */ makeMap(
  // event propagation management
  `stop,prevent,self,ctrl,shift,alt,meta,exact,middle`
);
const maybeKeyModifier = /* @__PURE__ */ makeMap("left,right");
const isKeyboardEvent = /* @__PURE__ */ makeMap(
  `onkeyup,onkeydown,onkeypress`,
  true
);
const resolveModifiers = (key, modifiers, context, loc) => {
  const keyModifiers = [];
  const nonKeyModifiers = [];
  const eventOptionModifiers = [];
  for (let i = 0; i < modifiers.length; i++) {
    const modifier = modifiers[i];
    if (isEventOptionModifier(modifier)) {
      eventOptionModifiers.push(modifier);
    } else {
      if (maybeKeyModifier(modifier)) {
        if (isStaticExp(key)) {
          if (isKeyboardEvent(key.content)) {
            keyModifiers.push(modifier);
          } else {
            nonKeyModifiers.push(modifier);
          }
        } else {
          keyModifiers.push(modifier);
          nonKeyModifiers.push(modifier);
        }
      } else {
        if (isNonKeyModifier(modifier)) {
          nonKeyModifiers.push(modifier);
        } else {
          keyModifiers.push(modifier);
        }
      }
    }
  }
  return {
    keyModifiers,
    nonKeyModifiers,
    eventOptionModifiers
  };
};
const transformClick = (key, event) => {
  const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === "onclick";
  return isStaticClick ? createSimpleExpression(event, true) : key.type !== 4 ? createCompoundExpression([
    `(`,
    key,
    `) === "onClick" ? "${event}" : (`,
    key,
    `)`
  ]) : key;
};
const transformOn = (dir, node2, context) => {
  return transformOn$1(dir, node2, context, (baseResult) => {
    const { modifiers } = dir;
    if (!modifiers.length)
      return baseResult;
    let { key, value: handlerExp } = baseResult.props[0];
    const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
    if (nonKeyModifiers.includes("right")) {
      key = transformClick(key, `onContextmenu`);
    }
    if (nonKeyModifiers.includes("middle")) {
      key = transformClick(key, `onMouseup`);
    }
    if (nonKeyModifiers.length) {
      handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
        handlerExp,
        JSON.stringify(nonKeyModifiers)
      ]);
    }
    if (keyModifiers.length && // if event name is dynamic, always wrap with keys guard
    (!isStaticExp(key) || isKeyboardEvent(key.content))) {
      handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
        handlerExp,
        JSON.stringify(keyModifiers)
      ]);
    }
    if (eventOptionModifiers.length) {
      const modifierPostfix = eventOptionModifiers.map(capitalize$1).join("");
      key = isStaticExp(key) ? createSimpleExpression(`${key.content}${modifierPostfix}`, true) : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
    }
    return {
      props: [createObjectProperty(key, handlerExp)]
    };
  });
};
const transformShow = (dir, node2, context) => {
  const { exp, loc } = dir;
  if (!exp) {
    context.onError(
      createDOMCompilerError(61, loc)
    );
  }
  return {
    props: [],
    needRuntime: context.helper(V_SHOW)
  };
};
const transformTransition = (node2, context) => {
  if (node2.type === 1 && node2.tagType === 1) {
    const component = context.isBuiltInComponent(node2.tag);
    if (component === TRANSITION) {
      return () => {
        if (!node2.children.length) {
          return;
        }
        if (hasMultipleChildren(node2)) {
          context.onError(
            createDOMCompilerError(
              62,
              {
                start: node2.children[0].loc.start,
                end: node2.children[node2.children.length - 1].loc.end,
                source: ""
              }
            )
          );
        }
        const child = node2.children[0];
        if (child.type === 1) {
          for (const p2 of child.props) {
            if (p2.type === 7 && p2.name === "show") {
              node2.props.push({
                type: 6,
                name: "persisted",
                value: void 0,
                loc: node2.loc
              });
            }
          }
        }
      };
    }
  }
};
function hasMultipleChildren(node2) {
  const children = node2.children = node2.children.filter(
    (c) => c.type !== 3 && !(c.type === 2 && !c.content.trim())
  );
  const child = children[0];
  return children.length !== 1 || child.type === 11 || child.type === 9 && child.branches.some(hasMultipleChildren);
}
const expReplaceRE = /__VUE_EXP_START__(.*?)__VUE_EXP_END__/g;
const stringifyStatic = (children, context, parent) => {
  if (context.scopes.vSlot > 0) {
    return;
  }
  let nc = 0;
  let ec = 0;
  const currentChunk = [];
  const stringifyCurrentChunk = (currentIndex) => {
    if (nc >= 20 || ec >= 5) {
      const staticCall = createCallExpression(context.helper(CREATE_STATIC), [
        JSON.stringify(
          currentChunk.map((node2) => stringifyNode(node2, context)).join("")
        ).replace(expReplaceRE, `" + $1 + "`),
        // the 2nd argument indicates the number of DOM nodes this static vnode
        // will insert / hydrate
        String(currentChunk.length)
      ]);
      replaceHoist(currentChunk[0], staticCall, context);
      if (currentChunk.length > 1) {
        for (let i2 = 1; i2 < currentChunk.length; i2++) {
          replaceHoist(currentChunk[i2], null, context);
        }
        const deleteCount = currentChunk.length - 1;
        children.splice(currentIndex - currentChunk.length + 1, deleteCount);
        return deleteCount;
      }
    }
    return 0;
  };
  let i = 0;
  for (; i < children.length; i++) {
    const child = children[i];
    const hoisted = getHoistedNode(child);
    if (hoisted) {
      const node2 = child;
      const result2 = analyzeNode(node2);
      if (result2) {
        nc += result2[0];
        ec += result2[1];
        currentChunk.push(node2);
        continue;
      }
    }
    i -= stringifyCurrentChunk(i);
    nc = 0;
    ec = 0;
    currentChunk.length = 0;
  }
  stringifyCurrentChunk(i);
};
const getHoistedNode = (node2) => (node2.type === 1 && node2.tagType === 0 || node2.type == 12) && node2.codegenNode && node2.codegenNode.type === 4 && node2.codegenNode.hoisted;
const dataAriaRE = /^(data|aria)-/;
const isStringifiableAttr = (name, ns) => {
  return (ns === 0 ? isKnownHtmlAttr(name) : ns === 1 ? isKnownSvgAttr(name) : false) || dataAriaRE.test(name);
};
const replaceHoist = (node2, replacement, context) => {
  const hoistToReplace = node2.codegenNode.hoisted;
  context.hoists[context.hoists.indexOf(hoistToReplace)] = replacement;
};
const isNonStringifiable = /* @__PURE__ */ makeMap(
  `caption,thead,tr,th,tbody,td,tfoot,colgroup,col`
);
function analyzeNode(node2) {
  if (node2.type === 1 && isNonStringifiable(node2.tag)) {
    return false;
  }
  if (node2.type === 12) {
    return [1, 0];
  }
  let nc = 1;
  let ec = node2.props.length > 0 ? 1 : 0;
  let bailed = false;
  const bail = () => {
    bailed = true;
    return false;
  };
  function walk2(node22) {
    for (let i = 0; i < node22.props.length; i++) {
      const p2 = node22.props[i];
      if (p2.type === 6 && !isStringifiableAttr(p2.name, node22.ns)) {
        return bail();
      }
      if (p2.type === 7 && p2.name === "bind") {
        if (p2.arg && (p2.arg.type === 8 || p2.arg.isStatic && !isStringifiableAttr(p2.arg.content, node22.ns))) {
          return bail();
        }
        if (p2.exp && (p2.exp.type === 8 || p2.exp.constType < 3)) {
          return bail();
        }
      }
    }
    for (let i = 0; i < node22.children.length; i++) {
      nc++;
      const child = node22.children[i];
      if (child.type === 1) {
        if (child.props.length > 0) {
          ec++;
        }
        walk2(child);
        if (bailed) {
          return false;
        }
      }
    }
    return true;
  }
  return walk2(node2) ? [nc, ec] : false;
}
function stringifyNode(node2, context) {
  if (isString$2(node2)) {
    return node2;
  }
  if (isSymbol$1(node2)) {
    return ``;
  }
  switch (node2.type) {
    case 1:
      return stringifyElement(node2, context);
    case 2:
      return escapeHtml(node2.content);
    case 3:
      return `<!--${escapeHtml(node2.content)}-->`;
    case 5:
      return escapeHtml(toDisplayString(evaluateConstant(node2.content)));
    case 8:
      return escapeHtml(evaluateConstant(node2));
    case 12:
      return stringifyNode(node2.content, context);
    default:
      return "";
  }
}
function stringifyElement(node2, context) {
  let res = `<${node2.tag}`;
  let innerHTML = "";
  for (let i = 0; i < node2.props.length; i++) {
    const p2 = node2.props[i];
    if (p2.type === 6) {
      res += ` ${p2.name}`;
      if (p2.value) {
        res += `="${escapeHtml(p2.value.content)}"`;
      }
    } else if (p2.type === 7) {
      if (p2.name === "bind") {
        const exp = p2.exp;
        if (exp.content[0] === "_") {
          res += ` ${p2.arg.content}="__VUE_EXP_START__${exp.content}__VUE_EXP_END__"`;
          continue;
        }
        if (isBooleanAttr(p2.arg.content) && exp.content === "false") {
          continue;
        }
        let evaluated = evaluateConstant(exp);
        if (evaluated != null) {
          const arg = p2.arg && p2.arg.content;
          if (arg === "class") {
            evaluated = normalizeClass(evaluated);
          } else if (arg === "style") {
            evaluated = stringifyStyle(normalizeStyle(evaluated));
          }
          res += ` ${p2.arg.content}="${escapeHtml(
            evaluated
          )}"`;
        }
      } else if (p2.name === "html") {
        innerHTML = evaluateConstant(p2.exp);
      } else if (p2.name === "text") {
        innerHTML = escapeHtml(
          toDisplayString(evaluateConstant(p2.exp))
        );
      }
    }
  }
  if (context.scopeId) {
    res += ` ${context.scopeId}`;
  }
  res += `>`;
  if (innerHTML) {
    res += innerHTML;
  } else {
    for (let i = 0; i < node2.children.length; i++) {
      res += stringifyNode(node2.children[i], context);
    }
  }
  if (!isVoidTag(node2.tag)) {
    res += `</${node2.tag}>`;
  }
  return res;
}
function evaluateConstant(exp) {
  if (exp.type === 4) {
    return new Function(`return (${exp.content})`)();
  } else {
    let res = ``;
    exp.children.forEach((c) => {
      if (isString$2(c) || isSymbol$1(c)) {
        return;
      }
      if (c.type === 2) {
        res += c.content;
      } else if (c.type === 5) {
        res += toDisplayString(evaluateConstant(c.content));
      } else {
        res += evaluateConstant(c);
      }
    });
    return res;
  }
}
const ignoreSideEffectTags = (node2, context) => {
  if (node2.type === 1 && node2.tagType === 0 && (node2.tag === "script" || node2.tag === "style")) {
    context.onError(
      createDOMCompilerError(
        63,
        node2.loc
      )
    );
    context.removeNode();
  }
};
const DOMNodeTransforms = [
  transformStyle,
  ...[transformTransition]
];
const DOMDirectiveTransforms = {
  cloak: noopDirectiveTransform,
  html: transformVHtml,
  text: transformVText,
  model: transformModel,
  // override compiler-core
  on: transformOn,
  // override compiler-core
  show: transformShow
};
function compile$1(template, options = {}) {
  return baseCompile(
    template,
    extend({}, parserOptions, options, {
      nodeTransforms: [
        // ignore <script> and <tag>
        // this is not put inside DOMNodeTransforms because that list is used
        // by compiler-ssr to generate vnode fallback branches
        ignoreSideEffectTags,
        ...DOMNodeTransforms,
        ...options.nodeTransforms || []
      ],
      directiveTransforms: extend(
        {},
        DOMDirectiveTransforms,
        options.directiveTransforms || {}
      ),
      transformHoist: stringifyStatic
    })
  );
}
function parse$8(template, options = {}) {
  return baseParse(template, extend({}, parserOptions, options));
}
var CompilerDOM = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  BASE_TRANSITION,
  CAMELIZE,
  CAPITALIZE,
  CREATE_BLOCK,
  CREATE_COMMENT,
  CREATE_ELEMENT_BLOCK,
  CREATE_ELEMENT_VNODE,
  CREATE_SLOTS,
  CREATE_STATIC,
  CREATE_TEXT,
  CREATE_VNODE,
  DOMDirectiveTransforms,
  DOMNodeTransforms,
  FRAGMENT,
  GUARD_REACTIVE_PROPS,
  IS_MEMO_SAME,
  IS_REF,
  KEEP_ALIVE,
  MERGE_PROPS,
  NORMALIZE_CLASS,
  NORMALIZE_PROPS,
  NORMALIZE_STYLE,
  OPEN_BLOCK,
  POP_SCOPE_ID,
  PUSH_SCOPE_ID,
  RENDER_LIST,
  RENDER_SLOT,
  RESOLVE_COMPONENT,
  RESOLVE_DIRECTIVE,
  RESOLVE_DYNAMIC_COMPONENT,
  RESOLVE_FILTER,
  SET_BLOCK_TRACKING,
  SUSPENSE,
  TELEPORT,
  TO_DISPLAY_STRING,
  TO_HANDLERS,
  TO_HANDLER_KEY,
  TRANSITION,
  TRANSITION_GROUP,
  TS_NODE_TYPES,
  UNREF,
  V_MODEL_CHECKBOX,
  V_MODEL_DYNAMIC,
  V_MODEL_RADIO,
  V_MODEL_SELECT,
  V_MODEL_TEXT,
  V_ON_WITH_KEYS,
  V_ON_WITH_MODIFIERS,
  V_SHOW,
  WITH_CTX,
  WITH_DIRECTIVES,
  WITH_MEMO,
  advancePositionWithClone,
  advancePositionWithMutation,
  assert,
  baseCompile,
  baseParse,
  buildDirectiveArgs,
  buildProps,
  buildSlots,
  checkCompatEnabled,
  compile: compile$1,
  convertToBlock,
  createArrayExpression,
  createAssignmentExpression,
  createBlockStatement,
  createCacheExpression,
  createCallExpression,
  createCompilerError,
  createCompoundExpression,
  createConditionalExpression,
  createDOMCompilerError,
  createForLoopParams,
  createFunctionExpression,
  createIfStatement,
  createInterpolation,
  createObjectExpression,
  createObjectProperty,
  createReturnStatement,
  createRoot,
  createSequenceExpression,
  createSimpleExpression,
  createStructuralDirectiveTransform,
  createTemplateLiteral,
  createTransformContext,
  createVNodeCall,
  extractIdentifiers,
  findDir,
  findProp,
  generate,
  generateCodeFrame,
  getBaseTransformPreset,
  getConstantType,
  getInnerRange,
  getMemoedVNodeCall,
  getVNodeBlockHelper,
  getVNodeHelper,
  hasDynamicKeyVBind,
  hasScopeRef,
  helperNameMap,
  injectProp,
  isBuiltInType,
  isCoreComponent,
  isFunctionType,
  isInDestructureAssignment,
  isMemberExpression,
  isMemberExpressionBrowser,
  isMemberExpressionNode,
  isReferencedIdentifier,
  isSimpleIdentifier,
  isSlotOutlet,
  isStaticArgOf,
  isStaticExp,
  isStaticProperty,
  isStaticPropertyKey,
  isTemplateNode,
  isText: isText$1,
  isVSlot,
  locStub,
  noopDirectiveTransform,
  parse: parse$8,
  parserOptions,
  processExpression,
  processFor,
  processIf,
  processSlotOutlet,
  registerRuntimeHelpers,
  resolveComponentType,
  stringifyExpression,
  toValidAssetId,
  trackSlotScopes,
  trackVForSlotScopes,
  transform: transform$1,
  transformBind,
  transformElement,
  transformExpression,
  transformModel: transformModel$1,
  transformOn: transformOn$1,
  transformStyle,
  traverseNode,
  walkBlockDeclarations,
  walkFunctionParams,
  walkIdentifiers,
  warnDeprecation
});
function normalizeArray(parts, allowAboveRoot) {
  var up = 0;
  for (var i = parts.length - 1; i >= 0; i--) {
    var last2 = parts[i];
    if (last2 === ".") {
      parts.splice(i, 1);
    } else if (last2 === "..") {
      parts.splice(i, 1);
      up++;
    } else if (up) {
      parts.splice(i, 1);
      up--;
    }
  }
  if (allowAboveRoot) {
    for (; up--; up) {
      parts.unshift("..");
    }
  }
  return parts;
}
var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
var splitPath = function(filename) {
  return splitPathRe.exec(filename).slice(1);
};
function resolve$2() {
  var resolvedPath = "", resolvedAbsolute = false;
  for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
    var path2 = i >= 0 ? arguments[i] : "/";
    if (typeof path2 !== "string") {
      throw new TypeError("Arguments to path.resolve must be strings");
    } else if (!path2) {
      continue;
    }
    resolvedPath = path2 + "/" + resolvedPath;
    resolvedAbsolute = path2.charAt(0) === "/";
  }
  resolvedPath = normalizeArray(filter(resolvedPath.split("/"), function(p2) {
    return !!p2;
  }), !resolvedAbsolute).join("/");
  return (resolvedAbsolute ? "/" : "") + resolvedPath || ".";
}
function normalize$1(path2) {
  var isPathAbsolute = isAbsolute$1(path2), trailingSlash = substr(path2, -1) === "/";
  path2 = normalizeArray(filter(path2.split("/"), function(p2) {
    return !!p2;
  }), !isPathAbsolute).join("/");
  if (!path2 && !isPathAbsolute) {
    path2 = ".";
  }
  if (path2 && trailingSlash) {
    path2 += "/";
  }
  return (isPathAbsolute ? "/" : "") + path2;
}
function isAbsolute$1(path2) {
  return path2.charAt(0) === "/";
}
function join$1() {
  var paths = Array.prototype.slice.call(arguments, 0);
  return normalize$1(filter(paths, function(p2, index) {
    if (typeof p2 !== "string") {
      throw new TypeError("Arguments to path.join must be strings");
    }
    return p2;
  }).join("/"));
}
function relative$1(from2, to) {
  from2 = resolve$2(from2).substr(1);
  to = resolve$2(to).substr(1);
  function trim2(arr) {
    var start = 0;
    for (; start < arr.length; start++) {
      if (arr[start] !== "")
        break;
    }
    var end = arr.length - 1;
    for (; end >= 0; end--) {
      if (arr[end] !== "")
        break;
    }
    if (start > end)
      return [];
    return arr.slice(start, end - start + 1);
  }
  var fromParts = trim2(from2.split("/"));
  var toParts = trim2(to.split("/"));
  var length2 = Math.min(fromParts.length, toParts.length);
  var samePartsLength = length2;
  for (var i = 0; i < length2; i++) {
    if (fromParts[i] !== toParts[i]) {
      samePartsLength = i;
      break;
    }
  }
  var outputParts = [];
  for (var i = samePartsLength; i < fromParts.length; i++) {
    outputParts.push("..");
  }
  outputParts = outputParts.concat(toParts.slice(samePartsLength));
  return outputParts.join("/");
}
var sep$1 = "/";
var delimiter$1 = ":";
function dirname$2(path2) {
  var result2 = splitPath(path2), root3 = result2[0], dir = result2[1];
  if (!root3 && !dir) {
    return ".";
  }
  if (dir) {
    dir = dir.substr(0, dir.length - 1);
  }
  return root3 + dir;
}
function basename(path2, ext) {
  var f = splitPath(path2)[2];
  if (ext && f.substr(-1 * ext.length) === ext) {
    f = f.substr(0, f.length - ext.length);
  }
  return f;
}
function extname(path2) {
  return splitPath(path2)[3];
}
var path = {
  extname,
  basename,
  dirname: dirname$2,
  sep: sep$1,
  delimiter: delimiter$1,
  relative: relative$1,
  join: join$1,
  isAbsolute: isAbsolute$1,
  normalize: normalize$1,
  resolve: resolve$2
};
function filter(xs, f) {
  if (xs.filter)
    return xs.filter(f);
  var res = [];
  for (var i = 0; i < xs.length; i++) {
    if (f(xs[i], i, xs))
      res.push(xs[i]);
  }
  return res;
}
var substr = "ab".substr(-1) === "b" ? function(str2, start, len) {
  return str2.substr(start, len);
} : function(str2, start, len) {
  if (start < 0)
    start = str2.length + start;
  return str2.substr(start, len);
};
var _polyfillNode_path = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  basename,
  default: path,
  delimiter: delimiter$1,
  dirname: dirname$2,
  extname,
  isAbsolute: isAbsolute$1,
  join: join$1,
  normalize: normalize$1,
  relative: relative$1,
  resolve: resolve$2,
  sep: sep$1
});
(path.posix || path).normalize;
(path.posix || path).join;
function normalizeExpression(exp) {
  exp = exp.trim();
  if (exp[0] === `'` && exp[exp.length - 1] === `'` || exp[0] === `"` && exp[exp.length - 1] === `"`) {
    return exp.slice(1, -1);
  }
  return exp;
}
const vBindRE = /v-bind\s*\(/g;
function parseCssVars(sfc) {
  const vars = [];
  sfc.styles.forEach((style2) => {
    let match2;
    const content = style2.content.replace(/\/\*([\s\S]*?)\*\//g, "");
    while (match2 = vBindRE.exec(content)) {
      const start = match2.index + match2[0].length;
      const end = lexBinding(content, start);
      if (end !== null) {
        const variable = normalizeExpression(content.slice(start, end));
        if (!vars.includes(variable)) {
          vars.push(variable);
        }
      }
    }
  });
  return vars;
}
function lexBinding(content, start) {
  let state = 0;
  let parenDepth = 0;
  for (let i = start; i < content.length; i++) {
    const char = content.charAt(i);
    switch (state) {
      case 0:
        if (char === `'`) {
          state = 1;
        } else if (char === `"`) {
          state = 2;
        } else if (char === `(`) {
          parenDepth++;
        } else if (char === `)`) {
          if (parenDepth > 0) {
            parenDepth--;
          } else {
            return i;
          }
        }
        break;
      case 1:
        if (char === `'`) {
          state = 0;
        }
        break;
      case 2:
        if (char === `"`) {
          state = 0;
        }
        break;
    }
  }
  return null;
}
function createCache(size2 = 500) {
  {
    return /* @__PURE__ */ new Map();
  }
}
function isImportUsed(local, sfc) {
  return new RegExp(
    // #4274 escape $ since it's a special char in regex
    // (and is the only regex special char that is valid in identifiers)
    `[^\\w$_]${local.replace(/\$/g, "\\$")}[^\\w$_]`
  ).test(resolveTemplateUsageCheckString(sfc));
}
const templateUsageCheckCache = createCache();
function resolveTemplateUsageCheckString(sfc) {
  const { content, ast } = sfc.template;
  const cached = templateUsageCheckCache.get(content);
  if (cached) {
    return cached;
  }
  let code = "";
  transform$1(createRoot([ast]), {
    nodeTransforms: [
      (node2) => {
        if (node2.type === 1) {
          if (!parserOptions.isNativeTag(node2.tag) && !parserOptions.isBuiltInComponent(node2.tag)) {
            code += `,${camelize(node2.tag)},${capitalize$1(camelize(node2.tag))}`;
          }
          for (let i = 0; i < node2.props.length; i++) {
            const prop = node2.props[i];
            if (prop.type === 7) {
              if (!isBuiltInDirective(prop.name)) {
                code += `,v${capitalize$1(camelize(prop.name))}`;
              }
              if (prop.exp) {
                code += `,${processExp(
                  prop.exp.content,
                  prop.name
                )}`;
              }
            }
          }
        } else if (node2.type === 5) {
          code += `,${processExp(
            node2.content.content
          )}`;
        }
      }
    ]
  });
  code += ";";
  templateUsageCheckCache.set(content, code);
  return code;
}
const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
function processExp(exp, dir) {
  if (/ as\s+\w|<.*>|:/.test(exp)) {
    if (dir === "slot") {
      exp = `(${exp})=>{}`;
    } else if (dir === "on") {
      exp = `()=>{return ${exp}}`;
    } else if (dir === "for") {
      const inMatch = exp.match(forAliasRE);
      if (inMatch) {
        let [, LHS, RHS] = inMatch;
        LHS = LHS.trim().replace(/^\(|\)$/g, "");
        return processExp(`(${LHS})=>{}`) + processExp(RHS);
      }
    }
    let ret = "";
    const ast = parseExpression_1(exp, { plugins: ["typescript"] });
    walkIdentifiers(ast, (node2) => {
      ret += `,` + node2.name;
    });
    return ret;
  }
  return stripStrings(exp);
}
function stripStrings(exp) {
  return exp.replace(/'[^']*'|"[^"]*"/g, "").replace(/`[^`]+`/g, stripTemplateString);
}
function stripTemplateString(str2) {
  const interpMatch = str2.match(/\${[^}]+}/g);
  if (interpMatch) {
    return interpMatch.map((m) => m.slice(2, -1)).join(",");
  }
  return "";
}
var __defProp$a = Object.defineProperty;
var __getOwnPropSymbols$a = Object.getOwnPropertySymbols;
var __hasOwnProp$a = Object.prototype.hasOwnProperty;
var __propIsEnum$a = Object.prototype.propertyIsEnumerable;
var __defNormalProp$a = (obj, key, value) => key in obj ? __defProp$a(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues$a = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp$a.call(b, prop))
      __defNormalProp$a(a, prop, b[prop]);
  if (__getOwnPropSymbols$a)
    for (var prop of __getOwnPropSymbols$a(b)) {
      if (__propIsEnum$a.call(b, prop))
        __defNormalProp$a(a, prop, b[prop]);
    }
  return a;
};
const DEFAULT_FILENAME = "anonymous.vue";
const parseCache = createCache();
function parse$7(source, {
  sourceMap = true,
  filename = DEFAULT_FILENAME,
  sourceRoot = "",
  pad: pad2 = false,
  ignoreEmpty = true,
  compiler = CompilerDOM
} = {}) {
  const sourceKey = source + sourceMap + filename + sourceRoot + pad2 + compiler.parse;
  const cache2 = parseCache.get(sourceKey);
  if (cache2) {
    return cache2;
  }
  const descriptor = {
    filename,
    source,
    template: null,
    script: null,
    scriptSetup: null,
    styles: [],
    customBlocks: [],
    cssVars: [],
    slotted: false,
    shouldForceReload: (prevImports) => hmrShouldReload(prevImports, descriptor)
  };
  const errors2 = [];
  const ast = compiler.parse(source, {
    // there are no components at SFC parsing level
    isNativeTag: () => true,
    // preserve all whitespaces
    isPreTag: () => true,
    getTextMode: ({ tag: tag3, props }, parent) => {
      if (!parent && tag3 !== "template" || // <template lang="xxx"> should also be treated as raw text
      tag3 === "template" && props.some(
        (p2) => p2.type === 6 && p2.name === "lang" && p2.value && p2.value.content && p2.value.content !== "html"
      )) {
        return 2;
      } else {
        return 0;
      }
    },
    onError: (e) => {
      errors2.push(e);
    }
  });
  ast.children.forEach((node2) => {
    if (node2.type !== 1) {
      return;
    }
    if (ignoreEmpty && node2.tag !== "template" && isEmpty(node2) && !hasSrc(node2)) {
      return;
    }
    switch (node2.tag) {
      case "template":
        if (!descriptor.template) {
          const templateBlock = descriptor.template = createBlock(
            node2,
            source,
            false
          );
          templateBlock.ast = node2;
          if (templateBlock.attrs.functional) {
            const err = new SyntaxError(
              `<template functional> is no longer supported in Vue 3, since functional components no longer have significant performance difference from stateful ones. Just use a normal <template> instead.`
            );
            err.loc = node2.props.find((p2) => p2.name === "functional").loc;
            errors2.push(err);
          }
        } else {
          errors2.push(createDuplicateBlockError(node2));
        }
        break;
      case "script":
        const scriptBlock = createBlock(node2, source, pad2);
        const isSetup = !!scriptBlock.attrs.setup;
        if (isSetup && !descriptor.scriptSetup) {
          descriptor.scriptSetup = scriptBlock;
          break;
        }
        if (!isSetup && !descriptor.script) {
          descriptor.script = scriptBlock;
          break;
        }
        errors2.push(createDuplicateBlockError(node2, isSetup));
        break;
      case "style":
        const styleBlock = createBlock(node2, source, pad2);
        if (styleBlock.attrs.vars) {
          errors2.push(
            new SyntaxError(
              `<style vars> has been replaced by a new proposal: https://github.com/vuejs/rfcs/pull/231`
            )
          );
        }
        descriptor.styles.push(styleBlock);
        break;
      default:
        descriptor.customBlocks.push(createBlock(node2, source, pad2));
        break;
    }
  });
  if (!descriptor.template && !descriptor.script && !descriptor.scriptSetup) {
    errors2.push(
      new SyntaxError(
        `At least one <template> or <script> is required in a single file component.`
      )
    );
  }
  if (descriptor.scriptSetup) {
    if (descriptor.scriptSetup.src) {
      errors2.push(
        new SyntaxError(
          `<script setup> cannot use the "src" attribute because its syntax will be ambiguous outside of the component.`
        )
      );
      descriptor.scriptSetup = null;
    }
    if (descriptor.script && descriptor.script.src) {
      errors2.push(
        new SyntaxError(
          `<script> cannot use the "src" attribute when <script setup> is also present because they must be processed together.`
        )
      );
      descriptor.script = null;
    }
  }
  if (sourceMap) {
    const genMap = (block) => {
      if (block && !block.src) {
        block.map = generateSourceMap(
          filename,
          source,
          block.content,
          sourceRoot,
          !pad2 || block.type === "template" ? block.loc.start.line - 1 : 0
        );
      }
    };
    genMap(descriptor.template);
    genMap(descriptor.script);
    descriptor.styles.forEach(genMap);
    descriptor.customBlocks.forEach(genMap);
  }
  descriptor.cssVars = parseCssVars(descriptor);
  const slottedRE = /(?:::v-|:)slotted\(/;
  descriptor.slotted = descriptor.styles.some(
    (s) => s.scoped && slottedRE.test(s.content)
  );
  const result2 = {
    descriptor,
    errors: errors2
  };
  parseCache.set(sourceKey, result2);
  return result2;
}
function createDuplicateBlockError(node2, isScriptSetup = false) {
  const err = new SyntaxError(
    `Single file component can contain only one <${node2.tag}${isScriptSetup ? ` setup` : ``}> element`
  );
  err.loc = node2.loc;
  return err;
}
function createBlock(node2, source, pad2) {
  const type = node2.tag;
  let { start, end } = node2.loc;
  let content = "";
  if (node2.children.length) {
    start = node2.children[0].loc.start;
    end = node2.children[node2.children.length - 1].loc.end;
    content = source.slice(start.offset, end.offset);
  } else {
    const offset = node2.loc.source.indexOf(`</`);
    if (offset > -1) {
      start = {
        line: start.line,
        column: start.column + offset,
        offset: start.offset + offset
      };
    }
    end = __spreadValues$a({}, start);
  }
  const loc = {
    source: content,
    start,
    end
  };
  const attrs = {};
  const block = {
    type,
    content,
    loc,
    attrs
  };
  if (pad2) {
    block.content = padContent(source, block, pad2) + block.content;
  }
  node2.props.forEach((p2) => {
    if (p2.type === 6) {
      attrs[p2.name] = p2.value ? p2.value.content || true : true;
      if (p2.name === "lang") {
        block.lang = p2.value && p2.value.content;
      } else if (p2.name === "src") {
        block.src = p2.value && p2.value.content;
      } else if (type === "style") {
        if (p2.name === "scoped") {
          block.scoped = true;
        } else if (p2.name === "module") {
          block.module = attrs[p2.name];
        }
      } else if (type === "script" && p2.name === "setup") {
        block.setup = attrs.setup;
      }
    }
  });
  return block;
}
const splitRE = /\r?\n/g;
const emptyRE = /^(?:\/\/)?\s*$/;
const replaceRE = /./g;
function generateSourceMap(filename, source, generated, sourceRoot, lineOffset) {
  const map2 = new SourceMapGenerator$6({
    file: filename.replace(/\\/g, "/"),
    sourceRoot: sourceRoot.replace(/\\/g, "/")
  });
  map2.setSourceContent(filename, source);
  generated.split(splitRE).forEach((line, index) => {
    if (!emptyRE.test(line)) {
      const originalLine = index + 1 + lineOffset;
      const generatedLine = index + 1;
      for (let i = 0; i < line.length; i++) {
        if (!/\s/.test(line[i])) {
          map2.addMapping({
            source: filename,
            original: {
              line: originalLine,
              column: i
            },
            generated: {
              line: generatedLine,
              column: i
            }
          });
        }
      }
    }
  });
  return JSON.parse(map2.toString());
}
function padContent(content, block, pad2) {
  content = content.slice(0, block.loc.start.offset);
  if (pad2 === "space") {
    return content.replace(replaceRE, " ");
  } else {
    const offset = content.split(splitRE).length;
    const padChar = block.type === "script" && !block.lang ? "//\n" : "\n";
    return Array(offset).join(padChar);
  }
}
function hasSrc(node2) {
  return node2.props.some((p2) => {
    if (p2.type !== 6) {
      return false;
    }
    return p2.name === "src";
  });
}
function isEmpty(node2) {
  for (let i = 0; i < node2.children.length; i++) {
    const child = node2.children[i];
    if (child.type !== 2 || child.content.trim() !== "") {
      return false;
    }
  }
  return true;
}
function hmrShouldReload(prevImports, next) {
  if (!next.scriptSetup || next.scriptSetup.lang !== "ts" && next.scriptSetup.lang !== "tsx") {
    return false;
  }
  for (const key in prevImports) {
    if (!prevImports[key].isUsedInTemplate && isImportUsed(key, next)) {
      return true;
    }
  }
  return false;
}
var global$1 = typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};
/*! https://mths.be/punycode v1.4.1 by @mathias */
var maxInt = 2147483647;
var base = 36;
var tMin = 1;
var tMax = 26;
var skew = 38;
var damp = 700;
var initialBias = 72;
var initialN = 128;
var delimiter = "-";
var regexNonASCII = /[^\x20-\x7E]/;
var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g;
var errors = {
  "overflow": "Overflow: input needs wider integers to process",
  "not-basic": "Illegal input >= 0x80 (not a basic code point)",
  "invalid-input": "Invalid input"
};
var baseMinusTMin = base - tMin;
var floor = Math.floor;
var stringFromCharCode = String.fromCharCode;
function error(type) {
  throw new RangeError(errors[type]);
}
function map$1(array2, fn) {
  var length2 = array2.length;
  var result2 = [];
  while (length2--) {
    result2[length2] = fn(array2[length2]);
  }
  return result2;
}
function mapDomain(string3, fn) {
  var parts = string3.split("@");
  var result2 = "";
  if (parts.length > 1) {
    result2 = parts[0] + "@";
    string3 = parts[1];
  }
  string3 = string3.replace(regexSeparators, ".");
  var labels = string3.split(".");
  var encoded = map$1(labels, fn).join(".");
  return result2 + encoded;
}
function ucs2decode(string3) {
  var output = [], counter = 0, length2 = string3.length, value, extra;
  while (counter < length2) {
    value = string3.charCodeAt(counter++);
    if (value >= 55296 && value <= 56319 && counter < length2) {
      extra = string3.charCodeAt(counter++);
      if ((extra & 64512) == 56320) {
        output.push(((value & 1023) << 10) + (extra & 1023) + 65536);
      } else {
        output.push(value);
        counter--;
      }
    } else {
      output.push(value);
    }
  }
  return output;
}
function digitToBasic(digit, flag) {
  return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
}
function adapt(delta, numPoints, firstTime) {
  var k = 0;
  delta = firstTime ? floor(delta / damp) : delta >> 1;
  delta += floor(delta / numPoints);
  for (; delta > baseMinusTMin * tMax >> 1; k += base) {
    delta = floor(delta / baseMinusTMin);
  }
  return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
}
function encode$1(input2) {
  var n2, delta, handledCPCount, basicLength, bias, j, m, q, k, t, currentValue, output = [], inputLength, handledCPCountPlusOne, baseMinusT, qMinusT;
  input2 = ucs2decode(input2);
  inputLength = input2.length;
  n2 = initialN;
  delta = 0;
  bias = initialBias;
  for (j = 0; j < inputLength; ++j) {
    currentValue = input2[j];
    if (currentValue < 128) {
      output.push(stringFromCharCode(currentValue));
    }
  }
  handledCPCount = basicLength = output.length;
  if (basicLength) {
    output.push(delimiter);
  }
  while (handledCPCount < inputLength) {
    for (m = maxInt, j = 0; j < inputLength; ++j) {
      currentValue = input2[j];
      if (currentValue >= n2 && currentValue < m) {
        m = currentValue;
      }
    }
    handledCPCountPlusOne = handledCPCount + 1;
    if (m - n2 > floor((maxInt - delta) / handledCPCountPlusOne)) {
      error("overflow");
    }
    delta += (m - n2) * handledCPCountPlusOne;
    n2 = m;
    for (j = 0; j < inputLength; ++j) {
      currentValue = input2[j];
      if (currentValue < n2 && ++delta > maxInt) {
        error("overflow");
      }
      if (currentValue == n2) {
        for (q = delta, k = base; ; k += base) {
          t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
          if (q < t) {
            break;
          }
          qMinusT = q - t;
          baseMinusT = base - t;
          output.push(
            stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
          );
          q = floor(qMinusT / baseMinusT);
        }
        output.push(stringFromCharCode(digitToBasic(q, 0)));
        bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
        delta = 0;
        ++handledCPCount;
      }
    }
    ++delta;
    ++n2;
  }
  return output.join("");
}
function toASCII(input2) {
  return mapDomain(input2, function(string3) {
    return regexNonASCII.test(string3) ? "xn--" + encode$1(string3) : string3;
  });
}
var lookup = [];
var revLookup = [];
var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
var inited = false;
function init() {
  inited = true;
  var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  for (var i = 0, len = code.length; i < len; ++i) {
    lookup[i] = code[i];
    revLookup[code.charCodeAt(i)] = i;
  }
  revLookup["-".charCodeAt(0)] = 62;
  revLookup["_".charCodeAt(0)] = 63;
}
function toByteArray(b64) {
  if (!inited) {
    init();
  }
  var i, j, l, tmp, placeHolders, arr;
  var len = b64.length;
  if (len % 4 > 0) {
    throw new Error("Invalid string. Length must be a multiple of 4");
  }
  placeHolders = b64[len - 2] === "=" ? 2 : b64[len - 1] === "=" ? 1 : 0;
  arr = new Arr(len * 3 / 4 - placeHolders);
  l = placeHolders > 0 ? len - 4 : len;
  var L = 0;
  for (i = 0, j = 0; i < l; i += 4, j += 3) {
    tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)];
    arr[L++] = tmp >> 16 & 255;
    arr[L++] = tmp >> 8 & 255;
    arr[L++] = tmp & 255;
  }
  if (placeHolders === 2) {
    tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4;
    arr[L++] = tmp & 255;
  } else if (placeHolders === 1) {
    tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2;
    arr[L++] = tmp >> 8 & 255;
    arr[L++] = tmp & 255;
  }
  return arr;
}
function tripletToBase64(num) {
  return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63];
}
function encodeChunk(uint8, start, end) {
  var tmp;
  var output = [];
  for (var i = start; i < end; i += 3) {
    tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2];
    output.push(tripletToBase64(tmp));
  }
  return output.join("");
}
function fromByteArray(uint8) {
  if (!inited) {
    init();
  }
  var tmp;
  var len = uint8.length;
  var extraBytes = len % 3;
  var output = "";
  var parts = [];
  var maxChunkLength = 16383;
  for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
    parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength));
  }
  if (extraBytes === 1) {
    tmp = uint8[len - 1];
    output += lookup[tmp >> 2];
    output += lookup[tmp << 4 & 63];
    output += "==";
  } else if (extraBytes === 2) {
    tmp = (uint8[len - 2] << 8) + uint8[len - 1];
    output += lookup[tmp >> 10];
    output += lookup[tmp >> 4 & 63];
    output += lookup[tmp << 2 & 63];
    output += "=";
  }
  parts.push(output);
  return parts.join("");
}
function read$1(buffer, offset, isLE, mLen, nBytes) {
  var e, m;
  var eLen = nBytes * 8 - mLen - 1;
  var eMax = (1 << eLen) - 1;
  var eBias = eMax >> 1;
  var nBits = -7;
  var i = isLE ? nBytes - 1 : 0;
  var d = isLE ? -1 : 1;
  var s = buffer[offset + i];
  i += d;
  e = s & (1 << -nBits) - 1;
  s >>= -nBits;
  nBits += eLen;
  for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {
  }
  m = e & (1 << -nBits) - 1;
  e >>= -nBits;
  nBits += mLen;
  for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {
  }
  if (e === 0) {
    e = 1 - eBias;
  } else if (e === eMax) {
    return m ? NaN : (s ? -1 : 1) * Infinity;
  } else {
    m = m + Math.pow(2, mLen);
    e = e - eBias;
  }
  return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
}
function write(buffer, value, offset, isLE, mLen, nBytes) {
  var e, m, c;
  var eLen = nBytes * 8 - mLen - 1;
  var eMax = (1 << eLen) - 1;
  var eBias = eMax >> 1;
  var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
  var i = isLE ? 0 : nBytes - 1;
  var d = isLE ? 1 : -1;
  var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
  value = Math.abs(value);
  if (isNaN(value) || value === Infinity) {
    m = isNaN(value) ? 1 : 0;
    e = eMax;
  } else {
    e = Math.floor(Math.log(value) / Math.LN2);
    if (value * (c = Math.pow(2, -e)) < 1) {
      e--;
      c *= 2;
    }
    if (e + eBias >= 1) {
      value += rt / c;
    } else {
      value += rt * Math.pow(2, 1 - eBias);
    }
    if (value * c >= 2) {
      e++;
      c /= 2;
    }
    if (e + eBias >= eMax) {
      m = 0;
      e = eMax;
    } else if (e + eBias >= 1) {
      m = (value * c - 1) * Math.pow(2, mLen);
      e = e + eBias;
    } else {
      m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
      e = 0;
    }
  }
  for (; mLen >= 8; buffer[offset + i] = m & 255, i += d, m /= 256, mLen -= 8) {
  }
  e = e << mLen | m;
  eLen += mLen;
  for (; eLen > 0; buffer[offset + i] = e & 255, i += d, e /= 256, eLen -= 8) {
  }
  buffer[offset + i - d] |= s * 128;
}
var toString$1 = {}.toString;
var isArray$2 = Array.isArray || function(arr) {
  return toString$1.call(arr) == "[object Array]";
};
/*!
 * The buffer module from node.js, for the browser.
 *
 * @author   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
 * @license  MIT
 */
var INSPECT_MAX_BYTES = 50;
Buffer$1.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== void 0 ? global$1.TYPED_ARRAY_SUPPORT : true;
kMaxLength();
function kMaxLength() {
  return Buffer$1.TYPED_ARRAY_SUPPORT ? 2147483647 : 1073741823;
}
function createBuffer(that, length2) {
  if (kMaxLength() < length2) {
    throw new RangeError("Invalid typed array length");
  }
  if (Buffer$1.TYPED_ARRAY_SUPPORT) {
    that = new Uint8Array(length2);
    that.__proto__ = Buffer$1.prototype;
  } else {
    if (that === null) {
      that = new Buffer$1(length2);
    }
    that.length = length2;
  }
  return that;
}
function Buffer$1(arg, encodingOrOffset, length2) {
  if (!Buffer$1.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$1)) {
    return new Buffer$1(arg, encodingOrOffset, length2);
  }
  if (typeof arg === "number") {
    if (typeof encodingOrOffset === "string") {
      throw new Error(
        "If encoding is specified then the first argument must be a string"
      );
    }
    return allocUnsafe(this, arg);
  }
  return from(this, arg, encodingOrOffset, length2);
}
Buffer$1.poolSize = 8192;
Buffer$1._augment = function(arr) {
  arr.__proto__ = Buffer$1.prototype;
  return arr;
};
function from(that, value, encodingOrOffset, length2) {
  if (typeof value === "number") {
    throw new TypeError('"value" argument must not be a number');
  }
  if (typeof ArrayBuffer !== "undefined" && value instanceof ArrayBuffer) {
    return fromArrayBuffer(that, value, encodingOrOffset, length2);
  }
  if (typeof value === "string") {
    return fromString(that, value, encodingOrOffset);
  }
  return fromObject(that, value);
}
Buffer$1.from = function(value, encodingOrOffset, length2) {
  return from(null, value, encodingOrOffset, length2);
};
if (Buffer$1.TYPED_ARRAY_SUPPORT) {
  Buffer$1.prototype.__proto__ = Uint8Array.prototype;
  Buffer$1.__proto__ = Uint8Array;
  if (typeof Symbol !== "undefined" && Symbol.species && Buffer$1[Symbol.species] === Buffer$1)
    ;
}
function assertSize(size2) {
  if (typeof size2 !== "number") {
    throw new TypeError('"size" argument must be a number');
  } else if (size2 < 0) {
    throw new RangeError('"size" argument must not be negative');
  }
}
function alloc(that, size2, fill3, encoding) {
  assertSize(size2);
  if (size2 <= 0) {
    return createBuffer(that, size2);
  }
  if (fill3 !== void 0) {
    return typeof encoding === "string" ? createBuffer(that, size2).fill(fill3, encoding) : createBuffer(that, size2).fill(fill3);
  }
  return createBuffer(that, size2);
}
Buffer$1.alloc = function(size2, fill3, encoding) {
  return alloc(null, size2, fill3, encoding);
};
function allocUnsafe(that, size2) {
  assertSize(size2);
  that = createBuffer(that, size2 < 0 ? 0 : checked(size2) | 0);
  if (!Buffer$1.TYPED_ARRAY_SUPPORT) {
    for (var i = 0; i < size2; ++i) {
      that[i] = 0;
    }
  }
  return that;
}
Buffer$1.allocUnsafe = function(size2) {
  return allocUnsafe(null, size2);
};
Buffer$1.allocUnsafeSlow = function(size2) {
  return allocUnsafe(null, size2);
};
function fromString(that, string3, encoding) {
  if (typeof encoding !== "string" || encoding === "") {
    encoding = "utf8";
  }
  if (!Buffer$1.isEncoding(encoding)) {
    throw new TypeError('"encoding" must be a valid string encoding');
  }
  var length2 = byteLength(string3, encoding) | 0;
  that = createBuffer(that, length2);
  var actual = that.write(string3, encoding);
  if (actual !== length2) {
    that = that.slice(0, actual);
  }
  return that;
}
function fromArrayLike(that, array2) {
  var length2 = array2.length < 0 ? 0 : checked(array2.length) | 0;
  that = createBuffer(that, length2);
  for (var i = 0; i < length2; i += 1) {
    that[i] = array2[i] & 255;
  }
  return that;
}
function fromArrayBuffer(that, array2, byteOffset, length2) {
  array2.byteLength;
  if (byteOffset < 0 || array2.byteLength < byteOffset) {
    throw new RangeError("'offset' is out of bounds");
  }
  if (array2.byteLength < byteOffset + (length2 || 0)) {
    throw new RangeError("'length' is out of bounds");
  }
  if (byteOffset === void 0 && length2 === void 0) {
    array2 = new Uint8Array(array2);
  } else if (length2 === void 0) {
    array2 = new Uint8Array(array2, byteOffset);
  } else {
    array2 = new Uint8Array(array2, byteOffset, length2);
  }
  if (Buffer$1.TYPED_ARRAY_SUPPORT) {
    that = array2;
    that.__proto__ = Buffer$1.prototype;
  } else {
    that = fromArrayLike(that, array2);
  }
  return that;
}
function fromObject(that, obj) {
  if (internalIsBuffer(obj)) {
    var len = checked(obj.length) | 0;
    that = createBuffer(that, len);
    if (that.length === 0) {
      return that;
    }
    obj.copy(that, 0, 0, len);
    return that;
  }
  if (obj) {
    if (typeof ArrayBuffer !== "undefined" && obj.buffer instanceof ArrayBuffer || "length" in obj) {
      if (typeof obj.length !== "number" || isnan(obj.length)) {
        return createBuffer(that, 0);
      }
      return fromArrayLike(that, obj);
    }
    if (obj.type === "Buffer" && isArray$2(obj.data)) {
      return fromArrayLike(that, obj.data);
    }
  }
  throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.");
}
function checked(length2) {
  if (length2 >= kMaxLength()) {
    throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + kMaxLength().toString(16) + " bytes");
  }
  return length2 | 0;
}
Buffer$1.isBuffer = isBuffer$1;
function internalIsBuffer(b) {
  return !!(b != null && b._isBuffer);
}
Buffer$1.compare = function compare2(a, b) {
  if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
    throw new TypeError("Arguments must be Buffers");
  }
  if (a === b)
    return 0;
  var x = a.length;
  var y = b.length;
  for (var i = 0, len = Math.min(x, y); i < len; ++i) {
    if (a[i] !== b[i]) {
      x = a[i];
      y = b[i];
      break;
    }
  }
  if (x < y)
    return -1;
  if (y < x)
    return 1;
  return 0;
};
Buffer$1.isEncoding = function isEncoding(encoding) {
  switch (String(encoding).toLowerCase()) {
    case "hex":
    case "utf8":
    case "utf-8":
    case "ascii":
    case "latin1":
    case "binary":
    case "base64":
    case "ucs2":
    case "ucs-2":
    case "utf16le":
    case "utf-16le":
      return true;
    default:
      return false;
  }
};
Buffer$1.concat = function concat2(list2, length2) {
  if (!isArray$2(list2)) {
    throw new TypeError('"list" argument must be an Array of Buffers');
  }
  if (list2.length === 0) {
    return Buffer$1.alloc(0);
  }
  var i;
  if (length2 === void 0) {
    length2 = 0;
    for (i = 0; i < list2.length; ++i) {
      length2 += list2[i].length;
    }
  }
  var buffer = Buffer$1.allocUnsafe(length2);
  var pos = 0;
  for (i = 0; i < list2.length; ++i) {
    var buf = list2[i];
    if (!internalIsBuffer(buf)) {
      throw new TypeError('"list" argument must be an Array of Buffers');
    }
    buf.copy(buffer, pos);
    pos += buf.length;
  }
  return buffer;
};
function byteLength(string3, encoding) {
  if (internalIsBuffer(string3)) {
    return string3.length;
  }
  if (typeof ArrayBuffer !== "undefined" && typeof ArrayBuffer.isView === "function" && (ArrayBuffer.isView(string3) || string3 instanceof ArrayBuffer)) {
    return string3.byteLength;
  }
  if (typeof string3 !== "string") {
    string3 = "" + string3;
  }
  var len = string3.length;
  if (len === 0)
    return 0;
  var loweredCase = false;
  for (; ; ) {
    switch (encoding) {
      case "ascii":
      case "latin1":
      case "binary":
        return len;
      case "utf8":
      case "utf-8":
      case void 0:
        return utf8ToBytes(string3).length;
      case "ucs2":
      case "ucs-2":
      case "utf16le":
      case "utf-16le":
        return len * 2;
      case "hex":
        return len >>> 1;
      case "base64":
        return base64ToBytes(string3).length;
      default:
        if (loweredCase)
          return utf8ToBytes(string3).length;
        encoding = ("" + encoding).toLowerCase();
        loweredCase = true;
    }
  }
}
Buffer$1.byteLength = byteLength;
function slowToString(encoding, start, end) {
  var loweredCase = false;
  if (start === void 0 || start < 0) {
    start = 0;
  }
  if (start > this.length) {
    return "";
  }
  if (end === void 0 || end > this.length) {
    end = this.length;
  }
  if (end <= 0) {
    return "";
  }
  end >>>= 0;
  start >>>= 0;
  if (end <= start) {
    return "";
  }
  if (!encoding)
    encoding = "utf8";
  while (true) {
    switch (encoding) {
      case "hex":
        return hexSlice(this, start, end);
      case "utf8":
      case "utf-8":
        return utf8Slice(this, start, end);
      case "ascii":
        return asciiSlice(this, start, end);
      case "latin1":
      case "binary":
        return latin1Slice(this, start, end);
      case "base64":
        return base64Slice(this, start, end);
      case "ucs2":
      case "ucs-2":
      case "utf16le":
      case "utf-16le":
        return utf16leSlice(this, start, end);
      default:
        if (loweredCase)
          throw new TypeError("Unknown encoding: " + encoding);
        encoding = (encoding + "").toLowerCase();
        loweredCase = true;
    }
  }
}
Buffer$1.prototype._isBuffer = true;
function swap$1(b, n2, m) {
  var i = b[n2];
  b[n2] = b[m];
  b[m] = i;
}
Buffer$1.prototype.swap16 = function swap16() {
  var len = this.length;
  if (len % 2 !== 0) {
    throw new RangeError("Buffer size must be a multiple of 16-bits");
  }
  for (var i = 0; i < len; i += 2) {
    swap$1(this, i, i + 1);
  }
  return this;
};
Buffer$1.prototype.swap32 = function swap32() {
  var len = this.length;
  if (len % 4 !== 0) {
    throw new RangeError("Buffer size must be a multiple of 32-bits");
  }
  for (var i = 0; i < len; i += 4) {
    swap$1(this, i, i + 3);
    swap$1(this, i + 1, i + 2);
  }
  return this;
};
Buffer$1.prototype.swap64 = function swap64() {
  var len = this.length;
  if (len % 8 !== 0) {
    throw new RangeError("Buffer size must be a multiple of 64-bits");
  }
  for (var i = 0; i < len; i += 8) {
    swap$1(this, i, i + 7);
    swap$1(this, i + 1, i + 6);
    swap$1(this, i + 2, i + 5);
    swap$1(this, i + 3, i + 4);
  }
  return this;
};
Buffer$1.prototype.toString = function toString() {
  var length2 = this.length | 0;
  if (length2 === 0)
    return "";
  if (arguments.length === 0)
    return utf8Slice(this, 0, length2);
  return slowToString.apply(this, arguments);
};
Buffer$1.prototype.equals = function equals(b) {
  if (!internalIsBuffer(b))
    throw new TypeError("Argument must be a Buffer");
  if (this === b)
    return true;
  return Buffer$1.compare(this, b) === 0;
};
Buffer$1.prototype.inspect = function inspect() {
  var str2 = "";
  var max = INSPECT_MAX_BYTES;
  if (this.length > 0) {
    str2 = this.toString("hex", 0, max).match(/.{2}/g).join(" ");
    if (this.length > max)
      str2 += " ... ";
  }
  return "<Buffer " + str2 + ">";
};
Buffer$1.prototype.compare = function compare3(target, start, end, thisStart, thisEnd) {
  if (!internalIsBuffer(target)) {
    throw new TypeError("Argument must be a Buffer");
  }
  if (start === void 0) {
    start = 0;
  }
  if (end === void 0) {
    end = target ? target.length : 0;
  }
  if (thisStart === void 0) {
    thisStart = 0;
  }
  if (thisEnd === void 0) {
    thisEnd = this.length;
  }
  if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
    throw new RangeError("out of range index");
  }
  if (thisStart >= thisEnd && start >= end) {
    return 0;
  }
  if (thisStart >= thisEnd) {
    return -1;
  }
  if (start >= end) {
    return 1;
  }
  start >>>= 0;
  end >>>= 0;
  thisStart >>>= 0;
  thisEnd >>>= 0;
  if (this === target)
    return 0;
  var x = thisEnd - thisStart;
  var y = end - start;
  var len = Math.min(x, y);
  var thisCopy = this.slice(thisStart, thisEnd);
  var targetCopy = target.slice(start, end);
  for (var i = 0; i < len; ++i) {
    if (thisCopy[i] !== targetCopy[i]) {
      x = thisCopy[i];
      y = targetCopy[i];
      break;
    }
  }
  if (x < y)
    return -1;
  if (y < x)
    return 1;
  return 0;
};
function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
  if (buffer.length === 0)
    return -1;
  if (typeof byteOffset === "string") {
    encoding = byteOffset;
    byteOffset = 0;
  } else if (byteOffset > 2147483647) {
    byteOffset = 2147483647;
  } else if (byteOffset < -2147483648) {
    byteOffset = -2147483648;
  }
  byteOffset = +byteOffset;
  if (isNaN(byteOffset)) {
    byteOffset = dir ? 0 : buffer.length - 1;
  }
  if (byteOffset < 0)
    byteOffset = buffer.length + byteOffset;
  if (byteOffset >= buffer.length) {
    if (dir)
      return -1;
    else
      byteOffset = buffer.length - 1;
  } else if (byteOffset < 0) {
    if (dir)
      byteOffset = 0;
    else
      return -1;
  }
  if (typeof val === "string") {
    val = Buffer$1.from(val, encoding);
  }
  if (internalIsBuffer(val)) {
    if (val.length === 0) {
      return -1;
    }
    return arrayIndexOf(buffer, val, byteOffset, encoding, dir);
  } else if (typeof val === "number") {
    val = val & 255;
    if (Buffer$1.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === "function") {
      if (dir) {
        return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
      } else {
        return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
      }
    }
    return arrayIndexOf(buffer, [val], byteOffset, encoding, dir);
  }
  throw new TypeError("val must be string, number or Buffer");
}
function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
  var indexSize = 1;
  var arrLength = arr.length;
  var valLength = val.length;
  if (encoding !== void 0) {
    encoding = String(encoding).toLowerCase();
    if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") {
      if (arr.length < 2 || val.length < 2) {
        return -1;
      }
      indexSize = 2;
      arrLength /= 2;
      valLength /= 2;
      byteOffset /= 2;
    }
  }
  function read2(buf, i2) {
    if (indexSize === 1) {
      return buf[i2];
    } else {
      return buf.readUInt16BE(i2 * indexSize);
    }
  }
  var i;
  if (dir) {
    var foundIndex = -1;
    for (i = byteOffset; i < arrLength; i++) {
      if (read2(arr, i) === read2(val, foundIndex === -1 ? 0 : i - foundIndex)) {
        if (foundIndex === -1)
          foundIndex = i;
        if (i - foundIndex + 1 === valLength)
          return foundIndex * indexSize;
      } else {
        if (foundIndex !== -1)
          i -= i - foundIndex;
        foundIndex = -1;
      }
    }
  } else {
    if (byteOffset + valLength > arrLength)
      byteOffset = arrLength - valLength;
    for (i = byteOffset; i >= 0; i--) {
      var found = true;
      for (var j = 0; j < valLength; j++) {
        if (read2(arr, i + j) !== read2(val, j)) {
          found = false;
          break;
        }
      }
      if (found)
        return i;
    }
  }
  return -1;
}
Buffer$1.prototype.includes = function includes(val, byteOffset, encoding) {
  return this.indexOf(val, byteOffset, encoding) !== -1;
};
Buffer$1.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
  return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
};
Buffer$1.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
  return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
};
function hexWrite(buf, string3, offset, length2) {
  offset = Number(offset) || 0;
  var remaining = buf.length - offset;
  if (!length2) {
    length2 = remaining;
  } else {
    length2 = Number(length2);
    if (length2 > remaining) {
      length2 = remaining;
    }
  }
  var strLen = string3.length;
  if (strLen % 2 !== 0)
    throw new TypeError("Invalid hex string");
  if (length2 > strLen / 2) {
    length2 = strLen / 2;
  }
  for (var i = 0; i < length2; ++i) {
    var parsed = parseInt(string3.substr(i * 2, 2), 16);
    if (isNaN(parsed))
      return i;
    buf[offset + i] = parsed;
  }
  return i;
}
function utf8Write(buf, string3, offset, length2) {
  return blitBuffer(utf8ToBytes(string3, buf.length - offset), buf, offset, length2);
}
function asciiWrite(buf, string3, offset, length2) {
  return blitBuffer(asciiToBytes(string3), buf, offset, length2);
}
function latin1Write(buf, string3, offset, length2) {
  return asciiWrite(buf, string3, offset, length2);
}
function base64Write(buf, string3, offset, length2) {
  return blitBuffer(base64ToBytes(string3), buf, offset, length2);
}
function ucs2Write(buf, string3, offset, length2) {
  return blitBuffer(utf16leToBytes(string3, buf.length - offset), buf, offset, length2);
}
Buffer$1.prototype.write = function write2(string3, offset, length2, encoding) {
  if (offset === void 0) {
    encoding = "utf8";
    length2 = this.length;
    offset = 0;
  } else if (length2 === void 0 && typeof offset === "string") {
    encoding = offset;
    length2 = this.length;
    offset = 0;
  } else if (isFinite(offset)) {
    offset = offset | 0;
    if (isFinite(length2)) {
      length2 = length2 | 0;
      if (encoding === void 0)
        encoding = "utf8";
    } else {
      encoding = length2;
      length2 = void 0;
    }
  } else {
    throw new Error(
      "Buffer.write(string, encoding, offset[, length]) is no longer supported"
    );
  }
  var remaining = this.length - offset;
  if (length2 === void 0 || length2 > remaining)
    length2 = remaining;
  if (string3.length > 0 && (length2 < 0 || offset < 0) || offset > this.length) {
    throw new RangeError("Attempt to write outside buffer bounds");
  }
  if (!encoding)
    encoding = "utf8";
  var loweredCase = false;
  for (; ; ) {
    switch (encoding) {
      case "hex":
        return hexWrite(this, string3, offset, length2);
      case "utf8":
      case "utf-8":
        return utf8Write(this, string3, offset, length2);
      case "ascii":
        return asciiWrite(this, string3, offset, length2);
      case "latin1":
      case "binary":
        return latin1Write(this, string3, offset, length2);
      case "base64":
        return base64Write(this, string3, offset, length2);
      case "ucs2":
      case "ucs-2":
      case "utf16le":
      case "utf-16le":
        return ucs2Write(this, string3, offset, length2);
      default:
        if (loweredCase)
          throw new TypeError("Unknown encoding: " + encoding);
        encoding = ("" + encoding).toLowerCase();
        loweredCase = true;
    }
  }
};
Buffer$1.prototype.toJSON = function toJSON() {
  return {
    type: "Buffer",
    data: Array.prototype.slice.call(this._arr || this, 0)
  };
};
function base64Slice(buf, start, end) {
  if (start === 0 && end === buf.length) {
    return fromByteArray(buf);
  } else {
    return fromByteArray(buf.slice(start, end));
  }
}
function utf8Slice(buf, start, end) {
  end = Math.min(buf.length, end);
  var res = [];
  var i = start;
  while (i < end) {
    var firstByte = buf[i];
    var codePoint = null;
    var bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;
    if (i + bytesPerSequence <= end) {
      var secondByte, thirdByte, fourthByte, tempCodePoint;
      switch (bytesPerSequence) {
        case 1:
          if (firstByte < 128) {
            codePoint = firstByte;
          }
          break;
        case 2:
          secondByte = buf[i + 1];
          if ((secondByte & 192) === 128) {
            tempCodePoint = (firstByte & 31) << 6 | secondByte & 63;
            if (tempCodePoint > 127) {
              codePoint = tempCodePoint;
            }
          }
          break;
        case 3:
          secondByte = buf[i + 1];
          thirdByte = buf[i + 2];
          if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) {
            tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63;
            if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) {
              codePoint = tempCodePoint;
            }
          }
          break;
        case 4:
          secondByte = buf[i + 1];
          thirdByte = buf[i + 2];
          fourthByte = buf[i + 3];
          if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) {
            tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63;
            if (tempCodePoint > 65535 && tempCodePoint < 1114112) {
              codePoint = tempCodePoint;
            }
          }
      }
    }
    if (codePoint === null) {
      codePoint = 65533;
      bytesPerSequence = 1;
    } else if (codePoint > 65535) {
      codePoint -= 65536;
      res.push(codePoint >>> 10 & 1023 | 55296);
      codePoint = 56320 | codePoint & 1023;
    }
    res.push(codePoint);
    i += bytesPerSequence;
  }
  return decodeCodePointsArray(res);
}
var MAX_ARGUMENTS_LENGTH = 4096;
function decodeCodePointsArray(codePoints) {
  var len = codePoints.length;
  if (len <= MAX_ARGUMENTS_LENGTH) {
    return String.fromCharCode.apply(String, codePoints);
  }
  var res = "";
  var i = 0;
  while (i < len) {
    res += String.fromCharCode.apply(
      String,
      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
    );
  }
  return res;
}
function asciiSlice(buf, start, end) {
  var ret = "";
  end = Math.min(buf.length, end);
  for (var i = start; i < end; ++i) {
    ret += String.fromCharCode(buf[i] & 127);
  }
  return ret;
}
function latin1Slice(buf, start, end) {
  var ret = "";
  end = Math.min(buf.length, end);
  for (var i = start; i < end; ++i) {
    ret += String.fromCharCode(buf[i]);
  }
  return ret;
}
function hexSlice(buf, start, end) {
  var len = buf.length;
  if (!start || start < 0)
    start = 0;
  if (!end || end < 0 || end > len)
    end = len;
  var out = "";
  for (var i = start; i < end; ++i) {
    out += toHex(buf[i]);
  }
  return out;
}
function utf16leSlice(buf, start, end) {
  var bytes = buf.slice(start, end);
  var res = "";
  for (var i = 0; i < bytes.length; i += 2) {
    res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
  }
  return res;
}
Buffer$1.prototype.slice = function slice(start, end) {
  var len = this.length;
  start = ~~start;
  end = end === void 0 ? len : ~~end;
  if (start < 0) {
    start += len;
    if (start < 0)
      start = 0;
  } else if (start > len) {
    start = len;
  }
  if (end < 0) {
    end += len;
    if (end < 0)
      end = 0;
  } else if (end > len) {
    end = len;
  }
  if (end < start)
    end = start;
  var newBuf;
  if (Buffer$1.TYPED_ARRAY_SUPPORT) {
    newBuf = this.subarray(start, end);
    newBuf.__proto__ = Buffer$1.prototype;
  } else {
    var sliceLen = end - start;
    newBuf = new Buffer$1(sliceLen, void 0);
    for (var i = 0; i < sliceLen; ++i) {
      newBuf[i] = this[i + start];
    }
  }
  return newBuf;
};
function checkOffset(offset, ext, length2) {
  if (offset % 1 !== 0 || offset < 0)
    throw new RangeError("offset is not uint");
  if (offset + ext > length2)
    throw new RangeError("Trying to access beyond buffer length");
}
Buffer$1.prototype.readUIntLE = function readUIntLE(offset, byteLength2, noAssert) {
  offset = offset | 0;
  byteLength2 = byteLength2 | 0;
  if (!noAssert)
    checkOffset(offset, byteLength2, this.length);
  var val = this[offset];
  var mul = 1;
  var i = 0;
  while (++i < byteLength2 && (mul *= 256)) {
    val += this[offset + i] * mul;
  }
  return val;
};
Buffer$1.prototype.readUIntBE = function readUIntBE(offset, byteLength2, noAssert) {
  offset = offset | 0;
  byteLength2 = byteLength2 | 0;
  if (!noAssert) {
    checkOffset(offset, byteLength2, this.length);
  }
  var val = this[offset + --byteLength2];
  var mul = 1;
  while (byteLength2 > 0 && (mul *= 256)) {
    val += this[offset + --byteLength2] * mul;
  }
  return val;
};
Buffer$1.prototype.readUInt8 = function readUInt82(offset, noAssert) {
  if (!noAssert)
    checkOffset(offset, 1, this.length);
  return this[offset];
};
Buffer$1.prototype.readUInt16LE = function readUInt16LE2(offset, noAssert) {
  if (!noAssert)
    checkOffset(offset, 2, this.length);
  return this[offset] | this[offset + 1] << 8;
};
Buffer$1.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
  if (!noAssert)
    checkOffset(offset, 2, this.length);
  return this[offset] << 8 | this[offset + 1];
};
Buffer$1.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
  if (!noAssert)
    checkOffset(offset, 4, this.length);
  return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216;
};
Buffer$1.prototype.readUInt32BE = function readUInt32BE2(offset, noAssert) {
  if (!noAssert)
    checkOffset(offset, 4, this.length);
  return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
};
Buffer$1.prototype.readIntLE = function readIntLE(offset, byteLength2, noAssert) {
  offset = offset | 0;
  byteLength2 = byteLength2 | 0;
  if (!noAssert)
    checkOffset(offset, byteLength2, this.length);
  var val = this[offset];
  var mul = 1;
  var i = 0;
  while (++i < byteLength2 && (mul *= 256)) {
    val += this[offset + i] * mul;
  }
  mul *= 128;
  if (val >= mul)
    val -= Math.pow(2, 8 * byteLength2);
  return val;
};
Buffer$1.prototype.readIntBE = function readIntBE(offset, byteLength2, noAssert) {
  offset = offset | 0;
  byteLength2 = byteLength2 | 0;
  if (!noAssert)
    checkOffset(offset, byteLength2, this.length);
  var i = byteLength2;
  var mul = 1;
  var val = this[offset + --i];
  while (i > 0 && (mul *= 256)) {
    val += this[offset + --i] * mul;
  }
  mul *= 128;
  if (val >= mul)
    val -= Math.pow(2, 8 * byteLength2);
  return val;
};
Buffer$1.prototype.readInt8 = function readInt8(offset, noAssert) {
  if (!noAssert)
    checkOffset(offset, 1, this.length);
  if (!(this[offset] & 128))
    return this[offset];
  return (255 - this[offset] + 1) * -1;
};
Buffer$1.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
  if (!noAssert)
    checkOffset(offset, 2, this.length);
  var val = this[offset] | this[offset + 1] << 8;
  return val & 32768 ? val | 4294901760 : val;
};
Buffer$1.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
  if (!noAssert)
    checkOffset(offset, 2, this.length);
  var val = this[offset + 1] | this[offset] << 8;
  return val & 32768 ? val | 4294901760 : val;
};
Buffer$1.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
  if (!noAssert)
    checkOffset(offset, 4, this.length);
  return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
};
Buffer$1.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
  if (!noAssert)
    checkOffset(offset, 4, this.length);
  return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
};
Buffer$1.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
  if (!noAssert)
    checkOffset(offset, 4, this.length);
  return read$1(this, offset, true, 23, 4);
};
Buffer$1.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
  if (!noAssert)
    checkOffset(offset, 4, this.length);
  return read$1(this, offset, false, 23, 4);
};
Buffer$1.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
  if (!noAssert)
    checkOffset(offset, 8, this.length);
  return read$1(this, offset, true, 52, 8);
};
Buffer$1.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
  if (!noAssert)
    checkOffset(offset, 8, this.length);
  return read$1(this, offset, false, 52, 8);
};
function checkInt(buf, value, offset, ext, max, min) {
  if (!internalIsBuffer(buf))
    throw new TypeError('"buffer" argument must be a Buffer instance');
  if (value > max || value < min)
    throw new RangeError('"value" argument is out of bounds');
  if (offset + ext > buf.length)
    throw new RangeError("Index out of range");
}
Buffer$1.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength2, noAssert) {
  value = +value;
  offset = offset | 0;
  byteLength2 = byteLength2 | 0;
  if (!noAssert) {
    var maxBytes = Math.pow(2, 8 * byteLength2) - 1;
    checkInt(this, value, offset, byteLength2, maxBytes, 0);
  }
  var mul = 1;
  var i = 0;
  this[offset] = value & 255;
  while (++i < byteLength2 && (mul *= 256)) {
    this[offset + i] = value / mul & 255;
  }
  return offset + byteLength2;
};
Buffer$1.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength2, noAssert) {
  value = +value;
  offset = offset | 0;
  byteLength2 = byteLength2 | 0;
  if (!noAssert) {
    var maxBytes = Math.pow(2, 8 * byteLength2) - 1;
    checkInt(this, value, offset, byteLength2, maxBytes, 0);
  }
  var i = byteLength2 - 1;
  var mul = 1;
  this[offset + i] = value & 255;
  while (--i >= 0 && (mul *= 256)) {
    this[offset + i] = value / mul & 255;
  }
  return offset + byteLength2;
};
Buffer$1.prototype.writeUInt8 = function writeUInt82(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert)
    checkInt(this, value, offset, 1, 255, 0);
  if (!Buffer$1.TYPED_ARRAY_SUPPORT)
    value = Math.floor(value);
  this[offset] = value & 255;
  return offset + 1;
};
function objectWriteUInt16(buf, value, offset, littleEndian) {
  if (value < 0)
    value = 65535 + value + 1;
  for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
    buf[offset + i] = (value & 255 << 8 * (littleEndian ? i : 1 - i)) >>> (littleEndian ? i : 1 - i) * 8;
  }
}
Buffer$1.prototype.writeUInt16LE = function writeUInt16LE2(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert)
    checkInt(this, value, offset, 2, 65535, 0);
  if (Buffer$1.TYPED_ARRAY_SUPPORT) {
    this[offset] = value & 255;
    this[offset + 1] = value >>> 8;
  } else {
    objectWriteUInt16(this, value, offset, true);
  }
  return offset + 2;
};
Buffer$1.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert)
    checkInt(this, value, offset, 2, 65535, 0);
  if (Buffer$1.TYPED_ARRAY_SUPPORT) {
    this[offset] = value >>> 8;
    this[offset + 1] = value & 255;
  } else {
    objectWriteUInt16(this, value, offset, false);
  }
  return offset + 2;
};
function objectWriteUInt32(buf, value, offset, littleEndian) {
  if (value < 0)
    value = 4294967295 + value + 1;
  for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
    buf[offset + i] = value >>> (littleEndian ? i : 3 - i) * 8 & 255;
  }
}
Buffer$1.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert)
    checkInt(this, value, offset, 4, 4294967295, 0);
  if (Buffer$1.TYPED_ARRAY_SUPPORT) {
    this[offset + 3] = value >>> 24;
    this[offset + 2] = value >>> 16;
    this[offset + 1] = value >>> 8;
    this[offset] = value & 255;
  } else {
    objectWriteUInt32(this, value, offset, true);
  }
  return offset + 4;
};
Buffer$1.prototype.writeUInt32BE = function writeUInt32BE2(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert)
    checkInt(this, value, offset, 4, 4294967295, 0);
  if (Buffer$1.TYPED_ARRAY_SUPPORT) {
    this[offset] = value >>> 24;
    this[offset + 1] = value >>> 16;
    this[offset + 2] = value >>> 8;
    this[offset + 3] = value & 255;
  } else {
    objectWriteUInt32(this, value, offset, false);
  }
  return offset + 4;
};
Buffer$1.prototype.writeIntLE = function writeIntLE(value, offset, byteLength2, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert) {
    var limit = Math.pow(2, 8 * byteLength2 - 1);
    checkInt(this, value, offset, byteLength2, limit - 1, -limit);
  }
  var i = 0;
  var mul = 1;
  var sub = 0;
  this[offset] = value & 255;
  while (++i < byteLength2 && (mul *= 256)) {
    if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
      sub = 1;
    }
    this[offset + i] = (value / mul >> 0) - sub & 255;
  }
  return offset + byteLength2;
};
Buffer$1.prototype.writeIntBE = function writeIntBE(value, offset, byteLength2, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert) {
    var limit = Math.pow(2, 8 * byteLength2 - 1);
    checkInt(this, value, offset, byteLength2, limit - 1, -limit);
  }
  var i = byteLength2 - 1;
  var mul = 1;
  var sub = 0;
  this[offset + i] = value & 255;
  while (--i >= 0 && (mul *= 256)) {
    if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
      sub = 1;
    }
    this[offset + i] = (value / mul >> 0) - sub & 255;
  }
  return offset + byteLength2;
};
Buffer$1.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert)
    checkInt(this, value, offset, 1, 127, -128);
  if (!Buffer$1.TYPED_ARRAY_SUPPORT)
    value = Math.floor(value);
  if (value < 0)
    value = 255 + value + 1;
  this[offset] = value & 255;
  return offset + 1;
};
Buffer$1.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert)
    checkInt(this, value, offset, 2, 32767, -32768);
  if (Buffer$1.TYPED_ARRAY_SUPPORT) {
    this[offset] = value & 255;
    this[offset + 1] = value >>> 8;
  } else {
    objectWriteUInt16(this, value, offset, true);
  }
  return offset + 2;
};
Buffer$1.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert)
    checkInt(this, value, offset, 2, 32767, -32768);
  if (Buffer$1.TYPED_ARRAY_SUPPORT) {
    this[offset] = value >>> 8;
    this[offset + 1] = value & 255;
  } else {
    objectWriteUInt16(this, value, offset, false);
  }
  return offset + 2;
};
Buffer$1.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert)
    checkInt(this, value, offset, 4, 2147483647, -2147483648);
  if (Buffer$1.TYPED_ARRAY_SUPPORT) {
    this[offset] = value & 255;
    this[offset + 1] = value >>> 8;
    this[offset + 2] = value >>> 16;
    this[offset + 3] = value >>> 24;
  } else {
    objectWriteUInt32(this, value, offset, true);
  }
  return offset + 4;
};
Buffer$1.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
  value = +value;
  offset = offset | 0;
  if (!noAssert)
    checkInt(this, value, offset, 4, 2147483647, -2147483648);
  if (value < 0)
    value = 4294967295 + value + 1;
  if (Buffer$1.TYPED_ARRAY_SUPPORT) {
    this[offset] = value >>> 24;
    this[offset + 1] = value >>> 16;
    this[offset + 2] = value >>> 8;
    this[offset + 3] = value & 255;
  } else {
    objectWriteUInt32(this, value, offset, false);
  }
  return offset + 4;
};
function checkIEEE754(buf, value, offset, ext, max, min) {
  if (offset + ext > buf.length)
    throw new RangeError("Index out of range");
  if (offset < 0)
    throw new RangeError("Index out of range");
}
function writeFloat(buf, value, offset, littleEndian, noAssert) {
  if (!noAssert) {
    checkIEEE754(buf, value, offset, 4);
  }
  write(buf, value, offset, littleEndian, 23, 4);
  return offset + 4;
}
Buffer$1.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
  return writeFloat(this, value, offset, true, noAssert);
};
Buffer$1.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
  return writeFloat(this, value, offset, false, noAssert);
};
function writeDouble(buf, value, offset, littleEndian, noAssert) {
  if (!noAssert) {
    checkIEEE754(buf, value, offset, 8);
  }
  write(buf, value, offset, littleEndian, 52, 8);
  return offset + 8;
}
Buffer$1.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
  return writeDouble(this, value, offset, true, noAssert);
};
Buffer$1.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
  return writeDouble(this, value, offset, false, noAssert);
};
Buffer$1.prototype.copy = function copy(target, targetStart, start, end) {
  if (!start)
    start = 0;
  if (!end && end !== 0)
    end = this.length;
  if (targetStart >= target.length)
    targetStart = target.length;
  if (!targetStart)
    targetStart = 0;
  if (end > 0 && end < start)
    end = start;
  if (end === start)
    return 0;
  if (target.length === 0 || this.length === 0)
    return 0;
  if (targetStart < 0) {
    throw new RangeError("targetStart out of bounds");
  }
  if (start < 0 || start >= this.length)
    throw new RangeError("sourceStart out of bounds");
  if (end < 0)
    throw new RangeError("sourceEnd out of bounds");
  if (end > this.length)
    end = this.length;
  if (target.length - targetStart < end - start) {
    end = target.length - targetStart + start;
  }
  var len = end - start;
  var i;
  if (this === target && start < targetStart && targetStart < end) {
    for (i = len - 1; i >= 0; --i) {
      target[i + targetStart] = this[i + start];
    }
  } else if (len < 1e3 || !Buffer$1.TYPED_ARRAY_SUPPORT) {
    for (i = 0; i < len; ++i) {
      target[i + targetStart] = this[i + start];
    }
  } else {
    Uint8Array.prototype.set.call(
      target,
      this.subarray(start, start + len),
      targetStart
    );
  }
  return len;
};
Buffer$1.prototype.fill = function fill2(val, start, end, encoding) {
  if (typeof val === "string") {
    if (typeof start === "string") {
      encoding = start;
      start = 0;
      end = this.length;
    } else if (typeof end === "string") {
      encoding = end;
      end = this.length;
    }
    if (val.length === 1) {
      var code = val.charCodeAt(0);
      if (code < 256) {
        val = code;
      }
    }
    if (encoding !== void 0 && typeof encoding !== "string") {
      throw new TypeError("encoding must be a string");
    }
    if (typeof encoding === "string" && !Buffer$1.isEncoding(encoding)) {
      throw new TypeError("Unknown encoding: " + encoding);
    }
  } else if (typeof val === "number") {
    val = val & 255;
  }
  if (start < 0 || this.length < start || this.length < end) {
    throw new RangeError("Out of range index");
  }
  if (end <= start) {
    return this;
  }
  start = start >>> 0;
  end = end === void 0 ? this.length : end >>> 0;
  if (!val)
    val = 0;
  var i;
  if (typeof val === "number") {
    for (i = start; i < end; ++i) {
      this[i] = val;
    }
  } else {
    var bytes = internalIsBuffer(val) ? val : utf8ToBytes(new Buffer$1(val, encoding).toString());
    var len = bytes.length;
    for (i = 0; i < end - start; ++i) {
      this[i + start] = bytes[i % len];
    }
  }
  return this;
};
var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
function base64clean(str2) {
  str2 = stringtrim(str2).replace(INVALID_BASE64_RE, "");
  if (str2.length < 2)
    return "";
  while (str2.length % 4 !== 0) {
    str2 = str2 + "=";
  }
  return str2;
}
function stringtrim(str2) {
  if (str2.trim)
    return str2.trim();
  return str2.replace(/^\s+|\s+$/g, "");
}
function toHex(n2) {
  if (n2 < 16)
    return "0" + n2.toString(16);
  return n2.toString(16);
}
function utf8ToBytes(string3, units) {
  units = units || Infinity;
  var codePoint;
  var length2 = string3.length;
  var leadSurrogate = null;
  var bytes = [];
  for (var i = 0; i < length2; ++i) {
    codePoint = string3.charCodeAt(i);
    if (codePoint > 55295 && codePoint < 57344) {
      if (!leadSurrogate) {
        if (codePoint > 56319) {
          if ((units -= 3) > -1)
            bytes.push(239, 191, 189);
          continue;
        } else if (i + 1 === length2) {
          if ((units -= 3) > -1)
            bytes.push(239, 191, 189);
          continue;
        }
        leadSurrogate = codePoint;
        continue;
      }
      if (codePoint < 56320) {
        if ((units -= 3) > -1)
          bytes.push(239, 191, 189);
        leadSurrogate = codePoint;
        continue;
      }
      codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536;
    } else if (leadSurrogate) {
      if ((units -= 3) > -1)
        bytes.push(239, 191, 189);
    }
    leadSurrogate = null;
    if (codePoint < 128) {
      if ((units -= 1) < 0)
        break;
      bytes.push(codePoint);
    } else if (codePoint < 2048) {
      if ((units -= 2) < 0)
        break;
      bytes.push(
        codePoint >> 6 | 192,
        codePoint & 63 | 128
      );
    } else if (codePoint < 65536) {
      if ((units -= 3) < 0)
        break;
      bytes.push(
        codePoint >> 12 | 224,
        codePoint >> 6 & 63 | 128,
        codePoint & 63 | 128
      );
    } else if (codePoint < 1114112) {
      if ((units -= 4) < 0)
        break;
      bytes.push(
        codePoint >> 18 | 240,
        codePoint >> 12 & 63 | 128,
        codePoint >> 6 & 63 | 128,
        codePoint & 63 | 128
      );
    } else {
      throw new Error("Invalid code point");
    }
  }
  return bytes;
}
function asciiToBytes(str2) {
  var byteArray = [];
  for (var i = 0; i < str2.length; ++i) {
    byteArray.push(str2.charCodeAt(i) & 255);
  }
  return byteArray;
}
function utf16leToBytes(str2, units) {
  var c, hi, lo;
  var byteArray = [];
  for (var i = 0; i < str2.length; ++i) {
    if ((units -= 2) < 0)
      break;
    c = str2.charCodeAt(i);
    hi = c >> 8;
    lo = c % 256;
    byteArray.push(lo);
    byteArray.push(hi);
  }
  return byteArray;
}
function base64ToBytes(str2) {
  return toByteArray(base64clean(str2));
}
function blitBuffer(src, dst, offset, length2) {
  for (var i = 0; i < length2; ++i) {
    if (i + offset >= dst.length || i >= src.length)
      break;
    dst[i + offset] = src[i];
  }
  return i;
}
function isnan(val) {
  return val !== val;
}
function isBuffer$1(obj) {
  return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj));
}
function isFastBuffer(obj) {
  return !!obj.constructor && typeof obj.constructor.isBuffer === "function" && obj.constructor.isBuffer(obj);
}
function isSlowBuffer(obj) {
  return typeof obj.readFloatLE === "function" && typeof obj.slice === "function" && isFastBuffer(obj.slice(0, 0));
}
function defaultSetTimout() {
  throw new Error("setTimeout has not been defined");
}
function defaultClearTimeout() {
  throw new Error("clearTimeout has not been defined");
}
var cachedSetTimeout = defaultSetTimout;
var cachedClearTimeout = defaultClearTimeout;
if (typeof global$1.setTimeout === "function") {
  cachedSetTimeout = setTimeout;
}
if (typeof global$1.clearTimeout === "function") {
  cachedClearTimeout = clearTimeout;
}
function runTimeout(fun) {
  if (cachedSetTimeout === setTimeout) {
    return setTimeout(fun, 0);
  }
  if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
    cachedSetTimeout = setTimeout;
    return setTimeout(fun, 0);
  }
  try {
    return cachedSetTimeout(fun, 0);
  } catch (e) {
    try {
      return cachedSetTimeout.call(null, fun, 0);
    } catch (e2) {
      return cachedSetTimeout.call(this, fun, 0);
    }
  }
}
function runClearTimeout(marker) {
  if (cachedClearTimeout === clearTimeout) {
    return clearTimeout(marker);
  }
  if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
    cachedClearTimeout = clearTimeout;
    return clearTimeout(marker);
  }
  try {
    return cachedClearTimeout(marker);
  } catch (e) {
    try {
      return cachedClearTimeout.call(null, marker);
    } catch (e2) {
      return cachedClearTimeout.call(this, marker);
    }
  }
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
  if (!draining || !currentQueue) {
    return;
  }
  draining = false;
  if (currentQueue.length) {
    queue = currentQueue.concat(queue);
  } else {
    queueIndex = -1;
  }
  if (queue.length) {
    drainQueue();
  }
}
function drainQueue() {
  if (draining) {
    return;
  }
  var timeout2 = runTimeout(cleanUpNextTick);
  draining = true;
  var len = queue.length;
  while (len) {
    currentQueue = queue;
    queue = [];
    while (++queueIndex < len) {
      if (currentQueue) {
        currentQueue[queueIndex].run();
      }
    }
    queueIndex = -1;
    len = queue.length;
  }
  currentQueue = null;
  draining = false;
  runClearTimeout(timeout2);
}
function nextTick(fun) {
  var args = new Array(arguments.length - 1);
  if (arguments.length > 1) {
    for (var i = 1; i < arguments.length; i++) {
      args[i - 1] = arguments[i];
    }
  }
  queue.push(new Item(fun, args));
  if (queue.length === 1 && !draining) {
    runTimeout(drainQueue);
  }
}
function Item(fun, array2) {
  this.fun = fun;
  this.array = array2;
}
Item.prototype.run = function() {
  this.fun.apply(null, this.array);
};
var title = "browser";
var platform = "browser";
var browser = true;
var env = {};
var argv = [];
var version$1 = "";
var versions = {};
var release = {};
var config = {};
function noop() {
}
var on = noop;
var addListener = noop;
var once = noop;
var off = noop;
var removeListener = noop;
var removeAllListeners = noop;
var emit = noop;
function binding(name) {
  throw new Error("process.binding is not supported");
}
function cwd() {
  return "/";
}
function chdir(dir) {
  throw new Error("process.chdir is not supported");
}
function umask() {
  return 0;
}
var performance$1 = global$1.performance || {};
var performanceNow = performance$1.now || performance$1.mozNow || performance$1.msNow || performance$1.oNow || performance$1.webkitNow || function() {
  return (/* @__PURE__ */ new Date()).getTime();
};
function hrtime(previousTimestamp) {
  var clocktime = performanceNow.call(performance$1) * 1e-3;
  var seconds = Math.floor(clocktime);
  var nanoseconds = Math.floor(clocktime % 1 * 1e9);
  if (previousTimestamp) {
    seconds = seconds - previousTimestamp[0];
    nanoseconds = nanoseconds - previousTimestamp[1];
    if (nanoseconds < 0) {
      seconds--;
      nanoseconds += 1e9;
    }
  }
  return [seconds, nanoseconds];
}
var startTime = /* @__PURE__ */ new Date();
function uptime() {
  var currentTime = /* @__PURE__ */ new Date();
  var dif = currentTime - startTime;
  return dif / 1e3;
}
var browser$1 = {
  nextTick,
  title,
  browser,
  env,
  argv,
  version: version$1,
  versions,
  on,
  addListener,
  once,
  off,
  removeListener,
  removeAllListeners,
  emit,
  binding,
  cwd,
  chdir,
  umask,
  hrtime,
  platform,
  release,
  config,
  uptime
};
var inherits;
if (typeof Object.create === "function") {
  inherits = function inherits2(ctor, superCtor) {
    ctor.super_ = superCtor;
    ctor.prototype = Object.create(superCtor.prototype, {
      constructor: {
        value: ctor,
        enumerable: false,
        writable: true,
        configurable: true
      }
    });
  };
} else {
  inherits = function inherits2(ctor, superCtor) {
    ctor.super_ = superCtor;
    var TempCtor = function() {
    };
    TempCtor.prototype = superCtor.prototype;
    ctor.prototype = new TempCtor();
    ctor.prototype.constructor = ctor;
  };
}
var inherits$1 = inherits;
var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || function getOwnPropertyDescriptors2(obj) {
  var keys = Object.keys(obj);
  var descriptors = {};
  for (var i = 0; i < keys.length; i++) {
    descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]);
  }
  return descriptors;
};
var formatRegExp = /%[sdj%]/g;
function format$1(f) {
  if (!isString$1(f)) {
    var objects = [];
    for (var i = 0; i < arguments.length; i++) {
      objects.push(inspect2(arguments[i]));
    }
    return objects.join(" ");
  }
  var i = 1;
  var args = arguments;
  var len = args.length;
  var str2 = String(f).replace(formatRegExp, function(x2) {
    if (x2 === "%%")
      return "%";
    if (i >= len)
      return x2;
    switch (x2) {
      case "%s":
        return String(args[i++]);
      case "%d":
        return Number(args[i++]);
      case "%j":
        try {
          return JSON.stringify(args[i++]);
        } catch (_) {
          return "[Circular]";
        }
      default:
        return x2;
    }
  });
  for (var x = args[i]; i < len; x = args[++i]) {
    if (isNull(x) || !isObject$1(x)) {
      str2 += " " + x;
    } else {
      str2 += " " + inspect2(x);
    }
  }
  return str2;
}
function deprecate(fn, msg) {
  if (isUndefined(global$1.process)) {
    return function() {
      return deprecate(fn, msg).apply(this, arguments);
    };
  }
  if (browser$1.noDeprecation === true) {
    return fn;
  }
  var warned2 = false;
  function deprecated() {
    if (!warned2) {
      if (browser$1.throwDeprecation) {
        throw new Error(msg);
      } else if (browser$1.traceDeprecation) {
        console.trace(msg);
      } else {
        console.error(msg);
      }
      warned2 = true;
    }
    return fn.apply(this, arguments);
  }
  return deprecated;
}
var debugs = {};
var debugEnviron;
function debuglog(set2) {
  if (isUndefined(debugEnviron))
    debugEnviron = browser$1.env.NODE_DEBUG || "";
  set2 = set2.toUpperCase();
  if (!debugs[set2]) {
    if (new RegExp("\\b" + set2 + "\\b", "i").test(debugEnviron)) {
      var pid = 0;
      debugs[set2] = function() {
        var msg = format$1.apply(null, arguments);
        console.error("%s %d: %s", set2, pid, msg);
      };
    } else {
      debugs[set2] = function() {
      };
    }
  }
  return debugs[set2];
}
function inspect2(obj, opts) {
  var ctx = {
    seen: [],
    stylize: stylizeNoColor
  };
  if (arguments.length >= 3)
    ctx.depth = arguments[2];
  if (arguments.length >= 4)
    ctx.colors = arguments[3];
  if (isBoolean(opts)) {
    ctx.showHidden = opts;
  } else if (opts) {
    _extend(ctx, opts);
  }
  if (isUndefined(ctx.showHidden))
    ctx.showHidden = false;
  if (isUndefined(ctx.depth))
    ctx.depth = 2;
  if (isUndefined(ctx.colors))
    ctx.colors = false;
  if (isUndefined(ctx.customInspect))
    ctx.customInspect = true;
  if (ctx.colors)
    ctx.stylize = stylizeWithColor;
  return formatValue(ctx, obj, ctx.depth);
}
inspect2.colors = {
  "bold": [1, 22],
  "italic": [3, 23],
  "underline": [4, 24],
  "inverse": [7, 27],
  "white": [37, 39],
  "grey": [90, 39],
  "black": [30, 39],
  "blue": [34, 39],
  "cyan": [36, 39],
  "green": [32, 39],
  "magenta": [35, 39],
  "red": [31, 39],
  "yellow": [33, 39]
};
inspect2.styles = {
  "special": "cyan",
  "number": "yellow",
  "boolean": "yellow",
  "undefined": "grey",
  "null": "bold",
  "string": "green",
  "date": "magenta",
  // "name": intentionally not styling
  "regexp": "red"
};
function stylizeWithColor(str2, styleType) {
  var style2 = inspect2.styles[styleType];
  if (style2) {
    return "\x1B[" + inspect2.colors[style2][0] + "m" + str2 + "\x1B[" + inspect2.colors[style2][1] + "m";
  } else {
    return str2;
  }
}
function stylizeNoColor(str2, styleType) {
  return str2;
}
function arrayToHash(array2) {
  var hash2 = {};
  array2.forEach(function(val, idx) {
    hash2[val] = true;
  });
  return hash2;
}
function formatValue(ctx, value, recurseTimes) {
  if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special
  value.inspect !== inspect2 && // Also filter out any prototype objects using the circular check.
  !(value.constructor && value.constructor.prototype === value)) {
    var ret = value.inspect(recurseTimes, ctx);
    if (!isString$1(ret)) {
      ret = formatValue(ctx, ret, recurseTimes);
    }
    return ret;
  }
  var primitive = formatPrimitive(ctx, value);
  if (primitive) {
    return primitive;
  }
  var keys = Object.keys(value);
  var visibleKeys = arrayToHash(keys);
  if (ctx.showHidden) {
    keys = Object.getOwnPropertyNames(value);
  }
  if (isError(value) && (keys.indexOf("message") >= 0 || keys.indexOf("description") >= 0)) {
    return formatError(value);
  }
  if (keys.length === 0) {
    if (isFunction(value)) {
      var name = value.name ? ": " + value.name : "";
      return ctx.stylize("[Function" + name + "]", "special");
    }
    if (isRegExp(value)) {
      return ctx.stylize(RegExp.prototype.toString.call(value), "regexp");
    }
    if (isDate(value)) {
      return ctx.stylize(Date.prototype.toString.call(value), "date");
    }
    if (isError(value)) {
      return formatError(value);
    }
  }
  var base2 = "", array2 = false, braces = ["{", "}"];
  if (isArray$1$1(value)) {
    array2 = true;
    braces = ["[", "]"];
  }
  if (isFunction(value)) {
    var n2 = value.name ? ": " + value.name : "";
    base2 = " [Function" + n2 + "]";
  }
  if (isRegExp(value)) {
    base2 = " " + RegExp.prototype.toString.call(value);
  }
  if (isDate(value)) {
    base2 = " " + Date.prototype.toUTCString.call(value);
  }
  if (isError(value)) {
    base2 = " " + formatError(value);
  }
  if (keys.length === 0 && (!array2 || value.length == 0)) {
    return braces[0] + base2 + braces[1];
  }
  if (recurseTimes < 0) {
    if (isRegExp(value)) {
      return ctx.stylize(RegExp.prototype.toString.call(value), "regexp");
    } else {
      return ctx.stylize("[Object]", "special");
    }
  }
  ctx.seen.push(value);
  var output;
  if (array2) {
    output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  } else {
    output = keys.map(function(key) {
      return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array2);
    });
  }
  ctx.seen.pop();
  return reduceToSingleString(output, base2, braces);
}
function formatPrimitive(ctx, value) {
  if (isUndefined(value))
    return ctx.stylize("undefined", "undefined");
  if (isString$1(value)) {
    var simple = "'" + JSON.stringify(value).replace(/^"|"$/g, "").replace(/'/g, "\\'").replace(/\\"/g, '"') + "'";
    return ctx.stylize(simple, "string");
  }
  if (isNumber(value))
    return ctx.stylize("" + value, "number");
  if (isBoolean(value))
    return ctx.stylize("" + value, "boolean");
  if (isNull(value))
    return ctx.stylize("null", "null");
}
function formatError(value) {
  return "[" + Error.prototype.toString.call(value) + "]";
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  var output = [];
  for (var i = 0, l = value.length; i < l; ++i) {
    if (hasOwnProperty$2(value, String(i))) {
      output.push(formatProperty(
        ctx,
        value,
        recurseTimes,
        visibleKeys,
        String(i),
        true
      ));
    } else {
      output.push("");
    }
  }
  keys.forEach(function(key) {
    if (!key.match(/^\d+$/)) {
      output.push(formatProperty(
        ctx,
        value,
        recurseTimes,
        visibleKeys,
        key,
        true
      ));
    }
  });
  return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array2) {
  var name, str2, desc;
  desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  if (desc.get) {
    if (desc.set) {
      str2 = ctx.stylize("[Getter/Setter]", "special");
    } else {
      str2 = ctx.stylize("[Getter]", "special");
    }
  } else {
    if (desc.set) {
      str2 = ctx.stylize("[Setter]", "special");
    }
  }
  if (!hasOwnProperty$2(visibleKeys, key)) {
    name = "[" + key + "]";
  }
  if (!str2) {
    if (ctx.seen.indexOf(desc.value) < 0) {
      if (isNull(recurseTimes)) {
        str2 = formatValue(ctx, desc.value, null);
      } else {
        str2 = formatValue(ctx, desc.value, recurseTimes - 1);
      }
      if (str2.indexOf("\n") > -1) {
        if (array2) {
          str2 = str2.split("\n").map(function(line) {
            return "  " + line;
          }).join("\n").substr(2);
        } else {
          str2 = "\n" + str2.split("\n").map(function(line) {
            return "   " + line;
          }).join("\n");
        }
      }
    } else {
      str2 = ctx.stylize("[Circular]", "special");
    }
  }
  if (isUndefined(name)) {
    if (array2 && key.match(/^\d+$/)) {
      return str2;
    }
    name = JSON.stringify("" + key);
    if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
      name = name.substr(1, name.length - 2);
      name = ctx.stylize(name, "name");
    } else {
      name = name.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'");
      name = ctx.stylize(name, "string");
    }
  }
  return name + ": " + str2;
}
function reduceToSingleString(output, base2, braces) {
  var length2 = output.reduce(function(prev, cur) {
    if (cur.indexOf("\n") >= 0)
      ;
    return prev + cur.replace(/\u001b\[\d\d?m/g, "").length + 1;
  }, 0);
  if (length2 > 60) {
    return braces[0] + (base2 === "" ? "" : base2 + "\n ") + " " + output.join(",\n  ") + " " + braces[1];
  }
  return braces[0] + base2 + " " + output.join(", ") + " " + braces[1];
}
function isArray$1$1(ar) {
  return Array.isArray(ar);
}
function isBoolean(arg) {
  return typeof arg === "boolean";
}
function isNull(arg) {
  return arg === null;
}
function isNullOrUndefined(arg) {
  return arg == null;
}
function isNumber(arg) {
  return typeof arg === "number";
}
function isString$1(arg) {
  return typeof arg === "string";
}
function isSymbol(arg) {
  return typeof arg === "symbol";
}
function isUndefined(arg) {
  return arg === void 0;
}
function isRegExp(re) {
  return isObject$1(re) && objectToString(re) === "[object RegExp]";
}
function isObject$1(arg) {
  return typeof arg === "object" && arg !== null;
}
function isDate(d) {
  return isObject$1(d) && objectToString(d) === "[object Date]";
}
function isError(e) {
  return isObject$1(e) && (objectToString(e) === "[object Error]" || e instanceof Error);
}
function isFunction(arg) {
  return typeof arg === "function";
}
function isPrimitive(arg) {
  return arg === null || typeof arg === "boolean" || typeof arg === "number" || typeof arg === "string" || typeof arg === "symbol" || // ES6 symbol
  typeof arg === "undefined";
}
function isBuffer(maybeBuf) {
  return Buffer$1.isBuffer(maybeBuf);
}
function objectToString(o) {
  return Object.prototype.toString.call(o);
}
function pad(n2) {
  return n2 < 10 ? "0" + n2.toString(10) : n2.toString(10);
}
var months = [
  "Jan",
  "Feb",
  "Mar",
  "Apr",
  "May",
  "Jun",
  "Jul",
  "Aug",
  "Sep",
  "Oct",
  "Nov",
  "Dec"
];
function timestamp() {
  var d = /* @__PURE__ */ new Date();
  var time = [
    pad(d.getHours()),
    pad(d.getMinutes()),
    pad(d.getSeconds())
  ].join(":");
  return [d.getDate(), months[d.getMonth()], time].join(" ");
}
function log() {
  console.log("%s - %s", timestamp(), format$1.apply(null, arguments));
}
function _extend(origin, add2) {
  if (!add2 || !isObject$1(add2))
    return origin;
  var keys = Object.keys(add2);
  var i = keys.length;
  while (i--) {
    origin[keys[i]] = add2[keys[i]];
  }
  return origin;
}
function hasOwnProperty$2(obj, prop) {
  return Object.prototype.hasOwnProperty.call(obj, prop);
}
var kCustomPromisifiedSymbol = typeof Symbol !== "undefined" ? Symbol("util.promisify.custom") : void 0;
function promisify(original) {
  if (typeof original !== "function")
    throw new TypeError('The "original" argument must be of type Function');
  if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {
    var fn = original[kCustomPromisifiedSymbol];
    if (typeof fn !== "function") {
      throw new TypeError('The "util.promisify.custom" argument must be of type Function');
    }
    Object.defineProperty(fn, kCustomPromisifiedSymbol, {
      value: fn,
      enumerable: false,
      writable: false,
      configurable: true
    });
    return fn;
  }
  function fn() {
    var promiseResolve, promiseReject;
    var promise = new Promise(function(resolve2, reject) {
      promiseResolve = resolve2;
      promiseReject = reject;
    });
    var args = [];
    for (var i = 0; i < arguments.length; i++) {
      args.push(arguments[i]);
    }
    args.push(function(err, value) {
      if (err) {
        promiseReject(err);
      } else {
        promiseResolve(value);
      }
    });
    try {
      original.apply(this, args);
    } catch (err) {
      promiseReject(err);
    }
    return promise;
  }
  Object.setPrototypeOf(fn, Object.getPrototypeOf(original));
  if (kCustomPromisifiedSymbol)
    Object.defineProperty(fn, kCustomPromisifiedSymbol, {
      value: fn,
      enumerable: false,
      writable: false,
      configurable: true
    });
  return Object.defineProperties(
    fn,
    getOwnPropertyDescriptors(original)
  );
}
promisify.custom = kCustomPromisifiedSymbol;
function callbackifyOnRejected(reason, cb) {
  if (!reason) {
    var newReason = new Error("Promise was rejected with a falsy value");
    newReason.reason = reason;
    reason = newReason;
  }
  return cb(reason);
}
function callbackify(original) {
  if (typeof original !== "function") {
    throw new TypeError('The "original" argument must be of type Function');
  }
  function callbackified() {
    var args = [];
    for (var i = 0; i < arguments.length; i++) {
      args.push(arguments[i]);
    }
    var maybeCb = args.pop();
    if (typeof maybeCb !== "function") {
      throw new TypeError("The last argument must be of type Function");
    }
    var self2 = this;
    var cb = function() {
      return maybeCb.apply(self2, arguments);
    };
    original.apply(this, args).then(
      function(ret) {
        browser$1.nextTick(cb.bind(null, null, ret));
      },
      function(rej) {
        browser$1.nextTick(callbackifyOnRejected.bind(null, rej, cb));
      }
    );
  }
  Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));
  Object.defineProperties(callbackified, getOwnPropertyDescriptors(original));
  return callbackified;
}
var _polyfillNode_util = {
  inherits: inherits$1,
  _extend,
  log,
  isBuffer,
  isPrimitive,
  isFunction,
  isError,
  isDate,
  isObject: isObject$1,
  isRegExp,
  isUndefined,
  isSymbol,
  isString: isString$1,
  isNumber,
  isNullOrUndefined,
  isNull,
  isBoolean,
  isArray: isArray$1$1,
  inspect: inspect2,
  deprecate,
  format: format$1,
  debuglog,
  promisify,
  callbackify
};
var _polyfillNode_util$1 = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  _extend,
  callbackify,
  debuglog,
  default: _polyfillNode_util,
  deprecate,
  format: format$1,
  inherits: inherits$1,
  inspect: inspect2,
  isArray: isArray$1$1,
  isBoolean,
  isBuffer,
  isDate,
  isError,
  isFunction,
  isNull,
  isNullOrUndefined,
  isNumber,
  isObject: isObject$1,
  isPrimitive,
  isRegExp,
  isString: isString$1,
  isSymbol,
  isUndefined,
  log,
  promisify
});
function hasOwnProperty$1(obj, prop) {
  return Object.prototype.hasOwnProperty.call(obj, prop);
}
var isArray$4 = Array.isArray || function(xs) {
  return Object.prototype.toString.call(xs) === "[object Array]";
};
function stringifyPrimitive(v) {
  switch (typeof v) {
    case "string":
      return v;
    case "boolean":
      return v ? "true" : "false";
    case "number":
      return isFinite(v) ? v : "";
    default:
      return "";
  }
}
function stringify$5(obj, sep2, eq, name) {
  sep2 = sep2 || "&";
  eq = eq || "=";
  if (obj === null) {
    obj = void 0;
  }
  if (typeof obj === "object") {
    return map(objectKeys(obj), function(k) {
      var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
      if (isArray$4(obj[k])) {
        return map(obj[k], function(v) {
          return ks + encodeURIComponent(stringifyPrimitive(v));
        }).join(sep2);
      } else {
        return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
      }
    }).join(sep2);
  }
  if (!name)
    return "";
  return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj));
}
function map(xs, f) {
  if (xs.map)
    return xs.map(f);
  var res = [];
  for (var i = 0; i < xs.length; i++) {
    res.push(f(xs[i], i));
  }
  return res;
}
var objectKeys = Object.keys || function(obj) {
  var res = [];
  for (var key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key))
      res.push(key);
  }
  return res;
};
function parse$6(qs, sep2, eq, options) {
  sep2 = sep2 || "&";
  eq = eq || "=";
  var obj = {};
  if (typeof qs !== "string" || qs.length === 0) {
    return obj;
  }
  var regexp = /\+/g;
  qs = qs.split(sep2);
  var maxKeys = 1e3;
  if (options && typeof options.maxKeys === "number") {
    maxKeys = options.maxKeys;
  }
  var len = qs.length;
  if (maxKeys > 0 && len > maxKeys) {
    len = maxKeys;
  }
  for (var i = 0; i < len; ++i) {
    var x = qs[i].replace(regexp, "%20"), idx = x.indexOf(eq), kstr, vstr, k, v;
    if (idx >= 0) {
      kstr = x.substr(0, idx);
      vstr = x.substr(idx + 1);
    } else {
      kstr = x;
      vstr = "";
    }
    k = decodeURIComponent(kstr);
    v = decodeURIComponent(vstr);
    if (!hasOwnProperty$1(obj, k)) {
      obj[k] = v;
    } else if (isArray$4(obj[k])) {
      obj[k].push(v);
    } else {
      obj[k] = [obj[k], v];
    }
  }
  return obj;
}
const URL$1 = global$1.URL;
const URLSearchParams$1 = global$1.URLSearchParams;
var _polyfillNode_url = {
  parse: urlParse,
  resolve: urlResolve,
  resolveObject: urlResolveObject,
  fileURLToPath: urlFileURLToPath,
  format: urlFormat,
  Url,
  // WHATWG API
  URL: URL$1,
  URLSearchParams: URLSearchParams$1
};
function Url() {
  this.protocol = null;
  this.slashes = null;
  this.auth = null;
  this.host = null;
  this.port = null;
  this.hostname = null;
  this.hash = null;
  this.search = null;
  this.query = null;
  this.pathname = null;
  this.path = null;
  this.href = null;
}
var protocolPattern = /^([a-z0-9.+-]+:)/i, portPattern = /:[0-9]*$/, simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, delims = ["<", ">", '"', "`", " ", "\r", "\n", "	"], unwise = ["{", "}", "|", "\\", "^", "`"].concat(delims), autoEscape = ["'"].concat(unwise), nonHostChars = ["%", "/", "?", ";", "#"].concat(autoEscape), hostEndingChars = ["/", "?", "#"], hostnameMaxLen = 255, hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, unsafeProtocol = {
  "javascript": true,
  "javascript:": true
}, hostlessProtocol = {
  "javascript": true,
  "javascript:": true
}, slashedProtocol = {
  "http": true,
  "https": true,
  "ftp": true,
  "gopher": true,
  "file": true,
  "http:": true,
  "https:": true,
  "ftp:": true,
  "gopher:": true,
  "file:": true
};
function urlParse(url, parseQueryString, slashesDenoteHost) {
  if (url && isObject$1(url) && url instanceof Url)
    return url;
  var u = new Url();
  u.parse(url, parseQueryString, slashesDenoteHost);
  return u;
}
Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  return parse$5(this, url, parseQueryString, slashesDenoteHost);
};
function parse$5(self2, url, parseQueryString, slashesDenoteHost) {
  if (!isString$1(url)) {
    throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
  }
  var queryIndex = url.indexOf("?"), splitter = queryIndex !== -1 && queryIndex < url.indexOf("#") ? "?" : "#", uSplit = url.split(splitter), slashRegex = /\\/g;
  uSplit[0] = uSplit[0].replace(slashRegex, "/");
  url = uSplit.join(splitter);
  var rest = url;
  rest = rest.trim();
  if (!slashesDenoteHost && url.split("#").length === 1) {
    var simplePath = simplePathPattern.exec(rest);
    if (simplePath) {
      self2.path = rest;
      self2.href = rest;
      self2.pathname = simplePath[1];
      if (simplePath[2]) {
        self2.search = simplePath[2];
        if (parseQueryString) {
          self2.query = parse$6(self2.search.substr(1));
        } else {
          self2.query = self2.search.substr(1);
        }
      } else if (parseQueryString) {
        self2.search = "";
        self2.query = {};
      }
      return self2;
    }
  }
  var proto = protocolPattern.exec(rest);
  if (proto) {
    proto = proto[0];
    var lowerProto = proto.toLowerCase();
    self2.protocol = lowerProto;
    rest = rest.substr(proto.length);
  }
  if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
    var slashes = rest.substr(0, 2) === "//";
    if (slashes && !(proto && hostlessProtocol[proto])) {
      rest = rest.substr(2);
      self2.slashes = true;
    }
  }
  var i, hec, l, p2;
  if (!hostlessProtocol[proto] && (slashes || proto && !slashedProtocol[proto])) {
    var hostEnd = -1;
    for (i = 0; i < hostEndingChars.length; i++) {
      hec = rest.indexOf(hostEndingChars[i]);
      if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
        hostEnd = hec;
    }
    var auth, atSign;
    if (hostEnd === -1) {
      atSign = rest.lastIndexOf("@");
    } else {
      atSign = rest.lastIndexOf("@", hostEnd);
    }
    if (atSign !== -1) {
      auth = rest.slice(0, atSign);
      rest = rest.slice(atSign + 1);
      self2.auth = decodeURIComponent(auth);
    }
    hostEnd = -1;
    for (i = 0; i < nonHostChars.length; i++) {
      hec = rest.indexOf(nonHostChars[i]);
      if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
        hostEnd = hec;
    }
    if (hostEnd === -1)
      hostEnd = rest.length;
    self2.host = rest.slice(0, hostEnd);
    rest = rest.slice(hostEnd);
    parseHost(self2);
    self2.hostname = self2.hostname || "";
    var ipv6Hostname = self2.hostname[0] === "[" && self2.hostname[self2.hostname.length - 1] === "]";
    if (!ipv6Hostname) {
      var hostparts = self2.hostname.split(/\./);
      for (i = 0, l = hostparts.length; i < l; i++) {
        var part = hostparts[i];
        if (!part)
          continue;
        if (!part.match(hostnamePartPattern)) {
          var newpart = "";
          for (var j = 0, k = part.length; j < k; j++) {
            if (part.charCodeAt(j) > 127) {
              newpart += "x";
            } else {
              newpart += part[j];
            }
          }
          if (!newpart.match(hostnamePartPattern)) {
            var validParts = hostparts.slice(0, i);
            var notHost = hostparts.slice(i + 1);
            var bit = part.match(hostnamePartStart);
            if (bit) {
              validParts.push(bit[1]);
              notHost.unshift(bit[2]);
            }
            if (notHost.length) {
              rest = "/" + notHost.join(".") + rest;
            }
            self2.hostname = validParts.join(".");
            break;
          }
        }
      }
    }
    if (self2.hostname.length > hostnameMaxLen) {
      self2.hostname = "";
    } else {
      self2.hostname = self2.hostname.toLowerCase();
    }
    if (!ipv6Hostname) {
      self2.hostname = toASCII(self2.hostname);
    }
    p2 = self2.port ? ":" + self2.port : "";
    var h2 = self2.hostname || "";
    self2.host = h2 + p2;
    self2.href += self2.host;
    if (ipv6Hostname) {
      self2.hostname = self2.hostname.substr(1, self2.hostname.length - 2);
      if (rest[0] !== "/") {
        rest = "/" + rest;
      }
    }
  }
  if (!unsafeProtocol[lowerProto]) {
    for (i = 0, l = autoEscape.length; i < l; i++) {
      var ae = autoEscape[i];
      if (rest.indexOf(ae) === -1)
        continue;
      var esc = encodeURIComponent(ae);
      if (esc === ae) {
        esc = escape(ae);
      }
      rest = rest.split(ae).join(esc);
    }
  }
  var hash2 = rest.indexOf("#");
  if (hash2 !== -1) {
    self2.hash = rest.substr(hash2);
    rest = rest.slice(0, hash2);
  }
  var qm = rest.indexOf("?");
  if (qm !== -1) {
    self2.search = rest.substr(qm);
    self2.query = rest.substr(qm + 1);
    if (parseQueryString) {
      self2.query = parse$6(self2.query);
    }
    rest = rest.slice(0, qm);
  } else if (parseQueryString) {
    self2.search = "";
    self2.query = {};
  }
  if (rest)
    self2.pathname = rest;
  if (slashedProtocol[lowerProto] && self2.hostname && !self2.pathname) {
    self2.pathname = "/";
  }
  if (self2.pathname || self2.search) {
    p2 = self2.pathname || "";
    var s = self2.search || "";
    self2.path = p2 + s;
  }
  self2.href = format(self2);
  return self2;
}
function urlFileURLToPath(path2) {
  if (typeof path2 === "string")
    path2 = new Url().parse(path2);
  else if (!(path2 instanceof Url))
    throw new TypeError('The "path" argument must be of type string or an instance of URL. Received type ' + typeof path2 + String(path2));
  if (path2.protocol !== "file:")
    throw new TypeError("The URL must be of scheme file");
  return getPathFromURLPosix(path2);
}
function getPathFromURLPosix(url) {
  const pathname = url.pathname;
  for (let n2 = 0; n2 < pathname.length; n2++) {
    if (pathname[n2] === "%") {
      const third = pathname.codePointAt(n2 + 2) | 32;
      if (pathname[n2 + 1] === "2" && third === 102) {
        throw new TypeError(
          "must not include encoded / characters"
        );
      }
    }
  }
  return decodeURIComponent(pathname);
}
function urlFormat(obj) {
  if (isString$1(obj))
    obj = parse$5({}, obj);
  return format(obj);
}
function format(self2) {
  var auth = self2.auth || "";
  if (auth) {
    auth = encodeURIComponent(auth);
    auth = auth.replace(/%3A/i, ":");
    auth += "@";
  }
  var protocol = self2.protocol || "", pathname = self2.pathname || "", hash2 = self2.hash || "", host = false, query = "";
  if (self2.host) {
    host = auth + self2.host;
  } else if (self2.hostname) {
    host = auth + (self2.hostname.indexOf(":") === -1 ? self2.hostname : "[" + this.hostname + "]");
    if (self2.port) {
      host += ":" + self2.port;
    }
  }
  if (self2.query && isObject$1(self2.query) && Object.keys(self2.query).length) {
    query = stringify$5(self2.query);
  }
  var search2 = self2.search || query && "?" + query || "";
  if (protocol && protocol.substr(-1) !== ":")
    protocol += ":";
  if (self2.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) {
    host = "//" + (host || "");
    if (pathname && pathname.charAt(0) !== "/")
      pathname = "/" + pathname;
  } else if (!host) {
    host = "";
  }
  if (hash2 && hash2.charAt(0) !== "#")
    hash2 = "#" + hash2;
  if (search2 && search2.charAt(0) !== "?")
    search2 = "?" + search2;
  pathname = pathname.replace(/[?#]/g, function(match2) {
    return encodeURIComponent(match2);
  });
  search2 = search2.replace("#", "%23");
  return protocol + host + pathname + search2 + hash2;
}
Url.prototype.format = function() {
  return format(this);
};
function urlResolve(source, relative2) {
  return urlParse(source, false, true).resolve(relative2);
}
Url.prototype.resolve = function(relative2) {
  return this.resolveObject(urlParse(relative2, false, true)).format();
};
function urlResolveObject(source, relative2) {
  if (!source)
    return relative2;
  return urlParse(source, false, true).resolveObject(relative2);
}
Url.prototype.resolveObject = function(relative2) {
  if (isString$1(relative2)) {
    var rel = new Url();
    rel.parse(relative2, false, true);
    relative2 = rel;
  }
  var result2 = new Url();
  var tkeys = Object.keys(this);
  for (var tk = 0; tk < tkeys.length; tk++) {
    var tkey = tkeys[tk];
    result2[tkey] = this[tkey];
  }
  result2.hash = relative2.hash;
  if (relative2.href === "") {
    result2.href = result2.format();
    return result2;
  }
  if (relative2.slashes && !relative2.protocol) {
    var rkeys = Object.keys(relative2);
    for (var rk = 0; rk < rkeys.length; rk++) {
      var rkey = rkeys[rk];
      if (rkey !== "protocol")
        result2[rkey] = relative2[rkey];
    }
    if (slashedProtocol[result2.protocol] && result2.hostname && !result2.pathname) {
      result2.path = result2.pathname = "/";
    }
    result2.href = result2.format();
    return result2;
  }
  var relPath;
  if (relative2.protocol && relative2.protocol !== result2.protocol) {
    if (!slashedProtocol[relative2.protocol]) {
      var keys = Object.keys(relative2);
      for (var v = 0; v < keys.length; v++) {
        var k = keys[v];
        result2[k] = relative2[k];
      }
      result2.href = result2.format();
      return result2;
    }
    result2.protocol = relative2.protocol;
    if (!relative2.host && !hostlessProtocol[relative2.protocol]) {
      relPath = (relative2.pathname || "").split("/");
      while (relPath.length && !(relative2.host = relPath.shift()))
        ;
      if (!relative2.host)
        relative2.host = "";
      if (!relative2.hostname)
        relative2.hostname = "";
      if (relPath[0] !== "")
        relPath.unshift("");
      if (relPath.length < 2)
        relPath.unshift("");
      result2.pathname = relPath.join("/");
    } else {
      result2.pathname = relative2.pathname;
    }
    result2.search = relative2.search;
    result2.query = relative2.query;
    result2.host = relative2.host || "";
    result2.auth = relative2.auth;
    result2.hostname = relative2.hostname || relative2.host;
    result2.port = relative2.port;
    if (result2.pathname || result2.search) {
      var p2 = result2.pathname || "";
      var s = result2.search || "";
      result2.path = p2 + s;
    }
    result2.slashes = result2.slashes || relative2.slashes;
    result2.href = result2.format();
    return result2;
  }
  var isSourceAbs = result2.pathname && result2.pathname.charAt(0) === "/", isRelAbs = relative2.host || relative2.pathname && relative2.pathname.charAt(0) === "/", mustEndAbs = isRelAbs || isSourceAbs || result2.host && relative2.pathname, removeAllDots = mustEndAbs, srcPath = result2.pathname && result2.pathname.split("/") || [], psychotic = result2.protocol && !slashedProtocol[result2.protocol];
  relPath = relative2.pathname && relative2.pathname.split("/") || [];
  if (psychotic) {
    result2.hostname = "";
    result2.port = null;
    if (result2.host) {
      if (srcPath[0] === "")
        srcPath[0] = result2.host;
      else
        srcPath.unshift(result2.host);
    }
    result2.host = "";
    if (relative2.protocol) {
      relative2.hostname = null;
      relative2.port = null;
      if (relative2.host) {
        if (relPath[0] === "")
          relPath[0] = relative2.host;
        else
          relPath.unshift(relative2.host);
      }
      relative2.host = null;
    }
    mustEndAbs = mustEndAbs && (relPath[0] === "" || srcPath[0] === "");
  }
  var authInHost;
  if (isRelAbs) {
    result2.host = relative2.host || relative2.host === "" ? relative2.host : result2.host;
    result2.hostname = relative2.hostname || relative2.hostname === "" ? relative2.hostname : result2.hostname;
    result2.search = relative2.search;
    result2.query = relative2.query;
    srcPath = relPath;
  } else if (relPath.length) {
    if (!srcPath)
      srcPath = [];
    srcPath.pop();
    srcPath = srcPath.concat(relPath);
    result2.search = relative2.search;
    result2.query = relative2.query;
  } else if (!isNullOrUndefined(relative2.search)) {
    if (psychotic) {
      result2.hostname = result2.host = srcPath.shift();
      authInHost = result2.host && result2.host.indexOf("@") > 0 ? result2.host.split("@") : false;
      if (authInHost) {
        result2.auth = authInHost.shift();
        result2.host = result2.hostname = authInHost.shift();
      }
    }
    result2.search = relative2.search;
    result2.query = relative2.query;
    if (!isNull(result2.pathname) || !isNull(result2.search)) {
      result2.path = (result2.pathname ? result2.pathname : "") + (result2.search ? result2.search : "");
    }
    result2.href = result2.format();
    return result2;
  }
  if (!srcPath.length) {
    result2.pathname = null;
    if (result2.search) {
      result2.path = "/" + result2.search;
    } else {
      result2.path = null;
    }
    result2.href = result2.format();
    return result2;
  }
  var last2 = srcPath.slice(-1)[0];
  var hasTrailingSlash = (result2.host || relative2.host || srcPath.length > 1) && (last2 === "." || last2 === "..") || last2 === "";
  var up = 0;
  for (var i = srcPath.length; i >= 0; i--) {
    last2 = srcPath[i];
    if (last2 === ".") {
      srcPath.splice(i, 1);
    } else if (last2 === "..") {
      srcPath.splice(i, 1);
      up++;
    } else if (up) {
      srcPath.splice(i, 1);
      up--;
    }
  }
  if (!mustEndAbs && !removeAllDots) {
    for (; up--; up) {
      srcPath.unshift("..");
    }
  }
  if (mustEndAbs && srcPath[0] !== "" && (!srcPath[0] || srcPath[0].charAt(0) !== "/")) {
    srcPath.unshift("");
  }
  if (hasTrailingSlash && srcPath.join("/").substr(-1) !== "/") {
    srcPath.push("");
  }
  var isAbsolute2 = srcPath[0] === "" || srcPath[0] && srcPath[0].charAt(0) === "/";
  if (psychotic) {
    result2.hostname = result2.host = isAbsolute2 ? "" : srcPath.length ? srcPath.shift() : "";
    authInHost = result2.host && result2.host.indexOf("@") > 0 ? result2.host.split("@") : false;
    if (authInHost) {
      result2.auth = authInHost.shift();
      result2.host = result2.hostname = authInHost.shift();
    }
  }
  mustEndAbs = mustEndAbs || result2.host && srcPath.length;
  if (mustEndAbs && !isAbsolute2) {
    srcPath.unshift("");
  }
  if (!srcPath.length) {
    result2.pathname = null;
    result2.path = null;
  } else {
    result2.pathname = srcPath.join("/");
  }
  if (!isNull(result2.pathname) || !isNull(result2.search)) {
    result2.path = (result2.pathname ? result2.pathname : "") + (result2.search ? result2.search : "");
  }
  result2.auth = relative2.auth || result2.auth;
  result2.slashes = result2.slashes || relative2.slashes;
  result2.href = result2.format();
  return result2;
};
Url.prototype.parseHost = function() {
  return parseHost(this);
};
function parseHost(self2) {
  var host = self2.host;
  var port = portPattern.exec(host);
  if (port) {
    port = port[0];
    if (port !== ":") {
      self2.port = port.substr(1);
    }
    host = host.substr(0, host.length - port.length);
  }
  if (host)
    self2.hostname = host;
}
var _polyfillNode_url$1 = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  URL: URL$1,
  URLSearchParams: URLSearchParams$1,
  Url,
  default: _polyfillNode_url,
  fileURLToPath: urlFileURLToPath,
  format: urlFormat,
  parse: urlParse,
  resolve: urlResolve,
  resolveObject: urlResolveObject
});
const SSR_INTERPOLATE = Symbol(`ssrInterpolate`);
const SSR_RENDER_VNODE = Symbol(`ssrRenderVNode`);
const SSR_RENDER_COMPONENT = Symbol(`ssrRenderComponent`);
const SSR_RENDER_SLOT = Symbol(`ssrRenderSlot`);
const SSR_RENDER_SLOT_INNER = Symbol(`ssrRenderSlotInner`);
const SSR_RENDER_CLASS = Symbol(`ssrRenderClass`);
const SSR_RENDER_STYLE = Symbol(`ssrRenderStyle`);
const SSR_RENDER_ATTRS = Symbol(`ssrRenderAttrs`);
const SSR_RENDER_ATTR = Symbol(`ssrRenderAttr`);
const SSR_RENDER_DYNAMIC_ATTR = Symbol(`ssrRenderDynamicAttr`);
const SSR_RENDER_LIST = Symbol(`ssrRenderList`);
const SSR_INCLUDE_BOOLEAN_ATTR = Symbol(`ssrIncludeBooleanAttr`);
const SSR_LOOSE_EQUAL = Symbol(`ssrLooseEqual`);
const SSR_LOOSE_CONTAIN = Symbol(`ssrLooseContain`);
const SSR_RENDER_DYNAMIC_MODEL = Symbol(`ssrRenderDynamicModel`);
const SSR_GET_DYNAMIC_MODEL_PROPS = Symbol(`ssrGetDynamicModelProps`);
const SSR_RENDER_TELEPORT = Symbol(`ssrRenderTeleport`);
const SSR_RENDER_SUSPENSE = Symbol(`ssrRenderSuspense`);
const SSR_GET_DIRECTIVE_PROPS = Symbol(`ssrGetDirectiveProps`);
const ssrHelpers = {
  [SSR_INTERPOLATE]: `ssrInterpolate`,
  [SSR_RENDER_VNODE]: `ssrRenderVNode`,
  [SSR_RENDER_COMPONENT]: `ssrRenderComponent`,
  [SSR_RENDER_SLOT]: `ssrRenderSlot`,
  [SSR_RENDER_SLOT_INNER]: `ssrRenderSlotInner`,
  [SSR_RENDER_CLASS]: `ssrRenderClass`,
  [SSR_RENDER_STYLE]: `ssrRenderStyle`,
  [SSR_RENDER_ATTRS]: `ssrRenderAttrs`,
  [SSR_RENDER_ATTR]: `ssrRenderAttr`,
  [SSR_RENDER_DYNAMIC_ATTR]: `ssrRenderDynamicAttr`,
  [SSR_RENDER_LIST]: `ssrRenderList`,
  [SSR_INCLUDE_BOOLEAN_ATTR]: `ssrIncludeBooleanAttr`,
  [SSR_LOOSE_EQUAL]: `ssrLooseEqual`,
  [SSR_LOOSE_CONTAIN]: `ssrLooseContain`,
  [SSR_RENDER_DYNAMIC_MODEL]: `ssrRenderDynamicModel`,
  [SSR_GET_DYNAMIC_MODEL_PROPS]: `ssrGetDynamicModelProps`,
  [SSR_RENDER_TELEPORT]: `ssrRenderTeleport`,
  [SSR_RENDER_SUSPENSE]: `ssrRenderSuspense`,
  [SSR_GET_DIRECTIVE_PROPS]: `ssrGetDirectiveProps`
};
registerRuntimeHelpers(ssrHelpers);
var __defProp$8 = Object.defineProperty;
var __getOwnPropSymbols$8 = Object.getOwnPropertySymbols;
var __hasOwnProp$8 = Object.prototype.hasOwnProperty;
var __propIsEnum$8 = Object.prototype.propertyIsEnumerable;
var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues$8 = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp$8.call(b, prop))
      __defNormalProp$8(a, prop, b[prop]);
  if (__getOwnPropSymbols$8)
    for (var prop of __getOwnPropSymbols$8(b)) {
      if (__propIsEnum$8.call(b, prop))
        __defNormalProp$8(a, prop, b[prop]);
    }
  return a;
};
const [baseNodeTransforms, baseDirectiveTransforms] = getBaseTransformPreset(true);
[...baseNodeTransforms, ...DOMNodeTransforms];
__spreadValues$8(__spreadValues$8({}, baseDirectiveTransforms), DOMDirectiveTransforms);
var _polyfillNode_fs = {};
var _polyfillNode_fs$1 = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  default: _polyfillNode_fs
});
var require$$0$2 = /* @__PURE__ */ getAugmentedNamespace(_polyfillNode_fs$1);
var require$$2$1 = /* @__PURE__ */ getAugmentedNamespace(_polyfillNode_path);
var require$$0$1 = /* @__PURE__ */ getAugmentedNamespace(_polyfillNode_util$1);
var picocolorsExports = {};
var picocolors = {
  get exports() {
    return picocolorsExports;
  },
  set exports(v) {
    picocolorsExports = v;
  }
};
function isatty() {
  return false;
}
function ReadStream() {
  throw new Error("tty.ReadStream is not implemented");
}
function WriteStream() {
  throw new Error("tty.ReadStream is not implemented");
}
var _polyfillNode_tty = {
  isatty,
  ReadStream,
  WriteStream
};
var _polyfillNode_tty$1 = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  ReadStream,
  WriteStream,
  default: _polyfillNode_tty,
  isatty
});
var require$$0 = /* @__PURE__ */ getAugmentedNamespace(_polyfillNode_tty$1);
let tty = require$$0;
let isColorSupported = !("NO_COLOR" in {} || browser$1.argv.includes("--no-color")) && ("FORCE_COLOR" in {} || browser$1.argv.includes("--color") || false || tty.isatty(1) && browser$1.env.TERM !== "dumb" || "CI" in {});
let formatter = (open, close, replace = open) => (input2) => {
  let string3 = "" + input2;
  let index = string3.indexOf(close, open.length);
  return ~index ? open + replaceClose(string3, close, replace, index) + close : open + string3 + close;
};
let replaceClose = (string3, close, replace, index) => {
  let start = string3.substring(0, index) + replace;
  let end = string3.substring(index + close.length);
  let nextIndex = end.indexOf(close);
  return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end;
};
let createColors = (enabled = isColorSupported) => ({
  isColorSupported: enabled,
  reset: enabled ? (s) => `\x1B[0m${s}\x1B[0m` : String,
  bold: enabled ? formatter("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m") : String,
  dim: enabled ? formatter("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m") : String,
  italic: enabled ? formatter("\x1B[3m", "\x1B[23m") : String,
  underline: enabled ? formatter("\x1B[4m", "\x1B[24m") : String,
  inverse: enabled ? formatter("\x1B[7m", "\x1B[27m") : String,
  hidden: enabled ? formatter("\x1B[8m", "\x1B[28m") : String,
  strikethrough: enabled ? formatter("\x1B[9m", "\x1B[29m") : String,
  black: enabled ? formatter("\x1B[30m", "\x1B[39m") : String,
  red: enabled ? formatter("\x1B[31m", "\x1B[39m") : String,
  green: enabled ? formatter("\x1B[32m", "\x1B[39m") : String,
  yellow: enabled ? formatter("\x1B[33m", "\x1B[39m") : String,
  blue: enabled ? formatter("\x1B[34m", "\x1B[39m") : String,
  magenta: enabled ? formatter("\x1B[35m", "\x1B[39m") : String,
  cyan: enabled ? formatter("\x1B[36m", "\x1B[39m") : String,
  white: enabled ? formatter("\x1B[37m", "\x1B[39m") : String,
  gray: enabled ? formatter("\x1B[90m", "\x1B[39m") : String,
  bgBlack: enabled ? formatter("\x1B[40m", "\x1B[49m") : String,
  bgRed: enabled ? formatter("\x1B[41m", "\x1B[49m") : String,
  bgGreen: enabled ? formatter("\x1B[42m", "\x1B[49m") : String,
  bgYellow: enabled ? formatter("\x1B[43m", "\x1B[49m") : String,
  bgBlue: enabled ? formatter("\x1B[44m", "\x1B[49m") : String,
  bgMagenta: enabled ? formatter("\x1B[45m", "\x1B[49m") : String,
  bgCyan: enabled ? formatter("\x1B[46m", "\x1B[49m") : String,
  bgWhite: enabled ? formatter("\x1B[47m", "\x1B[49m") : String
});
picocolors.exports = createColors();
picocolorsExports.createColors = createColors;
const SINGLE_QUOTE = "'".charCodeAt(0);
const DOUBLE_QUOTE = '"'.charCodeAt(0);
const BACKSLASH = "\\".charCodeAt(0);
const SLASH = "/".charCodeAt(0);
const NEWLINE = "\n".charCodeAt(0);
const SPACE = " ".charCodeAt(0);
const FEED = "\f".charCodeAt(0);
const TAB = "	".charCodeAt(0);
const CR = "\r".charCodeAt(0);
const OPEN_SQUARE = "[".charCodeAt(0);
const CLOSE_SQUARE = "]".charCodeAt(0);
const OPEN_PARENTHESES = "(".charCodeAt(0);
const CLOSE_PARENTHESES = ")".charCodeAt(0);
const OPEN_CURLY = "{".charCodeAt(0);
const CLOSE_CURLY = "}".charCodeAt(0);
const SEMICOLON = ";".charCodeAt(0);
const ASTERISK = "*".charCodeAt(0);
const COLON = ":".charCodeAt(0);
const AT = "@".charCodeAt(0);
const RE_AT_END = /[\t\n\f\r "#'()/;[\\\]{}]/g;
const RE_WORD_END = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g;
const RE_BAD_BRACKET = /.[\n"'(/\\]/;
const RE_HEX_ESCAPE = /[\da-f]/i;
var tokenize$1 = function tokenizer(input2, options = {}) {
  let css = input2.css.valueOf();
  let ignore = options.ignoreErrors;
  let code, next, quote, content, escape2;
  let escaped, escapePos, prev, n2, currentToken;
  let length2 = css.length;
  let pos = 0;
  let buffer = [];
  let returned = [];
  function position() {
    return pos;
  }
  function unclosed(what) {
    throw input2.error("Unclosed " + what, pos);
  }
  function endOfFile() {
    return returned.length === 0 && pos >= length2;
  }
  function nextToken(opts) {
    if (returned.length)
      return returned.pop();
    if (pos >= length2)
      return;
    let ignoreUnclosed = opts ? opts.ignoreUnclosed : false;
    code = css.charCodeAt(pos);
    switch (code) {
      case NEWLINE:
      case SPACE:
      case TAB:
      case CR:
      case FEED: {
        next = pos;
        do {
          next += 1;
          code = css.charCodeAt(next);
        } while (code === SPACE || code === NEWLINE || code === TAB || code === CR || code === FEED);
        currentToken = ["space", css.slice(pos, next)];
        pos = next - 1;
        break;
      }
      case OPEN_SQUARE:
      case CLOSE_SQUARE:
      case OPEN_CURLY:
      case CLOSE_CURLY:
      case COLON:
      case SEMICOLON:
      case CLOSE_PARENTHESES: {
        let controlChar = String.fromCharCode(code);
        currentToken = [controlChar, controlChar, pos];
        break;
      }
      case OPEN_PARENTHESES: {
        prev = buffer.length ? buffer.pop()[1] : "";
        n2 = css.charCodeAt(pos + 1);
        if (prev === "url" && n2 !== SINGLE_QUOTE && n2 !== DOUBLE_QUOTE && n2 !== SPACE && n2 !== NEWLINE && n2 !== TAB && n2 !== FEED && n2 !== CR) {
          next = pos;
          do {
            escaped = false;
            next = css.indexOf(")", next + 1);
            if (next === -1) {
              if (ignore || ignoreUnclosed) {
                next = pos;
                break;
              } else {
                unclosed("bracket");
              }
            }
            escapePos = next;
            while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
              escapePos -= 1;
              escaped = !escaped;
            }
          } while (escaped);
          currentToken = ["brackets", css.slice(pos, next + 1), pos, next];
          pos = next;
        } else {
          next = css.indexOf(")", pos + 1);
          content = css.slice(pos, next + 1);
          if (next === -1 || RE_BAD_BRACKET.test(content)) {
            currentToken = ["(", "(", pos];
          } else {
            currentToken = ["brackets", content, pos, next];
            pos = next;
          }
        }
        break;
      }
      case SINGLE_QUOTE:
      case DOUBLE_QUOTE: {
        quote = code === SINGLE_QUOTE ? "'" : '"';
        next = pos;
        do {
          escaped = false;
          next = css.indexOf(quote, next + 1);
          if (next === -1) {
            if (ignore || ignoreUnclosed) {
              next = pos + 1;
              break;
            } else {
              unclosed("string");
            }
          }
          escapePos = next;
          while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
            escapePos -= 1;
            escaped = !escaped;
          }
        } while (escaped);
        currentToken = ["string", css.slice(pos, next + 1), pos, next];
        pos = next;
        break;
      }
      case AT: {
        RE_AT_END.lastIndex = pos + 1;
        RE_AT_END.test(css);
        if (RE_AT_END.lastIndex === 0) {
          next = css.length - 1;
        } else {
          next = RE_AT_END.lastIndex - 2;
        }
        currentToken = ["at-word", css.slice(pos, next + 1), pos, next];
        pos = next;
        break;
      }
      case BACKSLASH: {
        next = pos;
        escape2 = true;
        while (css.charCodeAt(next + 1) === BACKSLASH) {
          next += 1;
          escape2 = !escape2;
        }
        code = css.charCodeAt(next + 1);
        if (escape2 && code !== SLASH && code !== SPACE && code !== NEWLINE && code !== TAB && code !== CR && code !== FEED) {
          next += 1;
          if (RE_HEX_ESCAPE.test(css.charAt(next))) {
            while (RE_HEX_ESCAPE.test(css.charAt(next + 1))) {
              next += 1;
            }
            if (css.charCodeAt(next + 1) === SPACE) {
              next += 1;
            }
          }
        }
        currentToken = ["word", css.slice(pos, next + 1), pos, next];
        pos = next;
        break;
      }
      default: {
        if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) {
          next = css.indexOf("*/", pos + 2) + 1;
          if (next === 0) {
            if (ignore || ignoreUnclosed) {
              next = css.length;
            } else {
              unclosed("comment");
            }
          }
          currentToken = ["comment", css.slice(pos, next + 1), pos, next];
          pos = next;
        } else {
          RE_WORD_END.lastIndex = pos + 1;
          RE_WORD_END.test(css);
          if (RE_WORD_END.lastIndex === 0) {
            next = css.length - 1;
          } else {
            next = RE_WORD_END.lastIndex - 2;
          }
          currentToken = ["word", css.slice(pos, next + 1), pos, next];
          buffer.push(currentToken);
          pos = next;
        }
        break;
      }
    }
    pos++;
    return currentToken;
  }
  function back(token) {
    returned.push(token);
  }
  return {
    back,
    nextToken,
    endOfFile,
    position
  };
};
let pico$1 = picocolorsExports;
let tokenizer$1 = tokenize$1;
let Input$5;
function registerInput(dependant) {
  Input$5 = dependant;
}
const HIGHLIGHT_THEME = {
  "brackets": pico$1.cyan,
  "at-word": pico$1.cyan,
  "comment": pico$1.gray,
  "string": pico$1.green,
  "class": pico$1.yellow,
  "hash": pico$1.magenta,
  "call": pico$1.cyan,
  "(": pico$1.cyan,
  ")": pico$1.cyan,
  "{": pico$1.yellow,
  "}": pico$1.yellow,
  "[": pico$1.yellow,
  "]": pico$1.yellow,
  ":": pico$1.yellow,
  ";": pico$1.yellow
};
function getTokenType([type, value], processor2) {
  if (type === "word") {
    if (value[0] === ".") {
      return "class";
    }
    if (value[0] === "#") {
      return "hash";
    }
  }
  if (!processor2.endOfFile()) {
    let next = processor2.nextToken();
    processor2.back(next);
    if (next[0] === "brackets" || next[0] === "(")
      return "call";
  }
  return type;
}
function terminalHighlight$2(css) {
  let processor2 = tokenizer$1(new Input$5(css), { ignoreErrors: true });
  let result2 = "";
  while (!processor2.endOfFile()) {
    let token = processor2.nextToken();
    let color = HIGHLIGHT_THEME[getTokenType(token, processor2)];
    if (color) {
      result2 += token[1].split(/\r?\n/).map((i) => color(i)).join("\n");
    } else {
      result2 += token[1];
    }
  }
  return result2;
}
terminalHighlight$2.registerInput = registerInput;
var terminalHighlight_1 = terminalHighlight$2;
let pico = picocolorsExports;
let terminalHighlight$1 = terminalHighlight_1;
let CssSyntaxError$3 = class CssSyntaxError extends Error {
  constructor(message, line, column, source, file, plugin2) {
    super(message);
    this.name = "CssSyntaxError";
    this.reason = message;
    if (file) {
      this.file = file;
    }
    if (source) {
      this.source = source;
    }
    if (plugin2) {
      this.plugin = plugin2;
    }
    if (typeof line !== "undefined" && typeof column !== "undefined") {
      if (typeof line === "number") {
        this.line = line;
        this.column = column;
      } else {
        this.line = line.line;
        this.column = line.column;
        this.endLine = column.line;
        this.endColumn = column.column;
      }
    }
    this.setMessage();
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, CssSyntaxError);
    }
  }
  setMessage() {
    this.message = this.plugin ? this.plugin + ": " : "";
    this.message += this.file ? this.file : "<css input>";
    if (typeof this.line !== "undefined") {
      this.message += ":" + this.line + ":" + this.column;
    }
    this.message += ": " + this.reason;
  }
  showSourceCode(color) {
    if (!this.source)
      return "";
    let css = this.source;
    if (color == null)
      color = pico.isColorSupported;
    if (terminalHighlight$1) {
      if (color)
        css = terminalHighlight$1(css);
    }
    let lines = css.split(/\r?\n/);
    let start = Math.max(this.line - 3, 0);
    let end = Math.min(this.line + 2, lines.length);
    let maxWidth = String(end).length;
    let mark, aside;
    if (color) {
      let { bold, red, gray } = pico.createColors(true);
      mark = (text2) => bold(red(text2));
      aside = (text2) => gray(text2);
    } else {
      mark = aside = (str2) => str2;
    }
    return lines.slice(start, end).map((line, index) => {
      let number = start + 1 + index;
      let gutter = " " + (" " + number).slice(-maxWidth) + " | ";
      if (number === this.line) {
        let spacing = aside(gutter.replace(/\d/g, " ")) + line.slice(0, this.column - 1).replace(/[^\t]/g, " ");
        return mark(">") + aside(gutter) + line + "\n " + spacing + mark("^");
      }
      return " " + aside(gutter) + line;
    }).join("\n");
  }
  toString() {
    let code = this.showSourceCode();
    if (code) {
      code = "\n\n" + code + "\n";
    }
    return this.name + ": " + this.message + code;
  }
};
var cssSyntaxError = CssSyntaxError$3;
CssSyntaxError$3.default = CssSyntaxError$3;
var symbols = {};
symbols.isClean = Symbol("isClean");
symbols.my = Symbol("my");
const DEFAULT_RAW = {
  colon: ": ",
  indent: "    ",
  beforeDecl: "\n",
  beforeRule: "\n",
  beforeOpen: " ",
  beforeClose: "\n",
  beforeComment: "\n",
  after: "\n",
  emptyBody: "",
  commentLeft: " ",
  commentRight: " ",
  semicolon: false
};
function capitalize(str2) {
  return str2[0].toUpperCase() + str2.slice(1);
}
let Stringifier$2 = class Stringifier {
  constructor(builder) {
    this.builder = builder;
  }
  stringify(node2, semicolon) {
    if (!this[node2.type]) {
      throw new Error(
        "Unknown AST node type " + node2.type + ". Maybe you need to change PostCSS stringifier."
      );
    }
    this[node2.type](node2, semicolon);
  }
  document(node2) {
    this.body(node2);
  }
  root(node2) {
    this.body(node2);
    if (node2.raws.after)
      this.builder(node2.raws.after);
  }
  comment(node2) {
    let left = this.raw(node2, "left", "commentLeft");
    let right = this.raw(node2, "right", "commentRight");
    this.builder("/*" + left + node2.text + right + "*/", node2);
  }
  decl(node2, semicolon) {
    let between = this.raw(node2, "between", "colon");
    let string3 = node2.prop + between + this.rawValue(node2, "value");
    if (node2.important) {
      string3 += node2.raws.important || " !important";
    }
    if (semicolon)
      string3 += ";";
    this.builder(string3, node2);
  }
  rule(node2) {
    this.block(node2, this.rawValue(node2, "selector"));
    if (node2.raws.ownSemicolon) {
      this.builder(node2.raws.ownSemicolon, node2, "end");
    }
  }
  atrule(node2, semicolon) {
    let name = "@" + node2.name;
    let params = node2.params ? this.rawValue(node2, "params") : "";
    if (typeof node2.raws.afterName !== "undefined") {
      name += node2.raws.afterName;
    } else if (params) {
      name += " ";
    }
    if (node2.nodes) {
      this.block(node2, name + params);
    } else {
      let end = (node2.raws.between || "") + (semicolon ? ";" : "");
      this.builder(name + params + end, node2);
    }
  }
  body(node2) {
    let last2 = node2.nodes.length - 1;
    while (last2 > 0) {
      if (node2.nodes[last2].type !== "comment")
        break;
      last2 -= 1;
    }
    let semicolon = this.raw(node2, "semicolon");
    for (let i = 0; i < node2.nodes.length; i++) {
      let child = node2.nodes[i];
      let before = this.raw(child, "before");
      if (before)
        this.builder(before);
      this.stringify(child, last2 !== i || semicolon);
    }
  }
  block(node2, start) {
    let between = this.raw(node2, "between", "beforeOpen");
    this.builder(start + between + "{", node2, "start");
    let after;
    if (node2.nodes && node2.nodes.length) {
      this.body(node2);
      after = this.raw(node2, "after");
    } else {
      after = this.raw(node2, "after", "emptyBody");
    }
    if (after)
      this.builder(after);
    this.builder("}", node2, "end");
  }
  raw(node2, own, detect) {
    let value;
    if (!detect)
      detect = own;
    if (own) {
      value = node2.raws[own];
      if (typeof value !== "undefined")
        return value;
    }
    let parent = node2.parent;
    if (detect === "before") {
      if (!parent || parent.type === "root" && parent.first === node2) {
        return "";
      }
      if (parent && parent.type === "document") {
        return "";
      }
    }
    if (!parent)
      return DEFAULT_RAW[detect];
    let root3 = node2.root();
    if (!root3.rawCache)
      root3.rawCache = {};
    if (typeof root3.rawCache[detect] !== "undefined") {
      return root3.rawCache[detect];
    }
    if (detect === "before" || detect === "after") {
      return this.beforeAfter(node2, detect);
    } else {
      let method = "raw" + capitalize(detect);
      if (this[method]) {
        value = this[method](root3, node2);
      } else {
        root3.walk((i) => {
          value = i.raws[own];
          if (typeof value !== "undefined")
            return false;
        });
      }
    }
    if (typeof value === "undefined")
      value = DEFAULT_RAW[detect];
    root3.rawCache[detect] = value;
    return value;
  }
  rawSemicolon(root3) {
    let value;
    root3.walk((i) => {
      if (i.nodes && i.nodes.length && i.last.type === "decl") {
        value = i.raws.semicolon;
        if (typeof value !== "undefined")
          return false;
      }
    });
    return value;
  }
  rawEmptyBody(root3) {
    let value;
    root3.walk((i) => {
      if (i.nodes && i.nodes.length === 0) {
        value = i.raws.after;
        if (typeof value !== "undefined")
          return false;
      }
    });
    return value;
  }
  rawIndent(root3) {
    if (root3.raws.indent)
      return root3.raws.indent;
    let value;
    root3.walk((i) => {
      let p2 = i.parent;
      if (p2 && p2 !== root3 && p2.parent && p2.parent === root3) {
        if (typeof i.raws.before !== "undefined") {
          let parts = i.raws.before.split("\n");
          value = parts[parts.length - 1];
          value = value.replace(/\S/g, "");
          return false;
        }
      }
    });
    return value;
  }
  rawBeforeComment(root3, node2) {
    let value;
    root3.walkComments((i) => {
      if (typeof i.raws.before !== "undefined") {
        value = i.raws.before;
        if (value.includes("\n")) {
          value = value.replace(/[^\n]+$/, "");
        }
        return false;
      }
    });
    if (typeof value === "undefined") {
      value = this.raw(node2, null, "beforeDecl");
    } else if (value) {
      value = value.replace(/\S/g, "");
    }
    return value;
  }
  rawBeforeDecl(root3, node2) {
    let value;
    root3.walkDecls((i) => {
      if (typeof i.raws.before !== "undefined") {
        value = i.raws.before;
        if (value.includes("\n")) {
          value = value.replace(/[^\n]+$/, "");
        }
        return false;
      }
    });
    if (typeof value === "undefined") {
      value = this.raw(node2, null, "beforeRule");
    } else if (value) {
      value = value.replace(/\S/g, "");
    }
    return value;
  }
  rawBeforeRule(root3) {
    let value;
    root3.walk((i) => {
      if (i.nodes && (i.parent !== root3 || root3.first !== i)) {
        if (typeof i.raws.before !== "undefined") {
          value = i.raws.before;
          if (value.includes("\n")) {
            value = value.replace(/[^\n]+$/, "");
          }
          return false;
        }
      }
    });
    if (value)
      value = value.replace(/\S/g, "");
    return value;
  }
  rawBeforeClose(root3) {
    let value;
    root3.walk((i) => {
      if (i.nodes && i.nodes.length > 0) {
        if (typeof i.raws.after !== "undefined") {
          value = i.raws.after;
          if (value.includes("\n")) {
            value = value.replace(/[^\n]+$/, "");
          }
          return false;
        }
      }
    });
    if (value)
      value = value.replace(/\S/g, "");
    return value;
  }
  rawBeforeOpen(root3) {
    let value;
    root3.walk((i) => {
      if (i.type !== "decl") {
        value = i.raws.between;
        if (typeof value !== "undefined")
          return false;
      }
    });
    return value;
  }
  rawColon(root3) {
    let value;
    root3.walkDecls((i) => {
      if (typeof i.raws.between !== "undefined") {
        value = i.raws.between.replace(/[^\s:]/g, "");
        return false;
      }
    });
    return value;
  }
  beforeAfter(node2, detect) {
    let value;
    if (node2.type === "decl") {
      value = this.raw(node2, null, "beforeDecl");
    } else if (node2.type === "comment") {
      value = this.raw(node2, null, "beforeComment");
    } else if (detect === "before") {
      value = this.raw(node2, null, "beforeRule");
    } else {
      value = this.raw(node2, null, "beforeClose");
    }
    let buf = node2.parent;
    let depth = 0;
    while (buf && buf.type !== "root") {
      depth += 1;
      buf = buf.parent;
    }
    if (value.includes("\n")) {
      let indent = this.raw(node2, null, "indent");
      if (indent.length) {
        for (let step = 0; step < depth; step++)
          value += indent;
      }
    }
    return value;
  }
  rawValue(node2, prop) {
    let value = node2[prop];
    let raw = node2.raws[prop];
    if (raw && raw.value === value) {
      return raw.raw;
    }
    return value;
  }
};
var stringifier = Stringifier$2;
Stringifier$2.default = Stringifier$2;
let Stringifier$1 = stringifier;
function stringify$4(node2, builder) {
  let str2 = new Stringifier$1(builder);
  str2.stringify(node2);
}
var stringify_1 = stringify$4;
stringify$4.default = stringify$4;
let { isClean: isClean$2, my: my$2 } = symbols;
let CssSyntaxError$2 = cssSyntaxError;
let Stringifier2 = stringifier;
let stringify$3 = stringify_1;
function cloneNode(obj, parent) {
  let cloned = new obj.constructor();
  for (let i in obj) {
    if (!Object.prototype.hasOwnProperty.call(obj, i)) {
      continue;
    }
    if (i === "proxyCache")
      continue;
    let value = obj[i];
    let type = typeof value;
    if (i === "parent" && type === "object") {
      if (parent)
        cloned[i] = parent;
    } else if (i === "source") {
      cloned[i] = value;
    } else if (Array.isArray(value)) {
      cloned[i] = value.map((j) => cloneNode(j, cloned));
    } else {
      if (type === "object" && value !== null)
        value = cloneNode(value);
      cloned[i] = value;
    }
  }
  return cloned;
}
let Node$4 = class Node5 {
  constructor(defaults = {}) {
    this.raws = {};
    this[isClean$2] = false;
    this[my$2] = true;
    for (let name in defaults) {
      if (name === "nodes") {
        this.nodes = [];
        for (let node2 of defaults[name]) {
          if (typeof node2.clone === "function") {
            this.append(node2.clone());
          } else {
            this.append(node2);
          }
        }
      } else {
        this[name] = defaults[name];
      }
    }
  }
  error(message, opts = {}) {
    if (this.source) {
      let { start, end } = this.rangeBy(opts);
      return this.source.input.error(
        message,
        { line: start.line, column: start.column },
        { line: end.line, column: end.column },
        opts
      );
    }
    return new CssSyntaxError$2(message);
  }
  warn(result2, text2, opts) {
    let data = { node: this };
    for (let i in opts)
      data[i] = opts[i];
    return result2.warn(text2, data);
  }
  remove() {
    if (this.parent) {
      this.parent.removeChild(this);
    }
    this.parent = void 0;
    return this;
  }
  toString(stringifier2 = stringify$3) {
    if (stringifier2.stringify)
      stringifier2 = stringifier2.stringify;
    let result2 = "";
    stringifier2(this, (i) => {
      result2 += i;
    });
    return result2;
  }
  assign(overrides = {}) {
    for (let name in overrides) {
      this[name] = overrides[name];
    }
    return this;
  }
  clone(overrides = {}) {
    let cloned = cloneNode(this);
    for (let name in overrides) {
      cloned[name] = overrides[name];
    }
    return cloned;
  }
  cloneBefore(overrides = {}) {
    let cloned = this.clone(overrides);
    this.parent.insertBefore(this, cloned);
    return cloned;
  }
  cloneAfter(overrides = {}) {
    let cloned = this.clone(overrides);
    this.parent.insertAfter(this, cloned);
    return cloned;
  }
  replaceWith(...nodes) {
    if (this.parent) {
      let bookmark = this;
      let foundSelf = false;
      for (let node2 of nodes) {
        if (node2 === this) {
          foundSelf = true;
        } else if (foundSelf) {
          this.parent.insertAfter(bookmark, node2);
          bookmark = node2;
        } else {
          this.parent.insertBefore(bookmark, node2);
        }
      }
      if (!foundSelf) {
        this.remove();
      }
    }
    return this;
  }
  next() {
    if (!this.parent)
      return void 0;
    let index = this.parent.index(this);
    return this.parent.nodes[index + 1];
  }
  prev() {
    if (!this.parent)
      return void 0;
    let index = this.parent.index(this);
    return this.parent.nodes[index - 1];
  }
  before(add2) {
    this.parent.insertBefore(this, add2);
    return this;
  }
  after(add2) {
    this.parent.insertAfter(this, add2);
    return this;
  }
  root() {
    let result2 = this;
    while (result2.parent && result2.parent.type !== "document") {
      result2 = result2.parent;
    }
    return result2;
  }
  raw(prop, defaultType) {
    let str2 = new Stringifier2();
    return str2.raw(this, prop, defaultType);
  }
  cleanRaws(keepBetween) {
    delete this.raws.before;
    delete this.raws.after;
    if (!keepBetween)
      delete this.raws.between;
  }
  toJSON(_, inputs) {
    let fixed = {};
    let emitInputs = inputs == null;
    inputs = inputs || /* @__PURE__ */ new Map();
    let inputsNextIndex = 0;
    for (let name in this) {
      if (!Object.prototype.hasOwnProperty.call(this, name)) {
        continue;
      }
      if (name === "parent" || name === "proxyCache")
        continue;
      let value = this[name];
      if (Array.isArray(value)) {
        fixed[name] = value.map((i) => {
          if (typeof i === "object" && i.toJSON) {
            return i.toJSON(null, inputs);
          } else {
            return i;
          }
        });
      } else if (typeof value === "object" && value.toJSON) {
        fixed[name] = value.toJSON(null, inputs);
      } else if (name === "source") {
        let inputId = inputs.get(value.input);
        if (inputId == null) {
          inputId = inputsNextIndex;
          inputs.set(value.input, inputsNextIndex);
          inputsNextIndex++;
        }
        fixed[name] = {
          inputId,
          start: value.start,
          end: value.end
        };
      } else {
        fixed[name] = value;
      }
    }
    if (emitInputs) {
      fixed.inputs = [...inputs.keys()].map((input2) => input2.toJSON());
    }
    return fixed;
  }
  positionInside(index) {
    let string3 = this.toString();
    let column = this.source.start.column;
    let line = this.source.start.line;
    for (let i = 0; i < index; i++) {
      if (string3[i] === "\n") {
        column = 1;
        line += 1;
      } else {
        column += 1;
      }
    }
    return { line, column };
  }
  positionBy(opts) {
    let pos = this.source.start;
    if (opts.index) {
      pos = this.positionInside(opts.index);
    } else if (opts.word) {
      let index = this.toString().indexOf(opts.word);
      if (index !== -1)
        pos = this.positionInside(index);
    }
    return pos;
  }
  rangeBy(opts) {
    let start = {
      line: this.source.start.line,
      column: this.source.start.column
    };
    let end = this.source.end ? {
      line: this.source.end.line,
      column: this.source.end.column + 1
    } : {
      line: start.line,
      column: start.column + 1
    };
    if (opts.word) {
      let index = this.toString().indexOf(opts.word);
      if (index !== -1) {
        start = this.positionInside(index);
        end = this.positionInside(index + opts.word.length);
      }
    } else {
      if (opts.start) {
        start = {
          line: opts.start.line,
          column: opts.start.column
        };
      } else if (opts.index) {
        start = this.positionInside(opts.index);
      }
      if (opts.end) {
        end = {
          line: opts.end.line,
          column: opts.end.column
        };
      } else if (opts.endIndex) {
        end = this.positionInside(opts.endIndex);
      } else if (opts.index) {
        end = this.positionInside(opts.index + 1);
      }
    }
    if (end.line < start.line || end.line === start.line && end.column <= start.column) {
      end = { line: start.line, column: start.column + 1 };
    }
    return { start, end };
  }
  getProxyProcessor() {
    return {
      set(node2, prop, value) {
        if (node2[prop] === value)
          return true;
        node2[prop] = value;
        if (prop === "prop" || prop === "value" || prop === "name" || prop === "params" || prop === "important" || /* c8 ignore next */
        prop === "text") {
          node2.markDirty();
        }
        return true;
      },
      get(node2, prop) {
        if (prop === "proxyOf") {
          return node2;
        } else if (prop === "root") {
          return () => node2.root().toProxy();
        } else {
          return node2[prop];
        }
      }
    };
  }
  toProxy() {
    if (!this.proxyCache) {
      this.proxyCache = new Proxy(this, this.getProxyProcessor());
    }
    return this.proxyCache;
  }
  addToError(error2) {
    error2.postcssNode = this;
    if (error2.stack && this.source && /\n\s{4}at /.test(error2.stack)) {
      let s = this.source;
      error2.stack = error2.stack.replace(
        /\n\s{4}at /,
        `$&${s.input.from}:${s.start.line}:${s.start.column}$&`
      );
    }
    return error2;
  }
  markDirty() {
    if (this[isClean$2]) {
      this[isClean$2] = false;
      let next = this;
      while (next = next.parent) {
        next[isClean$2] = false;
      }
    }
  }
  get proxyOf() {
    return this;
  }
};
var node$2 = Node$4;
Node$4.default = Node$4;
let Node$3 = node$2;
let Declaration$4 = class Declaration extends Node$3 {
  constructor(defaults) {
    if (defaults && typeof defaults.value !== "undefined" && typeof defaults.value !== "string") {
      defaults = { ...defaults, value: String(defaults.value) };
    }
    super(defaults);
    this.type = "decl";
  }
  get variable() {
    return this.prop.startsWith("--") || this.prop[0] === "$";
  }
};
var declaration = Declaration$4;
Declaration$4.default = Declaration$4;
var require$$2 = /* @__PURE__ */ getAugmentedNamespace(_polyfillNode_url$1);
let urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
let customAlphabet = (alphabet, defaultSize = 21) => {
  return (size2 = defaultSize) => {
    let id3 = "";
    let i = size2;
    while (i--) {
      id3 += alphabet[Math.random() * alphabet.length | 0];
    }
    return id3;
  };
};
let nanoid$1 = (size2 = 21) => {
  let id3 = "";
  let i = size2;
  while (i--) {
    id3 += urlAlphabet[Math.random() * 64 | 0];
  }
  return id3;
};
var nonSecure = { nanoid: nanoid$1, customAlphabet };
let { SourceMapConsumer: SourceMapConsumer$4, SourceMapGenerator: SourceMapGenerator$5 } = sourceMap$2;
let { existsSync, readFileSync } = require$$0$2;
let { dirname: dirname$1, join } = require$$2$1;
function fromBase64(str2) {
  if (Buffer$1) {
    return Buffer$1.from(str2, "base64").toString();
  } else {
    return window.atob(str2);
  }
}
let PreviousMap$2 = class PreviousMap {
  constructor(css, opts) {
    if (opts.map === false)
      return;
    this.loadAnnotation(css);
    this.inline = this.startWith(this.annotation, "data:");
    let prev = opts.map ? opts.map.prev : void 0;
    let text2 = this.loadMap(opts.from, prev);
    if (!this.mapFile && opts.from) {
      this.mapFile = opts.from;
    }
    if (this.mapFile)
      this.root = dirname$1(this.mapFile);
    if (text2)
      this.text = text2;
  }
  consumer() {
    if (!this.consumerCache) {
      this.consumerCache = new SourceMapConsumer$4(this.text);
    }
    return this.consumerCache;
  }
  withContent() {
    return !!(this.consumer().sourcesContent && this.consumer().sourcesContent.length > 0);
  }
  startWith(string3, start) {
    if (!string3)
      return false;
    return string3.substr(0, start.length) === start;
  }
  getAnnotationURL(sourceMapString) {
    return sourceMapString.replace(/^\/\*\s*# sourceMappingURL=/, "").trim();
  }
  loadAnnotation(css) {
    let comments = css.match(/\/\*\s*# sourceMappingURL=/gm);
    if (!comments)
      return;
    let start = css.lastIndexOf(comments.pop());
    let end = css.indexOf("*/", start);
    if (start > -1 && end > -1) {
      this.annotation = this.getAnnotationURL(css.substring(start, end));
    }
  }
  decodeInline(text2) {
    let baseCharsetUri = /^data:application\/json;charset=utf-?8;base64,/;
    let baseUri = /^data:application\/json;base64,/;
    let charsetUri = /^data:application\/json;charset=utf-?8,/;
    let uri = /^data:application\/json,/;
    if (charsetUri.test(text2) || uri.test(text2)) {
      return decodeURIComponent(text2.substr(RegExp.lastMatch.length));
    }
    if (baseCharsetUri.test(text2) || baseUri.test(text2)) {
      return fromBase64(text2.substr(RegExp.lastMatch.length));
    }
    let encoding = text2.match(/data:application\/json;([^,]+),/)[1];
    throw new Error("Unsupported source map encoding " + encoding);
  }
  loadFile(path2) {
    this.root = dirname$1(path2);
    if (existsSync(path2)) {
      this.mapFile = path2;
      return readFileSync(path2, "utf-8").toString().trim();
    }
  }
  loadMap(file, prev) {
    if (prev === false)
      return false;
    if (prev) {
      if (typeof prev === "string") {
        return prev;
      } else if (typeof prev === "function") {
        let prevPath = prev(file);
        if (prevPath) {
          let map2 = this.loadFile(prevPath);
          if (!map2) {
            throw new Error(
              "Unable to load previous source map: " + prevPath.toString()
            );
          }
          return map2;
        }
      } else if (prev instanceof SourceMapConsumer$4) {
        return SourceMapGenerator$5.fromSourceMap(prev).toString();
      } else if (prev instanceof SourceMapGenerator$5) {
        return prev.toString();
      } else if (this.isMap(prev)) {
        return JSON.stringify(prev);
      } else {
        throw new Error(
          "Unsupported previous source map format: " + prev.toString()
        );
      }
    } else if (this.inline) {
      return this.decodeInline(this.annotation);
    } else if (this.annotation) {
      let map2 = this.annotation;
      if (file)
        map2 = join(dirname$1(file), map2);
      return this.loadFile(map2);
    }
  }
  isMap(map2) {
    if (typeof map2 !== "object")
      return false;
    return typeof map2.mappings === "string" || typeof map2._mappings === "string" || Array.isArray(map2.sections);
  }
};
var previousMap = PreviousMap$2;
PreviousMap$2.default = PreviousMap$2;
let { SourceMapConsumer: SourceMapConsumer$3, SourceMapGenerator: SourceMapGenerator$4 } = sourceMap$2;
let { fileURLToPath, pathToFileURL: pathToFileURL$1 } = require$$2;
let { resolve: resolve$1, isAbsolute } = require$$2$1;
let { nanoid } = nonSecure;
let terminalHighlight = terminalHighlight_1;
let CssSyntaxError$1 = cssSyntaxError;
let PreviousMap$1 = previousMap;
let fromOffsetCache = Symbol("fromOffsetCache");
let sourceMapAvailable$1 = Boolean(SourceMapConsumer$3 && SourceMapGenerator$4);
let pathAvailable$1 = Boolean(resolve$1 && isAbsolute);
let Input$4 = class Input {
  constructor(css, opts = {}) {
    if (css === null || typeof css === "undefined" || typeof css === "object" && !css.toString) {
      throw new Error(`PostCSS received ${css} instead of CSS string`);
    }
    this.css = css.toString();
    if (this.css[0] === "\uFEFF" || this.css[0] === "") {
      this.hasBOM = true;
      this.css = this.css.slice(1);
    } else {
      this.hasBOM = false;
    }
    if (opts.from) {
      if (!pathAvailable$1 || /^\w+:\/\//.test(opts.from) || isAbsolute(opts.from)) {
        this.file = opts.from;
      } else {
        this.file = resolve$1(opts.from);
      }
    }
    if (pathAvailable$1 && sourceMapAvailable$1) {
      let map2 = new PreviousMap$1(this.css, opts);
      if (map2.text) {
        this.map = map2;
        let file = map2.consumer().file;
        if (!this.file && file)
          this.file = this.mapResolve(file);
      }
    }
    if (!this.file) {
      this.id = "<input css " + nanoid(6) + ">";
    }
    if (this.map)
      this.map.file = this.from;
  }
  fromOffset(offset) {
    let lastLine, lineToIndex;
    if (!this[fromOffsetCache]) {
      let lines = this.css.split("\n");
      lineToIndex = new Array(lines.length);
      let prevIndex = 0;
      for (let i = 0, l = lines.length; i < l; i++) {
        lineToIndex[i] = prevIndex;
        prevIndex += lines[i].length + 1;
      }
      this[fromOffsetCache] = lineToIndex;
    } else {
      lineToIndex = this[fromOffsetCache];
    }
    lastLine = lineToIndex[lineToIndex.length - 1];
    let min = 0;
    if (offset >= lastLine) {
      min = lineToIndex.length - 1;
    } else {
      let max = lineToIndex.length - 2;
      let mid;
      while (min < max) {
        mid = min + (max - min >> 1);
        if (offset < lineToIndex[mid]) {
          max = mid - 1;
        } else if (offset >= lineToIndex[mid + 1]) {
          min = mid + 1;
        } else {
          min = mid;
          break;
        }
      }
    }
    return {
      line: min + 1,
      col: offset - lineToIndex[min] + 1
    };
  }
  error(message, line, column, opts = {}) {
    let result2, endLine, endColumn;
    if (line && typeof line === "object") {
      let start = line;
      let end = column;
      if (typeof start.offset === "number") {
        let pos = this.fromOffset(start.offset);
        line = pos.line;
        column = pos.col;
      } else {
        line = start.line;
        column = start.column;
      }
      if (typeof end.offset === "number") {
        let pos = this.fromOffset(end.offset);
        endLine = pos.line;
        endColumn = pos.col;
      } else {
        endLine = end.line;
        endColumn = end.column;
      }
    } else if (!column) {
      let pos = this.fromOffset(line);
      line = pos.line;
      column = pos.col;
    }
    let origin = this.origin(line, column, endLine, endColumn);
    if (origin) {
      result2 = new CssSyntaxError$1(
        message,
        origin.endLine === void 0 ? origin.line : { line: origin.line, column: origin.column },
        origin.endLine === void 0 ? origin.column : { line: origin.endLine, column: origin.endColumn },
        origin.source,
        origin.file,
        opts.plugin
      );
    } else {
      result2 = new CssSyntaxError$1(
        message,
        endLine === void 0 ? line : { line, column },
        endLine === void 0 ? column : { line: endLine, column: endColumn },
        this.css,
        this.file,
        opts.plugin
      );
    }
    result2.input = { line, column, endLine, endColumn, source: this.css };
    if (this.file) {
      if (pathToFileURL$1) {
        result2.input.url = pathToFileURL$1(this.file).toString();
      }
      result2.input.file = this.file;
    }
    return result2;
  }
  origin(line, column, endLine, endColumn) {
    if (!this.map)
      return false;
    let consumer = this.map.consumer();
    let from2 = consumer.originalPositionFor({ line, column });
    if (!from2.source)
      return false;
    let to;
    if (typeof endLine === "number") {
      to = consumer.originalPositionFor({ line: endLine, column: endColumn });
    }
    let fromUrl;
    if (isAbsolute(from2.source)) {
      fromUrl = pathToFileURL$1(from2.source);
    } else {
      fromUrl = new URL(
        from2.source,
        this.map.consumer().sourceRoot || pathToFileURL$1(this.map.mapFile)
      );
    }
    let result2 = {
      url: fromUrl.toString(),
      line: from2.line,
      column: from2.column,
      endLine: to && to.line,
      endColumn: to && to.column
    };
    if (fromUrl.protocol === "file:") {
      if (fileURLToPath) {
        result2.file = fileURLToPath(fromUrl);
      } else {
        throw new Error(`file: protocol is not available in this PostCSS build`);
      }
    }
    let source = consumer.sourceContentFor(from2.source);
    if (source)
      result2.source = source;
    return result2;
  }
  mapResolve(file) {
    if (/^\w+:\/\//.test(file)) {
      return file;
    }
    return resolve$1(this.map.consumer().sourceRoot || this.map.root || ".", file);
  }
  get from() {
    return this.file || this.id;
  }
  toJSON() {
    let json = {};
    for (let name of ["hasBOM", "css", "file", "id"]) {
      if (this[name] != null) {
        json[name] = this[name];
      }
    }
    if (this.map) {
      json.map = { ...this.map };
      if (json.map.consumerCache) {
        json.map.consumerCache = void 0;
      }
    }
    return json;
  }
};
var input = Input$4;
Input$4.default = Input$4;
if (terminalHighlight && terminalHighlight.registerInput) {
  terminalHighlight.registerInput(Input$4);
}
let { SourceMapConsumer: SourceMapConsumer$2, SourceMapGenerator: SourceMapGenerator$3 } = sourceMap$2;
let { dirname, resolve, relative, sep } = require$$2$1;
let { pathToFileURL } = require$$2;
let Input$3 = input;
let sourceMapAvailable = Boolean(SourceMapConsumer$2 && SourceMapGenerator$3);
let pathAvailable = Boolean(dirname && resolve && relative && sep);
let MapGenerator$2 = class MapGenerator {
  constructor(stringify2, root3, opts, cssString) {
    this.stringify = stringify2;
    this.mapOpts = opts.map || {};
    this.root = root3;
    this.opts = opts;
    this.css = cssString;
    this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute;
  }
  isMap() {
    if (typeof this.opts.map !== "undefined") {
      return !!this.opts.map;
    }
    return this.previous().length > 0;
  }
  previous() {
    if (!this.previousMaps) {
      this.previousMaps = [];
      if (this.root) {
        this.root.walk((node2) => {
          if (node2.source && node2.source.input.map) {
            let map2 = node2.source.input.map;
            if (!this.previousMaps.includes(map2)) {
              this.previousMaps.push(map2);
            }
          }
        });
      } else {
        let input2 = new Input$3(this.css, this.opts);
        if (input2.map)
          this.previousMaps.push(input2.map);
      }
    }
    return this.previousMaps;
  }
  isInline() {
    if (typeof this.mapOpts.inline !== "undefined") {
      return this.mapOpts.inline;
    }
    let annotation = this.mapOpts.annotation;
    if (typeof annotation !== "undefined" && annotation !== true) {
      return false;
    }
    if (this.previous().length) {
      return this.previous().some((i) => i.inline);
    }
    return true;
  }
  isSourcesContent() {
    if (typeof this.mapOpts.sourcesContent !== "undefined") {
      return this.mapOpts.sourcesContent;
    }
    if (this.previous().length) {
      return this.previous().some((i) => i.withContent());
    }
    return true;
  }
  clearAnnotation() {
    if (this.mapOpts.annotation === false)
      return;
    if (this.root) {
      let node2;
      for (let i = this.root.nodes.length - 1; i >= 0; i--) {
        node2 = this.root.nodes[i];
        if (node2.type !== "comment")
          continue;
        if (node2.text.indexOf("# sourceMappingURL=") === 0) {
          this.root.removeChild(i);
        }
      }
    } else if (this.css) {
      this.css = this.css.replace(/(\n)?\/\*#[\S\s]*?\*\/$/gm, "");
    }
  }
  setSourcesContent() {
    let already = {};
    if (this.root) {
      this.root.walk((node2) => {
        if (node2.source) {
          let from2 = node2.source.input.from;
          if (from2 && !already[from2]) {
            already[from2] = true;
            let fromUrl = this.usesFileUrls ? this.toFileUrl(from2) : this.toUrl(this.path(from2));
            this.map.setSourceContent(fromUrl, node2.source.input.css);
          }
        }
      });
    } else if (this.css) {
      let from2 = this.opts.from ? this.toUrl(this.path(this.opts.from)) : "<no source>";
      this.map.setSourceContent(from2, this.css);
    }
  }
  applyPrevMaps() {
    for (let prev of this.previous()) {
      let from2 = this.toUrl(this.path(prev.file));
      let root3 = prev.root || dirname(prev.file);
      let map2;
      if (this.mapOpts.sourcesContent === false) {
        map2 = new SourceMapConsumer$2(prev.text);
        if (map2.sourcesContent) {
          map2.sourcesContent = map2.sourcesContent.map(() => null);
        }
      } else {
        map2 = prev.consumer();
      }
      this.map.applySourceMap(map2, from2, this.toUrl(this.path(root3)));
    }
  }
  isAnnotation() {
    if (this.isInline()) {
      return true;
    }
    if (typeof this.mapOpts.annotation !== "undefined") {
      return this.mapOpts.annotation;
    }
    if (this.previous().length) {
      return this.previous().some((i) => i.annotation);
    }
    return true;
  }
  toBase64(str2) {
    if (Buffer$1) {
      return Buffer$1.from(str2).toString("base64");
    } else {
      return window.btoa(unescape(encodeURIComponent(str2)));
    }
  }
  addAnnotation() {
    let content;
    if (this.isInline()) {
      content = "data:application/json;base64," + this.toBase64(this.map.toString());
    } else if (typeof this.mapOpts.annotation === "string") {
      content = this.mapOpts.annotation;
    } else if (typeof this.mapOpts.annotation === "function") {
      content = this.mapOpts.annotation(this.opts.to, this.root);
    } else {
      content = this.outputFile() + ".map";
    }
    let eol = "\n";
    if (this.css.includes("\r\n"))
      eol = "\r\n";
    this.css += eol + "/*# sourceMappingURL=" + content + " */";
  }
  outputFile() {
    if (this.opts.to) {
      return this.path(this.opts.to);
    } else if (this.opts.from) {
      return this.path(this.opts.from);
    } else {
      return "to.css";
    }
  }
  generateMap() {
    if (this.root) {
      this.generateString();
    } else if (this.previous().length === 1) {
      let prev = this.previous()[0].consumer();
      prev.file = this.outputFile();
      this.map = SourceMapGenerator$3.fromSourceMap(prev);
    } else {
      this.map = new SourceMapGenerator$3({ file: this.outputFile() });
      this.map.addMapping({
        source: this.opts.from ? this.toUrl(this.path(this.opts.from)) : "<no source>",
        generated: { line: 1, column: 0 },
        original: { line: 1, column: 0 }
      });
    }
    if (this.isSourcesContent())
      this.setSourcesContent();
    if (this.root && this.previous().length > 0)
      this.applyPrevMaps();
    if (this.isAnnotation())
      this.addAnnotation();
    if (this.isInline()) {
      return [this.css];
    } else {
      return [this.css, this.map];
    }
  }
  path(file) {
    if (file.indexOf("<") === 0)
      return file;
    if (/^\w+:\/\//.test(file))
      return file;
    if (this.mapOpts.absolute)
      return file;
    let from2 = this.opts.to ? dirname(this.opts.to) : ".";
    if (typeof this.mapOpts.annotation === "string") {
      from2 = dirname(resolve(from2, this.mapOpts.annotation));
    }
    file = relative(from2, file);
    return file;
  }
  toUrl(path2) {
    if (sep === "\\") {
      path2 = path2.replace(/\\/g, "/");
    }
    return encodeURI(path2).replace(/[#?]/g, encodeURIComponent);
  }
  toFileUrl(path2) {
    if (pathToFileURL) {
      return pathToFileURL(path2).toString();
    } else {
      throw new Error(
        "`map.absolute` option is not available in this PostCSS build"
      );
    }
  }
  sourcePath(node2) {
    if (this.mapOpts.from) {
      return this.toUrl(this.mapOpts.from);
    } else if (this.usesFileUrls) {
      return this.toFileUrl(node2.source.input.from);
    } else {
      return this.toUrl(this.path(node2.source.input.from));
    }
  }
  generateString() {
    this.css = "";
    this.map = new SourceMapGenerator$3({ file: this.outputFile() });
    let line = 1;
    let column = 1;
    let noSource = "<no source>";
    let mapping = {
      source: "",
      generated: { line: 0, column: 0 },
      original: { line: 0, column: 0 }
    };
    let lines, last2;
    this.stringify(this.root, (str2, node2, type) => {
      this.css += str2;
      if (node2 && type !== "end") {
        mapping.generated.line = line;
        mapping.generated.column = column - 1;
        if (node2.source && node2.source.start) {
          mapping.source = this.sourcePath(node2);
          mapping.original.line = node2.source.start.line;
          mapping.original.column = node2.source.start.column - 1;
          this.map.addMapping(mapping);
        } else {
          mapping.source = noSource;
          mapping.original.line = 1;
          mapping.original.column = 0;
          this.map.addMapping(mapping);
        }
      }
      lines = str2.match(/\n/g);
      if (lines) {
        line += lines.length;
        last2 = str2.lastIndexOf("\n");
        column = str2.length - last2;
      } else {
        column += str2.length;
      }
      if (node2 && type !== "start") {
        let p2 = node2.parent || { raws: {} };
        let childless = node2.type === "decl" || node2.type === "atrule" && !node2.nodes;
        if (!childless || node2 !== p2.last || p2.raws.semicolon) {
          if (node2.source && node2.source.end) {
            mapping.source = this.sourcePath(node2);
            mapping.original.line = node2.source.end.line;
            mapping.original.column = node2.source.end.column - 1;
            mapping.generated.line = line;
            mapping.generated.column = column - 2;
            this.map.addMapping(mapping);
          } else {
            mapping.source = noSource;
            mapping.original.line = 1;
            mapping.original.column = 0;
            mapping.generated.line = line;
            mapping.generated.column = column - 1;
            this.map.addMapping(mapping);
          }
        }
      }
    });
  }
  generate() {
    this.clearAnnotation();
    if (pathAvailable && sourceMapAvailable && this.isMap()) {
      return this.generateMap();
    } else {
      let result2 = "";
      this.stringify(this.root, (i) => {
        result2 += i;
      });
      return [result2];
    }
  }
};
var mapGenerator = MapGenerator$2;
let Node$2 = node$2;
let Comment$4 = class Comment extends Node$2 {
  constructor(defaults) {
    super(defaults);
    this.type = "comment";
  }
};
var comment$3 = Comment$4;
Comment$4.default = Comment$4;
let { isClean: isClean$1, my: my$1 } = symbols;
let Declaration$3 = declaration;
let Comment$3 = comment$3;
let Node$1$1 = node$2;
let parse$4, Rule$4, AtRule$4, Root$6;
function cleanSource(nodes) {
  return nodes.map((i) => {
    if (i.nodes)
      i.nodes = cleanSource(i.nodes);
    delete i.source;
    return i;
  });
}
function markDirtyUp(node2) {
  node2[isClean$1] = false;
  if (node2.proxyOf.nodes) {
    for (let i of node2.proxyOf.nodes) {
      markDirtyUp(i);
    }
  }
}
let Container$7 = class Container extends Node$1$1 {
  push(child) {
    child.parent = this;
    this.proxyOf.nodes.push(child);
    return this;
  }
  each(callback) {
    if (!this.proxyOf.nodes)
      return void 0;
    let iterator2 = this.getIterator();
    let index, result2;
    while (this.indexes[iterator2] < this.proxyOf.nodes.length) {
      index = this.indexes[iterator2];
      result2 = callback(this.proxyOf.nodes[index], index);
      if (result2 === false)
        break;
      this.indexes[iterator2] += 1;
    }
    delete this.indexes[iterator2];
    return result2;
  }
  walk(callback) {
    return this.each((child, i) => {
      let result2;
      try {
        result2 = callback(child, i);
      } catch (e) {
        throw child.addToError(e);
      }
      if (result2 !== false && child.walk) {
        result2 = child.walk(callback);
      }
      return result2;
    });
  }
  walkDecls(prop, callback) {
    if (!callback) {
      callback = prop;
      return this.walk((child, i) => {
        if (child.type === "decl") {
          return callback(child, i);
        }
      });
    }
    if (prop instanceof RegExp) {
      return this.walk((child, i) => {
        if (child.type === "decl" && prop.test(child.prop)) {
          return callback(child, i);
        }
      });
    }
    return this.walk((child, i) => {
      if (child.type === "decl" && child.prop === prop) {
        return callback(child, i);
      }
    });
  }
  walkRules(selector3, callback) {
    if (!callback) {
      callback = selector3;
      return this.walk((child, i) => {
        if (child.type === "rule") {
          return callback(child, i);
        }
      });
    }
    if (selector3 instanceof RegExp) {
      return this.walk((child, i) => {
        if (child.type === "rule" && selector3.test(child.selector)) {
          return callback(child, i);
        }
      });
    }
    return this.walk((child, i) => {
      if (child.type === "rule" && child.selector === selector3) {
        return callback(child, i);
      }
    });
  }
  walkAtRules(name, callback) {
    if (!callback) {
      callback = name;
      return this.walk((child, i) => {
        if (child.type === "atrule") {
          return callback(child, i);
        }
      });
    }
    if (name instanceof RegExp) {
      return this.walk((child, i) => {
        if (child.type === "atrule" && name.test(child.name)) {
          return callback(child, i);
        }
      });
    }
    return this.walk((child, i) => {
      if (child.type === "atrule" && child.name === name) {
        return callback(child, i);
      }
    });
  }
  walkComments(callback) {
    return this.walk((child, i) => {
      if (child.type === "comment") {
        return callback(child, i);
      }
    });
  }
  append(...children) {
    for (let child of children) {
      let nodes = this.normalize(child, this.last);
      for (let node2 of nodes)
        this.proxyOf.nodes.push(node2);
    }
    this.markDirty();
    return this;
  }
  prepend(...children) {
    children = children.reverse();
    for (let child of children) {
      let nodes = this.normalize(child, this.first, "prepend").reverse();
      for (let node2 of nodes)
        this.proxyOf.nodes.unshift(node2);
      for (let id3 in this.indexes) {
        this.indexes[id3] = this.indexes[id3] + nodes.length;
      }
    }
    this.markDirty();
    return this;
  }
  cleanRaws(keepBetween) {
    super.cleanRaws(keepBetween);
    if (this.nodes) {
      for (let node2 of this.nodes)
        node2.cleanRaws(keepBetween);
    }
  }
  insertBefore(exist, add2) {
    let existIndex = this.index(exist);
    let type = existIndex === 0 ? "prepend" : false;
    let nodes = this.normalize(add2, this.proxyOf.nodes[existIndex], type).reverse();
    existIndex = this.index(exist);
    for (let node2 of nodes)
      this.proxyOf.nodes.splice(existIndex, 0, node2);
    let index;
    for (let id3 in this.indexes) {
      index = this.indexes[id3];
      if (existIndex <= index) {
        this.indexes[id3] = index + nodes.length;
      }
    }
    this.markDirty();
    return this;
  }
  insertAfter(exist, add2) {
    let existIndex = this.index(exist);
    let nodes = this.normalize(add2, this.proxyOf.nodes[existIndex]).reverse();
    existIndex = this.index(exist);
    for (let node2 of nodes)
      this.proxyOf.nodes.splice(existIndex + 1, 0, node2);
    let index;
    for (let id3 in this.indexes) {
      index = this.indexes[id3];
      if (existIndex < index) {
        this.indexes[id3] = index + nodes.length;
      }
    }
    this.markDirty();
    return this;
  }
  removeChild(child) {
    child = this.index(child);
    this.proxyOf.nodes[child].parent = void 0;
    this.proxyOf.nodes.splice(child, 1);
    let index;
    for (let id3 in this.indexes) {
      index = this.indexes[id3];
      if (index >= child) {
        this.indexes[id3] = index - 1;
      }
    }
    this.markDirty();
    return this;
  }
  removeAll() {
    for (let node2 of this.proxyOf.nodes)
      node2.parent = void 0;
    this.proxyOf.nodes = [];
    this.markDirty();
    return this;
  }
  replaceValues(pattern, opts, callback) {
    if (!callback) {
      callback = opts;
      opts = {};
    }
    this.walkDecls((decl) => {
      if (opts.props && !opts.props.includes(decl.prop))
        return;
      if (opts.fast && !decl.value.includes(opts.fast))
        return;
      decl.value = decl.value.replace(pattern, callback);
    });
    this.markDirty();
    return this;
  }
  every(condition) {
    return this.nodes.every(condition);
  }
  some(condition) {
    return this.nodes.some(condition);
  }
  index(child) {
    if (typeof child === "number")
      return child;
    if (child.proxyOf)
      child = child.proxyOf;
    return this.proxyOf.nodes.indexOf(child);
  }
  get first() {
    if (!this.proxyOf.nodes)
      return void 0;
    return this.proxyOf.nodes[0];
  }
  get last() {
    if (!this.proxyOf.nodes)
      return void 0;
    return this.proxyOf.nodes[this.proxyOf.nodes.length - 1];
  }
  normalize(nodes, sample) {
    if (typeof nodes === "string") {
      nodes = cleanSource(parse$4(nodes).nodes);
    } else if (Array.isArray(nodes)) {
      nodes = nodes.slice(0);
      for (let i of nodes) {
        if (i.parent)
          i.parent.removeChild(i, "ignore");
      }
    } else if (nodes.type === "root" && this.type !== "document") {
      nodes = nodes.nodes.slice(0);
      for (let i of nodes) {
        if (i.parent)
          i.parent.removeChild(i, "ignore");
      }
    } else if (nodes.type) {
      nodes = [nodes];
    } else if (nodes.prop) {
      if (typeof nodes.value === "undefined") {
        throw new Error("Value field is missed in node creation");
      } else if (typeof nodes.value !== "string") {
        nodes.value = String(nodes.value);
      }
      nodes = [new Declaration$3(nodes)];
    } else if (nodes.selector) {
      nodes = [new Rule$4(nodes)];
    } else if (nodes.name) {
      nodes = [new AtRule$4(nodes)];
    } else if (nodes.text) {
      nodes = [new Comment$3(nodes)];
    } else {
      throw new Error("Unknown node type in node creation");
    }
    let processed = nodes.map((i) => {
      if (!i[my$1])
        Container.rebuild(i);
      i = i.proxyOf;
      if (i.parent)
        i.parent.removeChild(i);
      if (i[isClean$1])
        markDirtyUp(i);
      if (typeof i.raws.before === "undefined") {
        if (sample && typeof sample.raws.before !== "undefined") {
          i.raws.before = sample.raws.before.replace(/\S/g, "");
        }
      }
      i.parent = this.proxyOf;
      return i;
    });
    return processed;
  }
  getProxyProcessor() {
    return {
      set(node2, prop, value) {
        if (node2[prop] === value)
          return true;
        node2[prop] = value;
        if (prop === "name" || prop === "params" || prop === "selector") {
          node2.markDirty();
        }
        return true;
      },
      get(node2, prop) {
        if (prop === "proxyOf") {
          return node2;
        } else if (!node2[prop]) {
          return node2[prop];
        } else if (prop === "each" || typeof prop === "string" && prop.startsWith("walk")) {
          return (...args) => {
            return node2[prop](
              ...args.map((i) => {
                if (typeof i === "function") {
                  return (child, index) => i(child.toProxy(), index);
                } else {
                  return i;
                }
              })
            );
          };
        } else if (prop === "every" || prop === "some") {
          return (cb) => {
            return node2[prop](
              (child, ...other) => cb(child.toProxy(), ...other)
            );
          };
        } else if (prop === "root") {
          return () => node2.root().toProxy();
        } else if (prop === "nodes") {
          return node2.nodes.map((i) => i.toProxy());
        } else if (prop === "first" || prop === "last") {
          return node2[prop].toProxy();
        } else {
          return node2[prop];
        }
      }
    };
  }
  getIterator() {
    if (!this.lastEach)
      this.lastEach = 0;
    if (!this.indexes)
      this.indexes = {};
    this.lastEach += 1;
    let iterator2 = this.lastEach;
    this.indexes[iterator2] = 0;
    return iterator2;
  }
};
Container$7.registerParse = (dependant) => {
  parse$4 = dependant;
};
Container$7.registerRule = (dependant) => {
  Rule$4 = dependant;
};
Container$7.registerAtRule = (dependant) => {
  AtRule$4 = dependant;
};
Container$7.registerRoot = (dependant) => {
  Root$6 = dependant;
};
var container$1 = Container$7;
Container$7.default = Container$7;
Container$7.rebuild = (node2) => {
  if (node2.type === "atrule") {
    Object.setPrototypeOf(node2, AtRule$4.prototype);
  } else if (node2.type === "rule") {
    Object.setPrototypeOf(node2, Rule$4.prototype);
  } else if (node2.type === "decl") {
    Object.setPrototypeOf(node2, Declaration$3.prototype);
  } else if (node2.type === "comment") {
    Object.setPrototypeOf(node2, Comment$3.prototype);
  } else if (node2.type === "root") {
    Object.setPrototypeOf(node2, Root$6.prototype);
  }
  node2[my$1] = true;
  if (node2.nodes) {
    node2.nodes.forEach((child) => {
      Container$7.rebuild(child);
    });
  }
};
let Container$6 = container$1;
let LazyResult$4, Processor$3;
let Document$3 = class Document extends Container$6 {
  constructor(defaults) {
    super({ type: "document", ...defaults });
    if (!this.nodes) {
      this.nodes = [];
    }
  }
  toResult(opts = {}) {
    let lazy = new LazyResult$4(new Processor$3(), this, opts);
    return lazy.stringify();
  }
};
Document$3.registerLazyResult = (dependant) => {
  LazyResult$4 = dependant;
};
Document$3.registerProcessor = (dependant) => {
  Processor$3 = dependant;
};
var document$1 = Document$3;
Document$3.default = Document$3;
let printed = {};
var warnOnce$3 = function warnOnce(message) {
  if (printed[message])
    return;
  printed[message] = true;
  if (typeof console !== "undefined" && console.warn) {
    console.warn(message);
  }
};
let Warning$2 = class Warning {
  constructor(text2, opts = {}) {
    this.type = "warning";
    this.text = text2;
    if (opts.node && opts.node.source) {
      let range2 = opts.node.rangeBy(opts);
      this.line = range2.start.line;
      this.column = range2.start.column;
      this.endLine = range2.end.line;
      this.endColumn = range2.end.column;
    }
    for (let opt in opts)
      this[opt] = opts[opt];
  }
  toString() {
    if (this.node) {
      return this.node.error(this.text, {
        plugin: this.plugin,
        index: this.index,
        word: this.word
      }).message;
    }
    if (this.plugin) {
      return this.plugin + ": " + this.text;
    }
    return this.text;
  }
};
var warning = Warning$2;
Warning$2.default = Warning$2;
let Warning$1 = warning;
let Result$3 = class Result {
  constructor(processor2, root3, opts) {
    this.processor = processor2;
    this.messages = [];
    this.root = root3;
    this.opts = opts;
    this.css = void 0;
    this.map = void 0;
  }
  toString() {
    return this.css;
  }
  warn(text2, opts = {}) {
    if (!opts.plugin) {
      if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
        opts.plugin = this.lastPlugin.postcssPlugin;
      }
    }
    let warning2 = new Warning$1(text2, opts);
    this.messages.push(warning2);
    return warning2;
  }
  warnings() {
    return this.messages.filter((i) => i.type === "warning");
  }
  get content() {
    return this.css;
  }
};
var result = Result$3;
Result$3.default = Result$3;
let Container$5 = container$1;
let AtRule$3 = class AtRule extends Container$5 {
  constructor(defaults) {
    super(defaults);
    this.type = "atrule";
  }
  append(...children) {
    if (!this.proxyOf.nodes)
      this.nodes = [];
    return super.append(...children);
  }
  prepend(...children) {
    if (!this.proxyOf.nodes)
      this.nodes = [];
    return super.prepend(...children);
  }
};
var atRule = AtRule$3;
AtRule$3.default = AtRule$3;
Container$5.registerAtRule(AtRule$3);
let Container$4 = container$1;
let LazyResult$3, Processor$2;
let Root$5 = class Root extends Container$4 {
  constructor(defaults) {
    super(defaults);
    this.type = "root";
    if (!this.nodes)
      this.nodes = [];
  }
  removeChild(child, ignore) {
    let index = this.index(child);
    if (!ignore && index === 0 && this.nodes.length > 1) {
      this.nodes[1].raws.before = this.nodes[index].raws.before;
    }
    return super.removeChild(child);
  }
  normalize(child, sample, type) {
    let nodes = super.normalize(child);
    if (sample) {
      if (type === "prepend") {
        if (this.nodes.length > 1) {
          sample.raws.before = this.nodes[1].raws.before;
        } else {
          delete sample.raws.before;
        }
      } else if (this.first !== sample) {
        for (let node2 of nodes) {
          node2.raws.before = sample.raws.before;
        }
      }
    }
    return nodes;
  }
  toResult(opts = {}) {
    let lazy = new LazyResult$3(new Processor$2(), this, opts);
    return lazy.stringify();
  }
};
Root$5.registerLazyResult = (dependant) => {
  LazyResult$3 = dependant;
};
Root$5.registerProcessor = (dependant) => {
  Processor$2 = dependant;
};
var root$2 = Root$5;
Root$5.default = Root$5;
Container$4.registerRoot(Root$5);
let list$2 = {
  split(string3, separators, last2) {
    let array2 = [];
    let current = "";
    let split = false;
    let func = 0;
    let inQuote = false;
    let prevQuote = "";
    let escape2 = false;
    for (let letter of string3) {
      if (escape2) {
        escape2 = false;
      } else if (letter === "\\") {
        escape2 = true;
      } else if (inQuote) {
        if (letter === prevQuote) {
          inQuote = false;
        }
      } else if (letter === '"' || letter === "'") {
        inQuote = true;
        prevQuote = letter;
      } else if (letter === "(") {
        func += 1;
      } else if (letter === ")") {
        if (func > 0)
          func -= 1;
      } else if (func === 0) {
        if (separators.includes(letter))
          split = true;
      }
      if (split) {
        if (current !== "")
          array2.push(current.trim());
        current = "";
        split = false;
      } else {
        current += letter;
      }
    }
    if (last2 || current !== "")
      array2.push(current.trim());
    return array2;
  },
  space(string3) {
    let spaces2 = [" ", "\n", "	"];
    return list$2.split(string3, spaces2);
  },
  comma(string3) {
    return list$2.split(string3, [","], true);
  }
};
var list_1 = list$2;
list$2.default = list$2;
let Container$3 = container$1;
let list$1 = list_1;
let Rule$3 = class Rule2 extends Container$3 {
  constructor(defaults) {
    super(defaults);
    this.type = "rule";
    if (!this.nodes)
      this.nodes = [];
  }
  get selectors() {
    return list$1.comma(this.selector);
  }
  set selectors(values) {
    let match2 = this.selector ? this.selector.match(/,\s*/) : null;
    let sep2 = match2 ? match2[0] : "," + this.raw("between", "beforeOpen");
    this.selector = values.join(sep2);
  }
};
var rule = Rule$3;
Rule$3.default = Rule$3;
Container$3.registerRule(Rule$3);
let Declaration$2 = declaration;
let tokenizer2 = tokenize$1;
let Comment$2 = comment$3;
let AtRule$2 = atRule;
let Root$4 = root$2;
let Rule$2 = rule;
const SAFE_COMMENT_NEIGHBOR = {
  empty: true,
  space: true
};
function findLastWithPosition(tokens) {
  for (let i = tokens.length - 1; i >= 0; i--) {
    let token = tokens[i];
    let pos = token[3] || token[2];
    if (pos)
      return pos;
  }
}
let Parser$1 = class Parser4 {
  constructor(input2) {
    this.input = input2;
    this.root = new Root$4();
    this.current = this.root;
    this.spaces = "";
    this.semicolon = false;
    this.customProperty = false;
    this.createTokenizer();
    this.root.source = { input: input2, start: { offset: 0, line: 1, column: 1 } };
  }
  createTokenizer() {
    this.tokenizer = tokenizer2(this.input);
  }
  parse() {
    let token;
    while (!this.tokenizer.endOfFile()) {
      token = this.tokenizer.nextToken();
      switch (token[0]) {
        case "space":
          this.spaces += token[1];
          break;
        case ";":
          this.freeSemicolon(token);
          break;
        case "}":
          this.end(token);
          break;
        case "comment":
          this.comment(token);
          break;
        case "at-word":
          this.atrule(token);
          break;
        case "{":
          this.emptyRule(token);
          break;
        default:
          this.other(token);
          break;
      }
    }
    this.endFile();
  }
  comment(token) {
    let node2 = new Comment$2();
    this.init(node2, token[2]);
    node2.source.end = this.getPosition(token[3] || token[2]);
    let text2 = token[1].slice(2, -2);
    if (/^\s*$/.test(text2)) {
      node2.text = "";
      node2.raws.left = text2;
      node2.raws.right = "";
    } else {
      let match2 = text2.match(/^(\s*)([^]*\S)(\s*)$/);
      node2.text = match2[2];
      node2.raws.left = match2[1];
      node2.raws.right = match2[3];
    }
  }
  emptyRule(token) {
    let node2 = new Rule$2();
    this.init(node2, token[2]);
    node2.selector = "";
    node2.raws.between = "";
    this.current = node2;
  }
  other(start) {
    let end = false;
    let type = null;
    let colon2 = false;
    let bracket = null;
    let brackets = [];
    let customProperty = start[1].startsWith("--");
    let tokens = [];
    let token = start;
    while (token) {
      type = token[0];
      tokens.push(token);
      if (type === "(" || type === "[") {
        if (!bracket)
          bracket = token;
        brackets.push(type === "(" ? ")" : "]");
      } else if (customProperty && colon2 && type === "{") {
        if (!bracket)
          bracket = token;
        brackets.push("}");
      } else if (brackets.length === 0) {
        if (type === ";") {
          if (colon2) {
            this.decl(tokens, customProperty);
            return;
          } else {
            break;
          }
        } else if (type === "{") {
          this.rule(tokens);
          return;
        } else if (type === "}") {
          this.tokenizer.back(tokens.pop());
          end = true;
          break;
        } else if (type === ":") {
          colon2 = true;
        }
      } else if (type === brackets[brackets.length - 1]) {
        brackets.pop();
        if (brackets.length === 0)
          bracket = null;
      }
      token = this.tokenizer.nextToken();
    }
    if (this.tokenizer.endOfFile())
      end = true;
    if (brackets.length > 0)
      this.unclosedBracket(bracket);
    if (end && colon2) {
      if (!customProperty) {
        while (tokens.length) {
          token = tokens[tokens.length - 1][0];
          if (token !== "space" && token !== "comment")
            break;
          this.tokenizer.back(tokens.pop());
        }
      }
      this.decl(tokens, customProperty);
    } else {
      this.unknownWord(tokens);
    }
  }
  rule(tokens) {
    tokens.pop();
    let node2 = new Rule$2();
    this.init(node2, tokens[0][2]);
    node2.raws.between = this.spacesAndCommentsFromEnd(tokens);
    this.raw(node2, "selector", tokens);
    this.current = node2;
  }
  decl(tokens, customProperty) {
    let node2 = new Declaration$2();
    this.init(node2, tokens[0][2]);
    let last2 = tokens[tokens.length - 1];
    if (last2[0] === ";") {
      this.semicolon = true;
      tokens.pop();
    }
    node2.source.end = this.getPosition(
      last2[3] || last2[2] || findLastWithPosition(tokens)
    );
    while (tokens[0][0] !== "word") {
      if (tokens.length === 1)
        this.unknownWord(tokens);
      node2.raws.before += tokens.shift()[1];
    }
    node2.source.start = this.getPosition(tokens[0][2]);
    node2.prop = "";
    while (tokens.length) {
      let type = tokens[0][0];
      if (type === ":" || type === "space" || type === "comment") {
        break;
      }
      node2.prop += tokens.shift()[1];
    }
    node2.raws.between = "";
    let token;
    while (tokens.length) {
      token = tokens.shift();
      if (token[0] === ":") {
        node2.raws.between += token[1];
        break;
      } else {
        if (token[0] === "word" && /\w/.test(token[1])) {
          this.unknownWord([token]);
        }
        node2.raws.between += token[1];
      }
    }
    if (node2.prop[0] === "_" || node2.prop[0] === "*") {
      node2.raws.before += node2.prop[0];
      node2.prop = node2.prop.slice(1);
    }
    let firstSpaces = [];
    let next;
    while (tokens.length) {
      next = tokens[0][0];
      if (next !== "space" && next !== "comment")
        break;
      firstSpaces.push(tokens.shift());
    }
    this.precheckMissedSemicolon(tokens);
    for (let i = tokens.length - 1; i >= 0; i--) {
      token = tokens[i];
      if (token[1].toLowerCase() === "!important") {
        node2.important = true;
        let string3 = this.stringFrom(tokens, i);
        string3 = this.spacesFromEnd(tokens) + string3;
        if (string3 !== " !important")
          node2.raws.important = string3;
        break;
      } else if (token[1].toLowerCase() === "important") {
        let cache2 = tokens.slice(0);
        let str2 = "";
        for (let j = i; j > 0; j--) {
          let type = cache2[j][0];
          if (str2.trim().indexOf("!") === 0 && type !== "space") {
            break;
          }
          str2 = cache2.pop()[1] + str2;
        }
        if (str2.trim().indexOf("!") === 0) {
          node2.important = true;
          node2.raws.important = str2;
          tokens = cache2;
        }
      }
      if (token[0] !== "space" && token[0] !== "comment") {
        break;
      }
    }
    let hasWord = tokens.some((i) => i[0] !== "space" && i[0] !== "comment");
    if (hasWord) {
      node2.raws.between += firstSpaces.map((i) => i[1]).join("");
      firstSpaces = [];
    }
    this.raw(node2, "value", firstSpaces.concat(tokens), customProperty);
    if (node2.value.includes(":") && !customProperty) {
      this.checkMissedSemicolon(tokens);
    }
  }
  atrule(token) {
    let node2 = new AtRule$2();
    node2.name = token[1].slice(1);
    if (node2.name === "") {
      this.unnamedAtrule(node2, token);
    }
    this.init(node2, token[2]);
    let type;
    let prev;
    let shift2;
    let last2 = false;
    let open = false;
    let params = [];
    let brackets = [];
    while (!this.tokenizer.endOfFile()) {
      token = this.tokenizer.nextToken();
      type = token[0];
      if (type === "(" || type === "[") {
        brackets.push(type === "(" ? ")" : "]");
      } else if (type === "{" && brackets.length > 0) {
        brackets.push("}");
      } else if (type === brackets[brackets.length - 1]) {
        brackets.pop();
      }
      if (brackets.length === 0) {
        if (type === ";") {
          node2.source.end = this.getPosition(token[2]);
          this.semicolon = true;
          break;
        } else if (type === "{") {
          open = true;
          break;
        } else if (type === "}") {
          if (params.length > 0) {
            shift2 = params.length - 1;
            prev = params[shift2];
            while (prev && prev[0] === "space") {
              prev = params[--shift2];
            }
            if (prev) {
              node2.source.end = this.getPosition(prev[3] || prev[2]);
            }
          }
          this.end(token);
          break;
        } else {
          params.push(token);
        }
      } else {
        params.push(token);
      }
      if (this.tokenizer.endOfFile()) {
        last2 = true;
        break;
      }
    }
    node2.raws.between = this.spacesAndCommentsFromEnd(params);
    if (params.length) {
      node2.raws.afterName = this.spacesAndCommentsFromStart(params);
      this.raw(node2, "params", params);
      if (last2) {
        token = params[params.length - 1];
        node2.source.end = this.getPosition(token[3] || token[2]);
        this.spaces = node2.raws.between;
        node2.raws.between = "";
      }
    } else {
      node2.raws.afterName = "";
      node2.params = "";
    }
    if (open) {
      node2.nodes = [];
      this.current = node2;
    }
  }
  end(token) {
    if (this.current.nodes && this.current.nodes.length) {
      this.current.raws.semicolon = this.semicolon;
    }
    this.semicolon = false;
    this.current.raws.after = (this.current.raws.after || "") + this.spaces;
    this.spaces = "";
    if (this.current.parent) {
      this.current.source.end = this.getPosition(token[2]);
      this.current = this.current.parent;
    } else {
      this.unexpectedClose(token);
    }
  }
  endFile() {
    if (this.current.parent)
      this.unclosedBlock();
    if (this.current.nodes && this.current.nodes.length) {
      this.current.raws.semicolon = this.semicolon;
    }
    this.current.raws.after = (this.current.raws.after || "") + this.spaces;
  }
  freeSemicolon(token) {
    this.spaces += token[1];
    if (this.current.nodes) {
      let prev = this.current.nodes[this.current.nodes.length - 1];
      if (prev && prev.type === "rule" && !prev.raws.ownSemicolon) {
        prev.raws.ownSemicolon = this.spaces;
        this.spaces = "";
      }
    }
  }
  // Helpers
  getPosition(offset) {
    let pos = this.input.fromOffset(offset);
    return {
      offset,
      line: pos.line,
      column: pos.col
    };
  }
  init(node2, offset) {
    this.current.push(node2);
    node2.source = {
      start: this.getPosition(offset),
      input: this.input
    };
    node2.raws.before = this.spaces;
    this.spaces = "";
    if (node2.type !== "comment")
      this.semicolon = false;
  }
  raw(node2, prop, tokens, customProperty) {
    let token, type;
    let length2 = tokens.length;
    let value = "";
    let clean = true;
    let next, prev;
    for (let i = 0; i < length2; i += 1) {
      token = tokens[i];
      type = token[0];
      if (type === "space" && i === length2 - 1 && !customProperty) {
        clean = false;
      } else if (type === "comment") {
        prev = tokens[i - 1] ? tokens[i - 1][0] : "empty";
        next = tokens[i + 1] ? tokens[i + 1][0] : "empty";
        if (!SAFE_COMMENT_NEIGHBOR[prev] && !SAFE_COMMENT_NEIGHBOR[next]) {
          if (value.slice(-1) === ",") {
            clean = false;
          } else {
            value += token[1];
          }
        } else {
          clean = false;
        }
      } else {
        value += token[1];
      }
    }
    if (!clean) {
      let raw = tokens.reduce((all, i) => all + i[1], "");
      node2.raws[prop] = { value, raw };
    }
    node2[prop] = value;
  }
  spacesAndCommentsFromEnd(tokens) {
    let lastTokenType;
    let spaces2 = "";
    while (tokens.length) {
      lastTokenType = tokens[tokens.length - 1][0];
      if (lastTokenType !== "space" && lastTokenType !== "comment")
        break;
      spaces2 = tokens.pop()[1] + spaces2;
    }
    return spaces2;
  }
  spacesAndCommentsFromStart(tokens) {
    let next;
    let spaces2 = "";
    while (tokens.length) {
      next = tokens[0][0];
      if (next !== "space" && next !== "comment")
        break;
      spaces2 += tokens.shift()[1];
    }
    return spaces2;
  }
  spacesFromEnd(tokens) {
    let lastTokenType;
    let spaces2 = "";
    while (tokens.length) {
      lastTokenType = tokens[tokens.length - 1][0];
      if (lastTokenType !== "space")
        break;
      spaces2 = tokens.pop()[1] + spaces2;
    }
    return spaces2;
  }
  stringFrom(tokens, from2) {
    let result2 = "";
    for (let i = from2; i < tokens.length; i++) {
      result2 += tokens[i][1];
    }
    tokens.splice(from2, tokens.length - from2);
    return result2;
  }
  colon(tokens) {
    let brackets = 0;
    let token, type, prev;
    for (let [i, element] of tokens.entries()) {
      token = element;
      type = token[0];
      if (type === "(") {
        brackets += 1;
      }
      if (type === ")") {
        brackets -= 1;
      }
      if (brackets === 0 && type === ":") {
        if (!prev) {
          this.doubleColon(token);
        } else if (prev[0] === "word" && prev[1] === "progid") {
          continue;
        } else {
          return i;
        }
      }
      prev = token;
    }
    return false;
  }
  // Errors
  unclosedBracket(bracket) {
    throw this.input.error(
      "Unclosed bracket",
      { offset: bracket[2] },
      { offset: bracket[2] + 1 }
    );
  }
  unknownWord(tokens) {
    throw this.input.error(
      "Unknown word",
      { offset: tokens[0][2] },
      { offset: tokens[0][2] + tokens[0][1].length }
    );
  }
  unexpectedClose(token) {
    throw this.input.error(
      "Unexpected }",
      { offset: token[2] },
      { offset: token[2] + 1 }
    );
  }
  unclosedBlock() {
    let pos = this.current.source.start;
    throw this.input.error("Unclosed block", pos.line, pos.column);
  }
  doubleColon(token) {
    throw this.input.error(
      "Double colon",
      { offset: token[2] },
      { offset: token[2] + token[1].length }
    );
  }
  unnamedAtrule(node2, token) {
    throw this.input.error(
      "At-rule without name",
      { offset: token[2] },
      { offset: token[2] + token[1].length }
    );
  }
  precheckMissedSemicolon() {
  }
  checkMissedSemicolon(tokens) {
    let colon2 = this.colon(tokens);
    if (colon2 === false)
      return;
    let founded = 0;
    let token;
    for (let j = colon2 - 1; j >= 0; j--) {
      token = tokens[j];
      if (token[0] !== "space") {
        founded += 1;
        if (founded === 2)
          break;
      }
    }
    throw this.input.error(
      "Missed semicolon",
      token[0] === "word" ? token[3] + 1 : token[2]
    );
  }
};
var parser$1 = Parser$1;
let Container$2 = container$1;
let Parser5 = parser$1;
let Input$2 = input;
function parse$3(css, opts) {
  let input2 = new Input$2(css, opts);
  let parser2 = new Parser5(input2);
  try {
    parser2.parse();
  } catch (e) {
    if (browser$1.env.NODE_ENV !== "production") {
      if (e.name === "CssSyntaxError" && opts && opts.from) {
        if (/\.scss$/i.test(opts.from)) {
          e.message += "\nYou tried to parse SCSS with the standard CSS parser; try again with the postcss-scss parser";
        } else if (/\.sass/i.test(opts.from)) {
          e.message += "\nYou tried to parse Sass with the standard CSS parser; try again with the postcss-sass parser";
        } else if (/\.less$/i.test(opts.from)) {
          e.message += "\nYou tried to parse Less with the standard CSS parser; try again with the postcss-less parser";
        }
      }
    }
    throw e;
  }
  return parser2.root;
}
var parse_1 = parse$3;
parse$3.default = parse$3;
Container$2.registerParse(parse$3);
let { isClean, my } = symbols;
let MapGenerator$1 = mapGenerator;
let stringify$2 = stringify_1;
let Container$1 = container$1;
let Document$2 = document$1;
let warnOnce$2 = warnOnce$3;
let Result$2 = result;
let parse$2 = parse_1;
let Root$3 = root$2;
const TYPE_TO_CLASS_NAME = {
  document: "Document",
  root: "Root",
  atrule: "AtRule",
  rule: "Rule",
  decl: "Declaration",
  comment: "Comment"
};
const PLUGIN_PROPS = {
  postcssPlugin: true,
  prepare: true,
  Once: true,
  Document: true,
  Root: true,
  Declaration: true,
  Rule: true,
  AtRule: true,
  Comment: true,
  DeclarationExit: true,
  RuleExit: true,
  AtRuleExit: true,
  CommentExit: true,
  RootExit: true,
  DocumentExit: true,
  OnceExit: true
};
const NOT_VISITORS = {
  postcssPlugin: true,
  prepare: true,
  Once: true
};
const CHILDREN = 0;
function isPromise(obj) {
  return typeof obj === "object" && typeof obj.then === "function";
}
function getEvents(node2) {
  let key = false;
  let type = TYPE_TO_CLASS_NAME[node2.type];
  if (node2.type === "decl") {
    key = node2.prop.toLowerCase();
  } else if (node2.type === "atrule") {
    key = node2.name.toLowerCase();
  }
  if (key && node2.append) {
    return [
      type,
      type + "-" + key,
      CHILDREN,
      type + "Exit",
      type + "Exit-" + key
    ];
  } else if (key) {
    return [type, type + "-" + key, type + "Exit", type + "Exit-" + key];
  } else if (node2.append) {
    return [type, CHILDREN, type + "Exit"];
  } else {
    return [type, type + "Exit"];
  }
}
function toStack(node2) {
  let events;
  if (node2.type === "document") {
    events = ["Document", CHILDREN, "DocumentExit"];
  } else if (node2.type === "root") {
    events = ["Root", CHILDREN, "RootExit"];
  } else {
    events = getEvents(node2);
  }
  return {
    node: node2,
    events,
    eventIndex: 0,
    visitors: [],
    visitorIndex: 0,
    iterator: 0
  };
}
function cleanMarks(node2) {
  node2[isClean] = false;
  if (node2.nodes)
    node2.nodes.forEach((i) => cleanMarks(i));
  return node2;
}
let postcss$2 = {};
let LazyResult$2 = class LazyResult {
  constructor(processor2, css, opts) {
    this.stringified = false;
    this.processed = false;
    let root3;
    if (typeof css === "object" && css !== null && (css.type === "root" || css.type === "document")) {
      root3 = cleanMarks(css);
    } else if (css instanceof LazyResult || css instanceof Result$2) {
      root3 = cleanMarks(css.root);
      if (css.map) {
        if (typeof opts.map === "undefined")
          opts.map = {};
        if (!opts.map.inline)
          opts.map.inline = false;
        opts.map.prev = css.map;
      }
    } else {
      let parser2 = parse$2;
      if (opts.syntax)
        parser2 = opts.syntax.parse;
      if (opts.parser)
        parser2 = opts.parser;
      if (parser2.parse)
        parser2 = parser2.parse;
      try {
        root3 = parser2(css, opts);
      } catch (error2) {
        this.processed = true;
        this.error = error2;
      }
      if (root3 && !root3[my]) {
        Container$1.rebuild(root3);
      }
    }
    this.result = new Result$2(processor2, root3, opts);
    this.helpers = { ...postcss$2, result: this.result, postcss: postcss$2 };
    this.plugins = this.processor.plugins.map((plugin2) => {
      if (typeof plugin2 === "object" && plugin2.prepare) {
        return { ...plugin2, ...plugin2.prepare(this.result) };
      } else {
        return plugin2;
      }
    });
  }
  get [Symbol.toStringTag]() {
    return "LazyResult";
  }
  get processor() {
    return this.result.processor;
  }
  get opts() {
    return this.result.opts;
  }
  get css() {
    return this.stringify().css;
  }
  get content() {
    return this.stringify().content;
  }
  get map() {
    return this.stringify().map;
  }
  get root() {
    return this.sync().root;
  }
  get messages() {
    return this.sync().messages;
  }
  warnings() {
    return this.sync().warnings();
  }
  toString() {
    return this.css;
  }
  then(onFulfilled, onRejected) {
    if (browser$1.env.NODE_ENV !== "production") {
      if (!("from" in this.opts)) {
        warnOnce$2(
          "Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning."
        );
      }
    }
    return this.async().then(onFulfilled, onRejected);
  }
  catch(onRejected) {
    return this.async().catch(onRejected);
  }
  finally(onFinally) {
    return this.async().then(onFinally, onFinally);
  }
  async() {
    if (this.error)
      return Promise.reject(this.error);
    if (this.processed)
      return Promise.resolve(this.result);
    if (!this.processing) {
      this.processing = this.runAsync();
    }
    return this.processing;
  }
  sync() {
    if (this.error)
      throw this.error;
    if (this.processed)
      return this.result;
    this.processed = true;
    if (this.processing) {
      throw this.getAsyncError();
    }
    for (let plugin2 of this.plugins) {
      let promise = this.runOnRoot(plugin2);
      if (isPromise(promise)) {
        throw this.getAsyncError();
      }
    }
    this.prepareVisitors();
    if (this.hasListener) {
      let root3 = this.result.root;
      while (!root3[isClean]) {
        root3[isClean] = true;
        this.walkSync(root3);
      }
      if (this.listeners.OnceExit) {
        if (root3.type === "document") {
          for (let subRoot of root3.nodes) {
            this.visitSync(this.listeners.OnceExit, subRoot);
          }
        } else {
          this.visitSync(this.listeners.OnceExit, root3);
        }
      }
    }
    return this.result;
  }
  stringify() {
    if (this.error)
      throw this.error;
    if (this.stringified)
      return this.result;
    this.stringified = true;
    this.sync();
    let opts = this.result.opts;
    let str2 = stringify$2;
    if (opts.syntax)
      str2 = opts.syntax.stringify;
    if (opts.stringifier)
      str2 = opts.stringifier;
    if (str2.stringify)
      str2 = str2.stringify;
    let map2 = new MapGenerator$1(str2, this.result.root, this.result.opts);
    let data = map2.generate();
    this.result.css = data[0];
    this.result.map = data[1];
    return this.result;
  }
  walkSync(node2) {
    node2[isClean] = true;
    let events = getEvents(node2);
    for (let event of events) {
      if (event === CHILDREN) {
        if (node2.nodes) {
          node2.each((child) => {
            if (!child[isClean])
              this.walkSync(child);
          });
        }
      } else {
        let visitors = this.listeners[event];
        if (visitors) {
          if (this.visitSync(visitors, node2.toProxy()))
            return;
        }
      }
    }
  }
  visitSync(visitors, node2) {
    for (let [plugin2, visitor] of visitors) {
      this.result.lastPlugin = plugin2;
      let promise;
      try {
        promise = visitor(node2, this.helpers);
      } catch (e) {
        throw this.handleError(e, node2.proxyOf);
      }
      if (node2.type !== "root" && node2.type !== "document" && !node2.parent) {
        return true;
      }
      if (isPromise(promise)) {
        throw this.getAsyncError();
      }
    }
  }
  runOnRoot(plugin2) {
    this.result.lastPlugin = plugin2;
    try {
      if (typeof plugin2 === "object" && plugin2.Once) {
        if (this.result.root.type === "document") {
          let roots = this.result.root.nodes.map(
            (root3) => plugin2.Once(root3, this.helpers)
          );
          if (isPromise(roots[0])) {
            return Promise.all(roots);
          }
          return roots;
        }
        return plugin2.Once(this.result.root, this.helpers);
      } else if (typeof plugin2 === "function") {
        return plugin2(this.result.root, this.result);
      }
    } catch (error2) {
      throw this.handleError(error2);
    }
  }
  getAsyncError() {
    throw new Error("Use process(css).then(cb) to work with async plugins");
  }
  handleError(error2, node2) {
    let plugin2 = this.result.lastPlugin;
    try {
      if (node2)
        node2.addToError(error2);
      this.error = error2;
      if (error2.name === "CssSyntaxError" && !error2.plugin) {
        error2.plugin = plugin2.postcssPlugin;
        error2.setMessage();
      } else if (plugin2.postcssVersion) {
        if (browser$1.env.NODE_ENV !== "production") {
          let pluginName = plugin2.postcssPlugin;
          let pluginVer = plugin2.postcssVersion;
          let runtimeVer = this.result.processor.version;
          let a = pluginVer.split(".");
          let b = runtimeVer.split(".");
          if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) {
            console.error(
              "Unknown error from PostCSS plugin. Your current PostCSS version is " + runtimeVer + ", but " + pluginName + " uses " + pluginVer + ". Perhaps this is the source of the error below."
            );
          }
        }
      }
    } catch (err) {
      if (console && console.error)
        console.error(err);
    }
    return error2;
  }
  async runAsync() {
    this.plugin = 0;
    for (let i = 0; i < this.plugins.length; i++) {
      let plugin2 = this.plugins[i];
      let promise = this.runOnRoot(plugin2);
      if (isPromise(promise)) {
        try {
          await promise;
        } catch (error2) {
          throw this.handleError(error2);
        }
      }
    }
    this.prepareVisitors();
    if (this.hasListener) {
      let root3 = this.result.root;
      while (!root3[isClean]) {
        root3[isClean] = true;
        let stack = [toStack(root3)];
        while (stack.length > 0) {
          let promise = this.visitTick(stack);
          if (isPromise(promise)) {
            try {
              await promise;
            } catch (e) {
              let node2 = stack[stack.length - 1].node;
              throw this.handleError(e, node2);
            }
          }
        }
      }
      if (this.listeners.OnceExit) {
        for (let [plugin2, visitor] of this.listeners.OnceExit) {
          this.result.lastPlugin = plugin2;
          try {
            if (root3.type === "document") {
              let roots = root3.nodes.map(
                (subRoot) => visitor(subRoot, this.helpers)
              );
              await Promise.all(roots);
            } else {
              await visitor(root3, this.helpers);
            }
          } catch (e) {
            throw this.handleError(e);
          }
        }
      }
    }
    this.processed = true;
    return this.stringify();
  }
  prepareVisitors() {
    this.listeners = {};
    let add2 = (plugin2, type, cb) => {
      if (!this.listeners[type])
        this.listeners[type] = [];
      this.listeners[type].push([plugin2, cb]);
    };
    for (let plugin2 of this.plugins) {
      if (typeof plugin2 === "object") {
        for (let event in plugin2) {
          if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) {
            throw new Error(
              `Unknown event ${event} in ${plugin2.postcssPlugin}. Try to update PostCSS (${this.processor.version} now).`
            );
          }
          if (!NOT_VISITORS[event]) {
            if (typeof plugin2[event] === "object") {
              for (let filter2 in plugin2[event]) {
                if (filter2 === "*") {
                  add2(plugin2, event, plugin2[event][filter2]);
                } else {
                  add2(
                    plugin2,
                    event + "-" + filter2.toLowerCase(),
                    plugin2[event][filter2]
                  );
                }
              }
            } else if (typeof plugin2[event] === "function") {
              add2(plugin2, event, plugin2[event]);
            }
          }
        }
      }
    }
    this.hasListener = Object.keys(this.listeners).length > 0;
  }
  visitTick(stack) {
    let visit = stack[stack.length - 1];
    let { node: node2, visitors } = visit;
    if (node2.type !== "root" && node2.type !== "document" && !node2.parent) {
      stack.pop();
      return;
    }
    if (visitors.length > 0 && visit.visitorIndex < visitors.length) {
      let [plugin2, visitor] = visitors[visit.visitorIndex];
      visit.visitorIndex += 1;
      if (visit.visitorIndex === visitors.length) {
        visit.visitors = [];
        visit.visitorIndex = 0;
      }
      this.result.lastPlugin = plugin2;
      try {
        return visitor(node2.toProxy(), this.helpers);
      } catch (e) {
        throw this.handleError(e, node2);
      }
    }
    if (visit.iterator !== 0) {
      let iterator2 = visit.iterator;
      let child;
      while (child = node2.nodes[node2.indexes[iterator2]]) {
        node2.indexes[iterator2] += 1;
        if (!child[isClean]) {
          child[isClean] = true;
          stack.push(toStack(child));
          return;
        }
      }
      visit.iterator = 0;
      delete node2.indexes[iterator2];
    }
    let events = visit.events;
    while (visit.eventIndex < events.length) {
      let event = events[visit.eventIndex];
      visit.eventIndex += 1;
      if (event === CHILDREN) {
        if (node2.nodes && node2.nodes.length) {
          node2[isClean] = true;
          visit.iterator = node2.getIterator();
        }
        return;
      } else if (this.listeners[event]) {
        visit.visitors = this.listeners[event];
        return;
      }
    }
    stack.pop();
  }
};
LazyResult$2.registerPostcss = (dependant) => {
  postcss$2 = dependant;
};
var lazyResult = LazyResult$2;
LazyResult$2.default = LazyResult$2;
Root$3.registerLazyResult(LazyResult$2);
Document$2.registerLazyResult(LazyResult$2);
let MapGenerator2 = mapGenerator;
let stringify$1 = stringify_1;
let warnOnce$1 = warnOnce$3;
let parse$1 = parse_1;
const Result$1 = result;
let NoWorkResult$1 = class NoWorkResult {
  constructor(processor2, css, opts) {
    css = css.toString();
    this.stringified = false;
    this._processor = processor2;
    this._css = css;
    this._opts = opts;
    this._map = void 0;
    let root3;
    let str2 = stringify$1;
    this.result = new Result$1(this._processor, root3, this._opts);
    this.result.css = css;
    let self2 = this;
    Object.defineProperty(this.result, "root", {
      get() {
        return self2.root;
      }
    });
    let map2 = new MapGenerator2(str2, root3, this._opts, css);
    if (map2.isMap()) {
      let [generatedCSS, generatedMap] = map2.generate();
      if (generatedCSS) {
        this.result.css = generatedCSS;
      }
      if (generatedMap) {
        this.result.map = generatedMap;
      }
    }
  }
  get [Symbol.toStringTag]() {
    return "NoWorkResult";
  }
  get processor() {
    return this.result.processor;
  }
  get opts() {
    return this.result.opts;
  }
  get css() {
    return this.result.css;
  }
  get content() {
    return this.result.css;
  }
  get map() {
    return this.result.map;
  }
  get root() {
    if (this._root) {
      return this._root;
    }
    let root3;
    let parser2 = parse$1;
    try {
      root3 = parser2(this._css, this._opts);
    } catch (error2) {
      this.error = error2;
    }
    if (this.error) {
      throw this.error;
    } else {
      this._root = root3;
      return root3;
    }
  }
  get messages() {
    return [];
  }
  warnings() {
    return [];
  }
  toString() {
    return this._css;
  }
  then(onFulfilled, onRejected) {
    if (browser$1.env.NODE_ENV !== "production") {
      if (!("from" in this._opts)) {
        warnOnce$1(
          "Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning."
        );
      }
    }
    return this.async().then(onFulfilled, onRejected);
  }
  catch(onRejected) {
    return this.async().catch(onRejected);
  }
  finally(onFinally) {
    return this.async().then(onFinally, onFinally);
  }
  async() {
    if (this.error)
      return Promise.reject(this.error);
    return Promise.resolve(this.result);
  }
  sync() {
    if (this.error)
      throw this.error;
    return this.result;
  }
};
var noWorkResult = NoWorkResult$1;
NoWorkResult$1.default = NoWorkResult$1;
let NoWorkResult2 = noWorkResult;
let LazyResult$1 = lazyResult;
let Document$1 = document$1;
let Root$2 = root$2;
let Processor$1 = class Processor {
  constructor(plugins = []) {
    this.version = "8.4.21";
    this.plugins = this.normalize(plugins);
  }
  use(plugin2) {
    this.plugins = this.plugins.concat(this.normalize([plugin2]));
    return this;
  }
  process(css, opts = {}) {
    if (this.plugins.length === 0 && typeof opts.parser === "undefined" && typeof opts.stringifier === "undefined" && typeof opts.syntax === "undefined") {
      return new NoWorkResult2(this, css, opts);
    } else {
      return new LazyResult$1(this, css, opts);
    }
  }
  normalize(plugins) {
    let normalized = [];
    for (let i of plugins) {
      if (i.postcss === true) {
        i = i();
      } else if (i.postcss) {
        i = i.postcss;
      }
      if (typeof i === "object" && Array.isArray(i.plugins)) {
        normalized = normalized.concat(i.plugins);
      } else if (typeof i === "object" && i.postcssPlugin) {
        normalized.push(i);
      } else if (typeof i === "function") {
        normalized.push(i);
      } else if (typeof i === "object" && (i.parse || i.stringify)) {
        if (browser$1.env.NODE_ENV !== "production") {
          throw new Error(
            "PostCSS syntaxes cannot be used as plugins. Instead, please use one of the syntax/parser/stringifier options as outlined in your PostCSS runner documentation."
          );
        }
      } else {
        throw new Error(i + " is not a PostCSS plugin");
      }
    }
    return normalized;
  }
};
var processor$1 = Processor$1;
Processor$1.default = Processor$1;
Root$2.registerProcessor(Processor$1);
Document$1.registerProcessor(Processor$1);
let Declaration$1 = declaration;
let PreviousMap2 = previousMap;
let Comment$1 = comment$3;
let AtRule$1 = atRule;
let Input$1 = input;
let Root$1 = root$2;
let Rule$1 = rule;
function fromJSON$1(json, inputs) {
  if (Array.isArray(json))
    return json.map((n2) => fromJSON$1(n2));
  let { inputs: ownInputs, ...defaults } = json;
  if (ownInputs) {
    inputs = [];
    for (let input2 of ownInputs) {
      let inputHydrated = { ...input2, __proto__: Input$1.prototype };
      if (inputHydrated.map) {
        inputHydrated.map = {
          ...inputHydrated.map,
          __proto__: PreviousMap2.prototype
        };
      }
      inputs.push(inputHydrated);
    }
  }
  if (defaults.nodes) {
    defaults.nodes = json.nodes.map((n2) => fromJSON$1(n2, inputs));
  }
  if (defaults.source) {
    let { inputId, ...source } = defaults.source;
    defaults.source = source;
    if (inputId != null) {
      defaults.source.input = inputs[inputId];
    }
  }
  if (defaults.type === "root") {
    return new Root$1(defaults);
  } else if (defaults.type === "decl") {
    return new Declaration$1(defaults);
  } else if (defaults.type === "rule") {
    return new Rule$1(defaults);
  } else if (defaults.type === "comment") {
    return new Comment$1(defaults);
  } else if (defaults.type === "atrule") {
    return new AtRule$1(defaults);
  } else {
    throw new Error("Unknown node type: " + json.type);
  }
}
var fromJSON_1 = fromJSON$1;
fromJSON$1.default = fromJSON$1;
let CssSyntaxError2 = cssSyntaxError;
let Declaration2 = declaration;
let LazyResult2 = lazyResult;
let Container2 = container$1;
let Processor2 = processor$1;
let stringify = stringify_1;
let fromJSON = fromJSON_1;
let Document2 = document$1;
let Warning2 = warning;
let Comment2 = comment$3;
let AtRule2 = atRule;
let Result2 = result;
let Input2 = input;
let parse = parse_1;
let list = list_1;
let Rule3 = rule;
let Root2 = root$2;
let Node$6 = node$2;
function postcss(...plugins) {
  if (plugins.length === 1 && Array.isArray(plugins[0])) {
    plugins = plugins[0];
  }
  return new Processor2(plugins);
}
postcss.plugin = function plugin(name, initializer) {
  let warningPrinted = false;
  function creator(...args) {
    if (console && console.warn && !warningPrinted) {
      warningPrinted = true;
      console.warn(
        name + ": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration"
      );
      if (browser$1.env.LANG && browser$1.env.LANG.startsWith("cn")) {
        console.warn(
          name + ": 里面 postcss.plugin 被弃用. 迁移指南:\nhttps://www.w3ctech.com/topic/2226"
        );
      }
    }
    let transformer = initializer(...args);
    transformer.postcssPlugin = name;
    transformer.postcssVersion = new Processor2().version;
    return transformer;
  }
  let cache2;
  Object.defineProperty(creator, "postcss", {
    get() {
      if (!cache2)
        cache2 = creator();
      return cache2;
    }
  });
  creator.process = function(css, processOpts, pluginOpts) {
    return postcss([creator(pluginOpts)]).process(css, processOpts);
  };
  return creator;
};
postcss.stringify = stringify;
postcss.parse = parse;
postcss.fromJSON = fromJSON;
postcss.list = list;
postcss.comment = (defaults) => new Comment2(defaults);
postcss.atRule = (defaults) => new AtRule2(defaults);
postcss.decl = (defaults) => new Declaration2(defaults);
postcss.rule = (defaults) => new Rule3(defaults);
postcss.root = (defaults) => new Root2(defaults);
postcss.document = (defaults) => new Document2(defaults);
postcss.CssSyntaxError = CssSyntaxError2;
postcss.Declaration = Declaration2;
postcss.Container = Container2;
postcss.Processor = Processor2;
postcss.Document = Document2;
postcss.Comment = Comment2;
postcss.Warning = Warning2;
postcss.AtRule = AtRule2;
postcss.Result = Result2;
postcss.Input = Input2;
postcss.Rule = Rule3;
postcss.Root = Root2;
postcss.Node = Node$6;
LazyResult2.registerPostcss(postcss);
var postcss_1 = postcss;
postcss.default = postcss;
var postcss$1 = postcss_1;
postcss$1.stringify;
postcss$1.fromJSON;
postcss$1.plugin;
postcss$1.parse;
postcss$1.list;
postcss$1.document;
postcss$1.comment;
postcss$1.atRule;
postcss$1.rule;
postcss$1.decl;
postcss$1.root;
postcss$1.CssSyntaxError;
postcss$1.Declaration;
postcss$1.Container;
postcss$1.Processor;
postcss$1.Document;
postcss$1.Comment;
postcss$1.Warning;
postcss$1.AtRule;
postcss$1.Result;
postcss$1.Input;
postcss$1.Rule;
postcss$1.Root;
postcss$1.Node;
var distExports = {};
var dist = {
  get exports() {
    return distExports;
  },
  set exports(v) {
    distExports = v;
  }
};
var processorExports = {};
var processor = {
  get exports() {
    return processorExports;
  },
  set exports(v) {
    processorExports = v;
  }
};
var parserExports = {};
var parser = {
  get exports() {
    return parserExports;
  },
  set exports(v) {
    parserExports = v;
  }
};
var rootExports = {};
var root$1 = {
  get exports() {
    return rootExports;
  },
  set exports(v) {
    rootExports = v;
  }
};
var containerExports = {};
var container = {
  get exports() {
    return containerExports;
  },
  set exports(v) {
    containerExports = v;
  }
};
var nodeExports = {};
var node$1 = {
  get exports() {
    return nodeExports;
  },
  set exports(v) {
    nodeExports = v;
  }
};
var util$6 = {};
var unescExports = {};
var unesc = {
  get exports() {
    return unescExports;
  },
  set exports(v) {
    unescExports = v;
  }
};
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2["default"] = unesc2;
  function gobbleHex(str2) {
    var lower = str2.toLowerCase();
    var hex = "";
    var spaceTerminated = false;
    for (var i = 0; i < 6 && lower[i] !== void 0; i++) {
      var code = lower.charCodeAt(i);
      var valid = code >= 97 && code <= 102 || code >= 48 && code <= 57;
      spaceTerminated = code === 32;
      if (!valid) {
        break;
      }
      hex += lower[i];
    }
    if (hex.length === 0) {
      return void 0;
    }
    var codePoint = parseInt(hex, 16);
    var isSurrogate = codePoint >= 55296 && codePoint <= 57343;
    if (isSurrogate || codePoint === 0 || codePoint > 1114111) {
      return ["�", hex.length + (spaceTerminated ? 1 : 0)];
    }
    return [String.fromCodePoint(codePoint), hex.length + (spaceTerminated ? 1 : 0)];
  }
  var CONTAINS_ESCAPE = /\\/;
  function unesc2(str2) {
    var needToProcess = CONTAINS_ESCAPE.test(str2);
    if (!needToProcess) {
      return str2;
    }
    var ret = "";
    for (var i = 0; i < str2.length; i++) {
      if (str2[i] === "\\") {
        var gobbled = gobbleHex(str2.slice(i + 1, i + 7));
        if (gobbled !== void 0) {
          ret += gobbled[0];
          i += gobbled[1];
          continue;
        }
        if (str2[i + 1] === "\\") {
          ret += "\\";
          i++;
          continue;
        }
        if (str2.length === i + 1) {
          ret += str2[i];
        }
        continue;
      }
      ret += str2[i];
    }
    return ret;
  }
  module2.exports = exports2.default;
})(unesc, unescExports);
var getPropExports = {};
var getProp = {
  get exports() {
    return getPropExports;
  },
  set exports(v) {
    getPropExports = v;
  }
};
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2["default"] = getProp2;
  function getProp2(obj) {
    for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
      props[_key - 1] = arguments[_key];
    }
    while (props.length > 0) {
      var prop = props.shift();
      if (!obj[prop]) {
        return void 0;
      }
      obj = obj[prop];
    }
    return obj;
  }
  module2.exports = exports2.default;
})(getProp, getPropExports);
var ensureObjectExports = {};
var ensureObject = {
  get exports() {
    return ensureObjectExports;
  },
  set exports(v) {
    ensureObjectExports = v;
  }
};
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2["default"] = ensureObject2;
  function ensureObject2(obj) {
    for (var _len = arguments.length, props = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
      props[_key - 1] = arguments[_key];
    }
    while (props.length > 0) {
      var prop = props.shift();
      if (!obj[prop]) {
        obj[prop] = {};
      }
      obj = obj[prop];
    }
  }
  module2.exports = exports2.default;
})(ensureObject, ensureObjectExports);
var stripCommentsExports = {};
var stripComments = {
  get exports() {
    return stripCommentsExports;
  },
  set exports(v) {
    stripCommentsExports = v;
  }
};
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2["default"] = stripComments2;
  function stripComments2(str2) {
    var s = "";
    var commentStart = str2.indexOf("/*");
    var lastEnd = 0;
    while (commentStart >= 0) {
      s = s + str2.slice(lastEnd, commentStart);
      var commentEnd = str2.indexOf("*/", commentStart + 2);
      if (commentEnd < 0) {
        return s;
      }
      lastEnd = commentEnd + 2;
      commentStart = str2.indexOf("/*", lastEnd);
    }
    s = s + str2.slice(lastEnd);
    return s;
  }
  module2.exports = exports2.default;
})(stripComments, stripCommentsExports);
util$6.__esModule = true;
util$6.stripComments = util$6.ensureObject = util$6.getProp = util$6.unesc = void 0;
var _unesc = _interopRequireDefault$1(unescExports);
util$6.unesc = _unesc["default"];
var _getProp = _interopRequireDefault$1(getPropExports);
util$6.getProp = _getProp["default"];
var _ensureObject = _interopRequireDefault$1(ensureObjectExports);
util$6.ensureObject = _ensureObject["default"];
var _stripComments = _interopRequireDefault$1(stripCommentsExports);
util$6.stripComments = _stripComments["default"];
function _interopRequireDefault$1(obj) {
  return obj && obj.__esModule ? obj : { "default": obj };
}
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2["default"] = void 0;
  var _util2 = util$6;
  function _defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor)
        descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }
  function _createClass(Constructor, protoProps, staticProps) {
    if (protoProps)
      _defineProperties(Constructor.prototype, protoProps);
    if (staticProps)
      _defineProperties(Constructor, staticProps);
    return Constructor;
  }
  var cloneNode2 = function cloneNode3(obj, parent) {
    if (typeof obj !== "object" || obj === null) {
      return obj;
    }
    var cloned = new obj.constructor();
    for (var i in obj) {
      if (!obj.hasOwnProperty(i)) {
        continue;
      }
      var value = obj[i];
      var type = typeof value;
      if (i === "parent" && type === "object") {
        if (parent) {
          cloned[i] = parent;
        }
      } else if (value instanceof Array) {
        cloned[i] = value.map(function(j) {
          return cloneNode3(j, cloned);
        });
      } else {
        cloned[i] = cloneNode3(value, cloned);
      }
    }
    return cloned;
  };
  var Node6 = /* @__PURE__ */ function() {
    function Node7(opts) {
      if (opts === void 0) {
        opts = {};
      }
      Object.assign(this, opts);
      this.spaces = this.spaces || {};
      this.spaces.before = this.spaces.before || "";
      this.spaces.after = this.spaces.after || "";
    }
    var _proto = Node7.prototype;
    _proto.remove = function remove2() {
      if (this.parent) {
        this.parent.removeChild(this);
      }
      this.parent = void 0;
      return this;
    };
    _proto.replaceWith = function replaceWith() {
      if (this.parent) {
        for (var index in arguments) {
          this.parent.insertBefore(this, arguments[index]);
        }
        this.remove();
      }
      return this;
    };
    _proto.next = function next() {
      return this.parent.at(this.parent.index(this) + 1);
    };
    _proto.prev = function prev() {
      return this.parent.at(this.parent.index(this) - 1);
    };
    _proto.clone = function clone2(overrides) {
      if (overrides === void 0) {
        overrides = {};
      }
      var cloned = cloneNode2(this);
      for (var name in overrides) {
        cloned[name] = overrides[name];
      }
      return cloned;
    };
    _proto.appendToPropertyAndEscape = function appendToPropertyAndEscape(name, value, valueEscaped) {
      if (!this.raws) {
        this.raws = {};
      }
      var originalValue = this[name];
      var originalEscaped = this.raws[name];
      this[name] = originalValue + value;
      if (originalEscaped || valueEscaped !== value) {
        this.raws[name] = (originalEscaped || originalValue) + valueEscaped;
      } else {
        delete this.raws[name];
      }
    };
    _proto.setPropertyAndEscape = function setPropertyAndEscape(name, value, valueEscaped) {
      if (!this.raws) {
        this.raws = {};
      }
      this[name] = value;
      this.raws[name] = valueEscaped;
    };
    _proto.setPropertyWithoutEscape = function setPropertyWithoutEscape(name, value) {
      this[name] = value;
      if (this.raws) {
        delete this.raws[name];
      }
    };
    _proto.isAtPosition = function isAtPosition(line, column) {
      if (this.source && this.source.start && this.source.end) {
        if (this.source.start.line > line) {
          return false;
        }
        if (this.source.end.line < line) {
          return false;
        }
        if (this.source.start.line === line && this.source.start.column > column) {
          return false;
        }
        if (this.source.end.line === line && this.source.end.column < column) {
          return false;
        }
        return true;
      }
      return void 0;
    };
    _proto.stringifyProperty = function stringifyProperty(name) {
      return this.raws && this.raws[name] || this[name];
    };
    _proto.valueToString = function valueToString() {
      return String(this.stringifyProperty("value"));
    };
    _proto.toString = function toString3() {
      return [this.rawSpaceBefore, this.valueToString(), this.rawSpaceAfter].join("");
    };
    _createClass(Node7, [{
      key: "rawSpaceBefore",
      get: function get2() {
        var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.before;
        if (rawSpace === void 0) {
          rawSpace = this.spaces && this.spaces.before;
        }
        return rawSpace || "";
      },
      set: function set2(raw) {
        (0, _util2.ensureObject)(this, "raws", "spaces");
        this.raws.spaces.before = raw;
      }
    }, {
      key: "rawSpaceAfter",
      get: function get2() {
        var rawSpace = this.raws && this.raws.spaces && this.raws.spaces.after;
        if (rawSpace === void 0) {
          rawSpace = this.spaces.after;
        }
        return rawSpace || "";
      },
      set: function set2(raw) {
        (0, _util2.ensureObject)(this, "raws", "spaces");
        this.raws.spaces.after = raw;
      }
    }]);
    return Node7;
  }();
  exports2["default"] = Node6;
  module2.exports = exports2.default;
})(node$1, nodeExports);
var types = {};
types.__esModule = true;
types.UNIVERSAL = types.ATTRIBUTE = types.CLASS = types.COMBINATOR = types.COMMENT = types.ID = types.NESTING = types.PSEUDO = types.ROOT = types.SELECTOR = types.STRING = types.TAG = void 0;
var TAG = "tag";
types.TAG = TAG;
var STRING = "string";
types.STRING = STRING;
var SELECTOR = "selector";
types.SELECTOR = SELECTOR;
var ROOT = "root";
types.ROOT = ROOT;
var PSEUDO = "pseudo";
types.PSEUDO = PSEUDO;
var NESTING = "nesting";
types.NESTING = NESTING;
var ID = "id";
types.ID = ID;
var COMMENT = "comment";
types.COMMENT = COMMENT;
var COMBINATOR = "combinator";
types.COMBINATOR = COMBINATOR;
var CLASS = "class";
types.CLASS = CLASS;
var ATTRIBUTE = "attribute";
types.ATTRIBUTE = ATTRIBUTE;
var UNIVERSAL = "universal";
types.UNIVERSAL = UNIVERSAL;
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2["default"] = void 0;
  var _node = _interopRequireDefault2(nodeExports);
  var types$12 = _interopRequireWildcard(types);
  function _getRequireWildcardCache() {
    if (typeof WeakMap !== "function")
      return null;
    var cache2 = /* @__PURE__ */ new WeakMap();
    _getRequireWildcardCache = function _getRequireWildcardCache2() {
      return cache2;
    };
    return cache2;
  }
  function _interopRequireWildcard(obj) {
    if (obj && obj.__esModule) {
      return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
      return { "default": obj };
    }
    var cache2 = _getRequireWildcardCache();
    if (cache2 && cache2.has(obj)) {
      return cache2.get(obj);
    }
    var newObj = {};
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for (var key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
        if (desc && (desc.get || desc.set)) {
          Object.defineProperty(newObj, key, desc);
        } else {
          newObj[key] = obj[key];
        }
      }
    }
    newObj["default"] = obj;
    if (cache2) {
      cache2.set(obj, newObj);
    }
    return newObj;
  }
  function _interopRequireDefault2(obj) {
    return obj && obj.__esModule ? obj : { "default": obj };
  }
  function _createForOfIteratorHelperLoose(o, allowArrayLike) {
    var it;
    if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
      if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
        if (it)
          o = it;
        var i = 0;
        return function() {
          if (i >= o.length)
            return { done: true };
          return { done: false, value: o[i++] };
        };
      }
      throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
    }
    it = o[Symbol.iterator]();
    return it.next.bind(it);
  }
  function _unsupportedIterableToArray(o, minLen) {
    if (!o)
      return;
    if (typeof o === "string")
      return _arrayLikeToArray(o, minLen);
    var n2 = Object.prototype.toString.call(o).slice(8, -1);
    if (n2 === "Object" && o.constructor)
      n2 = o.constructor.name;
    if (n2 === "Map" || n2 === "Set")
      return Array.from(o);
    if (n2 === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n2))
      return _arrayLikeToArray(o, minLen);
  }
  function _arrayLikeToArray(arr, len) {
    if (len == null || len > arr.length)
      len = arr.length;
    for (var i = 0, arr2 = new Array(len); i < len; i++) {
      arr2[i] = arr[i];
    }
    return arr2;
  }
  function _defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor)
        descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }
  function _createClass(Constructor, protoProps, staticProps) {
    if (protoProps)
      _defineProperties(Constructor.prototype, protoProps);
    if (staticProps)
      _defineProperties(Constructor, staticProps);
    return Constructor;
  }
  function _inheritsLoose(subClass, superClass) {
    subClass.prototype = Object.create(superClass.prototype);
    subClass.prototype.constructor = subClass;
    _setPrototypeOf(subClass, superClass);
  }
  function _setPrototypeOf(o, p2) {
    _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p3) {
      o2.__proto__ = p3;
      return o2;
    };
    return _setPrototypeOf(o, p2);
  }
  var Container3 = /* @__PURE__ */ function(_Node) {
    _inheritsLoose(Container4, _Node);
    function Container4(opts) {
      var _this;
      _this = _Node.call(this, opts) || this;
      if (!_this.nodes) {
        _this.nodes = [];
      }
      return _this;
    }
    var _proto = Container4.prototype;
    _proto.append = function append2(selector3) {
      selector3.parent = this;
      this.nodes.push(selector3);
      return this;
    };
    _proto.prepend = function prepend2(selector3) {
      selector3.parent = this;
      this.nodes.unshift(selector3);
      return this;
    };
    _proto.at = function at2(index) {
      return this.nodes[index];
    };
    _proto.index = function index(child) {
      if (typeof child === "number") {
        return child;
      }
      return this.nodes.indexOf(child);
    };
    _proto.removeChild = function removeChild(child) {
      child = this.index(child);
      this.at(child).parent = void 0;
      this.nodes.splice(child, 1);
      var index;
      for (var id3 in this.indexes) {
        index = this.indexes[id3];
        if (index >= child) {
          this.indexes[id3] = index - 1;
        }
      }
      return this;
    };
    _proto.removeAll = function removeAll() {
      for (var _iterator = _createForOfIteratorHelperLoose(this.nodes), _step; !(_step = _iterator()).done; ) {
        var node2 = _step.value;
        node2.parent = void 0;
      }
      this.nodes = [];
      return this;
    };
    _proto.empty = function empty2() {
      return this.removeAll();
    };
    _proto.insertAfter = function insertAfter(oldNode, newNode) {
      newNode.parent = this;
      var oldIndex = this.index(oldNode);
      this.nodes.splice(oldIndex + 1, 0, newNode);
      newNode.parent = this;
      var index;
      for (var id3 in this.indexes) {
        index = this.indexes[id3];
        if (oldIndex <= index) {
          this.indexes[id3] = index + 1;
        }
      }
      return this;
    };
    _proto.insertBefore = function insertBefore(oldNode, newNode) {
      newNode.parent = this;
      var oldIndex = this.index(oldNode);
      this.nodes.splice(oldIndex, 0, newNode);
      newNode.parent = this;
      var index;
      for (var id3 in this.indexes) {
        index = this.indexes[id3];
        if (index <= oldIndex) {
          this.indexes[id3] = index + 1;
        }
      }
      return this;
    };
    _proto._findChildAtPosition = function _findChildAtPosition(line, col) {
      var found = void 0;
      this.each(function(node2) {
        if (node2.atPosition) {
          var foundChild = node2.atPosition(line, col);
          if (foundChild) {
            found = foundChild;
            return false;
          }
        } else if (node2.isAtPosition(line, col)) {
          found = node2;
          return false;
        }
      });
      return found;
    };
    _proto.atPosition = function atPosition(line, col) {
      if (this.isAtPosition(line, col)) {
        return this._findChildAtPosition(line, col) || this;
      } else {
        return void 0;
      }
    };
    _proto._inferEndPosition = function _inferEndPosition() {
      if (this.last && this.last.source && this.last.source.end) {
        this.source = this.source || {};
        this.source.end = this.source.end || {};
        Object.assign(this.source.end, this.last.source.end);
      }
    };
    _proto.each = function each(callback) {
      if (!this.lastEach) {
        this.lastEach = 0;
      }
      if (!this.indexes) {
        this.indexes = {};
      }
      this.lastEach++;
      var id3 = this.lastEach;
      this.indexes[id3] = 0;
      if (!this.length) {
        return void 0;
      }
      var index, result2;
      while (this.indexes[id3] < this.length) {
        index = this.indexes[id3];
        result2 = callback(this.at(index), index);
        if (result2 === false) {
          break;
        }
        this.indexes[id3] += 1;
      }
      delete this.indexes[id3];
      if (result2 === false) {
        return false;
      }
    };
    _proto.walk = function walk2(callback) {
      return this.each(function(node2, i) {
        var result2 = callback(node2, i);
        if (result2 !== false && node2.length) {
          result2 = node2.walk(callback);
        }
        if (result2 === false) {
          return false;
        }
      });
    };
    _proto.walkAttributes = function walkAttributes(callback) {
      var _this2 = this;
      return this.walk(function(selector3) {
        if (selector3.type === types$12.ATTRIBUTE) {
          return callback.call(_this2, selector3);
        }
      });
    };
    _proto.walkClasses = function walkClasses(callback) {
      var _this3 = this;
      return this.walk(function(selector3) {
        if (selector3.type === types$12.CLASS) {
          return callback.call(_this3, selector3);
        }
      });
    };
    _proto.walkCombinators = function walkCombinators(callback) {
      var _this4 = this;
      return this.walk(function(selector3) {
        if (selector3.type === types$12.COMBINATOR) {
          return callback.call(_this4, selector3);
        }
      });
    };
    _proto.walkComments = function walkComments(callback) {
      var _this5 = this;
      return this.walk(function(selector3) {
        if (selector3.type === types$12.COMMENT) {
          return callback.call(_this5, selector3);
        }
      });
    };
    _proto.walkIds = function walkIds(callback) {
      var _this6 = this;
      return this.walk(function(selector3) {
        if (selector3.type === types$12.ID) {
          return callback.call(_this6, selector3);
        }
      });
    };
    _proto.walkNesting = function walkNesting(callback) {
      var _this7 = this;
      return this.walk(function(selector3) {
        if (selector3.type === types$12.NESTING) {
          return callback.call(_this7, selector3);
        }
      });
    };
    _proto.walkPseudos = function walkPseudos(callback) {
      var _this8 = this;
      return this.walk(function(selector3) {
        if (selector3.type === types$12.PSEUDO) {
          return callback.call(_this8, selector3);
        }
      });
    };
    _proto.walkTags = function walkTags(callback) {
      var _this9 = this;
      return this.walk(function(selector3) {
        if (selector3.type === types$12.TAG) {
          return callback.call(_this9, selector3);
        }
      });
    };
    _proto.walkUniversals = function walkUniversals(callback) {
      var _this10 = this;
      return this.walk(function(selector3) {
        if (selector3.type === types$12.UNIVERSAL) {
          return callback.call(_this10, selector3);
        }
      });
    };
    _proto.split = function split(callback) {
      var _this11 = this;
      var current = [];
      return this.reduce(function(memo, node2, index) {
        var split2 = callback.call(_this11, node2);
        current.push(node2);
        if (split2) {
          memo.push(current);
          current = [];
        } else if (index === _this11.length - 1) {
          memo.push(current);
        }
        return memo;
      }, []);
    };
    _proto.map = function map2(callback) {
      return this.nodes.map(callback);
    };
    _proto.reduce = function reduce(callback, memo) {
      return this.nodes.reduce(callback, memo);
    };
    _proto.every = function every(callback) {
      return this.nodes.every(callback);
    };
    _proto.some = function some(callback) {
      return this.nodes.some(callback);
    };
    _proto.filter = function filter2(callback) {
      return this.nodes.filter(callback);
    };
    _proto.sort = function sort(callback) {
      return this.nodes.sort(callback);
    };
    _proto.toString = function toString3() {
      return this.map(String).join("");
    };
    _createClass(Container4, [{
      key: "first",
      get: function get2() {
        return this.at(0);
      }
    }, {
      key: "last",
      get: function get2() {
        return this.at(this.length - 1);
      }
    }, {
      key: "length",
      get: function get2() {
        return this.nodes.length;
      }
    }]);
    return Container4;
  }(_node["default"]);
  exports2["default"] = Container3;
  module2.exports = exports2.default;
})(container, containerExports);
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2["default"] = void 0;
  var _container = _interopRequireDefault2(containerExports);
  var _types2 = types;
  function _interopRequireDefault2(obj) {
    return obj && obj.__esModule ? obj : { "default": obj };
  }
  function _defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor)
        descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }
  function _createClass(Constructor, protoProps, staticProps) {
    if (protoProps)
      _defineProperties(Constructor.prototype, protoProps);
    if (staticProps)
      _defineProperties(Constructor, staticProps);
    return Constructor;
  }
  function _inheritsLoose(subClass, superClass) {
    subClass.prototype = Object.create(superClass.prototype);
    subClass.prototype.constructor = subClass;
    _setPrototypeOf(subClass, superClass);
  }
  function _setPrototypeOf(o, p2) {
    _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p3) {
      o2.__proto__ = p3;
      return o2;
    };
    return _setPrototypeOf(o, p2);
  }
  var Root3 = /* @__PURE__ */ function(_Container) {
    _inheritsLoose(Root4, _Container);
    function Root4(opts) {
      var _this;
      _this = _Container.call(this, opts) || this;
      _this.type = _types2.ROOT;
      return _this;
    }
    var _proto = Root4.prototype;
    _proto.toString = function toString3() {
      var str2 = this.reduce(function(memo, selector3) {
        memo.push(String(selector3));
        return memo;
      }, []).join(",");
      return this.trailingComma ? str2 + "," : str2;
    };
    _proto.error = function error2(message, options) {
      if (this._error) {
        return this._error(message, options);
      } else {
        return new Error(message);
      }
    };
    _createClass(Root4, [{
      key: "errorGenerator",
      set: function set2(handler) {
        this._error = handler;
      }
    }]);
    return Root4;
  }(_container["default"]);
  exports2["default"] = Root3;
  module2.exports = exports2.default;
})(root$1, rootExports);
var selectorExports = {};
var selector$1 = {
  get exports() {
    return selectorExports;
  },
  set exports(v) {
    selectorExports = v;
  }
};
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2["default"] = void 0;
  var _container = _interopRequireDefault2(containerExports);
  var _types2 = types;
  function _interopRequireDefault2(obj) {
    return obj && obj.__esModule ? obj : { "default": obj };
  }
  function _inheritsLoose(subClass, superClass) {
    subClass.prototype = Object.create(superClass.prototype);
    subClass.prototype.constructor = subClass;
    _setPrototypeOf(subClass, superClass);
  }
  function _setPrototypeOf(o, p2) {
    _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p3) {
      o2.__proto__ = p3;
      return o2;
    };
    return _setPrototypeOf(o, p2);
  }
  var Selector = /* @__PURE__ */ function(_Container) {
    _inheritsLoose(Selector2, _Container);
    function Selector2(opts) {
      var _this;
      _this = _Container.call(this, opts) || this;
      _this.type = _types2.SELECTOR;
      return _this;
    }
    return Selector2;
  }(_container["default"]);
  exports2["default"] = Selector;
  module2.exports = exports2.default;
})(selector$1, selectorExports);
var classNameExports = {};
var className$1 = {
  get exports() {
    return classNameExports;
  },
  set exports(v) {
    classNameExports = v;
  }
};
/*! https://mths.be/cssesc v3.0.0 by @mathias */
var object = {};
var hasOwnProperty = object.hasOwnProperty;
var merge$2 = function merge(options, defaults) {
  if (!options) {
    return defaults;
  }
  var result2 = {};
  for (var key in defaults) {
    result2[key] = hasOwnProperty.call(options, key) ? options[key] : defaults[key];
  }
  return result2;
};
var regexAnySingleEscape = /[ -,\.\/:-@\[-\^`\{-~]/;
var regexSingleEscape = /[ -,\.\/:-@\[\]\^`\{-~]/;
var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
var cssesc = function cssesc2(string3, options) {
  options = merge$2(options, cssesc2.options);
  if (options.quotes != "single" && options.quotes != "double") {
    options.quotes = "single";
  }
  var quote = options.quotes == "double" ? '"' : "'";
  var isIdentifier2 = options.isIdentifier;
  var firstChar = string3.charAt(0);
  var output = "";
  var counter = 0;
  var length2 = string3.length;
  while (counter < length2) {
    var character = string3.charAt(counter++);
    var codePoint = character.charCodeAt();
    var value = void 0;
    if (codePoint < 32 || codePoint > 126) {
      if (codePoint >= 55296 && codePoint <= 56319 && counter < length2) {
        var extra = string3.charCodeAt(counter++);
        if ((extra & 64512) == 56320) {
          codePoint = ((codePoint & 1023) << 10) + (extra & 1023) + 65536;
        } else {
          counter--;
        }
      }
      value = "\\" + codePoint.toString(16).toUpperCase() + " ";
    } else {
      if (options.escapeEverything) {
        if (regexAnySingleEscape.test(character)) {
          value = "\\" + character;
        } else {
          value = "\\" + codePoint.toString(16).toUpperCase() + " ";
        }
      } else if (/[\t\n\f\r\x0B]/.test(character)) {
        value = "\\" + codePoint.toString(16).toUpperCase() + " ";
      } else if (character == "\\" || !isIdentifier2 && (character == '"' && quote == character || character == "'" && quote == character) || isIdentifier2 && regexSingleEscape.test(character)) {
        value = "\\" + character;
      } else {
        value = character;
      }
    }
    output += value;
  }
  if (isIdentifier2) {
    if (/^-[-\d]/.test(output)) {
      output = "\\-" + output.slice(1);
    } else if (/\d/.test(firstChar)) {
      output = "\\3" + firstChar + " " + output.slice(1);
    }
  }
  output = output.replace(regexExcessiveSpaces, function($0, $1, $2) {
    if ($1 && $1.length % 2) {
      return $0;
    }
    return ($1 || "") + $2;
  });
  if (!isIdentifier2 && options.wrap) {
    return quote + output + quote;
  }
  return output;
};
cssesc.options = {
  "escapeEverything": false,
  "isIdentifier": false,
  "quotes": "single",
  "wrap": false
};
cssesc.version = "3.0.0";
var cssesc_1 = cssesc;
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2["default"] = void 0;
  var _cssesc = _interopRequireDefault2(cssesc_1);
  var _util2 = util$6;
  var _node = _interopRequireDefault2(nodeExports);
  var _types2 = types;
  function _interopRequireDefault2(obj) {
    return obj && obj.__esModule ? obj : { "default": obj };
  }
  function _defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor)
        descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }
  function _createClass(Constructor, protoProps, staticProps) {
    if (protoProps)
      _defineProperties(Constructor.prototype, protoProps);
    if (staticProps)
      _defineProperties(Constructor, staticProps);
    return Constructor;
  }
  function _inheritsLoose(subClass, superClass) {
    subClass.prototype = Object.create(superClass.prototype);
    subClass.prototype.constructor = subClass;
    _setPrototypeOf(subClass, superClass);
  }
  function _setPrototypeOf(o, p2) {
    _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p3) {
      o2.__proto__ = p3;
      return o2;
    };
    return _setPrototypeOf(o, p2);
  }
  var ClassName = /* @__PURE__ */ function(_Node) {
    _inheritsLoose(ClassName2, _Node);
    function ClassName2(opts) {
      var _this;
      _this = _Node.call(this, opts) || this;
      _this.type = _types2.CLASS;
      _this._constructed = true;
      return _this;
    }
    var _proto = ClassName2.prototype;
    _proto.valueToString = function valueToString() {
      return "." + _Node.prototype.valueToString.call(this);
    };
    _createClass(ClassName2, [{
      key: "value",
      get: function get2() {
        return this._value;
      },
      set: function set2(v) {
        if (this._constructed) {
          var escaped = (0, _cssesc["default"])(v, {
            isIdentifier: true
          });
          if (escaped !== v) {
            (0, _util2.ensureObject)(this, "raws");
            this.raws.value = escaped;
          } else if (this.raws) {
            delete this.raws.value;
          }
        }
        this._value = v;
      }
    }]);
    return ClassName2;
  }(_node["default"]);
  exports2["default"] = ClassName;
  module2.exports = exports2.default;
})(className$1, classNameExports);
var commentExports = {};
var comment$2 = {
  get exports() {
    return commentExports;
  },
  set exports(v) {
    commentExports = v;
  }
};
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2["default"] = void 0;
  var _node = _interopRequireDefault2(nodeExports);
  var _types2 = types;
  function _interopRequireDefault2(obj) {
    return obj && obj.__esModule ? obj : { "default": obj };
  }
  function _inheritsLoose(subClass, superClass) {
    subClass.prototype = Object.create(superClass.prototype);
    subClass.prototype.constructor = subClass;
    _setPrototypeOf(subClass, superClass);
  }
  function _setPrototypeOf(o, p2) {
    _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p3) {
      o2.__proto__ = p3;
      return o2;
    };
    return _setPrototypeOf(o, p2);
  }
  var Comment3 = /* @__PURE__ */ function(_Node) {
    _inheritsLoose(Comment4, _Node);
    function Comment4(opts) {
      var _this;
      _this = _Node.call(this, opts) || this;
      _this.type = _types2.COMMENT;
      return _this;
    }
    return Comment4;
  }(_node["default"]);
  exports2["default"] = Comment3;
  module2.exports = exports2.default;
})(comment$2, commentExports);
var idExports = {};
var id$1 = {
  get exports() {
    return idExports;
  },
  set exports(v) {
    idExports = v;
  }
};
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2["default"] = void 0;
  var _node = _interopRequireDefault2(nodeExports);
  var _types2 = types;
  function _interopRequireDefault2(obj) {
    return obj && obj.__esModule ? obj : { "default": obj };
  }
  function _inheritsLoose(subClass, superClass) {
    subClass.prototype = Object.create(superClass.prototype);
    subClass.prototype.constructor = subClass;
    _setPrototypeOf(subClass, superClass);
  }
  function _setPrototypeOf(o, p2) {
    _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p3) {
      o2.__proto__ = p3;
      return o2;
    };
    return _setPrototypeOf(o, p2);
  }
  var ID2 = /* @__PURE__ */ function(_Node) {
    _inheritsLoose(ID3, _Node);
    function ID3(opts) {
      var _this;
      _this = _Node.call(this, opts) || this;
      _this.type = _types2.ID;
      return _this;
    }
    var _proto = ID3.prototype;
    _proto.valueToString = function valueToString() {
      return "#" + _Node.prototype.valueToString.call(this);
    };
    return ID3;
  }(_node["default"]);
  exports2["default"] = ID2;
  module2.exports = exports2.default;
})(id$1, idExports);
var tagExports = {};
var tag$1 = {
  get exports() {
    return tagExports;
  },
  set exports(v) {
    tagExports = v;
  }
};
var namespaceExports = {};
var namespace = {
  get exports() {
    return namespaceExports;
  },
  set exports(v) {
    namespaceExports = v;
  }
};
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2["default"] = void 0;
  var _cssesc = _interopRequireDefault2(cssesc_1);
  var _util2 = util$6;
  var _node = _interopRequireDefault2(nodeExports);
  function _interopRequireDefault2(obj) {
    return obj && obj.__esModule ? obj : { "default": obj };
  }
  function _defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor)
        descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }
  function _createClass(Constructor, protoProps, staticProps) {
    if (protoProps)
      _defineProperties(Constructor.prototype, protoProps);
    if (staticProps)
      _defineProperties(Constructor, staticProps);
    return Constructor;
  }
  function _inheritsLoose(subClass, superClass) {
    subClass.prototype = Object.create(superClass.prototype);
    subClass.prototype.constructor = subClass;
    _setPrototypeOf(subClass, superClass);
  }
  function _setPrototypeOf(o, p2) {
    _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p3) {
      o2.__proto__ = p3;
      return o2;
    };
    return _setPrototypeOf(o, p2);
  }
  var Namespace2 = /* @__PURE__ */ function(_Node) {
    _inheritsLoose(Namespace3, _Node);
    function Namespace3() {
      return _Node.apply(this, arguments) || this;
    }
    var _proto = Namespace3.prototype;
    _proto.qualifiedName = function qualifiedName(value) {
      if (this.namespace) {
        return this.namespaceString + "|" + value;
      } else {
        return value;
      }
    };
    _proto.valueToString = function valueToString() {
      return this.qualifiedName(_Node.prototype.valueToString.call(this));
    };
    _createClass(Namespace3, [{
      key: "namespace",
      get: function get2() {
        return this._namespace;
      },
      set: function set2(namespace2) {
        if (namespace2 === true || namespace2 === "*" || namespace2 === "&") {
          this._namespace = namespace2;
          if (this.raws) {
            delete this.raws.namespace;
          }
          return;
        }
        var escaped = (0, _cssesc["default"])(namespace2, {
          isIdentifier: true
        });
        this._namespace = namespace2;
        if (escaped !== namespace2) {
          (0, _util2.ensureObject)(this, "raws");
          this.raws.namespace = escaped;
        } else if (this.raws) {
          delete this.raws.namespace;
        }
      }
    }, {
      key: "ns",
      get: function get2() {
        return this._namespace;
      },
      set: function set2(namespace2) {
        this.namespace = namespace2;
      }
    }, {
      key: "namespaceString",
      get: function get2() {
        if (this.namespace) {
          var ns = this.stringifyProperty("namespace");
          if (ns === true) {
            return "";
          } else {
            return ns;
          }
        } else {
          return "";
        }
      }
    }]);
    return Namespace3;
  }(_node["default"]);
  exports2["default"] = Namespace2;
  module2.exports = exports2.default;
})(namespace, namespaceExports);
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2["default"] = void 0;
  var _namespace = _interopRequireDefault2(namespaceExports);
  var _types2 = types;
  function _interopRequireDefault2(obj) {
    return obj && obj.__esModule ? obj : { "default": obj };
  }
  function _inheritsLoose(subClass, superClass) {
    subClass.prototype = Object.create(superClass.prototype);
    subClass.prototype.constructor = subClass;
    _setPrototypeOf(subClass, superClass);
  }
  function _setPrototypeOf(o, p2) {
    _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p3) {
      o2.__proto__ = p3;
      return o2;
    };
    return _setPrototypeOf(o, p2);
  }
  var Tag = /* @__PURE__ */ function(_Namespace) {
    _inheritsLoose(Tag2, _Namespace);
    function Tag2(opts) {
      var _this;
      _this = _Namespace.call(this, opts) || this;
      _this.type = _types2.TAG;
      return _this;
    }
    return Tag2;
  }(_namespace["default"]);
  exports2["default"] = Tag;
  module2.exports = exports2.default;
})(tag$1, tagExports);
var stringExports = {};
var string$1 = {
  get exports() {
    return stringExports;
  },
  set exports(v) {
    stringExports = v;
  }
};
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2["default"] = void 0;
  var _node = _interopRequireDefault2(nodeExports);
  var _types2 = types;
  function _interopRequireDefault2(obj) {
    return obj && obj.__esModule ? obj : { "default": obj };
  }
  function _inheritsLoose(subClass, superClass) {
    subClass.prototype = Object.create(superClass.prototype);
    subClass.prototype.constructor = subClass;
    _setPrototypeOf(subClass, superClass);
  }
  function _setPrototypeOf(o, p2) {
    _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p3) {
      o2.__proto__ = p3;
      return o2;
    };
    return _setPrototypeOf(o, p2);
  }
  var String2 = /* @__PURE__ */ function(_Node) {
    _inheritsLoose(String3, _Node);
    function String3(opts) {
      var _this;
      _this = _Node.call(this, opts) || this;
      _this.type = _types2.STRING;
      return _this;
    }
    return String3;
  }(_node["default"]);
  exports2["default"] = String2;
  module2.exports = exports2.default;
})(string$1, stringExports);
var pseudoExports = {};
var pseudo$1 = {
  get exports() {
    return pseudoExports;
  },
  set exports(v) {
    pseudoExports = v;
  }
};
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2["default"] = void 0;
  var _container = _interopRequireDefault2(containerExports);
  var _types2 = types;
  function _interopRequireDefault2(obj) {
    return obj && obj.__esModule ? obj : { "default": obj };
  }
  function _inheritsLoose(subClass, superClass) {
    subClass.prototype = Object.create(superClass.prototype);
    subClass.prototype.constructor = subClass;
    _setPrototypeOf(subClass, superClass);
  }
  function _setPrototypeOf(o, p2) {
    _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p3) {
      o2.__proto__ = p3;
      return o2;
    };
    return _setPrototypeOf(o, p2);
  }
  var Pseudo = /* @__PURE__ */ function(_Container) {
    _inheritsLoose(Pseudo2, _Container);
    function Pseudo2(opts) {
      var _this;
      _this = _Container.call(this, opts) || this;
      _this.type = _types2.PSEUDO;
      return _this;
    }
    var _proto = Pseudo2.prototype;
    _proto.toString = function toString3() {
      var params = this.length ? "(" + this.map(String).join(",") + ")" : "";
      return [this.rawSpaceBefore, this.stringifyProperty("value"), params, this.rawSpaceAfter].join("");
    };
    return Pseudo2;
  }(_container["default"]);
  exports2["default"] = Pseudo;
  module2.exports = exports2.default;
})(pseudo$1, pseudoExports);
var attribute$1 = {};
var node = require$$0$1.deprecate;
(function(exports2) {
  exports2.__esModule = true;
  exports2.unescapeValue = unescapeValue;
  exports2["default"] = void 0;
  var _cssesc = _interopRequireDefault2(cssesc_1);
  var _unesc2 = _interopRequireDefault2(unescExports);
  var _namespace = _interopRequireDefault2(namespaceExports);
  var _types2 = types;
  var _CSSESC_QUOTE_OPTIONS;
  function _interopRequireDefault2(obj) {
    return obj && obj.__esModule ? obj : { "default": obj };
  }
  function _defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor)
        descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }
  function _createClass(Constructor, protoProps, staticProps) {
    if (protoProps)
      _defineProperties(Constructor.prototype, protoProps);
    if (staticProps)
      _defineProperties(Constructor, staticProps);
    return Constructor;
  }
  function _inheritsLoose(subClass, superClass) {
    subClass.prototype = Object.create(superClass.prototype);
    subClass.prototype.constructor = subClass;
    _setPrototypeOf(subClass, superClass);
  }
  function _setPrototypeOf(o, p2) {
    _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p3) {
      o2.__proto__ = p3;
      return o2;
    };
    return _setPrototypeOf(o, p2);
  }
  var deprecate2 = node;
  var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
  var warnOfDeprecatedValueAssignment = deprecate2(function() {
  }, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. Call attribute.setValue() instead.");
  var warnOfDeprecatedQuotedAssignment = deprecate2(function() {
  }, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
  var warnOfDeprecatedConstructor = deprecate2(function() {
  }, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
  function unescapeValue(value) {
    var deprecatedUsage = false;
    var quoteMark = null;
    var unescaped = value;
    var m = unescaped.match(WRAPPED_IN_QUOTES);
    if (m) {
      quoteMark = m[1];
      unescaped = m[2];
    }
    unescaped = (0, _unesc2["default"])(unescaped);
    if (unescaped !== value) {
      deprecatedUsage = true;
    }
    return {
      deprecatedUsage,
      unescaped,
      quoteMark
    };
  }
  function handleDeprecatedContructorOpts(opts) {
    if (opts.quoteMark !== void 0) {
      return opts;
    }
    if (opts.value === void 0) {
      return opts;
    }
    warnOfDeprecatedConstructor();
    var _unescapeValue = unescapeValue(opts.value), quoteMark = _unescapeValue.quoteMark, unescaped = _unescapeValue.unescaped;
    if (!opts.raws) {
      opts.raws = {};
    }
    if (opts.raws.value === void 0) {
      opts.raws.value = opts.value;
    }
    opts.value = unescaped;
    opts.quoteMark = quoteMark;
    return opts;
  }
  var Attribute = /* @__PURE__ */ function(_Namespace) {
    _inheritsLoose(Attribute2, _Namespace);
    function Attribute2(opts) {
      var _this;
      if (opts === void 0) {
        opts = {};
      }
      _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
      _this.type = _types2.ATTRIBUTE;
      _this.raws = _this.raws || {};
      Object.defineProperty(_this.raws, "unquoted", {
        get: deprecate2(function() {
          return _this.value;
        }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
        set: deprecate2(function() {
          return _this.value;
        }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
      });
      _this._constructed = true;
      return _this;
    }
    var _proto = Attribute2.prototype;
    _proto.getQuotedValue = function getQuotedValue(options) {
      if (options === void 0) {
        options = {};
      }
      var quoteMark = this._determineQuoteMark(options);
      var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
      var escaped = (0, _cssesc["default"])(this._value, cssescopts);
      return escaped;
    };
    _proto._determineQuoteMark = function _determineQuoteMark(options) {
      return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
    };
    _proto.setValue = function setValue(value, options) {
      if (options === void 0) {
        options = {};
      }
      this._value = value;
      this._quoteMark = this._determineQuoteMark(options);
      this._syncRawValue();
    };
    _proto.smartQuoteMark = function smartQuoteMark(options) {
      var v = this.value;
      var numSingleQuotes = v.replace(/[^']/g, "").length;
      var numDoubleQuotes = v.replace(/[^"]/g, "").length;
      if (numSingleQuotes + numDoubleQuotes === 0) {
        var escaped = (0, _cssesc["default"])(v, {
          isIdentifier: true
        });
        if (escaped === v) {
          return Attribute2.NO_QUOTE;
        } else {
          var pref = this.preferredQuoteMark(options);
          if (pref === Attribute2.NO_QUOTE) {
            var quote = this.quoteMark || options.quoteMark || Attribute2.DOUBLE_QUOTE;
            var opts = CSSESC_QUOTE_OPTIONS[quote];
            var quoteValue = (0, _cssesc["default"])(v, opts);
            if (quoteValue.length < escaped.length) {
              return quote;
            }
          }
          return pref;
        }
      } else if (numDoubleQuotes === numSingleQuotes) {
        return this.preferredQuoteMark(options);
      } else if (numDoubleQuotes < numSingleQuotes) {
        return Attribute2.DOUBLE_QUOTE;
      } else {
        return Attribute2.SINGLE_QUOTE;
      }
    };
    _proto.preferredQuoteMark = function preferredQuoteMark(options) {
      var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
      if (quoteMark === void 0) {
        quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
      }
      if (quoteMark === void 0) {
        quoteMark = Attribute2.DOUBLE_QUOTE;
      }
      return quoteMark;
    };
    _proto._syncRawValue = function _syncRawValue() {
      var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
      if (rawValue === this._value) {
        if (this.raws) {
          delete this.raws.value;
        }
      } else {
        this.raws.value = rawValue;
      }
    };
    _proto._handleEscapes = function _handleEscapes(prop, value) {
      if (this._constructed) {
        var escaped = (0, _cssesc["default"])(value, {
          isIdentifier: true
        });
        if (escaped !== value) {
          this.raws[prop] = escaped;
        } else {
          delete this.raws[prop];
        }
      }
    };
    _proto._spacesFor = function _spacesFor(name) {
      var attrSpaces = {
        before: "",
        after: ""
      };
      var spaces2 = this.spaces[name] || {};
      var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
      return Object.assign(attrSpaces, spaces2, rawSpaces);
    };
    _proto._stringFor = function _stringFor(name, spaceName, concat3) {
      if (spaceName === void 0) {
        spaceName = name;
      }
      if (concat3 === void 0) {
        concat3 = defaultAttrConcat;
      }
      var attrSpaces = this._spacesFor(spaceName);
      return concat3(this.stringifyProperty(name), attrSpaces);
    };
    _proto.offsetOf = function offsetOf(name) {
      var count = 1;
      var attributeSpaces = this._spacesFor("attribute");
      count += attributeSpaces.before.length;
      if (name === "namespace" || name === "ns") {
        return this.namespace ? count : -1;
      }
      if (name === "attributeNS") {
        return count;
      }
      count += this.namespaceString.length;
      if (this.namespace) {
        count += 1;
      }
      if (name === "attribute") {
        return count;
      }
      count += this.stringifyProperty("attribute").length;
      count += attributeSpaces.after.length;
      var operatorSpaces = this._spacesFor("operator");
      count += operatorSpaces.before.length;
      var operator = this.stringifyProperty("operator");
      if (name === "operator") {
        return operator ? count : -1;
      }
      count += operator.length;
      count += operatorSpaces.after.length;
      var valueSpaces = this._spacesFor("value");
      count += valueSpaces.before.length;
      var value = this.stringifyProperty("value");
      if (name === "value") {
        return value ? count : -1;
      }
      count += value.length;
      count += valueSpaces.after.length;
      var insensitiveSpaces = this._spacesFor("insensitive");
      count += insensitiveSpaces.before.length;
      if (name === "insensitive") {
        return this.insensitive ? count : -1;
      }
      return -1;
    };
    _proto.toString = function toString3() {
      var _this2 = this;
      var selector3 = [this.rawSpaceBefore, "["];
      selector3.push(this._stringFor("qualifiedAttribute", "attribute"));
      if (this.operator && (this.value || this.value === "")) {
        selector3.push(this._stringFor("operator"));
        selector3.push(this._stringFor("value"));
        selector3.push(this._stringFor("insensitiveFlag", "insensitive", function(attrValue, attrSpaces) {
          if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
            attrSpaces.before = " ";
          }
          return defaultAttrConcat(attrValue, attrSpaces);
        }));
      }
      selector3.push("]");
      selector3.push(this.rawSpaceAfter);
      return selector3.join("");
    };
    _createClass(Attribute2, [{
      key: "quoted",
      get: function get2() {
        var qm = this.quoteMark;
        return qm === "'" || qm === '"';
      },
      set: function set2(value) {
        warnOfDeprecatedQuotedAssignment();
      }
      /**
       * returns a single (`'`) or double (`"`) quote character if the value is quoted.
       * returns `null` if the value is not quoted.
       * returns `undefined` if the quotation state is unknown (this can happen when
       * the attribute is constructed without specifying a quote mark.)
       */
    }, {
      key: "quoteMark",
      get: function get2() {
        return this._quoteMark;
      },
      set: function set2(quoteMark) {
        if (!this._constructed) {
          this._quoteMark = quoteMark;
          return;
        }
        if (this._quoteMark !== quoteMark) {
          this._quoteMark = quoteMark;
          this._syncRawValue();
        }
      }
    }, {
      key: "qualifiedAttribute",
      get: function get2() {
        return this.qualifiedName(this.raws.attribute || this.attribute);
      }
    }, {
      key: "insensitiveFlag",
      get: function get2() {
        return this.insensitive ? "i" : "";
      }
    }, {
      key: "value",
      get: function get2() {
        return this._value;
      },
      set: (
        /**
         * Before 3.0, the value had to be set to an escaped value including any wrapped
         * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
         * is unescaped during parsing and any quote marks are removed.
         *
         * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
         * a deprecation warning is raised when the new value contains any characters that would
         * require escaping (including if it contains wrapped quotes).
         *
         * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
         * how the new value is quoted.
         */
        function set2(v) {
          if (this._constructed) {
            var _unescapeValue2 = unescapeValue(v), deprecatedUsage = _unescapeValue2.deprecatedUsage, unescaped = _unescapeValue2.unescaped, quoteMark = _unescapeValue2.quoteMark;
            if (deprecatedUsage) {
              warnOfDeprecatedValueAssignment();
            }
            if (unescaped === this._value && quoteMark === this._quoteMark) {
              return;
            }
            this._value = unescaped;
            this._quoteMark = quoteMark;
            this._syncRawValue();
          } else {
            this._value = v;
          }
        }
      )
    }, {
      key: "insensitive",
      get: function get2() {
        return this._insensitive;
      },
      set: function set2(insensitive) {
        if (!insensitive) {
          this._insensitive = false;
          if (this.raws && (this.raws.insensitiveFlag === "I" || this.raws.insensitiveFlag === "i")) {
            this.raws.insensitiveFlag = void 0;
          }
        }
        this._insensitive = insensitive;
      }
    }, {
      key: "attribute",
      get: function get2() {
        return this._attribute;
      },
      set: function set2(name) {
        this._handleEscapes("attribute", name);
        this._attribute = name;
      }
    }]);
    return Attribute2;
  }(_namespace["default"]);
  exports2["default"] = Attribute;
  Attribute.NO_QUOTE = null;
  Attribute.SINGLE_QUOTE = "'";
  Attribute.DOUBLE_QUOTE = '"';
  var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
    "'": {
      quotes: "single",
      wrap: true
    },
    '"': {
      quotes: "double",
      wrap: true
    }
  }, _CSSESC_QUOTE_OPTIONS[null] = {
    isIdentifier: true
  }, _CSSESC_QUOTE_OPTIONS);
  function defaultAttrConcat(attrValue, attrSpaces) {
    return "" + attrSpaces.before + attrValue + attrSpaces.after;
  }
})(attribute$1);
var universalExports = {};
var universal$1 = {
  get exports() {
    return universalExports;
  },
  set exports(v) {
    universalExports = v;
  }
};
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2["default"] = void 0;
  var _namespace = _interopRequireDefault2(namespaceExports);
  var _types2 = types;
  function _interopRequireDefault2(obj) {
    return obj && obj.__esModule ? obj : { "default": obj };
  }
  function _inheritsLoose(subClass, superClass) {
    subClass.prototype = Object.create(superClass.prototype);
    subClass.prototype.constructor = subClass;
    _setPrototypeOf(subClass, superClass);
  }
  function _setPrototypeOf(o, p2) {
    _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p3) {
      o2.__proto__ = p3;
      return o2;
    };
    return _setPrototypeOf(o, p2);
  }
  var Universal = /* @__PURE__ */ function(_Namespace) {
    _inheritsLoose(Universal2, _Namespace);
    function Universal2(opts) {
      var _this;
      _this = _Namespace.call(this, opts) || this;
      _this.type = _types2.UNIVERSAL;
      _this.value = "*";
      return _this;
    }
    return Universal2;
  }(_namespace["default"]);
  exports2["default"] = Universal;
  module2.exports = exports2.default;
})(universal$1, universalExports);
var combinatorExports = {};
var combinator$2 = {
  get exports() {
    return combinatorExports;
  },
  set exports(v) {
    combinatorExports = v;
  }
};
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2["default"] = void 0;
  var _node = _interopRequireDefault2(nodeExports);
  var _types2 = types;
  function _interopRequireDefault2(obj) {
    return obj && obj.__esModule ? obj : { "default": obj };
  }
  function _inheritsLoose(subClass, superClass) {
    subClass.prototype = Object.create(superClass.prototype);
    subClass.prototype.constructor = subClass;
    _setPrototypeOf(subClass, superClass);
  }
  function _setPrototypeOf(o, p2) {
    _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p3) {
      o2.__proto__ = p3;
      return o2;
    };
    return _setPrototypeOf(o, p2);
  }
  var Combinator = /* @__PURE__ */ function(_Node) {
    _inheritsLoose(Combinator2, _Node);
    function Combinator2(opts) {
      var _this;
      _this = _Node.call(this, opts) || this;
      _this.type = _types2.COMBINATOR;
      return _this;
    }
    return Combinator2;
  }(_node["default"]);
  exports2["default"] = Combinator;
  module2.exports = exports2.default;
})(combinator$2, combinatorExports);
var nestingExports = {};
var nesting$1 = {
  get exports() {
    return nestingExports;
  },
  set exports(v) {
    nestingExports = v;
  }
};
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2["default"] = void 0;
  var _node = _interopRequireDefault2(nodeExports);
  var _types2 = types;
  function _interopRequireDefault2(obj) {
    return obj && obj.__esModule ? obj : { "default": obj };
  }
  function _inheritsLoose(subClass, superClass) {
    subClass.prototype = Object.create(superClass.prototype);
    subClass.prototype.constructor = subClass;
    _setPrototypeOf(subClass, superClass);
  }
  function _setPrototypeOf(o, p2) {
    _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p3) {
      o2.__proto__ = p3;
      return o2;
    };
    return _setPrototypeOf(o, p2);
  }
  var Nesting = /* @__PURE__ */ function(_Node) {
    _inheritsLoose(Nesting2, _Node);
    function Nesting2(opts) {
      var _this;
      _this = _Node.call(this, opts) || this;
      _this.type = _types2.NESTING;
      _this.value = "&";
      return _this;
    }
    return Nesting2;
  }(_node["default"]);
  exports2["default"] = Nesting;
  module2.exports = exports2.default;
})(nesting$1, nestingExports);
var sortAscendingExports = {};
var sortAscending = {
  get exports() {
    return sortAscendingExports;
  },
  set exports(v) {
    sortAscendingExports = v;
  }
};
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2["default"] = sortAscending2;
  function sortAscending2(list2) {
    return list2.sort(function(a, b) {
      return a - b;
    });
  }
  module2.exports = exports2.default;
})(sortAscending, sortAscendingExports);
var tokenize = {};
var tokenTypes = {};
tokenTypes.__esModule = true;
tokenTypes.combinator = tokenTypes.word = tokenTypes.comment = tokenTypes.str = tokenTypes.tab = tokenTypes.newline = tokenTypes.feed = tokenTypes.cr = tokenTypes.backslash = tokenTypes.bang = tokenTypes.slash = tokenTypes.doubleQuote = tokenTypes.singleQuote = tokenTypes.space = tokenTypes.greaterThan = tokenTypes.pipe = tokenTypes.equals = tokenTypes.plus = tokenTypes.caret = tokenTypes.tilde = tokenTypes.dollar = tokenTypes.closeSquare = tokenTypes.openSquare = tokenTypes.closeParenthesis = tokenTypes.openParenthesis = tokenTypes.semicolon = tokenTypes.colon = tokenTypes.comma = tokenTypes.at = tokenTypes.asterisk = tokenTypes.ampersand = void 0;
var ampersand = 38;
tokenTypes.ampersand = ampersand;
var asterisk = 42;
tokenTypes.asterisk = asterisk;
var at = 64;
tokenTypes.at = at;
var comma$1 = 44;
tokenTypes.comma = comma$1;
var colon = 58;
tokenTypes.colon = colon;
var semicolon$1 = 59;
tokenTypes.semicolon = semicolon$1;
var openParenthesis = 40;
tokenTypes.openParenthesis = openParenthesis;
var closeParenthesis = 41;
tokenTypes.closeParenthesis = closeParenthesis;
var openSquare = 91;
tokenTypes.openSquare = openSquare;
var closeSquare = 93;
tokenTypes.closeSquare = closeSquare;
var dollar = 36;
tokenTypes.dollar = dollar;
var tilde = 126;
tokenTypes.tilde = tilde;
var caret = 94;
tokenTypes.caret = caret;
var plus = 43;
tokenTypes.plus = plus;
var equals2 = 61;
tokenTypes.equals = equals2;
var pipe = 124;
tokenTypes.pipe = pipe;
var greaterThan = 62;
tokenTypes.greaterThan = greaterThan;
var space = 32;
tokenTypes.space = space;
var singleQuote = 39;
tokenTypes.singleQuote = singleQuote;
var doubleQuote = 34;
tokenTypes.doubleQuote = doubleQuote;
var slash = 47;
tokenTypes.slash = slash;
var bang = 33;
tokenTypes.bang = bang;
var backslash = 92;
tokenTypes.backslash = backslash;
var cr = 13;
tokenTypes.cr = cr;
var feed = 12;
tokenTypes.feed = feed;
var newline = 10;
tokenTypes.newline = newline;
var tab = 9;
tokenTypes.tab = tab;
var str = singleQuote;
tokenTypes.str = str;
var comment$1 = -1;
tokenTypes.comment = comment$1;
var word = -2;
tokenTypes.word = word;
var combinator$1 = -3;
tokenTypes.combinator = combinator$1;
(function(exports2) {
  exports2.__esModule = true;
  exports2["default"] = tokenize2;
  exports2.FIELDS = void 0;
  var t = _interopRequireWildcard(tokenTypes);
  var _unescapable, _wordDelimiters;
  function _getRequireWildcardCache() {
    if (typeof WeakMap !== "function")
      return null;
    var cache2 = /* @__PURE__ */ new WeakMap();
    _getRequireWildcardCache = function _getRequireWildcardCache2() {
      return cache2;
    };
    return cache2;
  }
  function _interopRequireWildcard(obj) {
    if (obj && obj.__esModule) {
      return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
      return { "default": obj };
    }
    var cache2 = _getRequireWildcardCache();
    if (cache2 && cache2.has(obj)) {
      return cache2.get(obj);
    }
    var newObj = {};
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for (var key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
        if (desc && (desc.get || desc.set)) {
          Object.defineProperty(newObj, key, desc);
        } else {
          newObj[key] = obj[key];
        }
      }
    }
    newObj["default"] = obj;
    if (cache2) {
      cache2.set(obj, newObj);
    }
    return newObj;
  }
  var unescapable = (_unescapable = {}, _unescapable[t.tab] = true, _unescapable[t.newline] = true, _unescapable[t.cr] = true, _unescapable[t.feed] = true, _unescapable);
  var wordDelimiters = (_wordDelimiters = {}, _wordDelimiters[t.space] = true, _wordDelimiters[t.tab] = true, _wordDelimiters[t.newline] = true, _wordDelimiters[t.cr] = true, _wordDelimiters[t.feed] = true, _wordDelimiters[t.ampersand] = true, _wordDelimiters[t.asterisk] = true, _wordDelimiters[t.bang] = true, _wordDelimiters[t.comma] = true, _wordDelimiters[t.colon] = true, _wordDelimiters[t.semicolon] = true, _wordDelimiters[t.openParenthesis] = true, _wordDelimiters[t.closeParenthesis] = true, _wordDelimiters[t.openSquare] = true, _wordDelimiters[t.closeSquare] = true, _wordDelimiters[t.singleQuote] = true, _wordDelimiters[t.doubleQuote] = true, _wordDelimiters[t.plus] = true, _wordDelimiters[t.pipe] = true, _wordDelimiters[t.tilde] = true, _wordDelimiters[t.greaterThan] = true, _wordDelimiters[t.equals] = true, _wordDelimiters[t.dollar] = true, _wordDelimiters[t.caret] = true, _wordDelimiters[t.slash] = true, _wordDelimiters);
  var hex = {};
  var hexChars = "0123456789abcdefABCDEF";
  for (var i = 0; i < hexChars.length; i++) {
    hex[hexChars.charCodeAt(i)] = true;
  }
  function consumeWord(css, start) {
    var next = start;
    var code;
    do {
      code = css.charCodeAt(next);
      if (wordDelimiters[code]) {
        return next - 1;
      } else if (code === t.backslash) {
        next = consumeEscape(css, next) + 1;
      } else {
        next++;
      }
    } while (next < css.length);
    return next - 1;
  }
  function consumeEscape(css, start) {
    var next = start;
    var code = css.charCodeAt(next + 1);
    if (unescapable[code])
      ;
    else if (hex[code]) {
      var hexDigits = 0;
      do {
        next++;
        hexDigits++;
        code = css.charCodeAt(next + 1);
      } while (hex[code] && hexDigits < 6);
      if (hexDigits < 6 && code === t.space) {
        next++;
      }
    } else {
      next++;
    }
    return next;
  }
  var FIELDS = {
    TYPE: 0,
    START_LINE: 1,
    START_COL: 2,
    END_LINE: 3,
    END_COL: 4,
    START_POS: 5,
    END_POS: 6
  };
  exports2.FIELDS = FIELDS;
  function tokenize2(input2) {
    var tokens = [];
    var css = input2.css.valueOf();
    var _css = css, length2 = _css.length;
    var offset = -1;
    var line = 1;
    var start = 0;
    var end = 0;
    var code, content, endColumn, endLine, escaped, escapePos, last2, lines, next, nextLine, nextOffset, quote, tokenType;
    function unclosed(what, fix) {
      if (input2.safe) {
        css += fix;
        next = css.length - 1;
      } else {
        throw input2.error("Unclosed " + what, line, start - offset, start);
      }
    }
    while (start < length2) {
      code = css.charCodeAt(start);
      if (code === t.newline) {
        offset = start;
        line += 1;
      }
      switch (code) {
        case t.space:
        case t.tab:
        case t.newline:
        case t.cr:
        case t.feed:
          next = start;
          do {
            next += 1;
            code = css.charCodeAt(next);
            if (code === t.newline) {
              offset = next;
              line += 1;
            }
          } while (code === t.space || code === t.newline || code === t.tab || code === t.cr || code === t.feed);
          tokenType = t.space;
          endLine = line;
          endColumn = next - offset - 1;
          end = next;
          break;
        case t.plus:
        case t.greaterThan:
        case t.tilde:
        case t.pipe:
          next = start;
          do {
            next += 1;
            code = css.charCodeAt(next);
          } while (code === t.plus || code === t.greaterThan || code === t.tilde || code === t.pipe);
          tokenType = t.combinator;
          endLine = line;
          endColumn = start - offset;
          end = next;
          break;
        case t.asterisk:
        case t.ampersand:
        case t.bang:
        case t.comma:
        case t.equals:
        case t.dollar:
        case t.caret:
        case t.openSquare:
        case t.closeSquare:
        case t.colon:
        case t.semicolon:
        case t.openParenthesis:
        case t.closeParenthesis:
          next = start;
          tokenType = code;
          endLine = line;
          endColumn = start - offset;
          end = next + 1;
          break;
        case t.singleQuote:
        case t.doubleQuote:
          quote = code === t.singleQuote ? "'" : '"';
          next = start;
          do {
            escaped = false;
            next = css.indexOf(quote, next + 1);
            if (next === -1) {
              unclosed("quote", quote);
            }
            escapePos = next;
            while (css.charCodeAt(escapePos - 1) === t.backslash) {
              escapePos -= 1;
              escaped = !escaped;
            }
          } while (escaped);
          tokenType = t.str;
          endLine = line;
          endColumn = start - offset;
          end = next + 1;
          break;
        default:
          if (code === t.slash && css.charCodeAt(start + 1) === t.asterisk) {
            next = css.indexOf("*/", start + 2) + 1;
            if (next === 0) {
              unclosed("comment", "*/");
            }
            content = css.slice(start, next + 1);
            lines = content.split("\n");
            last2 = lines.length - 1;
            if (last2 > 0) {
              nextLine = line + last2;
              nextOffset = next - lines[last2].length;
            } else {
              nextLine = line;
              nextOffset = offset;
            }
            tokenType = t.comment;
            line = nextLine;
            endLine = nextLine;
            endColumn = next - nextOffset;
          } else if (code === t.slash) {
            next = start;
            tokenType = code;
            endLine = line;
            endColumn = start - offset;
            end = next + 1;
          } else {
            next = consumeWord(css, start);
            tokenType = t.word;
            endLine = line;
            endColumn = next - offset;
          }
          end = next + 1;
          break;
      }
      tokens.push([
        tokenType,
        // [0] Token type
        line,
        // [1] Starting line
        start - offset,
        // [2] Starting column
        endLine,
        // [3] Ending line
        endColumn,
        // [4] Ending column
        start,
        // [5] Start position / Source index
        end
        // [6] End position
      ]);
      if (nextOffset) {
        offset = nextOffset;
        nextOffset = null;
      }
      start = end;
    }
    return tokens;
  }
})(tokenize);
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2["default"] = void 0;
  var _root2 = _interopRequireDefault2(rootExports);
  var _selector2 = _interopRequireDefault2(selectorExports);
  var _className2 = _interopRequireDefault2(classNameExports);
  var _comment2 = _interopRequireDefault2(commentExports);
  var _id2 = _interopRequireDefault2(idExports);
  var _tag2 = _interopRequireDefault2(tagExports);
  var _string2 = _interopRequireDefault2(stringExports);
  var _pseudo2 = _interopRequireDefault2(pseudoExports);
  var _attribute2 = _interopRequireWildcard(attribute$1);
  var _universal2 = _interopRequireDefault2(universalExports);
  var _combinator2 = _interopRequireDefault2(combinatorExports);
  var _nesting2 = _interopRequireDefault2(nestingExports);
  var _sortAscending = _interopRequireDefault2(sortAscendingExports);
  var _tokenize = _interopRequireWildcard(tokenize);
  var tokens = _interopRequireWildcard(tokenTypes);
  var types$12 = _interopRequireWildcard(types);
  var _util2 = util$6;
  var _WHITESPACE_TOKENS, _Object$assign;
  function _getRequireWildcardCache() {
    if (typeof WeakMap !== "function")
      return null;
    var cache2 = /* @__PURE__ */ new WeakMap();
    _getRequireWildcardCache = function _getRequireWildcardCache2() {
      return cache2;
    };
    return cache2;
  }
  function _interopRequireWildcard(obj) {
    if (obj && obj.__esModule) {
      return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
      return { "default": obj };
    }
    var cache2 = _getRequireWildcardCache();
    if (cache2 && cache2.has(obj)) {
      return cache2.get(obj);
    }
    var newObj = {};
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for (var key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
        if (desc && (desc.get || desc.set)) {
          Object.defineProperty(newObj, key, desc);
        } else {
          newObj[key] = obj[key];
        }
      }
    }
    newObj["default"] = obj;
    if (cache2) {
      cache2.set(obj, newObj);
    }
    return newObj;
  }
  function _interopRequireDefault2(obj) {
    return obj && obj.__esModule ? obj : { "default": obj };
  }
  function _defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor)
        descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }
  function _createClass(Constructor, protoProps, staticProps) {
    if (protoProps)
      _defineProperties(Constructor.prototype, protoProps);
    if (staticProps)
      _defineProperties(Constructor, staticProps);
    return Constructor;
  }
  var WHITESPACE_TOKENS = (_WHITESPACE_TOKENS = {}, _WHITESPACE_TOKENS[tokens.space] = true, _WHITESPACE_TOKENS[tokens.cr] = true, _WHITESPACE_TOKENS[tokens.feed] = true, _WHITESPACE_TOKENS[tokens.newline] = true, _WHITESPACE_TOKENS[tokens.tab] = true, _WHITESPACE_TOKENS);
  var WHITESPACE_EQUIV_TOKENS = Object.assign({}, WHITESPACE_TOKENS, (_Object$assign = {}, _Object$assign[tokens.comment] = true, _Object$assign));
  function tokenStart(token) {
    return {
      line: token[_tokenize.FIELDS.START_LINE],
      column: token[_tokenize.FIELDS.START_COL]
    };
  }
  function tokenEnd(token) {
    return {
      line: token[_tokenize.FIELDS.END_LINE],
      column: token[_tokenize.FIELDS.END_COL]
    };
  }
  function getSource(startLine, startColumn, endLine, endColumn) {
    return {
      start: {
        line: startLine,
        column: startColumn
      },
      end: {
        line: endLine,
        column: endColumn
      }
    };
  }
  function getTokenSource(token) {
    return getSource(token[_tokenize.FIELDS.START_LINE], token[_tokenize.FIELDS.START_COL], token[_tokenize.FIELDS.END_LINE], token[_tokenize.FIELDS.END_COL]);
  }
  function getTokenSourceSpan(startToken, endToken) {
    if (!startToken) {
      return void 0;
    }
    return getSource(startToken[_tokenize.FIELDS.START_LINE], startToken[_tokenize.FIELDS.START_COL], endToken[_tokenize.FIELDS.END_LINE], endToken[_tokenize.FIELDS.END_COL]);
  }
  function unescapeProp(node2, prop) {
    var value = node2[prop];
    if (typeof value !== "string") {
      return;
    }
    if (value.indexOf("\\") !== -1) {
      (0, _util2.ensureObject)(node2, "raws");
      node2[prop] = (0, _util2.unesc)(value);
      if (node2.raws[prop] === void 0) {
        node2.raws[prop] = value;
      }
    }
    return node2;
  }
  function indexesOf(array2, item) {
    var i = -1;
    var indexes = [];
    while ((i = array2.indexOf(item, i + 1)) !== -1) {
      indexes.push(i);
    }
    return indexes;
  }
  function uniqs() {
    var list2 = Array.prototype.concat.apply([], arguments);
    return list2.filter(function(item, i) {
      return i === list2.indexOf(item);
    });
  }
  var Parser6 = /* @__PURE__ */ function() {
    function Parser7(rule2, options) {
      if (options === void 0) {
        options = {};
      }
      this.rule = rule2;
      this.options = Object.assign({
        lossy: false,
        safe: false
      }, options);
      this.position = 0;
      this.css = typeof this.rule === "string" ? this.rule : this.rule.selector;
      this.tokens = (0, _tokenize["default"])({
        css: this.css,
        error: this._errorGenerator(),
        safe: this.options.safe
      });
      var rootSource = getTokenSourceSpan(this.tokens[0], this.tokens[this.tokens.length - 1]);
      this.root = new _root2["default"]({
        source: rootSource
      });
      this.root.errorGenerator = this._errorGenerator();
      var selector3 = new _selector2["default"]({
        source: {
          start: {
            line: 1,
            column: 1
          }
        }
      });
      this.root.append(selector3);
      this.current = selector3;
      this.loop();
    }
    var _proto = Parser7.prototype;
    _proto._errorGenerator = function _errorGenerator() {
      var _this = this;
      return function(message, errorOptions) {
        if (typeof _this.rule === "string") {
          return new Error(message);
        }
        return _this.rule.error(message, errorOptions);
      };
    };
    _proto.attribute = function attribute3() {
      var attr = [];
      var startingToken = this.currToken;
      this.position++;
      while (this.position < this.tokens.length && this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
        attr.push(this.currToken);
        this.position++;
      }
      if (this.currToken[_tokenize.FIELDS.TYPE] !== tokens.closeSquare) {
        return this.expected("closing square bracket", this.currToken[_tokenize.FIELDS.START_POS]);
      }
      var len = attr.length;
      var node2 = {
        source: getSource(startingToken[1], startingToken[2], this.currToken[3], this.currToken[4]),
        sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
      };
      if (len === 1 && !~[tokens.word].indexOf(attr[0][_tokenize.FIELDS.TYPE])) {
        return this.expected("attribute", attr[0][_tokenize.FIELDS.START_POS]);
      }
      var pos = 0;
      var spaceBefore = "";
      var commentBefore = "";
      var lastAdded = null;
      var spaceAfterMeaningfulToken = false;
      while (pos < len) {
        var token = attr[pos];
        var content = this.content(token);
        var next = attr[pos + 1];
        switch (token[_tokenize.FIELDS.TYPE]) {
          case tokens.space:
            spaceAfterMeaningfulToken = true;
            if (this.options.lossy) {
              break;
            }
            if (lastAdded) {
              (0, _util2.ensureObject)(node2, "spaces", lastAdded);
              var prevContent = node2.spaces[lastAdded].after || "";
              node2.spaces[lastAdded].after = prevContent + content;
              var existingComment = (0, _util2.getProp)(node2, "raws", "spaces", lastAdded, "after") || null;
              if (existingComment) {
                node2.raws.spaces[lastAdded].after = existingComment + content;
              }
            } else {
              spaceBefore = spaceBefore + content;
              commentBefore = commentBefore + content;
            }
            break;
          case tokens.asterisk:
            if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
              node2.operator = content;
              lastAdded = "operator";
            } else if ((!node2.namespace || lastAdded === "namespace" && !spaceAfterMeaningfulToken) && next) {
              if (spaceBefore) {
                (0, _util2.ensureObject)(node2, "spaces", "attribute");
                node2.spaces.attribute.before = spaceBefore;
                spaceBefore = "";
              }
              if (commentBefore) {
                (0, _util2.ensureObject)(node2, "raws", "spaces", "attribute");
                node2.raws.spaces.attribute.before = spaceBefore;
                commentBefore = "";
              }
              node2.namespace = (node2.namespace || "") + content;
              var rawValue = (0, _util2.getProp)(node2, "raws", "namespace") || null;
              if (rawValue) {
                node2.raws.namespace += content;
              }
              lastAdded = "namespace";
            }
            spaceAfterMeaningfulToken = false;
            break;
          case tokens.dollar:
            if (lastAdded === "value") {
              var oldRawValue = (0, _util2.getProp)(node2, "raws", "value");
              node2.value += "$";
              if (oldRawValue) {
                node2.raws.value = oldRawValue + "$";
              }
              break;
            }
          case tokens.caret:
            if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
              node2.operator = content;
              lastAdded = "operator";
            }
            spaceAfterMeaningfulToken = false;
            break;
          case tokens.combinator:
            if (content === "~" && next[_tokenize.FIELDS.TYPE] === tokens.equals) {
              node2.operator = content;
              lastAdded = "operator";
            }
            if (content !== "|") {
              spaceAfterMeaningfulToken = false;
              break;
            }
            if (next[_tokenize.FIELDS.TYPE] === tokens.equals) {
              node2.operator = content;
              lastAdded = "operator";
            } else if (!node2.namespace && !node2.attribute) {
              node2.namespace = true;
            }
            spaceAfterMeaningfulToken = false;
            break;
          case tokens.word:
            if (next && this.content(next) === "|" && attr[pos + 2] && attr[pos + 2][_tokenize.FIELDS.TYPE] !== tokens.equals && // this look-ahead probably fails with comment nodes involved.
            !node2.operator && !node2.namespace) {
              node2.namespace = content;
              lastAdded = "namespace";
            } else if (!node2.attribute || lastAdded === "attribute" && !spaceAfterMeaningfulToken) {
              if (spaceBefore) {
                (0, _util2.ensureObject)(node2, "spaces", "attribute");
                node2.spaces.attribute.before = spaceBefore;
                spaceBefore = "";
              }
              if (commentBefore) {
                (0, _util2.ensureObject)(node2, "raws", "spaces", "attribute");
                node2.raws.spaces.attribute.before = commentBefore;
                commentBefore = "";
              }
              node2.attribute = (node2.attribute || "") + content;
              var _rawValue = (0, _util2.getProp)(node2, "raws", "attribute") || null;
              if (_rawValue) {
                node2.raws.attribute += content;
              }
              lastAdded = "attribute";
            } else if (!node2.value && node2.value !== "" || lastAdded === "value" && !(spaceAfterMeaningfulToken || node2.quoteMark)) {
              var _unescaped = (0, _util2.unesc)(content);
              var _oldRawValue = (0, _util2.getProp)(node2, "raws", "value") || "";
              var oldValue = node2.value || "";
              node2.value = oldValue + _unescaped;
              node2.quoteMark = null;
              if (_unescaped !== content || _oldRawValue) {
                (0, _util2.ensureObject)(node2, "raws");
                node2.raws.value = (_oldRawValue || oldValue) + content;
              }
              lastAdded = "value";
            } else {
              var insensitive = content === "i" || content === "I";
              if ((node2.value || node2.value === "") && (node2.quoteMark || spaceAfterMeaningfulToken)) {
                node2.insensitive = insensitive;
                if (!insensitive || content === "I") {
                  (0, _util2.ensureObject)(node2, "raws");
                  node2.raws.insensitiveFlag = content;
                }
                lastAdded = "insensitive";
                if (spaceBefore) {
                  (0, _util2.ensureObject)(node2, "spaces", "insensitive");
                  node2.spaces.insensitive.before = spaceBefore;
                  spaceBefore = "";
                }
                if (commentBefore) {
                  (0, _util2.ensureObject)(node2, "raws", "spaces", "insensitive");
                  node2.raws.spaces.insensitive.before = commentBefore;
                  commentBefore = "";
                }
              } else if (node2.value || node2.value === "") {
                lastAdded = "value";
                node2.value += content;
                if (node2.raws.value) {
                  node2.raws.value += content;
                }
              }
            }
            spaceAfterMeaningfulToken = false;
            break;
          case tokens.str:
            if (!node2.attribute || !node2.operator) {
              return this.error("Expected an attribute followed by an operator preceding the string.", {
                index: token[_tokenize.FIELDS.START_POS]
              });
            }
            var _unescapeValue = (0, _attribute2.unescapeValue)(content), unescaped = _unescapeValue.unescaped, quoteMark = _unescapeValue.quoteMark;
            node2.value = unescaped;
            node2.quoteMark = quoteMark;
            lastAdded = "value";
            (0, _util2.ensureObject)(node2, "raws");
            node2.raws.value = content;
            spaceAfterMeaningfulToken = false;
            break;
          case tokens.equals:
            if (!node2.attribute) {
              return this.expected("attribute", token[_tokenize.FIELDS.START_POS], content);
            }
            if (node2.value) {
              return this.error('Unexpected "=" found; an operator was already defined.', {
                index: token[_tokenize.FIELDS.START_POS]
              });
            }
            node2.operator = node2.operator ? node2.operator + content : content;
            lastAdded = "operator";
            spaceAfterMeaningfulToken = false;
            break;
          case tokens.comment:
            if (lastAdded) {
              if (spaceAfterMeaningfulToken || next && next[_tokenize.FIELDS.TYPE] === tokens.space || lastAdded === "insensitive") {
                var lastComment = (0, _util2.getProp)(node2, "spaces", lastAdded, "after") || "";
                var rawLastComment = (0, _util2.getProp)(node2, "raws", "spaces", lastAdded, "after") || lastComment;
                (0, _util2.ensureObject)(node2, "raws", "spaces", lastAdded);
                node2.raws.spaces[lastAdded].after = rawLastComment + content;
              } else {
                var lastValue = node2[lastAdded] || "";
                var rawLastValue = (0, _util2.getProp)(node2, "raws", lastAdded) || lastValue;
                (0, _util2.ensureObject)(node2, "raws");
                node2.raws[lastAdded] = rawLastValue + content;
              }
            } else {
              commentBefore = commentBefore + content;
            }
            break;
          default:
            return this.error('Unexpected "' + content + '" found.', {
              index: token[_tokenize.FIELDS.START_POS]
            });
        }
        pos++;
      }
      unescapeProp(node2, "attribute");
      unescapeProp(node2, "namespace");
      this.newNode(new _attribute2["default"](node2));
      this.position++;
    };
    _proto.parseWhitespaceEquivalentTokens = function parseWhitespaceEquivalentTokens(stopPosition) {
      if (stopPosition < 0) {
        stopPosition = this.tokens.length;
      }
      var startPosition = this.position;
      var nodes = [];
      var space2 = "";
      var lastComment = void 0;
      do {
        if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]]) {
          if (!this.options.lossy) {
            space2 += this.content();
          }
        } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.comment) {
          var spaces2 = {};
          if (space2) {
            spaces2.before = space2;
            space2 = "";
          }
          lastComment = new _comment2["default"]({
            value: this.content(),
            source: getTokenSource(this.currToken),
            sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
            spaces: spaces2
          });
          nodes.push(lastComment);
        }
      } while (++this.position < stopPosition);
      if (space2) {
        if (lastComment) {
          lastComment.spaces.after = space2;
        } else if (!this.options.lossy) {
          var firstToken = this.tokens[startPosition];
          var lastToken = this.tokens[this.position - 1];
          nodes.push(new _string2["default"]({
            value: "",
            source: getSource(firstToken[_tokenize.FIELDS.START_LINE], firstToken[_tokenize.FIELDS.START_COL], lastToken[_tokenize.FIELDS.END_LINE], lastToken[_tokenize.FIELDS.END_COL]),
            sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
            spaces: {
              before: space2,
              after: ""
            }
          }));
        }
      }
      return nodes;
    };
    _proto.convertWhitespaceNodesToSpace = function convertWhitespaceNodesToSpace(nodes, requiredSpace) {
      var _this2 = this;
      if (requiredSpace === void 0) {
        requiredSpace = false;
      }
      var space2 = "";
      var rawSpace = "";
      nodes.forEach(function(n2) {
        var spaceBefore = _this2.lossySpace(n2.spaces.before, requiredSpace);
        var rawSpaceBefore = _this2.lossySpace(n2.rawSpaceBefore, requiredSpace);
        space2 += spaceBefore + _this2.lossySpace(n2.spaces.after, requiredSpace && spaceBefore.length === 0);
        rawSpace += spaceBefore + n2.value + _this2.lossySpace(n2.rawSpaceAfter, requiredSpace && rawSpaceBefore.length === 0);
      });
      if (rawSpace === space2) {
        rawSpace = void 0;
      }
      var result2 = {
        space: space2,
        rawSpace
      };
      return result2;
    };
    _proto.isNamedCombinator = function isNamedCombinator(position) {
      if (position === void 0) {
        position = this.position;
      }
      return this.tokens[position + 0] && this.tokens[position + 0][_tokenize.FIELDS.TYPE] === tokens.slash && this.tokens[position + 1] && this.tokens[position + 1][_tokenize.FIELDS.TYPE] === tokens.word && this.tokens[position + 2] && this.tokens[position + 2][_tokenize.FIELDS.TYPE] === tokens.slash;
    };
    _proto.namedCombinator = function namedCombinator() {
      if (this.isNamedCombinator()) {
        var nameRaw = this.content(this.tokens[this.position + 1]);
        var name = (0, _util2.unesc)(nameRaw).toLowerCase();
        var raws = {};
        if (name !== nameRaw) {
          raws.value = "/" + nameRaw + "/";
        }
        var node2 = new _combinator2["default"]({
          value: "/" + name + "/",
          source: getSource(this.currToken[_tokenize.FIELDS.START_LINE], this.currToken[_tokenize.FIELDS.START_COL], this.tokens[this.position + 2][_tokenize.FIELDS.END_LINE], this.tokens[this.position + 2][_tokenize.FIELDS.END_COL]),
          sourceIndex: this.currToken[_tokenize.FIELDS.START_POS],
          raws
        });
        this.position = this.position + 3;
        return node2;
      } else {
        this.unexpected();
      }
    };
    _proto.combinator = function combinator3() {
      var _this3 = this;
      if (this.content() === "|") {
        return this.namespace();
      }
      var nextSigTokenPos = this.locateNextMeaningfulToken(this.position);
      if (nextSigTokenPos < 0 || this.tokens[nextSigTokenPos][_tokenize.FIELDS.TYPE] === tokens.comma) {
        var nodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
        if (nodes.length > 0) {
          var last2 = this.current.last;
          if (last2) {
            var _this$convertWhitespa = this.convertWhitespaceNodesToSpace(nodes), space2 = _this$convertWhitespa.space, rawSpace = _this$convertWhitespa.rawSpace;
            if (rawSpace !== void 0) {
              last2.rawSpaceAfter += rawSpace;
            }
            last2.spaces.after += space2;
          } else {
            nodes.forEach(function(n2) {
              return _this3.newNode(n2);
            });
          }
        }
        return;
      }
      var firstToken = this.currToken;
      var spaceOrDescendantSelectorNodes = void 0;
      if (nextSigTokenPos > this.position) {
        spaceOrDescendantSelectorNodes = this.parseWhitespaceEquivalentTokens(nextSigTokenPos);
      }
      var node2;
      if (this.isNamedCombinator()) {
        node2 = this.namedCombinator();
      } else if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.combinator) {
        node2 = new _combinator2["default"]({
          value: this.content(),
          source: getTokenSource(this.currToken),
          sourceIndex: this.currToken[_tokenize.FIELDS.START_POS]
        });
        this.position++;
      } else if (WHITESPACE_TOKENS[this.currToken[_tokenize.FIELDS.TYPE]])
        ;
      else if (!spaceOrDescendantSelectorNodes) {
        this.unexpected();
      }
      if (node2) {
        if (spaceOrDescendantSelectorNodes) {
          var _this$convertWhitespa2 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes), _space = _this$convertWhitespa2.space, _rawSpace = _this$convertWhitespa2.rawSpace;
          node2.spaces.before = _space;
          node2.rawSpaceBefore = _rawSpace;
        }
      } else {
        var _this$convertWhitespa3 = this.convertWhitespaceNodesToSpace(spaceOrDescendantSelectorNodes, true), _space2 = _this$convertWhitespa3.space, _rawSpace2 = _this$convertWhitespa3.rawSpace;
        if (!_rawSpace2) {
          _rawSpace2 = _space2;
        }
        var spaces2 = {};
        var raws = {
          spaces: {}
        };
        if (_space2.endsWith(" ") && _rawSpace2.endsWith(" ")) {
          spaces2.before = _space2.slice(0, _space2.length - 1);
          raws.spaces.before = _rawSpace2.slice(0, _rawSpace2.length - 1);
        } else if (_space2.startsWith(" ") && _rawSpace2.startsWith(" ")) {
          spaces2.after = _space2.slice(1);
          raws.spaces.after = _rawSpace2.slice(1);
        } else {
          raws.value = _rawSpace2;
        }
        node2 = new _combinator2["default"]({
          value: " ",
          source: getTokenSourceSpan(firstToken, this.tokens[this.position - 1]),
          sourceIndex: firstToken[_tokenize.FIELDS.START_POS],
          spaces: spaces2,
          raws
        });
      }
      if (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.space) {
        node2.spaces.after = this.optionalSpace(this.content());
        this.position++;
      }
      return this.newNode(node2);
    };
    _proto.comma = function comma() {
      if (this.position === this.tokens.length - 1) {
        this.root.trailingComma = true;
        this.position++;
        return;
      }
      this.current._inferEndPosition();
      var selector3 = new _selector2["default"]({
        source: {
          start: tokenStart(this.tokens[this.position + 1])
        }
      });
      this.current.parent.append(selector3);
      this.current = selector3;
      this.position++;
    };
    _proto.comment = function comment3() {
      var current = this.currToken;
      this.newNode(new _comment2["default"]({
        value: this.content(),
        source: getTokenSource(current),
        sourceIndex: current[_tokenize.FIELDS.START_POS]
      }));
      this.position++;
    };
    _proto.error = function error2(message, opts) {
      throw this.root.error(message, opts);
    };
    _proto.missingBackslash = function missingBackslash() {
      return this.error("Expected a backslash preceding the semicolon.", {
        index: this.currToken[_tokenize.FIELDS.START_POS]
      });
    };
    _proto.missingParenthesis = function missingParenthesis() {
      return this.expected("opening parenthesis", this.currToken[_tokenize.FIELDS.START_POS]);
    };
    _proto.missingSquareBracket = function missingSquareBracket() {
      return this.expected("opening square bracket", this.currToken[_tokenize.FIELDS.START_POS]);
    };
    _proto.unexpected = function unexpected() {
      return this.error("Unexpected '" + this.content() + "'. Escaping special characters with \\ may help.", this.currToken[_tokenize.FIELDS.START_POS]);
    };
    _proto.namespace = function namespace2() {
      var before = this.prevToken && this.content(this.prevToken) || true;
      if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.word) {
        this.position++;
        return this.word(before);
      } else if (this.nextToken[_tokenize.FIELDS.TYPE] === tokens.asterisk) {
        this.position++;
        return this.universal(before);
      }
    };
    _proto.nesting = function nesting3() {
      if (this.nextToken) {
        var nextContent = this.content(this.nextToken);
        if (nextContent === "|") {
          this.position++;
          return;
        }
      }
      var current = this.currToken;
      this.newNode(new _nesting2["default"]({
        value: this.content(),
        source: getTokenSource(current),
        sourceIndex: current[_tokenize.FIELDS.START_POS]
      }));
      this.position++;
    };
    _proto.parentheses = function parentheses() {
      var last2 = this.current.last;
      var unbalanced = 1;
      this.position++;
      if (last2 && last2.type === types$12.PSEUDO) {
        var selector3 = new _selector2["default"]({
          source: {
            start: tokenStart(this.tokens[this.position - 1])
          }
        });
        var cache2 = this.current;
        last2.append(selector3);
        this.current = selector3;
        while (this.position < this.tokens.length && unbalanced) {
          if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
            unbalanced++;
          }
          if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
            unbalanced--;
          }
          if (unbalanced) {
            this.parse();
          } else {
            this.current.source.end = tokenEnd(this.currToken);
            this.current.parent.source.end = tokenEnd(this.currToken);
            this.position++;
          }
        }
        this.current = cache2;
      } else {
        var parenStart = this.currToken;
        var parenValue = "(";
        var parenEnd;
        while (this.position < this.tokens.length && unbalanced) {
          if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
            unbalanced++;
          }
          if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
            unbalanced--;
          }
          parenEnd = this.currToken;
          parenValue += this.parseParenthesisToken(this.currToken);
          this.position++;
        }
        if (last2) {
          last2.appendToPropertyAndEscape("value", parenValue, parenValue);
        } else {
          this.newNode(new _string2["default"]({
            value: parenValue,
            source: getSource(parenStart[_tokenize.FIELDS.START_LINE], parenStart[_tokenize.FIELDS.START_COL], parenEnd[_tokenize.FIELDS.END_LINE], parenEnd[_tokenize.FIELDS.END_COL]),
            sourceIndex: parenStart[_tokenize.FIELDS.START_POS]
          }));
        }
      }
      if (unbalanced) {
        return this.expected("closing parenthesis", this.currToken[_tokenize.FIELDS.START_POS]);
      }
    };
    _proto.pseudo = function pseudo3() {
      var _this4 = this;
      var pseudoStr = "";
      var startingToken = this.currToken;
      while (this.currToken && this.currToken[_tokenize.FIELDS.TYPE] === tokens.colon) {
        pseudoStr += this.content();
        this.position++;
      }
      if (!this.currToken) {
        return this.expected(["pseudo-class", "pseudo-element"], this.position - 1);
      }
      if (this.currToken[_tokenize.FIELDS.TYPE] === tokens.word) {
        this.splitWord(false, function(first2, length2) {
          pseudoStr += first2;
          _this4.newNode(new _pseudo2["default"]({
            value: pseudoStr,
            source: getTokenSourceSpan(startingToken, _this4.currToken),
            sourceIndex: startingToken[_tokenize.FIELDS.START_POS]
          }));
          if (length2 > 1 && _this4.nextToken && _this4.nextToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis) {
            _this4.error("Misplaced parenthesis.", {
              index: _this4.nextToken[_tokenize.FIELDS.START_POS]
            });
          }
        });
      } else {
        return this.expected(["pseudo-class", "pseudo-element"], this.currToken[_tokenize.FIELDS.START_POS]);
      }
    };
    _proto.space = function space2() {
      var content = this.content();
      if (this.position === 0 || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.prevToken[_tokenize.FIELDS.TYPE] === tokens.openParenthesis || this.current.nodes.every(function(node2) {
        return node2.type === "comment";
      })) {
        this.spaces = this.optionalSpace(content);
        this.position++;
      } else if (this.position === this.tokens.length - 1 || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.comma || this.nextToken[_tokenize.FIELDS.TYPE] === tokens.closeParenthesis) {
        this.current.last.spaces.after = this.optionalSpace(content);
        this.position++;
      } else {
        this.combinator();
      }
    };
    _proto.string = function string3() {
      var current = this.currToken;
      this.newNode(new _string2["default"]({
        value: this.content(),
        source: getTokenSource(current),
        sourceIndex: current[_tokenize.FIELDS.START_POS]
      }));
      this.position++;
    };
    _proto.universal = function universal3(namespace2) {
      var nextToken = this.nextToken;
      if (nextToken && this.content(nextToken) === "|") {
        this.position++;
        return this.namespace();
      }
      var current = this.currToken;
      this.newNode(new _universal2["default"]({
        value: this.content(),
        source: getTokenSource(current),
        sourceIndex: current[_tokenize.FIELDS.START_POS]
      }), namespace2);
      this.position++;
    };
    _proto.splitWord = function splitWord(namespace2, firstCallback) {
      var _this5 = this;
      var nextToken = this.nextToken;
      var word2 = this.content();
      while (nextToken && ~[tokens.dollar, tokens.caret, tokens.equals, tokens.word].indexOf(nextToken[_tokenize.FIELDS.TYPE])) {
        this.position++;
        var current = this.content();
        word2 += current;
        if (current.lastIndexOf("\\") === current.length - 1) {
          var next = this.nextToken;
          if (next && next[_tokenize.FIELDS.TYPE] === tokens.space) {
            word2 += this.requiredSpace(this.content(next));
            this.position++;
          }
        }
        nextToken = this.nextToken;
      }
      var hasClass = indexesOf(word2, ".").filter(function(i) {
        var escapedDot = word2[i - 1] === "\\";
        var isKeyframesPercent = /^\d+\.\d+%$/.test(word2);
        return !escapedDot && !isKeyframesPercent;
      });
      var hasId = indexesOf(word2, "#").filter(function(i) {
        return word2[i - 1] !== "\\";
      });
      var interpolations = indexesOf(word2, "#{");
      if (interpolations.length) {
        hasId = hasId.filter(function(hashIndex) {
          return !~interpolations.indexOf(hashIndex);
        });
      }
      var indices = (0, _sortAscending["default"])(uniqs([0].concat(hasClass, hasId)));
      indices.forEach(function(ind, i) {
        var index = indices[i + 1] || word2.length;
        var value = word2.slice(ind, index);
        if (i === 0 && firstCallback) {
          return firstCallback.call(_this5, value, indices.length);
        }
        var node2;
        var current2 = _this5.currToken;
        var sourceIndex = current2[_tokenize.FIELDS.START_POS] + indices[i];
        var source = getSource(current2[1], current2[2] + ind, current2[3], current2[2] + (index - 1));
        if (~hasClass.indexOf(ind)) {
          var classNameOpts = {
            value: value.slice(1),
            source,
            sourceIndex
          };
          node2 = new _className2["default"](unescapeProp(classNameOpts, "value"));
        } else if (~hasId.indexOf(ind)) {
          var idOpts = {
            value: value.slice(1),
            source,
            sourceIndex
          };
          node2 = new _id2["default"](unescapeProp(idOpts, "value"));
        } else {
          var tagOpts = {
            value,
            source,
            sourceIndex
          };
          unescapeProp(tagOpts, "value");
          node2 = new _tag2["default"](tagOpts);
        }
        _this5.newNode(node2, namespace2);
        namespace2 = null;
      });
      this.position++;
    };
    _proto.word = function word2(namespace2) {
      var nextToken = this.nextToken;
      if (nextToken && this.content(nextToken) === "|") {
        this.position++;
        return this.namespace();
      }
      return this.splitWord(namespace2);
    };
    _proto.loop = function loop() {
      while (this.position < this.tokens.length) {
        this.parse(true);
      }
      this.current._inferEndPosition();
      return this.root;
    };
    _proto.parse = function parse2(throwOnParenthesis) {
      switch (this.currToken[_tokenize.FIELDS.TYPE]) {
        case tokens.space:
          this.space();
          break;
        case tokens.comment:
          this.comment();
          break;
        case tokens.openParenthesis:
          this.parentheses();
          break;
        case tokens.closeParenthesis:
          if (throwOnParenthesis) {
            this.missingParenthesis();
          }
          break;
        case tokens.openSquare:
          this.attribute();
          break;
        case tokens.dollar:
        case tokens.caret:
        case tokens.equals:
        case tokens.word:
          this.word();
          break;
        case tokens.colon:
          this.pseudo();
          break;
        case tokens.comma:
          this.comma();
          break;
        case tokens.asterisk:
          this.universal();
          break;
        case tokens.ampersand:
          this.nesting();
          break;
        case tokens.slash:
        case tokens.combinator:
          this.combinator();
          break;
        case tokens.str:
          this.string();
          break;
        case tokens.closeSquare:
          this.missingSquareBracket();
        case tokens.semicolon:
          this.missingBackslash();
        default:
          this.unexpected();
      }
    };
    _proto.expected = function expected(description, index, found) {
      if (Array.isArray(description)) {
        var last2 = description.pop();
        description = description.join(", ") + " or " + last2;
      }
      var an = /^[aeiou]/.test(description[0]) ? "an" : "a";
      if (!found) {
        return this.error("Expected " + an + " " + description + ".", {
          index
        });
      }
      return this.error("Expected " + an + " " + description + ', found "' + found + '" instead.', {
        index
      });
    };
    _proto.requiredSpace = function requiredSpace(space2) {
      return this.options.lossy ? " " : space2;
    };
    _proto.optionalSpace = function optionalSpace(space2) {
      return this.options.lossy ? "" : space2;
    };
    _proto.lossySpace = function lossySpace(space2, required) {
      if (this.options.lossy) {
        return required ? " " : "";
      } else {
        return space2;
      }
    };
    _proto.parseParenthesisToken = function parseParenthesisToken(token) {
      var content = this.content(token);
      if (token[_tokenize.FIELDS.TYPE] === tokens.space) {
        return this.requiredSpace(content);
      } else {
        return content;
      }
    };
    _proto.newNode = function newNode(node2, namespace2) {
      if (namespace2) {
        if (/^ +$/.test(namespace2)) {
          if (!this.options.lossy) {
            this.spaces = (this.spaces || "") + namespace2;
          }
          namespace2 = true;
        }
        node2.namespace = namespace2;
        unescapeProp(node2, "namespace");
      }
      if (this.spaces) {
        node2.spaces.before = this.spaces;
        this.spaces = "";
      }
      return this.current.append(node2);
    };
    _proto.content = function content(token) {
      if (token === void 0) {
        token = this.currToken;
      }
      return this.css.slice(token[_tokenize.FIELDS.START_POS], token[_tokenize.FIELDS.END_POS]);
    };
    _proto.locateNextMeaningfulToken = function locateNextMeaningfulToken(startPosition) {
      if (startPosition === void 0) {
        startPosition = this.position + 1;
      }
      var searchPosition = startPosition;
      while (searchPosition < this.tokens.length) {
        if (WHITESPACE_EQUIV_TOKENS[this.tokens[searchPosition][_tokenize.FIELDS.TYPE]]) {
          searchPosition++;
          continue;
        } else {
          return searchPosition;
        }
      }
      return -1;
    };
    _createClass(Parser7, [{
      key: "currToken",
      get: function get2() {
        return this.tokens[this.position];
      }
    }, {
      key: "nextToken",
      get: function get2() {
        return this.tokens[this.position + 1];
      }
    }, {
      key: "prevToken",
      get: function get2() {
        return this.tokens[this.position - 1];
      }
    }]);
    return Parser7;
  }();
  exports2["default"] = Parser6;
  module2.exports = exports2.default;
})(parser, parserExports);
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2["default"] = void 0;
  var _parser = _interopRequireDefault2(parserExports);
  function _interopRequireDefault2(obj) {
    return obj && obj.__esModule ? obj : { "default": obj };
  }
  var Processor3 = /* @__PURE__ */ function() {
    function Processor4(func, options) {
      this.func = func || function noop2() {
      };
      this.funcRes = null;
      this.options = options;
    }
    var _proto = Processor4.prototype;
    _proto._shouldUpdateSelector = function _shouldUpdateSelector(rule2, options) {
      if (options === void 0) {
        options = {};
      }
      var merged = Object.assign({}, this.options, options);
      if (merged.updateSelector === false) {
        return false;
      } else {
        return typeof rule2 !== "string";
      }
    };
    _proto._isLossy = function _isLossy(options) {
      if (options === void 0) {
        options = {};
      }
      var merged = Object.assign({}, this.options, options);
      if (merged.lossless === false) {
        return true;
      } else {
        return false;
      }
    };
    _proto._root = function _root2(rule2, options) {
      if (options === void 0) {
        options = {};
      }
      var parser2 = new _parser["default"](rule2, this._parseOptions(options));
      return parser2.root;
    };
    _proto._parseOptions = function _parseOptions(options) {
      return {
        lossy: this._isLossy(options)
      };
    };
    _proto._run = function _run(rule2, options) {
      var _this = this;
      if (options === void 0) {
        options = {};
      }
      return new Promise(function(resolve2, reject) {
        try {
          var root3 = _this._root(rule2, options);
          Promise.resolve(_this.func(root3)).then(function(transform) {
            var string3 = void 0;
            if (_this._shouldUpdateSelector(rule2, options)) {
              string3 = root3.toString();
              rule2.selector = string3;
            }
            return {
              transform,
              root: root3,
              string: string3
            };
          }).then(resolve2, reject);
        } catch (e) {
          reject(e);
          return;
        }
      });
    };
    _proto._runSync = function _runSync(rule2, options) {
      if (options === void 0) {
        options = {};
      }
      var root3 = this._root(rule2, options);
      var transform = this.func(root3);
      if (transform && typeof transform.then === "function") {
        throw new Error("Selector processor returned a promise to a synchronous call.");
      }
      var string3 = void 0;
      if (options.updateSelector && typeof rule2 !== "string") {
        string3 = root3.toString();
        rule2.selector = string3;
      }
      return {
        transform,
        root: root3,
        string: string3
      };
    };
    _proto.ast = function ast(rule2, options) {
      return this._run(rule2, options).then(function(result2) {
        return result2.root;
      });
    };
    _proto.astSync = function astSync(rule2, options) {
      return this._runSync(rule2, options).root;
    };
    _proto.transform = function transform(rule2, options) {
      return this._run(rule2, options).then(function(result2) {
        return result2.transform;
      });
    };
    _proto.transformSync = function transformSync(rule2, options) {
      return this._runSync(rule2, options).transform;
    };
    _proto.process = function process2(rule2, options) {
      return this._run(rule2, options).then(function(result2) {
        return result2.string || result2.root.toString();
      });
    };
    _proto.processSync = function processSync(rule2, options) {
      var result2 = this._runSync(rule2, options);
      return result2.string || result2.root.toString();
    };
    return Processor4;
  }();
  exports2["default"] = Processor3;
  module2.exports = exports2.default;
})(processor, processorExports);
var selectors = {};
var constructors = {};
constructors.__esModule = true;
constructors.universal = constructors.tag = constructors.string = constructors.selector = constructors.root = constructors.pseudo = constructors.nesting = constructors.id = constructors.comment = constructors.combinator = constructors.className = constructors.attribute = void 0;
var _attribute = _interopRequireDefault(attribute$1);
var _className = _interopRequireDefault(classNameExports);
var _combinator = _interopRequireDefault(combinatorExports);
var _comment = _interopRequireDefault(commentExports);
var _id = _interopRequireDefault(idExports);
var _nesting = _interopRequireDefault(nestingExports);
var _pseudo = _interopRequireDefault(pseudoExports);
var _root = _interopRequireDefault(rootExports);
var _selector = _interopRequireDefault(selectorExports);
var _string = _interopRequireDefault(stringExports);
var _tag = _interopRequireDefault(tagExports);
var _universal = _interopRequireDefault(universalExports);
function _interopRequireDefault(obj) {
  return obj && obj.__esModule ? obj : { "default": obj };
}
var attribute = function attribute2(opts) {
  return new _attribute["default"](opts);
};
constructors.attribute = attribute;
var className = function className2(opts) {
  return new _className["default"](opts);
};
constructors.className = className;
var combinator = function combinator2(opts) {
  return new _combinator["default"](opts);
};
constructors.combinator = combinator;
var comment = function comment2(opts) {
  return new _comment["default"](opts);
};
constructors.comment = comment;
var id = function id2(opts) {
  return new _id["default"](opts);
};
constructors.id = id;
var nesting = function nesting2(opts) {
  return new _nesting["default"](opts);
};
constructors.nesting = nesting;
var pseudo = function pseudo2(opts) {
  return new _pseudo["default"](opts);
};
constructors.pseudo = pseudo;
var root = function root2(opts) {
  return new _root["default"](opts);
};
constructors.root = root;
var selector = function selector2(opts) {
  return new _selector["default"](opts);
};
constructors.selector = selector;
var string = function string2(opts) {
  return new _string["default"](opts);
};
constructors.string = string;
var tag = function tag2(opts) {
  return new _tag["default"](opts);
};
constructors.tag = tag;
var universal = function universal2(opts) {
  return new _universal["default"](opts);
};
constructors.universal = universal;
var guards = {};
guards.__esModule = true;
guards.isNode = isNode;
guards.isPseudoElement = isPseudoElement;
guards.isPseudoClass = isPseudoClass;
guards.isContainer = isContainer;
guards.isNamespace = isNamespace;
guards.isUniversal = guards.isTag = guards.isString = guards.isSelector = guards.isRoot = guards.isPseudo = guards.isNesting = guards.isIdentifier = guards.isComment = guards.isCombinator = guards.isClassName = guards.isAttribute = void 0;
var _types = types;
var _IS_TYPE;
var IS_TYPE = (_IS_TYPE = {}, _IS_TYPE[_types.ATTRIBUTE] = true, _IS_TYPE[_types.CLASS] = true, _IS_TYPE[_types.COMBINATOR] = true, _IS_TYPE[_types.COMMENT] = true, _IS_TYPE[_types.ID] = true, _IS_TYPE[_types.NESTING] = true, _IS_TYPE[_types.PSEUDO] = true, _IS_TYPE[_types.ROOT] = true, _IS_TYPE[_types.SELECTOR] = true, _IS_TYPE[_types.STRING] = true, _IS_TYPE[_types.TAG] = true, _IS_TYPE[_types.UNIVERSAL] = true, _IS_TYPE);
function isNode(node2) {
  return typeof node2 === "object" && IS_TYPE[node2.type];
}
function isNodeType(type, node2) {
  return isNode(node2) && node2.type === type;
}
var isAttribute = isNodeType.bind(null, _types.ATTRIBUTE);
guards.isAttribute = isAttribute;
var isClassName = isNodeType.bind(null, _types.CLASS);
guards.isClassName = isClassName;
var isCombinator = isNodeType.bind(null, _types.COMBINATOR);
guards.isCombinator = isCombinator;
var isComment = isNodeType.bind(null, _types.COMMENT);
guards.isComment = isComment;
var isIdentifier = isNodeType.bind(null, _types.ID);
guards.isIdentifier = isIdentifier;
var isNesting = isNodeType.bind(null, _types.NESTING);
guards.isNesting = isNesting;
var isPseudo = isNodeType.bind(null, _types.PSEUDO);
guards.isPseudo = isPseudo;
var isRoot = isNodeType.bind(null, _types.ROOT);
guards.isRoot = isRoot;
var isSelector = isNodeType.bind(null, _types.SELECTOR);
guards.isSelector = isSelector;
var isString = isNodeType.bind(null, _types.STRING);
guards.isString = isString;
var isTag = isNodeType.bind(null, _types.TAG);
guards.isTag = isTag;
var isUniversal = isNodeType.bind(null, _types.UNIVERSAL);
guards.isUniversal = isUniversal;
function isPseudoElement(node2) {
  return isPseudo(node2) && node2.value && (node2.value.startsWith("::") || node2.value.toLowerCase() === ":before" || node2.value.toLowerCase() === ":after" || node2.value.toLowerCase() === ":first-letter" || node2.value.toLowerCase() === ":first-line");
}
function isPseudoClass(node2) {
  return isPseudo(node2) && !isPseudoElement(node2);
}
function isContainer(node2) {
  return !!(isNode(node2) && node2.walk);
}
function isNamespace(node2) {
  return isAttribute(node2) || isTag(node2);
}
(function(exports2) {
  exports2.__esModule = true;
  var _types2 = types;
  Object.keys(_types2).forEach(function(key) {
    if (key === "default" || key === "__esModule")
      return;
    if (key in exports2 && exports2[key] === _types2[key])
      return;
    exports2[key] = _types2[key];
  });
  var _constructors = constructors;
  Object.keys(_constructors).forEach(function(key) {
    if (key === "default" || key === "__esModule")
      return;
    if (key in exports2 && exports2[key] === _constructors[key])
      return;
    exports2[key] = _constructors[key];
  });
  var _guards = guards;
  Object.keys(_guards).forEach(function(key) {
    if (key === "default" || key === "__esModule")
      return;
    if (key in exports2 && exports2[key] === _guards[key])
      return;
    exports2[key] = _guards[key];
  });
})(selectors);
(function(module2, exports2) {
  exports2.__esModule = true;
  exports2["default"] = void 0;
  var _processor = _interopRequireDefault2(processorExports);
  var selectors$1 = _interopRequireWildcard(selectors);
  function _getRequireWildcardCache() {
    if (typeof WeakMap !== "function")
      return null;
    var cache2 = /* @__PURE__ */ new WeakMap();
    _getRequireWildcardCache = function _getRequireWildcardCache2() {
      return cache2;
    };
    return cache2;
  }
  function _interopRequireWildcard(obj) {
    if (obj && obj.__esModule) {
      return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
      return { "default": obj };
    }
    var cache2 = _getRequireWildcardCache();
    if (cache2 && cache2.has(obj)) {
      return cache2.get(obj);
    }
    var newObj = {};
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for (var key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
        if (desc && (desc.get || desc.set)) {
          Object.defineProperty(newObj, key, desc);
        } else {
          newObj[key] = obj[key];
        }
      }
    }
    newObj["default"] = obj;
    if (cache2) {
      cache2.set(obj, newObj);
    }
    return newObj;
  }
  function _interopRequireDefault2(obj) {
    return obj && obj.__esModule ? obj : { "default": obj };
  }
  var parser2 = function parser3(processor2) {
    return new _processor["default"](processor2);
  };
  Object.assign(parser2, selectors$1);
  delete parser2.__esModule;
  var _default = parser2;
  exports2["default"] = _default;
  module2.exports = exports2.default;
})(dist, distExports);
var sourceMapGenerator = {};
var base64Vlq = {};
var base64$1 = {};
var intToCharMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
base64$1.encode = function(number) {
  if (0 <= number && number < intToCharMap.length) {
    return intToCharMap[number];
  }
  throw new TypeError("Must be between 0 and 63: " + number);
};
base64$1.decode = function(charCode) {
  var bigA = 65;
  var bigZ = 90;
  var littleA = 97;
  var littleZ = 122;
  var zero = 48;
  var nine = 57;
  var plus2 = 43;
  var slash2 = 47;
  var littleOffset = 26;
  var numberOffset = 52;
  if (bigA <= charCode && charCode <= bigZ) {
    return charCode - bigA;
  }
  if (littleA <= charCode && charCode <= littleZ) {
    return charCode - littleA + littleOffset;
  }
  if (zero <= charCode && charCode <= nine) {
    return charCode - zero + numberOffset;
  }
  if (charCode == plus2) {
    return 62;
  }
  if (charCode == slash2) {
    return 63;
  }
  return -1;
};
var base64 = base64$1;
var VLQ_BASE_SHIFT = 5;
var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
var VLQ_BASE_MASK = VLQ_BASE - 1;
var VLQ_CONTINUATION_BIT = VLQ_BASE;
function toVLQSigned(aValue) {
  return aValue < 0 ? (-aValue << 1) + 1 : (aValue << 1) + 0;
}
function fromVLQSigned(aValue) {
  var isNegative = (aValue & 1) === 1;
  var shifted = aValue >> 1;
  return isNegative ? -shifted : shifted;
}
base64Vlq.encode = function base64VLQ_encode2(aValue) {
  var encoded = "";
  var digit;
  var vlq = toVLQSigned(aValue);
  do {
    digit = vlq & VLQ_BASE_MASK;
    vlq >>>= VLQ_BASE_SHIFT;
    if (vlq > 0) {
      digit |= VLQ_CONTINUATION_BIT;
    }
    encoded += base64.encode(digit);
  } while (vlq > 0);
  return encoded;
};
base64Vlq.decode = function base64VLQ_decode2(aStr, aIndex, aOutParam) {
  var strLen = aStr.length;
  var result2 = 0;
  var shift2 = 0;
  var continuation, digit;
  do {
    if (aIndex >= strLen) {
      throw new Error("Expected more digits in base 64 VLQ value.");
    }
    digit = base64.decode(aStr.charCodeAt(aIndex++));
    if (digit === -1) {
      throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
    }
    continuation = !!(digit & VLQ_CONTINUATION_BIT);
    digit &= VLQ_BASE_MASK;
    result2 = result2 + (digit << shift2);
    shift2 += VLQ_BASE_SHIFT;
  } while (continuation);
  aOutParam.value = fromVLQSigned(result2);
  aOutParam.rest = aIndex;
};
var util$5 = {};
(function(exports2) {
  function getArg(aArgs, aName, aDefaultValue) {
    if (aName in aArgs) {
      return aArgs[aName];
    } else if (arguments.length === 3) {
      return aDefaultValue;
    } else {
      throw new Error('"' + aName + '" is a required argument.');
    }
  }
  exports2.getArg = getArg;
  var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/;
  var dataUrlRegexp = /^data:.+\,.+$/;
  function urlParse2(aUrl) {
    var match2 = aUrl.match(urlRegexp);
    if (!match2) {
      return null;
    }
    return {
      scheme: match2[1],
      auth: match2[2],
      host: match2[3],
      port: match2[4],
      path: match2[5]
    };
  }
  exports2.urlParse = urlParse2;
  function urlGenerate(aParsedUrl) {
    var url = "";
    if (aParsedUrl.scheme) {
      url += aParsedUrl.scheme + ":";
    }
    url += "//";
    if (aParsedUrl.auth) {
      url += aParsedUrl.auth + "@";
    }
    if (aParsedUrl.host) {
      url += aParsedUrl.host;
    }
    if (aParsedUrl.port) {
      url += ":" + aParsedUrl.port;
    }
    if (aParsedUrl.path) {
      url += aParsedUrl.path;
    }
    return url;
  }
  exports2.urlGenerate = urlGenerate;
  function normalize2(aPath) {
    var path2 = aPath;
    var url = urlParse2(aPath);
    if (url) {
      if (!url.path) {
        return aPath;
      }
      path2 = url.path;
    }
    var isAbsolute2 = exports2.isAbsolute(path2);
    var parts = path2.split(/\/+/);
    for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
      part = parts[i];
      if (part === ".") {
        parts.splice(i, 1);
      } else if (part === "..") {
        up++;
      } else if (up > 0) {
        if (part === "") {
          parts.splice(i + 1, up);
          up = 0;
        } else {
          parts.splice(i, 2);
          up--;
        }
      }
    }
    path2 = parts.join("/");
    if (path2 === "") {
      path2 = isAbsolute2 ? "/" : ".";
    }
    if (url) {
      url.path = path2;
      return urlGenerate(url);
    }
    return path2;
  }
  exports2.normalize = normalize2;
  function join2(aRoot, aPath) {
    if (aRoot === "") {
      aRoot = ".";
    }
    if (aPath === "") {
      aPath = ".";
    }
    var aPathUrl = urlParse2(aPath);
    var aRootUrl = urlParse2(aRoot);
    if (aRootUrl) {
      aRoot = aRootUrl.path || "/";
    }
    if (aPathUrl && !aPathUrl.scheme) {
      if (aRootUrl) {
        aPathUrl.scheme = aRootUrl.scheme;
      }
      return urlGenerate(aPathUrl);
    }
    if (aPathUrl || aPath.match(dataUrlRegexp)) {
      return aPath;
    }
    if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
      aRootUrl.host = aPath;
      return urlGenerate(aRootUrl);
    }
    var joined = aPath.charAt(0) === "/" ? aPath : normalize2(aRoot.replace(/\/+$/, "") + "/" + aPath);
    if (aRootUrl) {
      aRootUrl.path = joined;
      return urlGenerate(aRootUrl);
    }
    return joined;
  }
  exports2.join = join2;
  exports2.isAbsolute = function(aPath) {
    return aPath.charAt(0) === "/" || urlRegexp.test(aPath);
  };
  function relative2(aRoot, aPath) {
    if (aRoot === "") {
      aRoot = ".";
    }
    aRoot = aRoot.replace(/\/$/, "");
    var level = 0;
    while (aPath.indexOf(aRoot + "/") !== 0) {
      var index = aRoot.lastIndexOf("/");
      if (index < 0) {
        return aPath;
      }
      aRoot = aRoot.slice(0, index);
      if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
        return aPath;
      }
      ++level;
    }
    return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  }
  exports2.relative = relative2;
  var supportsNullProto = function() {
    var obj = /* @__PURE__ */ Object.create(null);
    return !("__proto__" in obj);
  }();
  function identity(s) {
    return s;
  }
  function toSetString(aStr) {
    if (isProtoString(aStr)) {
      return "$" + aStr;
    }
    return aStr;
  }
  exports2.toSetString = supportsNullProto ? identity : toSetString;
  function fromSetString(aStr) {
    if (isProtoString(aStr)) {
      return aStr.slice(1);
    }
    return aStr;
  }
  exports2.fromSetString = supportsNullProto ? identity : fromSetString;
  function isProtoString(s) {
    if (!s) {
      return false;
    }
    var length2 = s.length;
    if (length2 < 9) {
      return false;
    }
    if (s.charCodeAt(length2 - 1) !== 95 || s.charCodeAt(length2 - 2) !== 95 || s.charCodeAt(length2 - 3) !== 111 || s.charCodeAt(length2 - 4) !== 116 || s.charCodeAt(length2 - 5) !== 111 || s.charCodeAt(length2 - 6) !== 114 || s.charCodeAt(length2 - 7) !== 112 || s.charCodeAt(length2 - 8) !== 95 || s.charCodeAt(length2 - 9) !== 95) {
      return false;
    }
    for (var i = length2 - 10; i >= 0; i--) {
      if (s.charCodeAt(i) !== 36) {
        return false;
      }
    }
    return true;
  }
  function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
    var cmp3 = strcmp2(mappingA.source, mappingB.source);
    if (cmp3 !== 0) {
      return cmp3;
    }
    cmp3 = mappingA.originalLine - mappingB.originalLine;
    if (cmp3 !== 0) {
      return cmp3;
    }
    cmp3 = mappingA.originalColumn - mappingB.originalColumn;
    if (cmp3 !== 0 || onlyCompareOriginal) {
      return cmp3;
    }
    cmp3 = mappingA.generatedColumn - mappingB.generatedColumn;
    if (cmp3 !== 0) {
      return cmp3;
    }
    cmp3 = mappingA.generatedLine - mappingB.generatedLine;
    if (cmp3 !== 0) {
      return cmp3;
    }
    return strcmp2(mappingA.name, mappingB.name);
  }
  exports2.compareByOriginalPositions = compareByOriginalPositions;
  function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
    var cmp3 = mappingA.generatedLine - mappingB.generatedLine;
    if (cmp3 !== 0) {
      return cmp3;
    }
    cmp3 = mappingA.generatedColumn - mappingB.generatedColumn;
    if (cmp3 !== 0 || onlyCompareGenerated) {
      return cmp3;
    }
    cmp3 = strcmp2(mappingA.source, mappingB.source);
    if (cmp3 !== 0) {
      return cmp3;
    }
    cmp3 = mappingA.originalLine - mappingB.originalLine;
    if (cmp3 !== 0) {
      return cmp3;
    }
    cmp3 = mappingA.originalColumn - mappingB.originalColumn;
    if (cmp3 !== 0) {
      return cmp3;
    }
    return strcmp2(mappingA.name, mappingB.name);
  }
  exports2.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  function strcmp2(aStr1, aStr2) {
    if (aStr1 === aStr2) {
      return 0;
    }
    if (aStr1 === null) {
      return 1;
    }
    if (aStr2 === null) {
      return -1;
    }
    if (aStr1 > aStr2) {
      return 1;
    }
    return -1;
  }
  function compareByGeneratedPositionsInflated(mappingA, mappingB) {
    var cmp3 = mappingA.generatedLine - mappingB.generatedLine;
    if (cmp3 !== 0) {
      return cmp3;
    }
    cmp3 = mappingA.generatedColumn - mappingB.generatedColumn;
    if (cmp3 !== 0) {
      return cmp3;
    }
    cmp3 = strcmp2(mappingA.source, mappingB.source);
    if (cmp3 !== 0) {
      return cmp3;
    }
    cmp3 = mappingA.originalLine - mappingB.originalLine;
    if (cmp3 !== 0) {
      return cmp3;
    }
    cmp3 = mappingA.originalColumn - mappingB.originalColumn;
    if (cmp3 !== 0) {
      return cmp3;
    }
    return strcmp2(mappingA.name, mappingB.name);
  }
  exports2.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  function parseSourceMapInput(str2) {
    return JSON.parse(str2.replace(/^\)]}'[^\n]*\n/, ""));
  }
  exports2.parseSourceMapInput = parseSourceMapInput;
  function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) {
    sourceURL = sourceURL || "";
    if (sourceRoot) {
      if (sourceRoot[sourceRoot.length - 1] !== "/" && sourceURL[0] !== "/") {
        sourceRoot += "/";
      }
      sourceURL = sourceRoot + sourceURL;
    }
    if (sourceMapURL) {
      var parsed = urlParse2(sourceMapURL);
      if (!parsed) {
        throw new Error("sourceMapURL could not be parsed");
      }
      if (parsed.path) {
        var index = parsed.path.lastIndexOf("/");
        if (index >= 0) {
          parsed.path = parsed.path.substring(0, index + 1);
        }
      }
      sourceURL = join2(urlGenerate(parsed), sourceURL);
    }
    return normalize2(sourceURL);
  }
  exports2.computeSourceURL = computeSourceURL;
})(util$5);
var arraySet = {};
var util$4 = util$5;
var has = Object.prototype.hasOwnProperty;
var hasNativeMap = typeof Map !== "undefined";
function ArraySet$2() {
  this._array = [];
  this._set = hasNativeMap ? /* @__PURE__ */ new Map() : /* @__PURE__ */ Object.create(null);
}
ArraySet$2.fromArray = function ArraySet_fromArray2(aArray, aAllowDuplicates) {
  var set2 = new ArraySet$2();
  for (var i = 0, len = aArray.length; i < len; i++) {
    set2.add(aArray[i], aAllowDuplicates);
  }
  return set2;
};
ArraySet$2.prototype.size = function ArraySet_size2() {
  return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
};
ArraySet$2.prototype.add = function ArraySet_add2(aStr, aAllowDuplicates) {
  var sStr = hasNativeMap ? aStr : util$4.toSetString(aStr);
  var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr);
  var idx = this._array.length;
  if (!isDuplicate || aAllowDuplicates) {
    this._array.push(aStr);
  }
  if (!isDuplicate) {
    if (hasNativeMap) {
      this._set.set(aStr, idx);
    } else {
      this._set[sStr] = idx;
    }
  }
};
ArraySet$2.prototype.has = function ArraySet_has2(aStr) {
  if (hasNativeMap) {
    return this._set.has(aStr);
  } else {
    var sStr = util$4.toSetString(aStr);
    return has.call(this._set, sStr);
  }
};
ArraySet$2.prototype.indexOf = function ArraySet_indexOf2(aStr) {
  if (hasNativeMap) {
    var idx = this._set.get(aStr);
    if (idx >= 0) {
      return idx;
    }
  } else {
    var sStr = util$4.toSetString(aStr);
    if (has.call(this._set, sStr)) {
      return this._set[sStr];
    }
  }
  throw new Error('"' + aStr + '" is not in the set.');
};
ArraySet$2.prototype.at = function ArraySet_at2(aIdx) {
  if (aIdx >= 0 && aIdx < this._array.length) {
    return this._array[aIdx];
  }
  throw new Error("No element indexed by " + aIdx);
};
ArraySet$2.prototype.toArray = function ArraySet_toArray2() {
  return this._array.slice();
};
arraySet.ArraySet = ArraySet$2;
var mappingList = {};
var util$3 = util$5;
function generatedPositionAfter(mappingA, mappingB) {
  var lineA = mappingA.generatedLine;
  var lineB = mappingB.generatedLine;
  var columnA = mappingA.generatedColumn;
  var columnB = mappingB.generatedColumn;
  return lineB > lineA || lineB == lineA && columnB >= columnA || util$3.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
}
function MappingList$1() {
  this._array = [];
  this._sorted = true;
  this._last = { generatedLine: -1, generatedColumn: 0 };
}
MappingList$1.prototype.unsortedForEach = function MappingList_forEach2(aCallback, aThisArg) {
  this._array.forEach(aCallback, aThisArg);
};
MappingList$1.prototype.add = function MappingList_add2(aMapping) {
  if (generatedPositionAfter(this._last, aMapping)) {
    this._last = aMapping;
    this._array.push(aMapping);
  } else {
    this._sorted = false;
    this._array.push(aMapping);
  }
};
MappingList$1.prototype.toArray = function MappingList_toArray2() {
  if (!this._sorted) {
    this._array.sort(util$3.compareByGeneratedPositionsInflated);
    this._sorted = true;
  }
  return this._array;
};
mappingList.MappingList = MappingList$1;
var base64VLQ$1 = base64Vlq;
var util$2 = util$5;
var ArraySet$1 = arraySet.ArraySet;
var MappingList = mappingList.MappingList;
function SourceMapGenerator$2(aArgs) {
  if (!aArgs) {
    aArgs = {};
  }
  this._file = util$2.getArg(aArgs, "file", null);
  this._sourceRoot = util$2.getArg(aArgs, "sourceRoot", null);
  this._skipValidation = util$2.getArg(aArgs, "skipValidation", false);
  this._sources = new ArraySet$1();
  this._names = new ArraySet$1();
  this._mappings = new MappingList();
  this._sourcesContents = null;
}
SourceMapGenerator$2.prototype._version = 3;
SourceMapGenerator$2.fromSourceMap = function SourceMapGenerator_fromSourceMap2(aSourceMapConsumer) {
  var sourceRoot = aSourceMapConsumer.sourceRoot;
  var generator = new SourceMapGenerator$2({
    file: aSourceMapConsumer.file,
    sourceRoot
  });
  aSourceMapConsumer.eachMapping(function(mapping) {
    var newMapping = {
      generated: {
        line: mapping.generatedLine,
        column: mapping.generatedColumn
      }
    };
    if (mapping.source != null) {
      newMapping.source = mapping.source;
      if (sourceRoot != null) {
        newMapping.source = util$2.relative(sourceRoot, newMapping.source);
      }
      newMapping.original = {
        line: mapping.originalLine,
        column: mapping.originalColumn
      };
      if (mapping.name != null) {
        newMapping.name = mapping.name;
      }
    }
    generator.addMapping(newMapping);
  });
  aSourceMapConsumer.sources.forEach(function(sourceFile) {
    var sourceRelative = sourceFile;
    if (sourceRoot !== null) {
      sourceRelative = util$2.relative(sourceRoot, sourceFile);
    }
    if (!generator._sources.has(sourceRelative)) {
      generator._sources.add(sourceRelative);
    }
    var content = aSourceMapConsumer.sourceContentFor(sourceFile);
    if (content != null) {
      generator.setSourceContent(sourceFile, content);
    }
  });
  return generator;
};
SourceMapGenerator$2.prototype.addMapping = function SourceMapGenerator_addMapping2(aArgs) {
  var generated = util$2.getArg(aArgs, "generated");
  var original = util$2.getArg(aArgs, "original", null);
  var source = util$2.getArg(aArgs, "source", null);
  var name = util$2.getArg(aArgs, "name", null);
  if (!this._skipValidation) {
    this._validateMapping(generated, original, source, name);
  }
  if (source != null) {
    source = String(source);
    if (!this._sources.has(source)) {
      this._sources.add(source);
    }
  }
  if (name != null) {
    name = String(name);
    if (!this._names.has(name)) {
      this._names.add(name);
    }
  }
  this._mappings.add({
    generatedLine: generated.line,
    generatedColumn: generated.column,
    originalLine: original != null && original.line,
    originalColumn: original != null && original.column,
    source,
    name
  });
};
SourceMapGenerator$2.prototype.setSourceContent = function SourceMapGenerator_setSourceContent2(aSourceFile, aSourceContent) {
  var source = aSourceFile;
  if (this._sourceRoot != null) {
    source = util$2.relative(this._sourceRoot, source);
  }
  if (aSourceContent != null) {
    if (!this._sourcesContents) {
      this._sourcesContents = /* @__PURE__ */ Object.create(null);
    }
    this._sourcesContents[util$2.toSetString(source)] = aSourceContent;
  } else if (this._sourcesContents) {
    delete this._sourcesContents[util$2.toSetString(source)];
    if (Object.keys(this._sourcesContents).length === 0) {
      this._sourcesContents = null;
    }
  }
};
SourceMapGenerator$2.prototype.applySourceMap = function SourceMapGenerator_applySourceMap2(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  var sourceFile = aSourceFile;
  if (aSourceFile == null) {
    if (aSourceMapConsumer.file == null) {
      throw new Error(
        `SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`
      );
    }
    sourceFile = aSourceMapConsumer.file;
  }
  var sourceRoot = this._sourceRoot;
  if (sourceRoot != null) {
    sourceFile = util$2.relative(sourceRoot, sourceFile);
  }
  var newSources = new ArraySet$1();
  var newNames = new ArraySet$1();
  this._mappings.unsortedForEach(function(mapping) {
    if (mapping.source === sourceFile && mapping.originalLine != null) {
      var original = aSourceMapConsumer.originalPositionFor({
        line: mapping.originalLine,
        column: mapping.originalColumn
      });
      if (original.source != null) {
        mapping.source = original.source;
        if (aSourceMapPath != null) {
          mapping.source = util$2.join(aSourceMapPath, mapping.source);
        }
        if (sourceRoot != null) {
          mapping.source = util$2.relative(sourceRoot, mapping.source);
        }
        mapping.originalLine = original.line;
        mapping.originalColumn = original.column;
        if (original.name != null) {
          mapping.name = original.name;
        }
      }
    }
    var source = mapping.source;
    if (source != null && !newSources.has(source)) {
      newSources.add(source);
    }
    var name = mapping.name;
    if (name != null && !newNames.has(name)) {
      newNames.add(name);
    }
  }, this);
  this._sources = newSources;
  this._names = newNames;
  aSourceMapConsumer.sources.forEach(function(sourceFile2) {
    var content = aSourceMapConsumer.sourceContentFor(sourceFile2);
    if (content != null) {
      if (aSourceMapPath != null) {
        sourceFile2 = util$2.join(aSourceMapPath, sourceFile2);
      }
      if (sourceRoot != null) {
        sourceFile2 = util$2.relative(sourceRoot, sourceFile2);
      }
      this.setSourceContent(sourceFile2, content);
    }
  }, this);
};
SourceMapGenerator$2.prototype._validateMapping = function SourceMapGenerator_validateMapping2(aGenerated, aOriginal, aSource, aName) {
  if (aOriginal && typeof aOriginal.line !== "number" && typeof aOriginal.column !== "number") {
    throw new Error(
      "original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values."
    );
  }
  if (aGenerated && "line" in aGenerated && "column" in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) {
    return;
  } else if (aGenerated && "line" in aGenerated && "column" in aGenerated && aOriginal && "line" in aOriginal && "column" in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) {
    return;
  } else {
    throw new Error("Invalid mapping: " + JSON.stringify({
      generated: aGenerated,
      source: aSource,
      original: aOriginal,
      name: aName
    }));
  }
};
SourceMapGenerator$2.prototype._serializeMappings = function SourceMapGenerator_serializeMappings2() {
  var previousGeneratedColumn = 0;
  var previousGeneratedLine = 1;
  var previousOriginalColumn = 0;
  var previousOriginalLine = 0;
  var previousName = 0;
  var previousSource = 0;
  var result2 = "";
  var next;
  var mapping;
  var nameIdx;
  var sourceIdx;
  var mappings = this._mappings.toArray();
  for (var i = 0, len = mappings.length; i < len; i++) {
    mapping = mappings[i];
    next = "";
    if (mapping.generatedLine !== previousGeneratedLine) {
      previousGeneratedColumn = 0;
      while (mapping.generatedLine !== previousGeneratedLine) {
        next += ";";
        previousGeneratedLine++;
      }
    } else {
      if (i > 0) {
        if (!util$2.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
          continue;
        }
        next += ",";
      }
    }
    next += base64VLQ$1.encode(mapping.generatedColumn - previousGeneratedColumn);
    previousGeneratedColumn = mapping.generatedColumn;
    if (mapping.source != null) {
      sourceIdx = this._sources.indexOf(mapping.source);
      next += base64VLQ$1.encode(sourceIdx - previousSource);
      previousSource = sourceIdx;
      next += base64VLQ$1.encode(mapping.originalLine - 1 - previousOriginalLine);
      previousOriginalLine = mapping.originalLine - 1;
      next += base64VLQ$1.encode(mapping.originalColumn - previousOriginalColumn);
      previousOriginalColumn = mapping.originalColumn;
      if (mapping.name != null) {
        nameIdx = this._names.indexOf(mapping.name);
        next += base64VLQ$1.encode(nameIdx - previousName);
        previousName = nameIdx;
      }
    }
    result2 += next;
  }
  return result2;
};
SourceMapGenerator$2.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent2(aSources, aSourceRoot) {
  return aSources.map(function(source) {
    if (!this._sourcesContents) {
      return null;
    }
    if (aSourceRoot != null) {
      source = util$2.relative(aSourceRoot, source);
    }
    var key = util$2.toSetString(source);
    return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null;
  }, this);
};
SourceMapGenerator$2.prototype.toJSON = function SourceMapGenerator_toJSON2() {
  var map2 = {
    version: this._version,
    sources: this._sources.toArray(),
    names: this._names.toArray(),
    mappings: this._serializeMappings()
  };
  if (this._file != null) {
    map2.file = this._file;
  }
  if (this._sourceRoot != null) {
    map2.sourceRoot = this._sourceRoot;
  }
  if (this._sourcesContents) {
    map2.sourcesContent = this._generateSourcesContent(map2.sources, map2.sourceRoot);
  }
  return map2;
};
SourceMapGenerator$2.prototype.toString = function SourceMapGenerator_toString2() {
  return JSON.stringify(this.toJSON());
};
sourceMapGenerator.SourceMapGenerator = SourceMapGenerator$2;
var binarySearch$1 = {};
(function(exports2) {
  exports2.GREATEST_LOWER_BOUND = 1;
  exports2.LEAST_UPPER_BOUND = 2;
  function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
    var mid = Math.floor((aHigh - aLow) / 2) + aLow;
    var cmp3 = aCompare(aNeedle, aHaystack[mid], true);
    if (cmp3 === 0) {
      return mid;
    } else if (cmp3 > 0) {
      if (aHigh - mid > 1) {
        return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
      }
      if (aBias == exports2.LEAST_UPPER_BOUND) {
        return aHigh < aHaystack.length ? aHigh : -1;
      } else {
        return mid;
      }
    } else {
      if (mid - aLow > 1) {
        return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
      }
      if (aBias == exports2.LEAST_UPPER_BOUND) {
        return mid;
      } else {
        return aLow < 0 ? -1 : aLow;
      }
    }
  }
  exports2.search = function search2(aNeedle, aHaystack, aCompare, aBias) {
    if (aHaystack.length === 0) {
      return -1;
    }
    var index = recursiveSearch(
      -1,
      aHaystack.length,
      aNeedle,
      aHaystack,
      aCompare,
      aBias || exports2.GREATEST_LOWER_BOUND
    );
    if (index < 0) {
      return -1;
    }
    while (index - 1 >= 0) {
      if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
        break;
      }
      --index;
    }
    return index;
  };
})(binarySearch$1);
var quickSort$1 = {};
function swap(ary, x, y) {
  var temp = ary[x];
  ary[x] = ary[y];
  ary[y] = temp;
}
function randomIntInRange(low, high) {
  return Math.round(low + Math.random() * (high - low));
}
function doQuickSort(ary, comparator2, p2, r) {
  if (p2 < r) {
    var pivotIndex = randomIntInRange(p2, r);
    var i = p2 - 1;
    swap(ary, pivotIndex, r);
    var pivot = ary[r];
    for (var j = p2; j < r; j++) {
      if (comparator2(ary[j], pivot) <= 0) {
        i += 1;
        swap(ary, i, j);
      }
    }
    swap(ary, i + 1, j);
    var q = i + 1;
    doQuickSort(ary, comparator2, p2, q - 1);
    doQuickSort(ary, comparator2, q + 1, r);
  }
}
quickSort$1.quickSort = function(ary, comparator2) {
  doQuickSort(ary, comparator2, 0, ary.length - 1);
};
var util$1 = util$5;
var binarySearch = binarySearch$1;
var ArraySet = arraySet.ArraySet;
var base64VLQ = base64Vlq;
var quickSort = quickSort$1.quickSort;
function SourceMapConsumer$1(aSourceMap, aSourceMapURL) {
  var sourceMap = aSourceMap;
  if (typeof aSourceMap === "string") {
    sourceMap = util$1.parseSourceMapInput(aSourceMap);
  }
  return sourceMap.sections != null ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) : new BasicSourceMapConsumer(sourceMap, aSourceMapURL);
}
SourceMapConsumer$1.fromSourceMap = function(aSourceMap, aSourceMapURL) {
  return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL);
};
SourceMapConsumer$1.prototype._version = 3;
SourceMapConsumer$1.prototype.__generatedMappings = null;
Object.defineProperty(SourceMapConsumer$1.prototype, "_generatedMappings", {
  configurable: true,
  enumerable: true,
  get: function() {
    if (!this.__generatedMappings) {
      this._parseMappings(this._mappings, this.sourceRoot);
    }
    return this.__generatedMappings;
  }
});
SourceMapConsumer$1.prototype.__originalMappings = null;
Object.defineProperty(SourceMapConsumer$1.prototype, "_originalMappings", {
  configurable: true,
  enumerable: true,
  get: function() {
    if (!this.__originalMappings) {
      this._parseMappings(this._mappings, this.sourceRoot);
    }
    return this.__originalMappings;
  }
});
SourceMapConsumer$1.prototype._charIsMappingSeparator = function SourceMapConsumer_charIsMappingSeparator2(aStr, index) {
  var c = aStr.charAt(index);
  return c === ";" || c === ",";
};
SourceMapConsumer$1.prototype._parseMappings = function SourceMapConsumer_parseMappings3(aStr, aSourceRoot) {
  throw new Error("Subclasses must implement _parseMappings");
};
SourceMapConsumer$1.GENERATED_ORDER = 1;
SourceMapConsumer$1.ORIGINAL_ORDER = 2;
SourceMapConsumer$1.GREATEST_LOWER_BOUND = 1;
SourceMapConsumer$1.LEAST_UPPER_BOUND = 2;
SourceMapConsumer$1.prototype.eachMapping = function SourceMapConsumer_eachMapping2(aCallback, aContext, aOrder) {
  var context = aContext || null;
  var order = aOrder || SourceMapConsumer$1.GENERATED_ORDER;
  var mappings;
  switch (order) {
    case SourceMapConsumer$1.GENERATED_ORDER:
      mappings = this._generatedMappings;
      break;
    case SourceMapConsumer$1.ORIGINAL_ORDER:
      mappings = this._originalMappings;
      break;
    default:
      throw new Error("Unknown order of iteration.");
  }
  var sourceRoot = this.sourceRoot;
  mappings.map(function(mapping) {
    var source = mapping.source === null ? null : this._sources.at(mapping.source);
    source = util$1.computeSourceURL(sourceRoot, source, this._sourceMapURL);
    return {
      source,
      generatedLine: mapping.generatedLine,
      generatedColumn: mapping.generatedColumn,
      originalLine: mapping.originalLine,
      originalColumn: mapping.originalColumn,
      name: mapping.name === null ? null : this._names.at(mapping.name)
    };
  }, this).forEach(aCallback, context);
};
SourceMapConsumer$1.prototype.allGeneratedPositionsFor = function SourceMapConsumer_allGeneratedPositionsFor2(aArgs) {
  var line = util$1.getArg(aArgs, "line");
  var needle = {
    source: util$1.getArg(aArgs, "source"),
    originalLine: line,
    originalColumn: util$1.getArg(aArgs, "column", 0)
  };
  needle.source = this._findSourceIndex(needle.source);
  if (needle.source < 0) {
    return [];
  }
  var mappings = [];
  var index = this._findMapping(
    needle,
    this._originalMappings,
    "originalLine",
    "originalColumn",
    util$1.compareByOriginalPositions,
    binarySearch.LEAST_UPPER_BOUND
  );
  if (index >= 0) {
    var mapping = this._originalMappings[index];
    if (aArgs.column === void 0) {
      var originalLine = mapping.originalLine;
      while (mapping && mapping.originalLine === originalLine) {
        mappings.push({
          line: util$1.getArg(mapping, "generatedLine", null),
          column: util$1.getArg(mapping, "generatedColumn", null),
          lastColumn: util$1.getArg(mapping, "lastGeneratedColumn", null)
        });
        mapping = this._originalMappings[++index];
      }
    } else {
      var originalColumn = mapping.originalColumn;
      while (mapping && mapping.originalLine === line && mapping.originalColumn == originalColumn) {
        mappings.push({
          line: util$1.getArg(mapping, "generatedLine", null),
          column: util$1.getArg(mapping, "generatedColumn", null),
          lastColumn: util$1.getArg(mapping, "lastGeneratedColumn", null)
        });
        mapping = this._originalMappings[++index];
      }
    }
  }
  return mappings;
};
function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) {
  var sourceMap = aSourceMap;
  if (typeof aSourceMap === "string") {
    sourceMap = util$1.parseSourceMapInput(aSourceMap);
  }
  var version2 = util$1.getArg(sourceMap, "version");
  var sources = util$1.getArg(sourceMap, "sources");
  var names = util$1.getArg(sourceMap, "names", []);
  var sourceRoot = util$1.getArg(sourceMap, "sourceRoot", null);
  var sourcesContent = util$1.getArg(sourceMap, "sourcesContent", null);
  var mappings = util$1.getArg(sourceMap, "mappings");
  var file = util$1.getArg(sourceMap, "file", null);
  if (version2 != this._version) {
    throw new Error("Unsupported version: " + version2);
  }
  if (sourceRoot) {
    sourceRoot = util$1.normalize(sourceRoot);
  }
  sources = sources.map(String).map(util$1.normalize).map(function(source) {
    return sourceRoot && util$1.isAbsolute(sourceRoot) && util$1.isAbsolute(source) ? util$1.relative(sourceRoot, source) : source;
  });
  this._names = ArraySet.fromArray(names.map(String), true);
  this._sources = ArraySet.fromArray(sources, true);
  this._absoluteSources = this._sources.toArray().map(function(s) {
    return util$1.computeSourceURL(sourceRoot, s, aSourceMapURL);
  });
  this.sourceRoot = sourceRoot;
  this.sourcesContent = sourcesContent;
  this._mappings = mappings;
  this._sourceMapURL = aSourceMapURL;
  this.file = file;
}
BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer$1.prototype);
BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer$1;
BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) {
  var relativeSource = aSource;
  if (this.sourceRoot != null) {
    relativeSource = util$1.relative(this.sourceRoot, relativeSource);
  }
  if (this._sources.has(relativeSource)) {
    return this._sources.indexOf(relativeSource);
  }
  var i;
  for (i = 0; i < this._absoluteSources.length; ++i) {
    if (this._absoluteSources[i] == aSource) {
      return i;
    }
  }
  return -1;
};
BasicSourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap2(aSourceMap, aSourceMapURL) {
  var smc = Object.create(BasicSourceMapConsumer.prototype);
  var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  smc.sourceRoot = aSourceMap._sourceRoot;
  smc.sourcesContent = aSourceMap._generateSourcesContent(
    smc._sources.toArray(),
    smc.sourceRoot
  );
  smc.file = aSourceMap._file;
  smc._sourceMapURL = aSourceMapURL;
  smc._absoluteSources = smc._sources.toArray().map(function(s) {
    return util$1.computeSourceURL(smc.sourceRoot, s, aSourceMapURL);
  });
  var generatedMappings = aSourceMap._mappings.toArray().slice();
  var destGeneratedMappings = smc.__generatedMappings = [];
  var destOriginalMappings = smc.__originalMappings = [];
  for (var i = 0, length2 = generatedMappings.length; i < length2; i++) {
    var srcMapping = generatedMappings[i];
    var destMapping = new Mapping();
    destMapping.generatedLine = srcMapping.generatedLine;
    destMapping.generatedColumn = srcMapping.generatedColumn;
    if (srcMapping.source) {
      destMapping.source = sources.indexOf(srcMapping.source);
      destMapping.originalLine = srcMapping.originalLine;
      destMapping.originalColumn = srcMapping.originalColumn;
      if (srcMapping.name) {
        destMapping.name = names.indexOf(srcMapping.name);
      }
      destOriginalMappings.push(destMapping);
    }
    destGeneratedMappings.push(destMapping);
  }
  quickSort(smc.__originalMappings, util$1.compareByOriginalPositions);
  return smc;
};
BasicSourceMapConsumer.prototype._version = 3;
Object.defineProperty(BasicSourceMapConsumer.prototype, "sources", {
  get: function() {
    return this._absoluteSources.slice();
  }
});
function Mapping() {
  this.generatedLine = 0;
  this.generatedColumn = 0;
  this.source = null;
  this.originalLine = null;
  this.originalColumn = null;
  this.name = null;
}
BasicSourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings4(aStr, aSourceRoot) {
  var generatedLine = 1;
  var previousGeneratedColumn = 0;
  var previousOriginalLine = 0;
  var previousOriginalColumn = 0;
  var previousSource = 0;
  var previousName = 0;
  var length2 = aStr.length;
  var index = 0;
  var cachedSegments = {};
  var temp = {};
  var originalMappings = [];
  var generatedMappings = [];
  var mapping, str2, segment, end, value;
  while (index < length2) {
    if (aStr.charAt(index) === ";") {
      generatedLine++;
      index++;
      previousGeneratedColumn = 0;
    } else if (aStr.charAt(index) === ",") {
      index++;
    } else {
      mapping = new Mapping();
      mapping.generatedLine = generatedLine;
      for (end = index; end < length2; end++) {
        if (this._charIsMappingSeparator(aStr, end)) {
          break;
        }
      }
      str2 = aStr.slice(index, end);
      segment = cachedSegments[str2];
      if (segment) {
        index += str2.length;
      } else {
        segment = [];
        while (index < end) {
          base64VLQ.decode(aStr, index, temp);
          value = temp.value;
          index = temp.rest;
          segment.push(value);
        }
        if (segment.length === 2) {
          throw new Error("Found a source, but no line and column");
        }
        if (segment.length === 3) {
          throw new Error("Found a source and line, but no column");
        }
        cachedSegments[str2] = segment;
      }
      mapping.generatedColumn = previousGeneratedColumn + segment[0];
      previousGeneratedColumn = mapping.generatedColumn;
      if (segment.length > 1) {
        mapping.source = previousSource + segment[1];
        previousSource += segment[1];
        mapping.originalLine = previousOriginalLine + segment[2];
        previousOriginalLine = mapping.originalLine;
        mapping.originalLine += 1;
        mapping.originalColumn = previousOriginalColumn + segment[3];
        previousOriginalColumn = mapping.originalColumn;
        if (segment.length > 4) {
          mapping.name = previousName + segment[4];
          previousName += segment[4];
        }
      }
      generatedMappings.push(mapping);
      if (typeof mapping.originalLine === "number") {
        originalMappings.push(mapping);
      }
    }
  }
  quickSort(generatedMappings, util$1.compareByGeneratedPositionsDeflated);
  this.__generatedMappings = generatedMappings;
  quickSort(originalMappings, util$1.compareByOriginalPositions);
  this.__originalMappings = originalMappings;
};
BasicSourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping2(aNeedle, aMappings, aLineName, aColumnName, aComparator, aBias) {
  if (aNeedle[aLineName] <= 0) {
    throw new TypeError("Line must be greater than or equal to 1, got " + aNeedle[aLineName]);
  }
  if (aNeedle[aColumnName] < 0) {
    throw new TypeError("Column must be greater than or equal to 0, got " + aNeedle[aColumnName]);
  }
  return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
};
BasicSourceMapConsumer.prototype.computeColumnSpans = function SourceMapConsumer_computeColumnSpans2() {
  for (var index = 0; index < this._generatedMappings.length; ++index) {
    var mapping = this._generatedMappings[index];
    if (index + 1 < this._generatedMappings.length) {
      var nextMapping = this._generatedMappings[index + 1];
      if (mapping.generatedLine === nextMapping.generatedLine) {
        mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
        continue;
      }
    }
    mapping.lastGeneratedColumn = Infinity;
  }
};
BasicSourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor2(aArgs) {
  var needle = {
    generatedLine: util$1.getArg(aArgs, "line"),
    generatedColumn: util$1.getArg(aArgs, "column")
  };
  var index = this._findMapping(
    needle,
    this._generatedMappings,
    "generatedLine",
    "generatedColumn",
    util$1.compareByGeneratedPositionsDeflated,
    util$1.getArg(aArgs, "bias", SourceMapConsumer$1.GREATEST_LOWER_BOUND)
  );
  if (index >= 0) {
    var mapping = this._generatedMappings[index];
    if (mapping.generatedLine === needle.generatedLine) {
      var source = util$1.getArg(mapping, "source", null);
      if (source !== null) {
        source = this._sources.at(source);
        source = util$1.computeSourceURL(this.sourceRoot, source, this._sourceMapURL);
      }
      var name = util$1.getArg(mapping, "name", null);
      if (name !== null) {
        name = this._names.at(name);
      }
      return {
        source,
        line: util$1.getArg(mapping, "originalLine", null),
        column: util$1.getArg(mapping, "originalColumn", null),
        name
      };
    }
  }
  return {
    source: null,
    line: null,
    column: null,
    name: null
  };
};
BasicSourceMapConsumer.prototype.hasContentsOfAllSources = function BasicSourceMapConsumer_hasContentsOfAllSources2() {
  if (!this.sourcesContent) {
    return false;
  }
  return this.sourcesContent.length >= this._sources.size() && !this.sourcesContent.some(function(sc) {
    return sc == null;
  });
};
BasicSourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor2(aSource, nullOnMissing) {
  if (!this.sourcesContent) {
    return null;
  }
  var index = this._findSourceIndex(aSource);
  if (index >= 0) {
    return this.sourcesContent[index];
  }
  var relativeSource = aSource;
  if (this.sourceRoot != null) {
    relativeSource = util$1.relative(this.sourceRoot, relativeSource);
  }
  var url;
  if (this.sourceRoot != null && (url = util$1.urlParse(this.sourceRoot))) {
    var fileUriAbsPath = relativeSource.replace(/^file:\/\//, "");
    if (url.scheme == "file" && this._sources.has(fileUriAbsPath)) {
      return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)];
    }
    if ((!url.path || url.path == "/") && this._sources.has("/" + relativeSource)) {
      return this.sourcesContent[this._sources.indexOf("/" + relativeSource)];
    }
  }
  if (nullOnMissing) {
    return null;
  } else {
    throw new Error('"' + relativeSource + '" is not in the SourceMap.');
  }
};
BasicSourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor2(aArgs) {
  var source = util$1.getArg(aArgs, "source");
  source = this._findSourceIndex(source);
  if (source < 0) {
    return {
      line: null,
      column: null,
      lastColumn: null
    };
  }
  var needle = {
    source,
    originalLine: util$1.getArg(aArgs, "line"),
    originalColumn: util$1.getArg(aArgs, "column")
  };
  var index = this._findMapping(
    needle,
    this._originalMappings,
    "originalLine",
    "originalColumn",
    util$1.compareByOriginalPositions,
    util$1.getArg(aArgs, "bias", SourceMapConsumer$1.GREATEST_LOWER_BOUND)
  );
  if (index >= 0) {
    var mapping = this._originalMappings[index];
    if (mapping.source === needle.source) {
      return {
        line: util$1.getArg(mapping, "generatedLine", null),
        column: util$1.getArg(mapping, "generatedColumn", null),
        lastColumn: util$1.getArg(mapping, "lastGeneratedColumn", null)
      };
    }
  }
  return {
    line: null,
    column: null,
    lastColumn: null
  };
};
function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
  var sourceMap = aSourceMap;
  if (typeof aSourceMap === "string") {
    sourceMap = util$1.parseSourceMapInput(aSourceMap);
  }
  var version2 = util$1.getArg(sourceMap, "version");
  var sections = util$1.getArg(sourceMap, "sections");
  if (version2 != this._version) {
    throw new Error("Unsupported version: " + version2);
  }
  this._sources = new ArraySet();
  this._names = new ArraySet();
  var lastOffset = {
    line: -1,
    column: 0
  };
  this._sections = sections.map(function(s) {
    if (s.url) {
      throw new Error("Support for url field in sections not implemented.");
    }
    var offset = util$1.getArg(s, "offset");
    var offsetLine = util$1.getArg(offset, "line");
    var offsetColumn = util$1.getArg(offset, "column");
    if (offsetLine < lastOffset.line || offsetLine === lastOffset.line && offsetColumn < lastOffset.column) {
      throw new Error("Section offsets must be ordered and non-overlapping.");
    }
    lastOffset = offset;
    return {
      generatedOffset: {
        // The offset fields are 0-based, but we use 1-based indices when
        // encoding/decoding from VLQ.
        generatedLine: offsetLine + 1,
        generatedColumn: offsetColumn + 1
      },
      consumer: new SourceMapConsumer$1(util$1.getArg(s, "map"), aSourceMapURL)
    };
  });
}
IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer$1.prototype);
IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer$1;
IndexedSourceMapConsumer.prototype._version = 3;
Object.defineProperty(IndexedSourceMapConsumer.prototype, "sources", {
  get: function() {
    var sources = [];
    for (var i = 0; i < this._sections.length; i++) {
      for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
        sources.push(this._sections[i].consumer.sources[j]);
      }
    }
    return sources;
  }
});
IndexedSourceMapConsumer.prototype.originalPositionFor = function IndexedSourceMapConsumer_originalPositionFor2(aArgs) {
  var needle = {
    generatedLine: util$1.getArg(aArgs, "line"),
    generatedColumn: util$1.getArg(aArgs, "column")
  };
  var sectionIndex = binarySearch.search(
    needle,
    this._sections,
    function(needle2, section2) {
      var cmp3 = needle2.generatedLine - section2.generatedOffset.generatedLine;
      if (cmp3) {
        return cmp3;
      }
      return needle2.generatedColumn - section2.generatedOffset.generatedColumn;
    }
  );
  var section = this._sections[sectionIndex];
  if (!section) {
    return {
      source: null,
      line: null,
      column: null,
      name: null
    };
  }
  return section.consumer.originalPositionFor({
    line: needle.generatedLine - (section.generatedOffset.generatedLine - 1),
    column: needle.generatedColumn - (section.generatedOffset.generatedLine === needle.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0),
    bias: aArgs.bias
  });
};
IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = function IndexedSourceMapConsumer_hasContentsOfAllSources2() {
  return this._sections.every(function(s) {
    return s.consumer.hasContentsOfAllSources();
  });
};
IndexedSourceMapConsumer.prototype.sourceContentFor = function IndexedSourceMapConsumer_sourceContentFor2(aSource, nullOnMissing) {
  for (var i = 0; i < this._sections.length; i++) {
    var section = this._sections[i];
    var content = section.consumer.sourceContentFor(aSource, true);
    if (content) {
      return content;
    }
  }
  if (nullOnMissing) {
    return null;
  } else {
    throw new Error('"' + aSource + '" is not in the SourceMap.');
  }
};
IndexedSourceMapConsumer.prototype.generatedPositionFor = function IndexedSourceMapConsumer_generatedPositionFor2(aArgs) {
  for (var i = 0; i < this._sections.length; i++) {
    var section = this._sections[i];
    if (section.consumer._findSourceIndex(util$1.getArg(aArgs, "source")) === -1) {
      continue;
    }
    var generatedPosition = section.consumer.generatedPositionFor(aArgs);
    if (generatedPosition) {
      var ret = {
        line: generatedPosition.line + (section.generatedOffset.generatedLine - 1),
        column: generatedPosition.column + (section.generatedOffset.generatedLine === generatedPosition.line ? section.generatedOffset.generatedColumn - 1 : 0)
      };
      return ret;
    }
  }
  return {
    line: null,
    column: null
  };
};
IndexedSourceMapConsumer.prototype._parseMappings = function IndexedSourceMapConsumer_parseMappings2(aStr, aSourceRoot) {
  this.__generatedMappings = [];
  this.__originalMappings = [];
  for (var i = 0; i < this._sections.length; i++) {
    var section = this._sections[i];
    var sectionMappings = section.consumer._generatedMappings;
    for (var j = 0; j < sectionMappings.length; j++) {
      var mapping = sectionMappings[j];
      var source = section.consumer._sources.at(mapping.source);
      source = util$1.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL);
      this._sources.add(source);
      source = this._sources.indexOf(source);
      var name = null;
      if (mapping.name) {
        name = section.consumer._names.at(mapping.name);
        this._names.add(name);
        name = this._names.indexOf(name);
      }
      var adjustedMapping = {
        source,
        generatedLine: mapping.generatedLine + (section.generatedOffset.generatedLine - 1),
        generatedColumn: mapping.generatedColumn + (section.generatedOffset.generatedLine === mapping.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0),
        originalLine: mapping.originalLine,
        originalColumn: mapping.originalColumn,
        name
      };
      this.__generatedMappings.push(adjustedMapping);
      if (typeof adjustedMapping.originalLine === "number") {
        this.__originalMappings.push(adjustedMapping);
      }
    }
  }
  quickSort(this.__generatedMappings, util$1.compareByGeneratedPositionsDeflated);
  quickSort(this.__originalMappings, util$1.compareByOriginalPositions);
};
var SourceMapGenerator$1 = sourceMapGenerator.SourceMapGenerator;
var util = util$5;
var REGEX_NEWLINE = /(\r?\n)/;
var NEWLINE_CODE = 10;
var isSourceNode = "$$$isSourceNode$$$";
function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  this.children = [];
  this.sourceContents = {};
  this.line = aLine == null ? null : aLine;
  this.column = aColumn == null ? null : aColumn;
  this.source = aSource == null ? null : aSource;
  this.name = aName == null ? null : aName;
  this[isSourceNode] = true;
  if (aChunks != null)
    this.add(aChunks);
}
SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap2(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  var node2 = new SourceNode();
  var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  var remainingLinesIndex = 0;
  var shiftNextLine = function() {
    var lineContents = getNextLine();
    var newLine = getNextLine() || "";
    return lineContents + newLine;
    function getNextLine() {
      return remainingLinesIndex < remainingLines.length ? remainingLines[remainingLinesIndex++] : void 0;
    }
  };
  var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  var lastMapping = null;
  aSourceMapConsumer.eachMapping(function(mapping) {
    if (lastMapping !== null) {
      if (lastGeneratedLine < mapping.generatedLine) {
        addMappingWithCode(lastMapping, shiftNextLine());
        lastGeneratedLine++;
        lastGeneratedColumn = 0;
      } else {
        var nextLine = remainingLines[remainingLinesIndex] || "";
        var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn);
        remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn);
        lastGeneratedColumn = mapping.generatedColumn;
        addMappingWithCode(lastMapping, code);
        lastMapping = mapping;
        return;
      }
    }
    while (lastGeneratedLine < mapping.generatedLine) {
      node2.add(shiftNextLine());
      lastGeneratedLine++;
    }
    if (lastGeneratedColumn < mapping.generatedColumn) {
      var nextLine = remainingLines[remainingLinesIndex] || "";
      node2.add(nextLine.substr(0, mapping.generatedColumn));
      remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
      lastGeneratedColumn = mapping.generatedColumn;
    }
    lastMapping = mapping;
  }, this);
  if (remainingLinesIndex < remainingLines.length) {
    if (lastMapping) {
      addMappingWithCode(lastMapping, shiftNextLine());
    }
    node2.add(remainingLines.splice(remainingLinesIndex).join(""));
  }
  aSourceMapConsumer.sources.forEach(function(sourceFile) {
    var content = aSourceMapConsumer.sourceContentFor(sourceFile);
    if (content != null) {
      if (aRelativePath != null) {
        sourceFile = util.join(aRelativePath, sourceFile);
      }
      node2.setSourceContent(sourceFile, content);
    }
  });
  return node2;
  function addMappingWithCode(mapping, code) {
    if (mapping === null || mapping.source === void 0) {
      node2.add(code);
    } else {
      var source = aRelativePath ? util.join(aRelativePath, mapping.source) : mapping.source;
      node2.add(new SourceNode(
        mapping.originalLine,
        mapping.originalColumn,
        source,
        code,
        mapping.name
      ));
    }
  }
};
SourceNode.prototype.add = function SourceNode_add2(aChunk) {
  if (Array.isArray(aChunk)) {
    aChunk.forEach(function(chunk) {
      this.add(chunk);
    }, this);
  } else if (aChunk[isSourceNode] || typeof aChunk === "string") {
    if (aChunk) {
      this.children.push(aChunk);
    }
  } else {
    throw new TypeError(
      "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
    );
  }
  return this;
};
SourceNode.prototype.prepend = function SourceNode_prepend2(aChunk) {
  if (Array.isArray(aChunk)) {
    for (var i = aChunk.length - 1; i >= 0; i--) {
      this.prepend(aChunk[i]);
    }
  } else if (aChunk[isSourceNode] || typeof aChunk === "string") {
    this.children.unshift(aChunk);
  } else {
    throw new TypeError(
      "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
    );
  }
  return this;
};
SourceNode.prototype.walk = function SourceNode_walk2(aFn) {
  var chunk;
  for (var i = 0, len = this.children.length; i < len; i++) {
    chunk = this.children[i];
    if (chunk[isSourceNode]) {
      chunk.walk(aFn);
    } else {
      if (chunk !== "") {
        aFn(chunk, {
          source: this.source,
          line: this.line,
          column: this.column,
          name: this.name
        });
      }
    }
  }
};
SourceNode.prototype.join = function SourceNode_join2(aSep) {
  var newChildren;
  var i;
  var len = this.children.length;
  if (len > 0) {
    newChildren = [];
    for (i = 0; i < len - 1; i++) {
      newChildren.push(this.children[i]);
      newChildren.push(aSep);
    }
    newChildren.push(this.children[i]);
    this.children = newChildren;
  }
  return this;
};
SourceNode.prototype.replaceRight = function SourceNode_replaceRight2(aPattern, aReplacement) {
  var lastChild = this.children[this.children.length - 1];
  if (lastChild[isSourceNode]) {
    lastChild.replaceRight(aPattern, aReplacement);
  } else if (typeof lastChild === "string") {
    this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  } else {
    this.children.push("".replace(aPattern, aReplacement));
  }
  return this;
};
SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent2(aSourceFile, aSourceContent) {
  this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
};
SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents2(aFn) {
  for (var i = 0, len = this.children.length; i < len; i++) {
    if (this.children[i][isSourceNode]) {
      this.children[i].walkSourceContents(aFn);
    }
  }
  var sources = Object.keys(this.sourceContents);
  for (var i = 0, len = sources.length; i < len; i++) {
    aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  }
};
SourceNode.prototype.toString = function SourceNode_toString2() {
  var str2 = "";
  this.walk(function(chunk) {
    str2 += chunk;
  });
  return str2;
};
SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap2(aArgs) {
  var generated = {
    code: "",
    line: 1,
    column: 0
  };
  var map2 = new SourceMapGenerator$1(aArgs);
  var sourceMappingActive = false;
  var lastOriginalSource = null;
  var lastOriginalLine = null;
  var lastOriginalColumn = null;
  var lastOriginalName = null;
  this.walk(function(chunk, original) {
    generated.code += chunk;
    if (original.source !== null && original.line !== null && original.column !== null) {
      if (lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) {
        map2.addMapping({
          source: original.source,
          original: {
            line: original.line,
            column: original.column
          },
          generated: {
            line: generated.line,
            column: generated.column
          },
          name: original.name
        });
      }
      lastOriginalSource = original.source;
      lastOriginalLine = original.line;
      lastOriginalColumn = original.column;
      lastOriginalName = original.name;
      sourceMappingActive = true;
    } else if (sourceMappingActive) {
      map2.addMapping({
        generated: {
          line: generated.line,
          column: generated.column
        }
      });
      lastOriginalSource = null;
      sourceMappingActive = false;
    }
    for (var idx = 0, length2 = chunk.length; idx < length2; idx++) {
      if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
        generated.line++;
        generated.column = 0;
        if (idx + 1 === length2) {
          lastOriginalSource = null;
          sourceMappingActive = false;
        } else if (sourceMappingActive) {
          map2.addMapping({
            source: original.source,
            original: {
              line: original.line,
              column: original.column
            },
            generated: {
              line: generated.line,
              column: generated.column
            },
            name: original.name
          });
        }
      } else {
        generated.column++;
      }
    }
  });
  this.walkSourceContents(function(sourceFile, sourceContent) {
    map2.setSourceContent(sourceFile, sourceContent);
  });
  return { code: generated.code, map: map2 };
};
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const intToChar = new Uint8Array(64);
const charToInt = new Uint8Array(128);
for (let i = 0; i < chars.length; i++) {
  const c = chars.charCodeAt(i);
  intToChar[i] = c;
  charToInt[c] = i;
}
var toString2 = {}.toString;
var isarray = Array.isArray || function(arr) {
  return toString2.call(arr) == "[object Array]";
};
/*!
 * isobject <https://github.com/jonschlinkert/isobject>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */
var isArray$1 = isarray;
var isobject = function isObject(val) {
  return val != null && typeof val === "object" && isArray$1(val) === false;
};
/**
 * line-column - Convert efficiently index to/from line-column in a string
 * @module  lineColumn
 * @license MIT
 */
var isArray = isarray;
var isObject2 = isobject;
var lineColumn = LineColumnFinder;
function LineColumnFinder(str2, options) {
  if (!(this instanceof LineColumnFinder)) {
    if (typeof options === "number") {
      return new LineColumnFinder(str2).fromIndex(options);
    }
    return new LineColumnFinder(str2, options);
  }
  this.str = str2 || "";
  this.lineToIndex = buildLineToIndex(this.str);
  options = options || {};
  this.origin = typeof options.origin === "undefined" ? 1 : options.origin;
}
LineColumnFinder.prototype.fromIndex = function(index) {
  if (index < 0 || index >= this.str.length || isNaN(index)) {
    return null;
  }
  var line = findLowerIndexInRangeArray(index, this.lineToIndex);
  return {
    line: line + this.origin,
    col: index - this.lineToIndex[line] + this.origin
  };
};
LineColumnFinder.prototype.toIndex = function(line, column) {
  if (typeof column === "undefined") {
    if (isArray(line) && line.length >= 2) {
      return this.toIndex(line[0], line[1]);
    }
    if (isObject2(line) && "line" in line && ("col" in line || "column" in line)) {
      return this.toIndex(line.line, "col" in line ? line.col : line.column);
    }
    return -1;
  }
  if (isNaN(line) || isNaN(column)) {
    return -1;
  }
  line -= this.origin;
  column -= this.origin;
  if (line >= 0 && column >= 0 && line < this.lineToIndex.length) {
    var lineIndex = this.lineToIndex[line];
    var nextIndex = line === this.lineToIndex.length - 1 ? this.str.length : this.lineToIndex[line + 1];
    if (column < nextIndex - lineIndex) {
      return lineIndex + column;
    }
  }
  return -1;
};
function buildLineToIndex(str2) {
  var lines = str2.split("\n"), lineToIndex = new Array(lines.length), index = 0;
  for (var i = 0, l = lines.length; i < l; i++) {
    lineToIndex[i] = index;
    index += lines[i].length + /* "\n".length */
    1;
  }
  return lineToIndex;
}
function findLowerIndexInRangeArray(value, arr) {
  if (value >= arr[arr.length - 1]) {
    return arr.length - 1;
  }
  var min = 0, max = arr.length - 2, mid;
  while (min < max) {
    mid = min + (max - min >> 1);
    if (value < arr[mid]) {
      max = mid - 1;
    } else if (value >= arr[mid + 1]) {
      min = mid + 1;
    } else {
      min = mid;
      break;
    }
  }
  return min;
}
const lineColumn$1 = /* @__PURE__ */ getDefaultExportFromCjs(lineColumn);
function getOrCreateModel(uri, lang, value) {
  const model = editor.getModel(uri);
  if (model) {
    model.setValue(value);
    return model;
  }
  return editor.createModel(value, lang, uri);
}
function WorkerWrapper$1() {
  return new Worker("/assets/editor.worker-2757ccac.js");
}
var lib = {};
var onigasmH = {};
var onigasm = { exports: {} };
(function(module2, exports2) {
  var Onigasm = function() {
    typeof document !== "undefined" && document.currentScript ? document.currentScript.src : void 0;
    return function(Onigasm2) {
      Onigasm2 = Onigasm2 || {};
      var Module = typeof Onigasm2 !== "undefined" ? Onigasm2 : {};
      var moduleOverrides = {};
      var key;
      for (key in Module) {
        if (Module.hasOwnProperty(key)) {
          moduleOverrides[key] = Module[key];
        }
      }
      var ENVIRONMENT_IS_WORKER = false;
      var scriptDirectory = "";
      function locateFile(path2) {
        if (Module["locateFile"]) {
          return Module["locateFile"](path2, scriptDirectory);
        }
        return scriptDirectory + path2;
      }
      var readBinary;
      {
        readBinary = function readBinary2(f) {
          var data;
          if (typeof readbuffer === "function") {
            return new Uint8Array(readbuffer(f));
          }
          data = read(f, "binary");
          assert2(typeof data === "object");
          return data;
        };
        if (typeof scriptArgs != "undefined") {
          scriptArgs;
        }
        if (typeof print !== "undefined") {
          if (typeof console === "undefined")
            console = {};
          console.log = print;
          console.warn = console.error = typeof printErr !== "undefined" ? printErr : print;
        }
      }
      var out = Module["print"] || console.log.bind(console);
      var err = Module["printErr"] || console.warn.bind(console);
      for (key in moduleOverrides) {
        if (moduleOverrides.hasOwnProperty(key)) {
          Module[key] = moduleOverrides[key];
        }
      }
      moduleOverrides = null;
      if (Module["arguments"])
        Module["arguments"];
      if (Module["thisProgram"])
        Module["thisProgram"];
      if (Module["quit"])
        Module["quit"];
      var wasmBinary;
      if (Module["wasmBinary"])
        wasmBinary = Module["wasmBinary"];
      if (Module["noExitRuntime"])
        Module["noExitRuntime"];
      if (typeof WebAssembly !== "object") {
        err("no native wasm support detected");
      }
      var wasmMemory;
      var wasmTable = new WebAssembly.Table({ "initial": 244, "maximum": 244 + 0, "element": "anyfunc" });
      var ABORT = false;
      function assert2(condition, text2) {
        if (!condition) {
          abort("Assertion failed: " + text2);
        }
      }
      function getCFunc(ident) {
        var func = Module["_" + ident];
        assert2(func, "Cannot call unknown function " + ident + ", make sure it is exported");
        return func;
      }
      function ccall(ident, returnType, argTypes, args, opts) {
        var toC = { "string": function(str2) {
          var ret2 = 0;
          if (str2 !== null && str2 !== void 0 && str2 !== 0) {
            var len = (str2.length << 2) + 1;
            ret2 = stackAlloc(len);
            stringToUTF8(str2, ret2, len);
          }
          return ret2;
        }, "array": function(arr) {
          var ret2 = stackAlloc(arr.length);
          writeArrayToMemory(arr, ret2);
          return ret2;
        } };
        function convertReturnValue(ret2) {
          if (returnType === "string")
            return UTF8ToString(ret2);
          if (returnType === "boolean")
            return Boolean(ret2);
          return ret2;
        }
        var func = getCFunc(ident);
        var cArgs = [];
        var stack = 0;
        if (args) {
          for (var i = 0; i < args.length; i++) {
            var converter = toC[argTypes[i]];
            if (converter) {
              if (stack === 0)
                stack = stackSave();
              cArgs[i] = converter(args[i]);
            } else {
              cArgs[i] = args[i];
            }
          }
        }
        var ret = func.apply(null, cArgs);
        ret = convertReturnValue(ret);
        if (stack !== 0)
          stackRestore(stack);
        return ret;
      }
      var UTF8Decoder = typeof TextDecoder !== "undefined" ? new TextDecoder("utf8") : void 0;
      function UTF8ArrayToString(u8Array, idx, maxBytesToRead) {
        var endIdx = idx + maxBytesToRead;
        var endPtr = idx;
        while (u8Array[endPtr] && !(endPtr >= endIdx))
          ++endPtr;
        if (endPtr - idx > 16 && u8Array.subarray && UTF8Decoder) {
          return UTF8Decoder.decode(u8Array.subarray(idx, endPtr));
        } else {
          var str2 = "";
          while (idx < endPtr) {
            var u0 = u8Array[idx++];
            if (!(u0 & 128)) {
              str2 += String.fromCharCode(u0);
              continue;
            }
            var u1 = u8Array[idx++] & 63;
            if ((u0 & 224) == 192) {
              str2 += String.fromCharCode((u0 & 31) << 6 | u1);
              continue;
            }
            var u2 = u8Array[idx++] & 63;
            if ((u0 & 240) == 224) {
              u0 = (u0 & 15) << 12 | u1 << 6 | u2;
            } else {
              u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | u8Array[idx++] & 63;
            }
            if (u0 < 65536) {
              str2 += String.fromCharCode(u0);
            } else {
              var ch = u0 - 65536;
              str2 += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023);
            }
          }
        }
        return str2;
      }
      function UTF8ToString(ptr, maxBytesToRead) {
        return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : "";
      }
      function stringToUTF8Array(str2, outU8Array, outIdx, maxBytesToWrite) {
        if (!(maxBytesToWrite > 0))
          return 0;
        var startIdx = outIdx;
        var endIdx = outIdx + maxBytesToWrite - 1;
        for (var i = 0; i < str2.length; ++i) {
          var u = str2.charCodeAt(i);
          if (u >= 55296 && u <= 57343) {
            var u1 = str2.charCodeAt(++i);
            u = 65536 + ((u & 1023) << 10) | u1 & 1023;
          }
          if (u <= 127) {
            if (outIdx >= endIdx)
              break;
            outU8Array[outIdx++] = u;
          } else if (u <= 2047) {
            if (outIdx + 1 >= endIdx)
              break;
            outU8Array[outIdx++] = 192 | u >> 6;
            outU8Array[outIdx++] = 128 | u & 63;
          } else if (u <= 65535) {
            if (outIdx + 2 >= endIdx)
              break;
            outU8Array[outIdx++] = 224 | u >> 12;
            outU8Array[outIdx++] = 128 | u >> 6 & 63;
            outU8Array[outIdx++] = 128 | u & 63;
          } else {
            if (outIdx + 3 >= endIdx)
              break;
            outU8Array[outIdx++] = 240 | u >> 18;
            outU8Array[outIdx++] = 128 | u >> 12 & 63;
            outU8Array[outIdx++] = 128 | u >> 6 & 63;
            outU8Array[outIdx++] = 128 | u & 63;
          }
        }
        outU8Array[outIdx] = 0;
        return outIdx - startIdx;
      }
      function stringToUTF8(str2, outPtr, maxBytesToWrite) {
        return stringToUTF8Array(str2, HEAPU8, outPtr, maxBytesToWrite);
      }
      typeof TextDecoder !== "undefined" ? new TextDecoder("utf-16le") : void 0;
      function writeArrayToMemory(array2, buffer2) {
        HEAP8.set(array2, buffer2);
      }
      var WASM_PAGE_SIZE = 65536;
      function alignUp(x, multiple) {
        if (x % multiple > 0) {
          x += multiple - x % multiple;
        }
        return x;
      }
      var buffer, HEAP8, HEAPU8, HEAP32;
      function updateGlobalBufferAndViews(buf) {
        buffer = buf;
        Module["HEAP8"] = HEAP8 = new Int8Array(buf);
        Module["HEAP16"] = new Int16Array(buf);
        Module["HEAP32"] = HEAP32 = new Int32Array(buf);
        Module["HEAPU8"] = HEAPU8 = new Uint8Array(buf);
        Module["HEAPU16"] = new Uint16Array(buf);
        Module["HEAPU32"] = new Uint32Array(buf);
        Module["HEAPF32"] = new Float32Array(buf);
        Module["HEAPF64"] = new Float64Array(buf);
      }
      var DYNAMIC_BASE = 5507664, DYNAMICTOP_PTR = 264624;
      var INITIAL_TOTAL_MEMORY = Module["TOTAL_MEMORY"] || 157286400;
      if (Module["wasmMemory"]) {
        wasmMemory = Module["wasmMemory"];
      } else {
        wasmMemory = new WebAssembly.Memory({ "initial": INITIAL_TOTAL_MEMORY / WASM_PAGE_SIZE });
      }
      if (wasmMemory) {
        buffer = wasmMemory.buffer;
      }
      INITIAL_TOTAL_MEMORY = buffer.byteLength;
      updateGlobalBufferAndViews(buffer);
      HEAP32[DYNAMICTOP_PTR >> 2] = DYNAMIC_BASE;
      function callRuntimeCallbacks(callbacks) {
        while (callbacks.length > 0) {
          var callback = callbacks.shift();
          if (typeof callback == "function") {
            callback();
            continue;
          }
          var func = callback.func;
          if (typeof func === "number") {
            if (callback.arg === void 0) {
              Module["dynCall_v"](func);
            } else {
              Module["dynCall_vi"](func, callback.arg);
            }
          } else {
            func(callback.arg === void 0 ? null : callback.arg);
          }
        }
      }
      var __ATPRERUN__ = [];
      var __ATINIT__ = [];
      var __ATMAIN__ = [];
      var __ATPOSTRUN__ = [];
      function preRun() {
        if (Module["preRun"]) {
          if (typeof Module["preRun"] == "function")
            Module["preRun"] = [Module["preRun"]];
          while (Module["preRun"].length) {
            addOnPreRun(Module["preRun"].shift());
          }
        }
        callRuntimeCallbacks(__ATPRERUN__);
      }
      function initRuntime() {
        callRuntimeCallbacks(__ATINIT__);
      }
      function preMain() {
        callRuntimeCallbacks(__ATMAIN__);
      }
      function postRun() {
        if (Module["postRun"]) {
          if (typeof Module["postRun"] == "function")
            Module["postRun"] = [Module["postRun"]];
          while (Module["postRun"].length) {
            addOnPostRun(Module["postRun"].shift());
          }
        }
        callRuntimeCallbacks(__ATPOSTRUN__);
      }
      function addOnPreRun(cb) {
        __ATPRERUN__.unshift(cb);
      }
      function addOnPostRun(cb) {
        __ATPOSTRUN__.unshift(cb);
      }
      var runDependencies = 0;
      var dependenciesFulfilled = null;
      function addRunDependency(id3) {
        runDependencies++;
        if (Module["monitorRunDependencies"]) {
          Module["monitorRunDependencies"](runDependencies);
        }
      }
      function removeRunDependency(id3) {
        runDependencies--;
        if (Module["monitorRunDependencies"]) {
          Module["monitorRunDependencies"](runDependencies);
        }
        if (runDependencies == 0) {
          if (dependenciesFulfilled) {
            var callback = dependenciesFulfilled;
            dependenciesFulfilled = null;
            callback();
          }
        }
      }
      Module["preloadedImages"] = {};
      Module["preloadedAudios"] = {};
      function abort(what) {
        if (Module["onAbort"]) {
          Module["onAbort"](what);
        }
        what += "";
        out(what);
        err(what);
        ABORT = true;
        what = "abort(" + what + "). Build with -s ASSERTIONS=1 for more info.";
        throw new WebAssembly.RuntimeError(what);
      }
      var dataURIPrefix = "data:application/octet-stream;base64,";
      function isDataURI(filename) {
        return String.prototype.startsWith ? filename.startsWith(dataURIPrefix) : filename.indexOf(dataURIPrefix) === 0;
      }
      var wasmBinaryFile = "onigasm.wasm";
      if (!isDataURI(wasmBinaryFile)) {
        wasmBinaryFile = locateFile(wasmBinaryFile);
      }
      function getBinary() {
        try {
          if (wasmBinary) {
            return new Uint8Array(wasmBinary);
          }
          if (readBinary) {
            return readBinary(wasmBinaryFile);
          } else {
            throw "both async and sync fetching of the wasm failed";
          }
        } catch (err2) {
          abort(err2);
        }
      }
      function getBinaryPromise() {
        if (!wasmBinary && ENVIRONMENT_IS_WORKER && typeof fetch === "function") {
          return fetch(wasmBinaryFile, { credentials: "same-origin" }).then(function(response) {
            if (!response["ok"]) {
              throw "failed to load wasm binary file at '" + wasmBinaryFile + "'";
            }
            return response["arrayBuffer"]();
          }).catch(function() {
            return getBinary();
          });
        }
        return new Promise(function(resolve2, reject) {
          resolve2(getBinary());
        });
      }
      function createWasm() {
        var info = { "env": asmLibraryArg, "wasi_unstable": asmLibraryArg };
        function receiveInstance(instance, module3) {
          var exports4 = instance.exports;
          Module["asm"] = exports4;
          removeRunDependency();
        }
        addRunDependency();
        function receiveInstantiatedSource(output) {
          receiveInstance(output["instance"]);
        }
        function instantiateArrayBuffer(receiver) {
          return getBinaryPromise().then(function(binary) {
            return WebAssembly.instantiate(binary, info);
          }).then(receiver, function(reason) {
            err("failed to asynchronously prepare wasm: " + reason);
            abort(reason);
          });
        }
        function instantiateAsync() {
          if (!wasmBinary && typeof WebAssembly.instantiateStreaming === "function" && !isDataURI(wasmBinaryFile) && typeof fetch === "function") {
            fetch(wasmBinaryFile, { credentials: "same-origin" }).then(function(response) {
              var result2 = WebAssembly.instantiateStreaming(response, info);
              return result2.then(receiveInstantiatedSource, function(reason) {
                err("wasm streaming compile failed: " + reason);
                err("falling back to ArrayBuffer instantiation");
                instantiateArrayBuffer(receiveInstantiatedSource);
              });
            });
          } else {
            return instantiateArrayBuffer(receiveInstantiatedSource);
          }
        }
        if (Module["instantiateWasm"]) {
          try {
            var exports3 = Module["instantiateWasm"](info, receiveInstance);
            return exports3;
          } catch (e) {
            err("Module.instantiateWasm callback failed with error: " + e);
            return false;
          }
        }
        instantiateAsync();
        return {};
      }
      __ATINIT__.push({ func: function() {
        ___wasm_call_ctors();
      } });
      function _abort() {
        abort();
      }
      function _emscripten_get_heap_size() {
        return HEAP8.length;
      }
      function _emscripten_get_sbrk_ptr() {
        return 264624;
      }
      function _emscripten_memcpy_big(dest, src, num) {
        HEAPU8.set(HEAPU8.subarray(src, src + num), dest);
      }
      function emscripten_realloc_buffer(size2) {
        try {
          wasmMemory.grow(size2 - buffer.byteLength + 65535 >> 16);
          updateGlobalBufferAndViews(wasmMemory.buffer);
          return 1;
        } catch (e) {
        }
      }
      function _emscripten_resize_heap(requestedSize) {
        var oldSize = _emscripten_get_heap_size();
        var PAGE_MULTIPLE = 65536;
        var LIMIT = 2147483648 - PAGE_MULTIPLE;
        if (requestedSize > LIMIT) {
          return false;
        }
        var MIN_TOTAL_MEMORY = 16777216;
        var newSize = Math.max(oldSize, MIN_TOTAL_MEMORY);
        while (newSize < requestedSize) {
          if (newSize <= 536870912) {
            newSize = alignUp(2 * newSize, PAGE_MULTIPLE);
          } else {
            newSize = Math.min(alignUp((3 * newSize + 2147483648) / 4, PAGE_MULTIPLE), LIMIT);
          }
        }
        var replacement = emscripten_realloc_buffer(newSize);
        if (!replacement) {
          return false;
        }
        return true;
      }
      var SYSCALLS = { buffers: [null, [], []], printChar: function(stream, curr) {
        var buffer2 = SYSCALLS.buffers[stream];
        if (curr === 0 || curr === 10) {
          (stream === 1 ? out : err)(UTF8ArrayToString(buffer2, 0));
          buffer2.length = 0;
        } else {
          buffer2.push(curr);
        }
      }, varargs: 0, get: function(varargs) {
        SYSCALLS.varargs += 4;
        var ret = HEAP32[SYSCALLS.varargs - 4 >> 2];
        return ret;
      }, getStr: function() {
        var ret = UTF8ToString(SYSCALLS.get());
        return ret;
      }, get64: function() {
        var low = SYSCALLS.get();
        SYSCALLS.get();
        return low;
      }, getZero: function() {
        SYSCALLS.get();
      } };
      function _fd_close(fd) {
        try {
          return 0;
        } catch (e) {
          if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError))
            abort(e);
          return e.errno;
        }
      }
      function _fd_seek(fd, offset_low, offset_high, whence, newOffset) {
        try {
          return 0;
        } catch (e) {
          if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError))
            abort(e);
          return e.errno;
        }
      }
      function _fd_write(fd, iov, iovcnt, pnum) {
        try {
          var num = 0;
          for (var i = 0; i < iovcnt; i++) {
            var ptr = HEAP32[iov + i * 8 >> 2];
            var len = HEAP32[iov + (i * 8 + 4) >> 2];
            for (var j = 0; j < len; j++) {
              SYSCALLS.printChar(fd, HEAPU8[ptr + j]);
            }
            num += len;
          }
          HEAP32[pnum >> 2] = num;
          return 0;
        } catch (e) {
          if (typeof FS === "undefined" || !(e instanceof FS.ErrnoError))
            abort(e);
          return e.errno;
        }
      }
      function _setTempRet0($i) {
      }
      var asmLibraryArg = { "abort": _abort, "emscripten_get_sbrk_ptr": _emscripten_get_sbrk_ptr, "emscripten_memcpy_big": _emscripten_memcpy_big, "emscripten_resize_heap": _emscripten_resize_heap, "fd_close": _fd_close, "fd_seek": _fd_seek, "fd_write": _fd_write, "memory": wasmMemory, "setTempRet0": _setTempRet0, "table": wasmTable };
      var asm = createWasm();
      Module["asm"] = asm;
      var ___wasm_call_ctors = Module["___wasm_call_ctors"] = function() {
        return Module["asm"]["__wasm_call_ctors"].apply(null, arguments);
      };
      Module["_malloc"] = function() {
        return Module["asm"]["malloc"].apply(null, arguments);
      };
      Module["_free"] = function() {
        return Module["asm"]["free"].apply(null, arguments);
      };
      Module["_getLastError"] = function() {
        return Module["asm"]["getLastError"].apply(null, arguments);
      };
      Module["_compilePattern"] = function() {
        return Module["asm"]["compilePattern"].apply(null, arguments);
      };
      Module["_disposeCompiledPatterns"] = function() {
        return Module["asm"]["disposeCompiledPatterns"].apply(null, arguments);
      };
      Module["_findBestMatch"] = function() {
        return Module["asm"]["findBestMatch"].apply(null, arguments);
      };
      Module["___cxa_demangle"] = function() {
        return Module["asm"]["__cxa_demangle"].apply(null, arguments);
      };
      Module["_setThrew"] = function() {
        return Module["asm"]["setThrew"].apply(null, arguments);
      };
      var stackSave = Module["stackSave"] = function() {
        return Module["asm"]["stackSave"].apply(null, arguments);
      };
      var stackAlloc = Module["stackAlloc"] = function() {
        return Module["asm"]["stackAlloc"].apply(null, arguments);
      };
      var stackRestore = Module["stackRestore"] = function() {
        return Module["asm"]["stackRestore"].apply(null, arguments);
      };
      Module["__growWasmMemory"] = function() {
        return Module["asm"]["__growWasmMemory"].apply(null, arguments);
      };
      Module["dynCall_vi"] = function() {
        return Module["asm"]["dynCall_vi"].apply(null, arguments);
      };
      Module["dynCall_iiii"] = function() {
        return Module["asm"]["dynCall_iiii"].apply(null, arguments);
      };
      Module["dynCall_iiiii"] = function() {
        return Module["asm"]["dynCall_iiiii"].apply(null, arguments);
      };
      Module["dynCall_iii"] = function() {
        return Module["asm"]["dynCall_iii"].apply(null, arguments);
      };
      Module["dynCall_iidiiii"] = function() {
        return Module["asm"]["dynCall_iidiiii"].apply(null, arguments);
      };
      Module["dynCall_vii"] = function() {
        return Module["asm"]["dynCall_vii"].apply(null, arguments);
      };
      Module["dynCall_ii"] = function() {
        return Module["asm"]["dynCall_ii"].apply(null, arguments);
      };
      Module["dynCall_i"] = function() {
        return Module["asm"]["dynCall_i"].apply(null, arguments);
      };
      Module["dynCall_v"] = function() {
        return Module["asm"]["dynCall_v"].apply(null, arguments);
      };
      Module["dynCall_viiiiii"] = function() {
        return Module["asm"]["dynCall_viiiiii"].apply(null, arguments);
      };
      Module["dynCall_viiiii"] = function() {
        return Module["asm"]["dynCall_viiiii"].apply(null, arguments);
      };
      Module["dynCall_viiii"] = function() {
        return Module["asm"]["dynCall_viiii"].apply(null, arguments);
      };
      Module["dynCall_jiji"] = function() {
        return Module["asm"]["dynCall_jiji"].apply(null, arguments);
      };
      Module["asm"] = asm;
      Module["ccall"] = ccall;
      var calledRun;
      Module["then"] = function(func) {
        if (calledRun) {
          func(Module);
        } else {
          var old = Module["onRuntimeInitialized"];
          Module["onRuntimeInitialized"] = function() {
            if (old)
              old();
            func(Module);
          };
        }
        return Module;
      };
      dependenciesFulfilled = function runCaller() {
        if (!calledRun)
          run();
        if (!calledRun)
          dependenciesFulfilled = runCaller;
      };
      function run(args) {
        if (runDependencies > 0) {
          return;
        }
        preRun();
        if (runDependencies > 0)
          return;
        function doRun() {
          if (calledRun)
            return;
          calledRun = true;
          if (ABORT)
            return;
          initRuntime();
          preMain();
          if (Module["onRuntimeInitialized"])
            Module["onRuntimeInitialized"]();
          postRun();
        }
        if (Module["setStatus"]) {
          Module["setStatus"]("Running...");
          setTimeout(function() {
            setTimeout(function() {
              Module["setStatus"]("");
            }, 1);
            doRun();
          }, 1);
        } else {
          doRun();
        }
      }
      Module["run"] = run;
      if (Module["preInit"]) {
        if (typeof Module["preInit"] == "function")
          Module["preInit"] = [Module["preInit"]];
        while (Module["preInit"].length > 0) {
          Module["preInit"].pop()();
        }
      }
      run();
      return Onigasm2;
    };
  }();
  module2.exports = Onigasm;
})(onigasm);
var onigasmExports = onigasm.exports;
Object.defineProperty(onigasmH, "__esModule", { value: true });
const OnigasmModuleFactory = onigasmExports;
async function initModule(bytes) {
  return new Promise((resolve2, reject) => {
    const { log: log2, warn: warn2, error: error2 } = console;
    OnigasmModuleFactory({
      instantiateWasm(imports, successCallback) {
        WebAssembly.instantiate(bytes, imports).then((output) => {
          successCallback(output.instance);
        }).catch((e) => {
          throw e;
        });
        return {};
      }
    }).then((moduleH) => {
      onigasmH.onigasmH = moduleH;
      resolve2();
    });
    if (typeof print !== "undefined") {
      console.log = log2;
      console.error = error2;
      console.warn = warn2;
    }
  });
}
let isInitialized = false;
async function loadWASM$1(data) {
  if (isInitialized) {
    throw new Error(`Onigasm#init has been called and was succesful, subsequent calls are not allowed once initialized`);
  }
  if (typeof data === "string") {
    const arrayBuffer = await (await fetch(data)).arrayBuffer();
    await initModule(arrayBuffer);
  } else if (data instanceof ArrayBuffer) {
    await initModule(data);
  } else {
    throw new TypeError(`Expected a string (URL of .wasm file) or ArrayBuffer (.wasm file itself) as first parameter`);
  }
  isInitialized = true;
}
onigasmH.loadWASM = loadWASM$1;
var OnigRegExp$1 = {};
var OnigScanner$1 = {};
var iterator;
var hasRequiredIterator;
function requireIterator() {
  if (hasRequiredIterator)
    return iterator;
  hasRequiredIterator = 1;
  iterator = function(Yallist2) {
    Yallist2.prototype[Symbol.iterator] = function* () {
      for (let walker = this.head; walker; walker = walker.next) {
        yield walker.value;
      }
    };
  };
  return iterator;
}
var yallist = Yallist$1;
Yallist$1.Node = Node$1;
Yallist$1.create = Yallist$1;
function Yallist$1(list2) {
  var self2 = this;
  if (!(self2 instanceof Yallist$1)) {
    self2 = new Yallist$1();
  }
  self2.tail = null;
  self2.head = null;
  self2.length = 0;
  if (list2 && typeof list2.forEach === "function") {
    list2.forEach(function(item) {
      self2.push(item);
    });
  } else if (arguments.length > 0) {
    for (var i = 0, l = arguments.length; i < l; i++) {
      self2.push(arguments[i]);
    }
  }
  return self2;
}
Yallist$1.prototype.removeNode = function(node2) {
  if (node2.list !== this) {
    throw new Error("removing node which does not belong to this list");
  }
  var next = node2.next;
  var prev = node2.prev;
  if (next) {
    next.prev = prev;
  }
  if (prev) {
    prev.next = next;
  }
  if (node2 === this.head) {
    this.head = next;
  }
  if (node2 === this.tail) {
    this.tail = prev;
  }
  node2.list.length--;
  node2.next = null;
  node2.prev = null;
  node2.list = null;
  return next;
};
Yallist$1.prototype.unshiftNode = function(node2) {
  if (node2 === this.head) {
    return;
  }
  if (node2.list) {
    node2.list.removeNode(node2);
  }
  var head = this.head;
  node2.list = this;
  node2.next = head;
  if (head) {
    head.prev = node2;
  }
  this.head = node2;
  if (!this.tail) {
    this.tail = node2;
  }
  this.length++;
};
Yallist$1.prototype.pushNode = function(node2) {
  if (node2 === this.tail) {
    return;
  }
  if (node2.list) {
    node2.list.removeNode(node2);
  }
  var tail3 = this.tail;
  node2.list = this;
  node2.prev = tail3;
  if (tail3) {
    tail3.next = node2;
  }
  this.tail = node2;
  if (!this.head) {
    this.head = node2;
  }
  this.length++;
};
Yallist$1.prototype.push = function() {
  for (var i = 0, l = arguments.length; i < l; i++) {
    push(this, arguments[i]);
  }
  return this.length;
};
Yallist$1.prototype.unshift = function() {
  for (var i = 0, l = arguments.length; i < l; i++) {
    unshift(this, arguments[i]);
  }
  return this.length;
};
Yallist$1.prototype.pop = function() {
  if (!this.tail) {
    return void 0;
  }
  var res = this.tail.value;
  this.tail = this.tail.prev;
  if (this.tail) {
    this.tail.next = null;
  } else {
    this.head = null;
  }
  this.length--;
  return res;
};
Yallist$1.prototype.shift = function() {
  if (!this.head) {
    return void 0;
  }
  var res = this.head.value;
  this.head = this.head.next;
  if (this.head) {
    this.head.prev = null;
  } else {
    this.tail = null;
  }
  this.length--;
  return res;
};
Yallist$1.prototype.forEach = function(fn, thisp) {
  thisp = thisp || this;
  for (var walker = this.head, i = 0; walker !== null; i++) {
    fn.call(thisp, walker.value, i, this);
    walker = walker.next;
  }
};
Yallist$1.prototype.forEachReverse = function(fn, thisp) {
  thisp = thisp || this;
  for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {
    fn.call(thisp, walker.value, i, this);
    walker = walker.prev;
  }
};
Yallist$1.prototype.get = function(n2) {
  for (var i = 0, walker = this.head; walker !== null && i < n2; i++) {
    walker = walker.next;
  }
  if (i === n2 && walker !== null) {
    return walker.value;
  }
};
Yallist$1.prototype.getReverse = function(n2) {
  for (var i = 0, walker = this.tail; walker !== null && i < n2; i++) {
    walker = walker.prev;
  }
  if (i === n2 && walker !== null) {
    return walker.value;
  }
};
Yallist$1.prototype.map = function(fn, thisp) {
  thisp = thisp || this;
  var res = new Yallist$1();
  for (var walker = this.head; walker !== null; ) {
    res.push(fn.call(thisp, walker.value, this));
    walker = walker.next;
  }
  return res;
};
Yallist$1.prototype.mapReverse = function(fn, thisp) {
  thisp = thisp || this;
  var res = new Yallist$1();
  for (var walker = this.tail; walker !== null; ) {
    res.push(fn.call(thisp, walker.value, this));
    walker = walker.prev;
  }
  return res;
};
Yallist$1.prototype.reduce = function(fn, initial) {
  var acc;
  var walker = this.head;
  if (arguments.length > 1) {
    acc = initial;
  } else if (this.head) {
    walker = this.head.next;
    acc = this.head.value;
  } else {
    throw new TypeError("Reduce of empty list with no initial value");
  }
  for (var i = 0; walker !== null; i++) {
    acc = fn(acc, walker.value, i);
    walker = walker.next;
  }
  return acc;
};
Yallist$1.prototype.reduceReverse = function(fn, initial) {
  var acc;
  var walker = this.tail;
  if (arguments.length > 1) {
    acc = initial;
  } else if (this.tail) {
    walker = this.tail.prev;
    acc = this.tail.value;
  } else {
    throw new TypeError("Reduce of empty list with no initial value");
  }
  for (var i = this.length - 1; walker !== null; i--) {
    acc = fn(acc, walker.value, i);
    walker = walker.prev;
  }
  return acc;
};
Yallist$1.prototype.toArray = function() {
  var arr = new Array(this.length);
  for (var i = 0, walker = this.head; walker !== null; i++) {
    arr[i] = walker.value;
    walker = walker.next;
  }
  return arr;
};
Yallist$1.prototype.toArrayReverse = function() {
  var arr = new Array(this.length);
  for (var i = 0, walker = this.tail; walker !== null; i++) {
    arr[i] = walker.value;
    walker = walker.prev;
  }
  return arr;
};
Yallist$1.prototype.slice = function(from2, to) {
  to = to || this.length;
  if (to < 0) {
    to += this.length;
  }
  from2 = from2 || 0;
  if (from2 < 0) {
    from2 += this.length;
  }
  var ret = new Yallist$1();
  if (to < from2 || to < 0) {
    return ret;
  }
  if (from2 < 0) {
    from2 = 0;
  }
  if (to > this.length) {
    to = this.length;
  }
  for (var i = 0, walker = this.head; walker !== null && i < from2; i++) {
    walker = walker.next;
  }
  for (; walker !== null && i < to; i++, walker = walker.next) {
    ret.push(walker.value);
  }
  return ret;
};
Yallist$1.prototype.sliceReverse = function(from2, to) {
  to = to || this.length;
  if (to < 0) {
    to += this.length;
  }
  from2 = from2 || 0;
  if (from2 < 0) {
    from2 += this.length;
  }
  var ret = new Yallist$1();
  if (to < from2 || to < 0) {
    return ret;
  }
  if (from2 < 0) {
    from2 = 0;
  }
  if (to > this.length) {
    to = this.length;
  }
  for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {
    walker = walker.prev;
  }
  for (; walker !== null && i > from2; i--, walker = walker.prev) {
    ret.push(walker.value);
  }
  return ret;
};
Yallist$1.prototype.splice = function(start, deleteCount) {
  if (start > this.length) {
    start = this.length - 1;
  }
  if (start < 0) {
    start = this.length + start;
  }
  for (var i = 0, walker = this.head; walker !== null && i < start; i++) {
    walker = walker.next;
  }
  var ret = [];
  for (var i = 0; walker && i < deleteCount; i++) {
    ret.push(walker.value);
    walker = this.removeNode(walker);
  }
  if (walker === null) {
    walker = this.tail;
  }
  if (walker !== this.head && walker !== this.tail) {
    walker = walker.prev;
  }
  for (var i = 2; i < arguments.length; i++) {
    walker = insert(this, walker, arguments[i]);
  }
  return ret;
};
Yallist$1.prototype.reverse = function() {
  var head = this.head;
  var tail3 = this.tail;
  for (var walker = head; walker !== null; walker = walker.prev) {
    var p2 = walker.prev;
    walker.prev = walker.next;
    walker.next = p2;
  }
  this.head = tail3;
  this.tail = head;
  return this;
};
function insert(self2, node2, value) {
  var inserted = node2 === self2.head ? new Node$1(value, null, node2, self2) : new Node$1(value, node2, node2.next, self2);
  if (inserted.next === null) {
    self2.tail = inserted;
  }
  if (inserted.prev === null) {
    self2.head = inserted;
  }
  self2.length++;
  return inserted;
}
function push(self2, item) {
  self2.tail = new Node$1(item, self2.tail, null, self2);
  if (!self2.head) {
    self2.head = self2.tail;
  }
  self2.length++;
}
function unshift(self2, item) {
  self2.head = new Node$1(item, null, self2.head, self2);
  if (!self2.tail) {
    self2.tail = self2.head;
  }
  self2.length++;
}
function Node$1(value, prev, next, list2) {
  if (!(this instanceof Node$1)) {
    return new Node$1(value, prev, next, list2);
  }
  this.list = list2;
  this.value = value;
  if (prev) {
    prev.next = this;
    this.prev = prev;
  } else {
    this.prev = null;
  }
  if (next) {
    next.prev = this;
    this.next = next;
  } else {
    this.next = null;
  }
}
try {
  requireIterator()(Yallist$1);
} catch (er) {
}
const Yallist = yallist;
const MAX = Symbol("max");
const LENGTH = Symbol("length");
const LENGTH_CALCULATOR = Symbol("lengthCalculator");
const ALLOW_STALE = Symbol("allowStale");
const MAX_AGE = Symbol("maxAge");
const DISPOSE = Symbol("dispose");
const NO_DISPOSE_ON_SET = Symbol("noDisposeOnSet");
const LRU_LIST = Symbol("lruList");
const CACHE = Symbol("cache");
const UPDATE_AGE_ON_GET = Symbol("updateAgeOnGet");
const naiveLength = () => 1;
let LRUCache$1 = class LRUCache2 {
  constructor(options) {
    if (typeof options === "number")
      options = { max: options };
    if (!options)
      options = {};
    if (options.max && (typeof options.max !== "number" || options.max < 0))
      throw new TypeError("max must be a non-negative number");
    this[MAX] = options.max || Infinity;
    const lc = options.length || naiveLength;
    this[LENGTH_CALCULATOR] = typeof lc !== "function" ? naiveLength : lc;
    this[ALLOW_STALE] = options.stale || false;
    if (options.maxAge && typeof options.maxAge !== "number")
      throw new TypeError("maxAge must be a number");
    this[MAX_AGE] = options.maxAge || 0;
    this[DISPOSE] = options.dispose;
    this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false;
    this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false;
    this.reset();
  }
  // resize the cache when the max changes.
  set max(mL) {
    if (typeof mL !== "number" || mL < 0)
      throw new TypeError("max must be a non-negative number");
    this[MAX] = mL || Infinity;
    trim(this);
  }
  get max() {
    return this[MAX];
  }
  set allowStale(allowStale) {
    this[ALLOW_STALE] = !!allowStale;
  }
  get allowStale() {
    return this[ALLOW_STALE];
  }
  set maxAge(mA) {
    if (typeof mA !== "number")
      throw new TypeError("maxAge must be a non-negative number");
    this[MAX_AGE] = mA;
    trim(this);
  }
  get maxAge() {
    return this[MAX_AGE];
  }
  // resize the cache when the lengthCalculator changes.
  set lengthCalculator(lC) {
    if (typeof lC !== "function")
      lC = naiveLength;
    if (lC !== this[LENGTH_CALCULATOR]) {
      this[LENGTH_CALCULATOR] = lC;
      this[LENGTH] = 0;
      this[LRU_LIST].forEach((hit) => {
        hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key);
        this[LENGTH] += hit.length;
      });
    }
    trim(this);
  }
  get lengthCalculator() {
    return this[LENGTH_CALCULATOR];
  }
  get length() {
    return this[LENGTH];
  }
  get itemCount() {
    return this[LRU_LIST].length;
  }
  rforEach(fn, thisp) {
    thisp = thisp || this;
    for (let walker = this[LRU_LIST].tail; walker !== null; ) {
      const prev = walker.prev;
      forEachStep(this, fn, walker, thisp);
      walker = prev;
    }
  }
  forEach(fn, thisp) {
    thisp = thisp || this;
    for (let walker = this[LRU_LIST].head; walker !== null; ) {
      const next = walker.next;
      forEachStep(this, fn, walker, thisp);
      walker = next;
    }
  }
  keys() {
    return this[LRU_LIST].toArray().map((k) => k.key);
  }
  values() {
    return this[LRU_LIST].toArray().map((k) => k.value);
  }
  reset() {
    if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) {
      this[LRU_LIST].forEach((hit) => this[DISPOSE](hit.key, hit.value));
    }
    this[CACHE] = /* @__PURE__ */ new Map();
    this[LRU_LIST] = new Yallist();
    this[LENGTH] = 0;
  }
  dump() {
    return this[LRU_LIST].map((hit) => isStale(this, hit) ? false : {
      k: hit.key,
      v: hit.value,
      e: hit.now + (hit.maxAge || 0)
    }).toArray().filter((h2) => h2);
  }
  dumpLru() {
    return this[LRU_LIST];
  }
  set(key, value, maxAge) {
    maxAge = maxAge || this[MAX_AGE];
    if (maxAge && typeof maxAge !== "number")
      throw new TypeError("maxAge must be a number");
    const now = maxAge ? Date.now() : 0;
    const len = this[LENGTH_CALCULATOR](value, key);
    if (this[CACHE].has(key)) {
      if (len > this[MAX]) {
        del(this, this[CACHE].get(key));
        return false;
      }
      const node2 = this[CACHE].get(key);
      const item = node2.value;
      if (this[DISPOSE]) {
        if (!this[NO_DISPOSE_ON_SET])
          this[DISPOSE](key, item.value);
      }
      item.now = now;
      item.maxAge = maxAge;
      item.value = value;
      this[LENGTH] += len - item.length;
      item.length = len;
      this.get(key);
      trim(this);
      return true;
    }
    const hit = new Entry(key, value, len, now, maxAge);
    if (hit.length > this[MAX]) {
      if (this[DISPOSE])
        this[DISPOSE](key, value);
      return false;
    }
    this[LENGTH] += hit.length;
    this[LRU_LIST].unshift(hit);
    this[CACHE].set(key, this[LRU_LIST].head);
    trim(this);
    return true;
  }
  has(key) {
    if (!this[CACHE].has(key))
      return false;
    const hit = this[CACHE].get(key).value;
    return !isStale(this, hit);
  }
  get(key) {
    return get(this, key, true);
  }
  peek(key) {
    return get(this, key, false);
  }
  pop() {
    const node2 = this[LRU_LIST].tail;
    if (!node2)
      return null;
    del(this, node2);
    return node2.value;
  }
  del(key) {
    del(this, this[CACHE].get(key));
  }
  load(arr) {
    this.reset();
    const now = Date.now();
    for (let l = arr.length - 1; l >= 0; l--) {
      const hit = arr[l];
      const expiresAt = hit.e || 0;
      if (expiresAt === 0)
        this.set(hit.k, hit.v);
      else {
        const maxAge = expiresAt - now;
        if (maxAge > 0) {
          this.set(hit.k, hit.v, maxAge);
        }
      }
    }
  }
  prune() {
    this[CACHE].forEach((value, key) => get(this, key, false));
  }
};
const get = (self2, key, doUse) => {
  const node2 = self2[CACHE].get(key);
  if (node2) {
    const hit = node2.value;
    if (isStale(self2, hit)) {
      del(self2, node2);
      if (!self2[ALLOW_STALE])
        return void 0;
    } else {
      if (doUse) {
        if (self2[UPDATE_AGE_ON_GET])
          node2.value.now = Date.now();
        self2[LRU_LIST].unshiftNode(node2);
      }
    }
    return hit.value;
  }
};
const isStale = (self2, hit) => {
  if (!hit || !hit.maxAge && !self2[MAX_AGE])
    return false;
  const diff = Date.now() - hit.now;
  return hit.maxAge ? diff > hit.maxAge : self2[MAX_AGE] && diff > self2[MAX_AGE];
};
const trim = (self2) => {
  if (self2[LENGTH] > self2[MAX]) {
    for (let walker = self2[LRU_LIST].tail; self2[LENGTH] > self2[MAX] && walker !== null; ) {
      const prev = walker.prev;
      del(self2, walker);
      walker = prev;
    }
  }
};
const del = (self2, node2) => {
  if (node2) {
    const hit = node2.value;
    if (self2[DISPOSE])
      self2[DISPOSE](hit.key, hit.value);
    self2[LENGTH] -= hit.length;
    self2[CACHE].delete(hit.key);
    self2[LRU_LIST].removeNode(node2);
  }
};
class Entry {
  constructor(key, value, length2, now, maxAge) {
    this.key = key;
    this.value = value;
    this.length = length2;
    this.now = now;
    this.maxAge = maxAge || 0;
  }
}
const forEachStep = (self2, fn, node2, thisp) => {
  let hit = node2.value;
  if (isStale(self2, hit)) {
    del(self2, node2);
    if (!self2[ALLOW_STALE])
      hit = void 0;
  }
  if (hit)
    fn.call(thisp, hit.value, hit.key, self2);
};
var lruCache = LRUCache$1;
var OnigString$1 = {};
Object.defineProperty(OnigString$1, "__esModule", { value: true });
class OnigString {
  constructor(content) {
    this.substring = (start, end) => {
      return this.source.substring(start, end);
    };
    this.toString = (start, end) => {
      return this.source;
    };
    if (typeof content !== "string") {
      throw new TypeError("Argument must be a string");
    }
    this.source = content;
    this._utf8Bytes = null;
    this._utf8Indexes = null;
  }
  get utf8Bytes() {
    if (!this._utf8Bytes) {
      this.encode();
    }
    return this._utf8Bytes;
  }
  /**
   * Returns `null` if all utf8 offsets match utf-16 offset (content has no multi byte characters)
   */
  get utf8Indexes() {
    if (!this._utf8Bytes) {
      this.encode();
    }
    return this._utf8Indexes;
  }
  get content() {
    return this.source;
  }
  get length() {
    return this.source.length;
  }
  get hasMultiByteCharacters() {
    return this.utf8Indexes !== null;
  }
  convertUtf8OffsetToUtf16(utf8Offset) {
    if (utf8Offset < 0) {
      return 0;
    }
    const utf8Array = this._utf8Bytes;
    if (utf8Offset >= utf8Array.length - 1) {
      return this.source.length;
    }
    const utf8OffsetMap = this.utf8Indexes;
    if (utf8OffsetMap && utf8Offset >= this._mappingTableStartOffset) {
      return findFirstInSorted(utf8OffsetMap, utf8Offset - this._mappingTableStartOffset) + this._mappingTableStartOffset;
    }
    return utf8Offset;
  }
  convertUtf16OffsetToUtf8(utf16Offset) {
    if (utf16Offset < 0) {
      return 0;
    }
    const utf8Array = this._utf8Bytes;
    if (utf16Offset >= this.source.length) {
      return utf8Array.length - 1;
    }
    const utf8OffsetMap = this.utf8Indexes;
    if (utf8OffsetMap && utf16Offset >= this._mappingTableStartOffset) {
      return utf8OffsetMap[utf16Offset - this._mappingTableStartOffset] + this._mappingTableStartOffset;
    }
    return utf16Offset;
  }
  encode() {
    const str2 = this.source;
    const n2 = str2.length;
    let utf16OffsetToUtf8;
    let utf8Offset = 0;
    let mappingTableStartOffset = 0;
    function createOffsetTable(startOffset) {
      const maxUtf8Len = (n2 - startOffset) * 3;
      if (maxUtf8Len <= 255) {
        utf16OffsetToUtf8 = new Uint8Array(n2 - startOffset);
      } else if (maxUtf8Len <= 65535) {
        utf16OffsetToUtf8 = new Uint16Array(n2 - startOffset);
      } else {
        utf16OffsetToUtf8 = new Uint32Array(n2 - startOffset);
      }
      mappingTableStartOffset = startOffset;
      utf16OffsetToUtf8[utf8Offset++] = 0;
    }
    const u8view = new Uint8Array(
      n2 * 3 + 1
      /** null termination character */
    );
    let ptrHead = 0;
    let i = 0;
    while (i < str2.length) {
      let codepoint;
      const c = str2.charCodeAt(i);
      if (utf16OffsetToUtf8) {
        utf16OffsetToUtf8[utf8Offset++] = ptrHead - mappingTableStartOffset;
      }
      if (c < 55296 || c > 57343) {
        codepoint = c;
      } else if (c >= 56320) {
        codepoint = 65533;
      } else {
        if (i === n2 - 1) {
          codepoint = 65533;
        } else {
          const d = str2.charCodeAt(i + 1);
          if (56320 <= d && d <= 57343) {
            if (!utf16OffsetToUtf8) {
              createOffsetTable(i);
            }
            const a = c & 1023;
            const b = d & 1023;
            codepoint = 65536 + (a << 10) + b;
            i += 1;
            utf16OffsetToUtf8[utf8Offset++] = ptrHead - mappingTableStartOffset;
          } else {
            codepoint = 65533;
          }
        }
      }
      let bytesRequiredToEncode;
      let offset;
      if (codepoint <= 127) {
        bytesRequiredToEncode = 1;
        offset = 0;
      } else if (codepoint <= 2047) {
        bytesRequiredToEncode = 2;
        offset = 192;
      } else if (codepoint <= 65535) {
        bytesRequiredToEncode = 3;
        offset = 224;
      } else {
        bytesRequiredToEncode = 4;
        offset = 240;
      }
      if (bytesRequiredToEncode === 1) {
        u8view[ptrHead++] = codepoint;
      } else {
        if (!utf16OffsetToUtf8) {
          createOffsetTable(ptrHead);
        }
        u8view[ptrHead++] = (codepoint >> 6 * --bytesRequiredToEncode) + offset;
        while (bytesRequiredToEncode > 0) {
          const temp = codepoint >> 6 * (bytesRequiredToEncode - 1);
          u8view[ptrHead++] = 128 | temp & 63;
          bytesRequiredToEncode -= 1;
        }
      }
      i += 1;
    }
    const utf8 = u8view.slice(0, ptrHead + 1);
    utf8[ptrHead] = 0;
    this._utf8Bytes = utf8;
    if (utf16OffsetToUtf8) {
      this._utf8Indexes = utf16OffsetToUtf8;
      this._mappingTableStartOffset = mappingTableStartOffset;
    }
  }
}
function findFirstInSorted(array2, i) {
  let low = 0;
  let high = array2.length;
  if (high === 0) {
    return 0;
  }
  while (low < high) {
    const mid = Math.floor((low + high) / 2);
    if (array2[mid] >= i) {
      high = mid;
    } else {
      low = mid + 1;
    }
  }
  while (low > 0 && (low >= array2.length || array2[low] > i)) {
    low--;
  }
  if (low > 0 && array2[low] === array2[low - 1]) {
    low--;
  }
  return low;
}
OnigString$1.default = OnigString;
Object.defineProperty(OnigScanner$1, "__esModule", { value: true });
const LRUCache3 = lruCache;
const onigasmH_1$1 = onigasmH;
const OnigString_1$1 = OnigString$1;
function mallocAndWriteString(str2) {
  const ptr = onigasmH_1$1.onigasmH._malloc(str2.utf8Bytes.length);
  onigasmH_1$1.onigasmH.HEAPU8.set(str2.utf8Bytes, ptr);
  return ptr;
}
function convertUTF8BytesFromPtrToString(ptr) {
  const chars2 = [];
  let i = 0;
  while (onigasmH_1$1.onigasmH.HEAPU8[ptr] !== 0) {
    chars2[i++] = onigasmH_1$1.onigasmH.HEAPU8[ptr++];
  }
  return chars2.join();
}
const cache = new LRUCache3({
  dispose: (scanner, info) => {
    const regexTPtrsPtr = onigasmH_1$1.onigasmH._malloc(info.regexTPtrs.length);
    onigasmH_1$1.onigasmH.HEAPU8.set(info.regexTPtrs, regexTPtrsPtr);
    const status2 = onigasmH_1$1.onigasmH._disposeCompiledPatterns(regexTPtrsPtr, scanner.patterns.length);
    if (status2 !== 0) {
      const errMessage = convertUTF8BytesFromPtrToString(onigasmH_1$1.onigasmH._getLastError());
      throw new Error(errMessage);
    }
    onigasmH_1$1.onigasmH._free(regexTPtrsPtr);
  },
  max: 1e3
});
class OnigScanner {
  /**
   * Create a new scanner with the given patterns
   * @param patterns  An array of string patterns
   */
  constructor(patterns) {
    if (onigasmH_1$1.onigasmH === null) {
      throw new Error(`Onigasm has not been initialized, call loadWASM from 'onigasm' exports before using any other API`);
    }
    for (let i = 0; i < patterns.length; i++) {
      const pattern = patterns[i];
      if (typeof pattern !== "string") {
        throw new TypeError(`First parameter to OnigScanner constructor must be array of (pattern) strings`);
      }
    }
    this.sources = patterns.slice();
  }
  get patterns() {
    return this.sources.slice();
  }
  /**
   * Find the next match from a given position
   * @param string The string to search
   * @param startPosition The optional position to start at, defaults to 0
   * @param callback The (error, match) function to call when done, match will null when there is no match
   */
  findNextMatch(string3, startPosition, callback) {
    if (startPosition == null) {
      startPosition = 0;
    }
    if (typeof startPosition === "function") {
      callback = startPosition;
      startPosition = 0;
    }
    try {
      const match2 = this.findNextMatchSync(string3, startPosition);
      callback(null, match2);
    } catch (error2) {
      callback(error2);
    }
  }
  /**
   * Find the next match from a given position
   * @param string The string to search
   * @param startPosition The optional position to start at, defaults to 0
   */
  findNextMatchSync(string3, startPosition) {
    if (startPosition == null) {
      startPosition = 0;
    }
    startPosition = this.convertToNumber(startPosition);
    let onigNativeInfo = cache.get(this);
    let status2 = 0;
    if (!onigNativeInfo) {
      const regexTAddrRecieverPtr = onigasmH_1$1.onigasmH._malloc(4);
      const regexTPtrs = [];
      for (let i = 0; i < this.sources.length; i++) {
        const pattern = this.sources[i];
        const patternStrPtr = mallocAndWriteString(new OnigString_1$1.default(pattern));
        status2 = onigasmH_1$1.onigasmH._compilePattern(patternStrPtr, regexTAddrRecieverPtr);
        if (status2 !== 0) {
          const errMessage = convertUTF8BytesFromPtrToString(onigasmH_1$1.onigasmH._getLastError());
          throw new Error(errMessage);
        }
        const regexTAddress = onigasmH_1$1.onigasmH.HEAP32[regexTAddrRecieverPtr / 4];
        regexTPtrs.push(regexTAddress);
        onigasmH_1$1.onigasmH._free(patternStrPtr);
      }
      onigNativeInfo = {
        regexTPtrs: new Uint8Array(Uint32Array.from(regexTPtrs).buffer)
      };
      onigasmH_1$1.onigasmH._free(regexTAddrRecieverPtr);
      cache.set(this, onigNativeInfo);
    }
    const onigString = string3 instanceof OnigString_1$1.default ? string3 : new OnigString_1$1.default(this.convertToString(string3));
    const strPtr = mallocAndWriteString(onigString);
    const resultInfoReceiverPtr = onigasmH_1$1.onigasmH._malloc(8);
    const regexTPtrsPtr = onigasmH_1$1.onigasmH._malloc(onigNativeInfo.regexTPtrs.length);
    onigasmH_1$1.onigasmH.HEAPU8.set(onigNativeInfo.regexTPtrs, regexTPtrsPtr);
    status2 = onigasmH_1$1.onigasmH._findBestMatch(
      // regex_t **patterns
      regexTPtrsPtr,
      // int patternCount
      this.sources.length,
      // UChar *utf8String
      strPtr,
      // int strLen
      onigString.utf8Bytes.length - 1,
      // int startOffset
      onigString.convertUtf16OffsetToUtf8(startPosition),
      // int *resultInfo
      resultInfoReceiverPtr
    );
    if (status2 !== 0) {
      const errMessage = convertUTF8BytesFromPtrToString(onigasmH_1$1.onigasmH._getLastError());
      throw new Error(errMessage);
    }
    const [
      // The index of pattern which matched the string at least offset from 0 (start)
      bestPatternIdx,
      // Begin address of capture info encoded as pairs
      // like [start, end, start, end, start, end, ...]
      //  - first start-end pair is entire match (index 0 and 1)
      //  - subsequent pairs are capture groups (2, 3 = first capture group, 4, 5 = second capture group and so on)
      encodedResultBeginAddress,
      // Length of the [start, end, ...] sequence so we know how much memory to read (will always be 0 or multiple of 2)
      encodedResultLength
    ] = new Uint32Array(onigasmH_1$1.onigasmH.HEAPU32.buffer, resultInfoReceiverPtr, 3);
    onigasmH_1$1.onigasmH._free(strPtr);
    onigasmH_1$1.onigasmH._free(resultInfoReceiverPtr);
    onigasmH_1$1.onigasmH._free(regexTPtrsPtr);
    if (encodedResultLength > 0) {
      const encodedResult = new Uint32Array(onigasmH_1$1.onigasmH.HEAPU32.buffer, encodedResultBeginAddress, encodedResultLength);
      const captureIndices = [];
      let i = 0;
      let captureIdx = 0;
      while (i < encodedResultLength) {
        const index = captureIdx++;
        let start = encodedResult[i++];
        let end = encodedResult[i++];
        if (onigString.hasMultiByteCharacters) {
          start = onigString.convertUtf8OffsetToUtf16(start);
          end = onigString.convertUtf8OffsetToUtf16(end);
        }
        captureIndices.push({
          end,
          index,
          length: end - start,
          start
        });
      }
      onigasmH_1$1.onigasmH._free(encodedResultBeginAddress);
      return {
        captureIndices,
        index: bestPatternIdx,
        scanner: this
      };
    }
    return null;
  }
  convertToString(value) {
    if (value === void 0) {
      return "undefined";
    }
    if (value === null) {
      return "null";
    }
    if (value instanceof OnigString_1$1.default) {
      return value.content;
    }
    return value.toString();
  }
  convertToNumber(value) {
    value = parseInt(value, 10);
    if (!isFinite(value)) {
      value = 0;
    }
    value = Math.max(value, 0);
    return value;
  }
}
OnigScanner$1.OnigScanner = OnigScanner;
OnigScanner$1.default = OnigScanner;
Object.defineProperty(OnigRegExp$1, "__esModule", { value: true });
const OnigScanner_1$1 = OnigScanner$1;
class OnigRegExp {
  /**
   * Create a new regex with the given pattern
   * @param source A string pattern
   */
  constructor(source) {
    this.source = source;
    try {
      this.scanner = new OnigScanner_1$1.default([this.source]);
    } catch (error2) {
    }
  }
  /**
   * Synchronously search the string for a match starting at the given position
   * @param string The string to search
   * @param startPosition The optional position to start the search at, defaults to `0`
   */
  searchSync(string3, startPosition) {
    let match2;
    if (startPosition == null) {
      startPosition = 0;
    }
    match2 = this.scanner.findNextMatchSync(string3, startPosition);
    return this.captureIndicesForMatch(string3, match2);
  }
  /**
   * Search the string for a match starting at the given position
   * @param string The string to search
   * @param startPosition The optional position to start the search at, defaults to `0`
   * @param callback The `(error, match)` function to call when done, match will be null if no matches were found. match will be an array of objects for each matched group on a successful search
   */
  search(string3, startPosition, callback) {
    if (startPosition == null) {
      startPosition = 0;
    }
    if (typeof startPosition === "function") {
      callback = startPosition;
      startPosition = 0;
    }
    try {
      const ret = this.searchSync(string3, startPosition);
      callback(null, ret);
    } catch (error2) {
      callback(error2);
    }
  }
  /**
   * Synchronously test if this regular expression matches the given string
   * @param string The string to test against
   */
  testSync(string3) {
    if (typeof this.source === "boolean" || typeof string3 === "boolean") {
      return this.source === string3;
    }
    return this.searchSync(string3) != null;
  }
  /**
   * Test if this regular expression matches the given string
   * @param string The string to test against
   * @param callback The (error, matches) function to call when done, matches will be true if at least one match is found, false otherwise
   */
  test(string3, callback) {
    if (typeof callback !== "function") {
      callback = () => {
      };
    }
    try {
      callback(null, this.testSync(string3));
    } catch (error2) {
      callback(error2);
    }
  }
  captureIndicesForMatch(string3, match2) {
    if (match2 != null) {
      const { captureIndices } = match2;
      let capture;
      string3 = this.scanner.convertToString(string3);
      for (let i = 0; i < captureIndices.length; i++) {
        capture = captureIndices[i];
        capture.match = string3.slice(capture.start, capture.end);
      }
      return captureIndices;
    } else {
      return null;
    }
  }
}
OnigRegExp$1.default = OnigRegExp;
Object.defineProperty(lib, "__esModule", { value: true });
const onigasmH_1 = onigasmH;
var loadWASM = lib.loadWASM = onigasmH_1.loadWASM;
const OnigRegExp_1 = OnigRegExp$1;
lib.OnigRegExp = OnigRegExp_1.default;
const OnigScanner_1 = OnigScanner$1;
lib.OnigScanner = OnigScanner_1.default;
const OnigString_1 = OnigString$1;
lib.OnigString = OnigString_1.default;
const onigasmWasm = "/assets/onigasm-b63d2d2d.wasm";
function WorkerWrapper() {
  return new Worker("/assets/vue.worker-ed7fa2db.js");
}
let initted = false;
function initMonaco() {
  if (initted) {
    return;
  }
  loadMonacoEnv();
  loadWasm();
  initted = true;
}
function loadWasm() {
  return loadWASM(onigasmWasm);
}
function loadMonacoEnv() {
  self.MonacoEnvironment = {
    async getWorker(_, label) {
      if (label === "vue") {
        const worker = new WorkerWrapper();
        const init2 = new Promise((resolve2) => {
          worker.addEventListener("message", (data) => {
            if (data.data === "inited") {
              resolve2();
            }
          });
        });
        await init2;
        return worker;
      }
      return new WorkerWrapper$1();
    }
  };
  languages.register({ id: "vue", extensions: [".vue"] });
  languages.register({ id: "javascript", extensions: [".js"] });
  languages.register({ id: "typescript", extensions: [".ts"] });
  languages.register({ id: "json", extensions: [".json"] });
}
const _sfc_main$6 = /* @__PURE__ */ defineComponent({
  __name: "Monaco",
  props: {
    filename: {},
    lang: {},
    value: {},
    readonly: { type: Boolean, default: false }
  },
  emits: ["update:modelValue", "change", "selection", "cursor", "mount"],
  setup(__props, { emit: emit2 }) {
    const props = __props;
    const containerRef = ref();
    const ready = ref(false);
    const editor$12 = shallowRef();
    initMonaco();
    const lang = computed(() => (props == null ? void 0 : props.lang) || "vue");
    const replTheme = ref("dark");
    onMounted(async () => {
      const theme = await loadTheme(editor);
      ready.value = true;
      await nextTick$1();
      if (!containerRef.value) {
        throw new Error("Cannot find containerRef");
      }
      const editorInstance = editor.create(containerRef.value, {
        ...props.readonly ? { value: props.value, language: lang.value } : { model: null },
        "fontSize": 12,
        "theme": replTheme.value === "light" ? theme.light : theme.dark,
        "readOnly": props.readonly,
        "automaticLayout": true,
        "scrollBeyondLastLine": false,
        "minimap": {
          enabled: false
        },
        "inlineSuggest": {
          enabled: false
        },
        "semanticHighlighting.enabled": true,
        "fixedOverflowWidgets": true
      });
      editor$12.value = editorInstance;
      const t = editorInstance._themeService._theme;
      t.getTokenStyleMetadata = (type, modifiers, _language2) => {
        const _readonly = modifiers.includes("readonly");
        switch (type) {
          case "function":
          case "method":
            return { foreground: 12 };
          case "class":
            return { foreground: 11 };
          case "variable":
          case "property":
            return { foreground: _readonly ? 21 : 9 };
          default:
            return { foreground: 0 };
        }
      };
      watch(
        () => props.value,
        (value) => {
          if (editorInstance.getValue() === value) {
            return;
          }
          editorInstance.setValue(value || "");
        },
        { immediate: true }
      );
      watch(
        lang,
        (lang2) => editor.setModelLanguage(editorInstance.getModel(), lang2)
      );
      if (!props.readonly) {
        watch(
          () => props.filename,
          (_) => {
            if (!editorInstance) {
              return;
            }
            const model = getOrCreateModel(
              Uri2.parse(`file:///${props.filename}`),
              "vue",
              props.value || ""
            );
            editorInstance.setModel(model);
          },
          { immediate: true }
        );
      }
      await loadGrammars(monaco, editorInstance);
      editorInstance.addCommand(KeyMod2.CtrlCmd | KeyCode.KeyS, () => {
      });
      editorInstance.onDidChangeModelContent((e) => {
        emit2("change", e);
        emit2("update:modelValue", editorInstance.getValue());
      });
      watch(replTheme, (n2) => {
        editorInstance.updateOptions({
          theme: n2 === "light" ? theme.light : theme.dark
        });
      });
      editorInstance.onDidChangeCursorPosition((e) => {
        emit2("cursor", e);
      });
      editorInstance.onDidChangeCursorSelection((e) => {
        emit2("selection", e);
      });
      emit2("mount", editorInstance);
    });
    onBeforeUnmount(() => {
      var _a2;
      (_a2 = editor$12.value) == null ? void 0 : _a2.dispose();
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", {
        ref_key: "containerRef",
        ref: containerRef,
        class: "editor"
      }, null, 512);
    };
  }
});
const Monaco_vue_vue_type_style_index_0_lang = "";
const _hoisted_1$4 = { class: "block" };
const _hoisted_2$4 = { class: "output" };
const _hoisted_3$1 = { class: "actions" };
const _hoisted_4$1 = { class: "selection" };
const _hoisted_5 = { class: "ms-functions" };
const _hoisted_6 = ["placeholder"];
const _sfc_main$5 = /* @__PURE__ */ defineComponent({
  __name: "EditBlock",
  props: {
    source: {},
    id: {},
    type: {},
    index: {}
  },
  emits: ["parse", "select"],
  setup(__props, { emit: $emit }) {
    const props = __props;
    const lang = computed(() => {
      switch (props.type) {
        case "templates":
          return "html";
        case "scripts":
          return "javascript";
        case "styles":
          return "css";
        default:
          return "json";
      }
    });
    const block = computed(() => {
      var _a2, _b2;
      return (_b2 = (_a2 = props.source) == null ? void 0 : _a2[props.type]) == null ? void 0 : _b2[props.index];
    });
    const editor2 = shallowRef();
    const localContent = computed(() => {
      var _a2;
      return ((_a2 = block == null ? void 0 : block.value) == null ? void 0 : _a2.toString()) || "";
    });
    const parsedLocalContent = computed(() => `sfc[\`${props.type}\`][${props.index}] = ${JSON.stringify(block.value, null, 2)}`);
    function getOffset(content2, lineNumber, column) {
      const lines = content2.split("\n");
      let offset = 0;
      for (let i = 0; i < lineNumber - 1; i++) {
        offset += lines[i].length + 1;
      }
      offset += column - 1;
      return offset;
    }
    const cursor = ref();
    function handleCursor(e) {
      const { lineNumber, column } = e.position;
      const offset = getOffset(block.value.content, lineNumber, column);
      cursor.value = offset;
    }
    const selection = ref();
    const selectionStart = ref();
    const selectionEnd = ref();
    function handleSelection(e) {
      const { selection: { startColumn, startLineNumber, endColumn, endLineNumber } } = e;
      const startOffset = getOffset(block.value.content, startLineNumber, startColumn);
      const endOffset = getOffset(block.value.content, endLineNumber, endColumn);
      selectionStart.value = startOffset;
      selectionEnd.value = endOffset;
      selection.value = e;
      $emit(
        "select",
        {
          id: props.id,
          target: block.value,
          raw: selection.value,
          selectionStart: selectionStart.value,
          selectionEnd: selectionEnd.value,
          sourceStart: block.value.loc.start.offset + selectionStart.value,
          sourceEnd: block.value.loc.start.offset + selectionEnd.value
        }
      );
    }
    let decorations2;
    watch(selection, (newSel) => {
      if (editor2.value && newSel) {
        if (decorations2) {
          decorations2.clear();
          decorations2 = void 0;
        }
        const { selection: selection2 } = newSel;
        const { startColumn, startLineNumber, endColumn, endLineNumber } = selection2;
        decorations2 = editor2.value.createDecorationsCollection([
          {
            range: new Range2(startLineNumber, startColumn, endLineNumber, endColumn),
            options: {
              inlineClassName: "highlited-line"
            }
          },
          {
            range: new Range2(startLineNumber, startColumn, endLineNumber, endColumn),
            options: { inlineClassName: "highlighted-range" }
          }
        ]);
      }
    });
    const content = ref("");
    const magicStringMethods = computed(() => ({
      appendLeft: [cursor.value, content.value],
      appendRight: [cursor.value, content.value],
      append: [content.value],
      prepend: [cursor.value, content.value],
      prependLeft: [cursor.value, content.value],
      prependRight: [cursor.value, content.value],
      overwrite: [selectionStart.value, selectionEnd.value, content.value],
      remove: [selectionStart.value, selectionEnd.value]
    }));
    const method = ref("overwrite");
    function apply2() {
      var _a2;
      const args = (_a2 = magicStringMethods == null ? void 0 : magicStringMethods.value) == null ? void 0 : _a2[method.value];
      if (block.value[method.value]) {
        block.value[method.value](...args);
        triggerRef(localContent);
        triggerRef(parsedLocalContent);
        $emit("parse");
      }
    }
    function handleMounted(e) {
      editor2.value = e;
    }
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$4, [
        createBaseVNode("div", _hoisted_2$4, [
          createBaseVNode("div", null, [
            createVNode(_sfc_main$6, {
              class: "editor",
              value: localContent.value,
              filename: `${_ctx.id}.${lang.value}`,
              lang: lang.value,
              readonly: "",
              onSelection: handleSelection,
              onCursor: handleCursor,
              onMount: handleMounted
            }, null, 8, ["value", "filename", "lang"])
          ]),
          createBaseVNode("div", null, [
            createVNode(_sfc_main$6, {
              class: "editor",
              value: parsedLocalContent.value,
              filename: `${_ctx.id}.${lang.value}`,
              lang: "typescript",
              readonly: ""
            }, null, 8, ["value", "filename"])
          ])
        ]),
        createBaseVNode("div", _hoisted_3$1, [
          createBaseVNode("div", _hoisted_4$1, [
            createBaseVNode("p", null, [
              createBaseVNode("span", null, "sfc[`" + toDisplayString$1(_ctx.type) + "`][" + toDisplayString$1(_ctx.index) + "]", 1)
            ]),
            createBaseVNode("p", null, [
              createTextVNode(" Cursor: "),
              createBaseVNode("span", null, toDisplayString$1(cursor.value || 0), 1)
            ]),
            createBaseVNode("p", null, [
              createTextVNode(" Selection start: "),
              createBaseVNode("span", null, toDisplayString$1(selectionStart.value || 0), 1)
            ]),
            createBaseVNode("p", null, [
              createTextVNode(" Selection end: "),
              createBaseVNode("span", null, toDisplayString$1(selectionEnd.value || 0), 1)
            ])
          ]),
          createBaseVNode("div", _hoisted_5, [
            withDirectives(createBaseVNode("input", {
              "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => content.value = $event),
              placeholder: `${method.value} content`,
              type: "text"
            }, null, 8, _hoisted_6), [
              [vModelText, content.value]
            ]),
            createBaseVNode("div", null, [
              withDirectives(createBaseVNode("select", {
                "onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => method.value = $event)
              }, [
                (openBlock(true), createElementBlock(Fragment, null, renderList(Object.keys(magicStringMethods.value), (msMethod) => {
                  return openBlock(), createElementBlock("option", { key: msMethod }, toDisplayString$1(msMethod), 1);
                }), 128))
              ], 512), [
                [vModelSelect, method.value]
              ])
            ]),
            createBaseVNode("button", { onClick: apply2 }, " Apply ")
          ])
        ])
      ]);
    };
  }
});
const EditBlock_vue_vue_type_style_index_0_scoped_f0717d80_lang = "";
const _export_sfc = (sfc, props) => {
  const target = sfc.__vccOpts || sfc;
  for (const [key, val] of props) {
    target[key] = val;
  }
  return target;
};
const EditBlock = /* @__PURE__ */ _export_sfc(_sfc_main$5, [["__scopeId", "data-v-f0717d80"]]);
const _hoisted_1$3 = { class: "block" };
const _hoisted_2$3 = { class: "actions" };
const _sfc_main$4 = /* @__PURE__ */ defineComponent({
  __name: "EditSource",
  props: {
    source: {}
  },
  emits: ["update", "cancel"],
  setup(__props, { emit: emit2 }) {
    const props = __props;
    const localContent = ref(props.source.ms.toString());
    function handleUpdate() {
      emit2("update", localContent.value);
    }
    function handleUpdateModel(e) {
      localContent.value = e;
    }
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$3, [
        createBaseVNode("div", _hoisted_2$3, [
          createBaseVNode("button", {
            onClick: _cache[0] || (_cache[0] = ($event) => _ctx.$emit("cancel"))
          }, " Cancel "),
          createBaseVNode("button", { onClick: handleUpdate }, " Save ")
        ]),
        createVNode(_sfc_main$6, {
          value: localContent.value,
          class: "source",
          filename: "source.vue",
          "onUpdate:modelValue": handleUpdateModel
        }, null, 8, ["value"])
      ]);
    };
  }
});
const EditSource_vue_vue_type_style_index_0_scoped_50cb6e7c_lang = "";
const EditSource = /* @__PURE__ */ _export_sfc(_sfc_main$4, [["__scopeId", "data-v-50cb6e7c"]]);
const _sfc_main$3 = /* @__PURE__ */ defineComponent({
  __name: "MonacoDiff",
  props: {
    filename: {},
    source: {},
    value: {},
    readonly: { type: Boolean, default: false }
  },
  emits: ["change", "selection", "cursor", "mount"],
  setup(__props, { emit: emit2 }) {
    const props = __props;
    const containerRef = ref();
    const ready = ref(false);
    const editor$12 = shallowRef();
    initMonaco();
    const lang = computed(() => "vue");
    const replTheme = ref("dark");
    onMounted(async () => {
      const theme = await loadTheme(editor);
      ready.value = true;
      await nextTick$1();
      if (!containerRef.value) {
        throw new Error("Cannot find containerRef");
      }
      const editorInstance = editor.createDiffEditor(
        containerRef.value,
        {
          ...props.readonly ? {
            value: props.value,
            language: lang.value
          } : {
            model: null
          },
          fontSize: 12,
          theme: replTheme.value === "light" ? theme.light : theme.dark,
          readOnly: props.readonly,
          automaticLayout: true,
          scrollBeyondLastLine: false,
          minimap: {
            enabled: false
          },
          inlineSuggest: {
            enabled: false
          },
          fixedOverflowWidgets: true
        }
      );
      editor$12.value = editorInstance;
      const t = editorInstance._themeService._theme;
      t.getTokenStyleMetadata = (type, modifiers, _language2) => {
        const _readonly = modifiers.includes("readonly");
        switch (type) {
          case "function":
          case "method":
            return { foreground: 12 };
          case "class":
            return { foreground: 11 };
          case "variable":
          case "property":
            return { foreground: _readonly ? 21 : 9 };
          default:
            return { foreground: 0 };
        }
      };
      watch(
        () => props.value,
        (value) => {
          if (editorInstance.getModifiedEditor().getValue() === value) {
            return;
          }
          editorInstance.getModifiedEditor().setValue(value || "");
        },
        { immediate: true }
      );
      watch(
        () => props.source,
        (value) => {
          if (editorInstance.getOriginalEditor().getValue() === value) {
            return;
          }
          editorInstance.getOriginalEditor().setValue(value || "");
        },
        { immediate: true }
      );
      if (!props.readonly) {
        watch(
          () => props.filename,
          (_) => {
            if (!editorInstance) {
              return;
            }
            const sourceModel = getOrCreateModel(
              Uri2.parse(`file:///source-${props.filename}`),
              "vue",
              props.source || ""
            );
            const valueModel = getOrCreateModel(
              Uri2.parse(`file:///value-${props.filename}`),
              "vue",
              props.value || ""
            );
            editorInstance.setModel({
              original: sourceModel,
              modified: valueModel
            });
          },
          { immediate: true }
        );
      }
      await loadGrammars(monaco, editorInstance.getModifiedEditor());
      await loadGrammars(monaco, editorInstance.getOriginalEditor());
      editorInstance.addCommand(KeyMod2.CtrlCmd | KeyCode.KeyS, () => {
      });
      emit2("mount", editorInstance);
    });
    onBeforeUnmount(() => {
      var _a2;
      (_a2 = editor$12.value) == null ? void 0 : _a2.dispose();
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", {
        ref_key: "containerRef",
        ref: containerRef,
        class: "editor"
      }, null, 512);
    };
  }
});
const MonacoDiff_vue_vue_type_style_index_0_lang = "";
const _hoisted_1$2 = { class: "block" };
const _hoisted_2$2 = { class: "actions" };
const _sfc_main$2 = /* @__PURE__ */ defineComponent({
  __name: "Source",
  props: {
    source: {}
  },
  emits: ["mount", "edit"],
  setup(__props) {
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1$2, [
        createBaseVNode("div", _hoisted_2$2, [
          createBaseVNode("button", {
            onClick: _cache[0] || (_cache[0] = ($event) => _ctx.$emit("edit"))
          }, " Edit source ")
        ]),
        createVNode(_sfc_main$3, {
          class: "diff",
          filename: "test-file.vue",
          source: `// Source:
${_ctx.source.ms.original}`,
          value: `// Output:
${_ctx.source.ms.toString()}`,
          onMount: _cache[1] || (_cache[1] = (e) => _ctx.$emit("mount", e))
        }, null, 8, ["source", "value"]),
        createVNode(_sfc_main$6, {
          class: "map",
          filename: "test-file-map.vue",
          value: `Sourcemap:

${JSON.stringify(_ctx.source.getSourcemap(), null, 2)}

Decoded mappings:

${JSON.stringify(_ctx.source.ms.generateDecodedMap(), null, 2)}`
        }, null, 8, ["value"])
      ]);
    };
  }
});
const Source_vue_vue_type_style_index_0_scoped_d0e4fc8f_lang = "";
const Source = /* @__PURE__ */ _export_sfc(_sfc_main$2, [["__scopeId", "data-v-d0e4fc8f"]]);
const Motd_vue_vue_type_style_index_0_scoped_a912b182_lang = "";
const _sfc_main$1 = {};
const _withScopeId$1 = (n2) => (pushScopeId("data-v-a912b182"), n2 = n2(), popScopeId(), n2);
const _hoisted_1$1 = { class: "motd" };
const _hoisted_2$1 = /* @__PURE__ */ _withScopeId$1(() => /* @__PURE__ */ createBaseVNode("p", null, [
  /* @__PURE__ */ createTextVNode(" SFC Composer provides wrapper classes around "),
  /* @__PURE__ */ createBaseVNode("a", null, "MagicString"),
  /* @__PURE__ */ createTextVNode(" making the orchestration of transforms on Single File Components a breeze. ")
], -1));
const _hoisted_3 = /* @__PURE__ */ _withScopeId$1(() => /* @__PURE__ */ createBaseVNode("p", null, " In this example you can try editing each of the source SFC blocks independently. ", -1));
const _hoisted_4 = [
  _hoisted_2$1,
  _hoisted_3
];
function _sfc_render(_ctx, _cache) {
  return openBlock(), createElementBlock("div", _hoisted_1$1, _hoisted_4);
}
const Motd = /* @__PURE__ */ _export_sfc(_sfc_main$1, [["render", _sfc_render], ["__scopeId", "data-v-a912b182"]]);
const TestComponent = `<script setup lang="ts">
console.log('Hello World!')
<\/script>

<template>
  <div>
    <button>Hello World</button>
  </div>
</template>

<style>
#app {
  background-color: red;
}
</style>

<style scoped lang="postcss">
div {
  background-color: red;

  button {
    color: blue;
  }
}
</style>

<i18n>
{
  "test": "hello-world"
}
</i18n>
`;
const _withScopeId = (n2) => (pushScopeId("data-v-f5c5785d"), n2 = n2(), popScopeId(), n2);
const _hoisted_1 = /* @__PURE__ */ _withScopeId(() => /* @__PURE__ */ createBaseVNode("h1", null, "🎼 SFC Composer", -1));
const _hoisted_2 = /* @__PURE__ */ _withScopeId(() => /* @__PURE__ */ createBaseVNode("div", { class: "credits" }, [
  /* @__PURE__ */ createBaseVNode("a", { href: "https://github.com/Tahul/sfc-composer" }, " ↩️  Bring me back to GitHub "),
  /* @__PURE__ */ createBaseVNode("p", null, [
    /* @__PURE__ */ createTextVNode(" Made by "),
    /* @__PURE__ */ createBaseVNode("a", {
      href: "https://twitter.com/yaeeelglx",
      target: "_blank"
    }, "@Tahul")
  ])
], -1));
const _sfc_main = /* @__PURE__ */ defineComponent({
  __name: "App",
  setup(__props) {
    magicVueSfcDefaultOptions.parser = parse$7;
    const sfc = shallowRef(new MagicVueSFC(TestComponent, { filename: "test-file.vue" }));
    const lastErrored = ref(false);
    const editingSource = ref(false);
    function updateSource(source) {
      sfc.value = new MagicVueSFC(source, { filename: "test-file.vue" });
      editingSource.value = false;
    }
    function update() {
      try {
        sfc.value.parse();
        lastErrored.value = false;
      } catch (e) {
        lastErrored.value = true;
        console.log({ "compile-error": e });
        return;
      }
      triggerRef(sfc);
    }
    const templates = computed(() => sfc.value.templates);
    const scripts = computed(() => sfc.value.scripts);
    const styles = computed(() => sfc.value.styles);
    const customs = computed(() => sfc.value.customs);
    const sourceEditor = shallowRef();
    function handleSourceMounted(e) {
      sourceEditor.value = e;
    }
    let decorations2;
    function handleBlockSelection(newSel) {
      var _a2;
      if (decorations2) {
        decorations2.clear();
        decorations2 = void 0;
      }
      const { sourceStart, sourceEnd } = newSel;
      const { line: startLine, col: startColumn } = lineColumn$1(sfc.value.toString()).fromIndex(sourceStart);
      const { line: endLine, col: endColumn } = lineColumn$1(sfc.value.toString()).fromIndex(sourceEnd);
      decorations2 = (_a2 = sourceEditor.value) == null ? void 0 : _a2.getOriginalEditor().createDecorationsCollection([
        {
          range: new Range2(
            startLine,
            startColumn,
            endLine,
            endColumn
          ),
          options: {
            inlineClassName: "highlited-line"
          }
        },
        {
          range: new Range2(
            startLine,
            startColumn,
            endLine,
            endColumn
          ),
          options: { inlineClassName: "highlighted-range" }
        }
      ]);
    }
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("main", null, [
        _hoisted_1,
        createVNode(Motd),
        editingSource.value ? (openBlock(), createBlock$1(EditSource, {
          key: 0,
          source: sfc.value,
          onUpdate: updateSource,
          onCancel: _cache[0] || (_cache[0] = ($event) => editingSource.value = false)
        }, null, 8, ["source"])) : (openBlock(), createElementBlock(Fragment, { key: 1 }, [
          (openBlock(), createBlock$1(Source, {
            key: sfc.value.toString(),
            source: sfc.value,
            onParse: update,
            onMount: handleSourceMounted,
            onEdit: _cache[1] || (_cache[1] = ($event) => editingSource.value = true)
          }, null, 8, ["source"])),
          (openBlock(), createElementBlock("div", {
            key: sfc.value.toString(),
            class: "blocks"
          }, [
            (openBlock(true), createElementBlock(Fragment, null, renderList(templates.value, (_, index) => {
              return openBlock(), createBlock$1(EditBlock, {
                id: `templates-${index}`,
                key: `templates-${index}`,
                type: "templates",
                source: sfc.value,
                index,
                onParse: update,
                onSelect: handleBlockSelection
              }, null, 8, ["id", "source", "index"]);
            }), 128)),
            (openBlock(true), createElementBlock(Fragment, null, renderList(scripts.value, (_, index) => {
              return openBlock(), createBlock$1(EditBlock, {
                id: `scripts-${index}`,
                key: `scripts-${index}`,
                source: sfc.value,
                index,
                type: "scripts",
                onParse: update,
                onSelect: handleBlockSelection
              }, null, 8, ["id", "source", "index"]);
            }), 128)),
            (openBlock(true), createElementBlock(Fragment, null, renderList(styles.value, (_, index) => {
              return openBlock(), createBlock$1(EditBlock, {
                id: `styles-${index}`,
                key: `styles-${index}`,
                source: sfc.value,
                index,
                type: "styles",
                onParse: update,
                onSelect: handleBlockSelection
              }, null, 8, ["id", "source", "index"]);
            }), 128)),
            (openBlock(true), createElementBlock(Fragment, null, renderList(customs.value, (_, index) => {
              return openBlock(), createBlock$1(EditBlock, {
                id: `customs-${index}`,
                key: `customs-${index}`,
                source: sfc.value,
                type: "customs",
                index,
                onParse: update,
                onSelect: handleBlockSelection
              }, null, 8, ["id", "source", "index"]);
            }), 128))
          ]))
        ], 64)),
        _hoisted_2
      ]);
    };
  }
});
const App_vue_vue_type_style_index_0_scoped_f5c5785d_lang = "";
const App = /* @__PURE__ */ _export_sfc(_sfc_main, [["__scopeId", "data-v-f5c5785d"]]);
const app = createApp(App);
app.mount("#app");
export {
  __vitePreload as _,
  commonjsGlobal as c,
  lib as l
};
